framesheet 0.1.0__py3-none-any.whl
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.
- framesheet/__init__.py +46 -0
- framesheet/analysis.py +392 -0
- framesheet/checks.py +246 -0
- framesheet/cli.py +113 -0
- framesheet/compose.py +259 -0
- framesheet/core.py +340 -0
- framesheet/log.py +25 -0
- framesheet/models.py +195 -0
- framesheet/py.typed +0 -0
- framesheet/render.py +192 -0
- framesheet/runtime.js +323 -0
- framesheet/sources.py +135 -0
- framesheet/timing.py +118 -0
- framesheet-0.1.0.dist-info/METADATA +219 -0
- framesheet-0.1.0.dist-info/RECORD +18 -0
- framesheet-0.1.0.dist-info/WHEEL +4 -0
- framesheet-0.1.0.dist-info/entry_points.txt +3 -0
- framesheet-0.1.0.dist-info/licenses/LICENSE +22 -0
framesheet/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""framesheet: main package.
|
|
2
|
+
|
|
3
|
+
Frame-accurate contact sheets and motion maps for animated SVG and HTML, for humans
|
|
4
|
+
and AI agents.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import version
|
|
10
|
+
|
|
11
|
+
__version__ = version("framesheet")
|
|
12
|
+
__title__ = "framesheet"
|
|
13
|
+
|
|
14
|
+
__author__ = "Philipp Temminghoff"
|
|
15
|
+
__author_email__ = "philipptemminghoff@googlemail.com"
|
|
16
|
+
__copyright__ = "Copyright (c) 2026 Philipp Temminghoff"
|
|
17
|
+
__license__ = "MIT"
|
|
18
|
+
__url__ = "https://github.com/phil65/framesheet"
|
|
19
|
+
|
|
20
|
+
from framesheet.core import inspect
|
|
21
|
+
from framesheet.models import (
|
|
22
|
+
AnimationTiming,
|
|
23
|
+
DurationInfo,
|
|
24
|
+
ElementTrack,
|
|
25
|
+
Finding,
|
|
26
|
+
FrameMetrics,
|
|
27
|
+
Images,
|
|
28
|
+
InspectionResult,
|
|
29
|
+
LoopInfo,
|
|
30
|
+
)
|
|
31
|
+
from framesheet.render import BrowserNotInstalledError, install_browser
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"AnimationTiming",
|
|
35
|
+
"BrowserNotInstalledError",
|
|
36
|
+
"DurationInfo",
|
|
37
|
+
"ElementTrack",
|
|
38
|
+
"Finding",
|
|
39
|
+
"FrameMetrics",
|
|
40
|
+
"Images",
|
|
41
|
+
"InspectionResult",
|
|
42
|
+
"LoopInfo",
|
|
43
|
+
"__version__",
|
|
44
|
+
"inspect",
|
|
45
|
+
"install_browser",
|
|
46
|
+
]
|
framesheet/analysis.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Render checks: geometry of every element across all sampled frames.
|
|
2
|
+
|
|
3
|
+
Each check is a function ``(Geometry) -> list[Finding]`` registered in :data:`CHECKS`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from framesheet.models import AnimationTiming, ElementTrack, Finding, Rect, as_rect
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
|
|
17
|
+
from framesheet.render import Snapshot
|
|
18
|
+
|
|
19
|
+
TOLERANCE = 1.0
|
|
20
|
+
"""Pixels an element may poke out of its container/canvas before it is reported."""
|
|
21
|
+
MAX_TRACKS = 30
|
|
22
|
+
MAX_REPORTED = 12
|
|
23
|
+
SMALL_FRACTION = 0.2
|
|
24
|
+
CONTAINERS = {"g", "svg", "a", "switch", "div", "section", "main", "article", "span"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Element:
|
|
29
|
+
index: int
|
|
30
|
+
tag: str
|
|
31
|
+
label: str
|
|
32
|
+
svg: bool
|
|
33
|
+
parent: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Geometry:
|
|
38
|
+
"""Inputs shared by all render checks."""
|
|
39
|
+
|
|
40
|
+
elements: dict[int, Element]
|
|
41
|
+
times: list[float]
|
|
42
|
+
client: dict[int, list[Rect | None]]
|
|
43
|
+
"""Client rect (CSS px) per element per frame; ``None`` = not rendered/invisible."""
|
|
44
|
+
user: dict[int, list[Rect | None]]
|
|
45
|
+
"""SVG user-space rect (outermost ``<svg>``) per element per frame."""
|
|
46
|
+
canvas: Rect
|
|
47
|
+
viewbox: Rect | None
|
|
48
|
+
targets: dict[int, list[str]]
|
|
49
|
+
animations: list[AnimationTiming]
|
|
50
|
+
is_svg_doc: bool
|
|
51
|
+
html_overflow: list[list[Any]] = field(default_factory=list)
|
|
52
|
+
"""``[index, dx, dy]`` per frame (list of lists)."""
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def build(
|
|
56
|
+
cls,
|
|
57
|
+
description: list[dict[str, Any]],
|
|
58
|
+
snapshots: list[Snapshot],
|
|
59
|
+
*,
|
|
60
|
+
canvas: Rect,
|
|
61
|
+
viewbox: Rect | None,
|
|
62
|
+
targets: dict[str, list[str]],
|
|
63
|
+
animations: list[AnimationTiming],
|
|
64
|
+
is_svg_doc: bool,
|
|
65
|
+
) -> Geometry:
|
|
66
|
+
elements = {
|
|
67
|
+
d["i"]: Element(d["i"], d["tag"], d["label"], d["svg"], d["parent"])
|
|
68
|
+
for d in description
|
|
69
|
+
}
|
|
70
|
+
n = len(snapshots)
|
|
71
|
+
client: dict[int, list[Rect | None]] = {}
|
|
72
|
+
user: dict[int, list[Rect | None]] = {}
|
|
73
|
+
for k, snap in enumerate(snapshots):
|
|
74
|
+
for index, rect, user_rect, visible in snap.geometry:
|
|
75
|
+
if not visible:
|
|
76
|
+
continue
|
|
77
|
+
client.setdefault(index, [None] * n)[k] = as_rect(rect)
|
|
78
|
+
if user_rect is not None:
|
|
79
|
+
user.setdefault(index, [None] * n)[k] = as_rect(user_rect)
|
|
80
|
+
return cls(
|
|
81
|
+
elements=elements,
|
|
82
|
+
times=[s.t for s in snapshots],
|
|
83
|
+
client=client,
|
|
84
|
+
user=user,
|
|
85
|
+
canvas=canvas,
|
|
86
|
+
viewbox=viewbox,
|
|
87
|
+
targets={int(k): v for k, v in targets.items()},
|
|
88
|
+
animations=animations,
|
|
89
|
+
is_svg_doc=is_svg_doc,
|
|
90
|
+
html_overflow=[s.overflow for s in snapshots],
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def ancestors(self, index: int) -> list[int]:
|
|
94
|
+
out = []
|
|
95
|
+
parent = self.elements[index].parent if index in self.elements else -1
|
|
96
|
+
while parent != -1 and parent in self.elements:
|
|
97
|
+
out.append(parent)
|
|
98
|
+
parent = self.elements[parent].parent
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
def label(self, index: int) -> str:
|
|
102
|
+
return self.elements[index].label if index in self.elements else f"element {index}"
|
|
103
|
+
|
|
104
|
+
def moved(self) -> set[int]:
|
|
105
|
+
out = set()
|
|
106
|
+
for index, rects in self.client.items():
|
|
107
|
+
present = [r for r in rects if r is not None]
|
|
108
|
+
if len(present) != len(rects) and present:
|
|
109
|
+
out.add(index) # appears / disappears
|
|
110
|
+
continue
|
|
111
|
+
if present and any(_differs(present[0], r) for r in present[1:]):
|
|
112
|
+
out.add(index)
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _differs(a: Rect, b: Rect, tol: float = 0.5) -> bool:
|
|
117
|
+
return any(abs(x - y) > tol for x, y in zip(a, b))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _leaves(geo: Geometry, flagged: set[int]) -> set[int]:
|
|
121
|
+
"""Drop flagged elements that have a flagged descendant (report the innermost)."""
|
|
122
|
+
covered = {a for i in flagged for a in geo.ancestors(i)}
|
|
123
|
+
return {i for i in flagged if i not in covered}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _times(geo: Geometry, ks: list[int]) -> list[float]:
|
|
127
|
+
return [geo.times[k] for k in ks]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _fmt_times(times: list[float]) -> str:
|
|
131
|
+
if len(times) > 4: # noqa: PLR2004
|
|
132
|
+
return f"t={times[0]:.2f}s..{times[-1]:.2f}s ({len(times)} frames)"
|
|
133
|
+
return "t=" + ", ".join(f"{t:.2f}s" for t in times)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _finding(code: str, message: str, element: str | None, times: list[float] | None) -> Finding:
|
|
137
|
+
return Finding(
|
|
138
|
+
severity="warning",
|
|
139
|
+
code=code,
|
|
140
|
+
message=message,
|
|
141
|
+
check="render",
|
|
142
|
+
element=element,
|
|
143
|
+
times=times,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def tracks(geo: Geometry) -> list[ElementTrack]:
|
|
148
|
+
"""Per-frame boxes of animated elements (declared targets or anything that moved)."""
|
|
149
|
+
moved = geo.moved()
|
|
150
|
+
# A moving group moves all its children: keep the outermost mover. A group whose box
|
|
151
|
+
# only changes because an animated descendant moves is not reported on its own.
|
|
152
|
+
explained = {a for i in geo.targets for a in geo.ancestors(i)} - set(geo.targets)
|
|
153
|
+
indices = {
|
|
154
|
+
i for i in moved - explained if not (set(geo.ancestors(i)) & (moved - explained))
|
|
155
|
+
} | set(geo.targets)
|
|
156
|
+
out = []
|
|
157
|
+
for index in sorted(indices)[:MAX_TRACKS]:
|
|
158
|
+
boxes = geo.user.get(index) or geo.client.get(index)
|
|
159
|
+
if boxes is None:
|
|
160
|
+
continue
|
|
161
|
+
kinds = list(geo.targets.get(index, []))
|
|
162
|
+
if index in moved:
|
|
163
|
+
kinds.append("moved")
|
|
164
|
+
out.append(
|
|
165
|
+
ElementTrack(
|
|
166
|
+
element=geo.label(index),
|
|
167
|
+
animated_by=kinds,
|
|
168
|
+
units="viewBox" if index in geo.user else "px",
|
|
169
|
+
boxes=boxes,
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def check_outside(geo: Geometry) -> list[Finding]:
|
|
176
|
+
"""Elements extending past the viewBox (SVG) or viewport (HTML)."""
|
|
177
|
+
cx, cy, cw, ch = geo.canvas
|
|
178
|
+
hits: dict[int, list[int]] = {}
|
|
179
|
+
amounts: dict[int, dict[str, float]] = {}
|
|
180
|
+
for index, rects in geo.client.items():
|
|
181
|
+
for k, rect in enumerate(rects):
|
|
182
|
+
if rect is None:
|
|
183
|
+
continue
|
|
184
|
+
x, y, w, h = rect
|
|
185
|
+
over = {
|
|
186
|
+
"left": cx - x,
|
|
187
|
+
"top": cy - y,
|
|
188
|
+
"right": x + w - (cx + cw),
|
|
189
|
+
"bottom": y + h - (cy + ch),
|
|
190
|
+
}
|
|
191
|
+
worst = {side: v for side, v in over.items() if v > TOLERANCE}
|
|
192
|
+
if worst:
|
|
193
|
+
hits.setdefault(index, []).append(k)
|
|
194
|
+
agg = amounts.setdefault(index, {})
|
|
195
|
+
for side, v in worst.items():
|
|
196
|
+
agg[side] = max(agg.get(side, 0), v)
|
|
197
|
+
keep = _leaves(geo, set(hits))
|
|
198
|
+
area = "viewBox" if geo.is_svg_doc else "viewport"
|
|
199
|
+
out = []
|
|
200
|
+
ordered = sorted(keep, key=lambda i: -max(amounts[i].values()))
|
|
201
|
+
for index in ordered[:MAX_REPORTED]:
|
|
202
|
+
ks = hits[index]
|
|
203
|
+
sides = ", ".join(f"{v:.0f}px {side}" for side, v in amounts[index].items())
|
|
204
|
+
when = (
|
|
205
|
+
"at every frame" if len(ks) == len(geo.times) else f"at {_fmt_times(_times(geo, ks))}"
|
|
206
|
+
)
|
|
207
|
+
out.append(
|
|
208
|
+
_finding(
|
|
209
|
+
"outside-bounds",
|
|
210
|
+
f"{geo.label(index)} extends outside the {area} {when} (up to {sides}).",
|
|
211
|
+
geo.label(index),
|
|
212
|
+
_times(geo, ks),
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
if len(ordered) > MAX_REPORTED:
|
|
216
|
+
out.append(
|
|
217
|
+
_finding(
|
|
218
|
+
"outside-bounds",
|
|
219
|
+
f"... and {len(ordered) - MAX_REPORTED} more element(s) outside the {area}.",
|
|
220
|
+
None,
|
|
221
|
+
None,
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
return out
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def check_parked(geo: Geometry) -> list[Finding]:
|
|
228
|
+
"""Small SVG elements sitting on the user-space origin (0,0), e.g. before ``begin``."""
|
|
229
|
+
if geo.viewbox is None:
|
|
230
|
+
return []
|
|
231
|
+
_, _, vw, vh = geo.viewbox
|
|
232
|
+
hits: dict[int, list[int]] = {}
|
|
233
|
+
for index, rects in geo.user.items():
|
|
234
|
+
element = geo.elements.get(index)
|
|
235
|
+
if element is None or element.tag in CONTAINERS:
|
|
236
|
+
continue
|
|
237
|
+
for k, rect in enumerate(rects):
|
|
238
|
+
if rect is None:
|
|
239
|
+
continue
|
|
240
|
+
x, y, w, h = rect
|
|
241
|
+
small = w < SMALL_FRACTION * vw and h < SMALL_FRACTION * vh
|
|
242
|
+
covers_origin = x <= TOLERANCE and y <= TOLERANCE and x + w >= 0 and y + h >= 0
|
|
243
|
+
if small and covers_origin:
|
|
244
|
+
hits.setdefault(index, []).append(k)
|
|
245
|
+
out = []
|
|
246
|
+
for index in sorted(_leaves(geo, set(hits))):
|
|
247
|
+
ks = hits[index]
|
|
248
|
+
times = _times(geo, ks)
|
|
249
|
+
out.append(
|
|
250
|
+
_finding(
|
|
251
|
+
"parked-at-origin",
|
|
252
|
+
f"{geo.label(index)} sits at the SVG origin (0,0) at {_fmt_times(times)}; "
|
|
253
|
+
"typical cause: <animateMotion> with a positive begin, or a missing x/y/cx/cy.",
|
|
254
|
+
geo.label(index),
|
|
255
|
+
times,
|
|
256
|
+
)
|
|
257
|
+
)
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def check_text_overflow(geo: Geometry) -> list[Finding]:
|
|
262
|
+
"""SVG ``<text>`` poking out of the ``<rect>`` painted under it; HTML text overflow."""
|
|
263
|
+
hits: dict[tuple[int, int], list[int]] = {}
|
|
264
|
+
amounts: dict[tuple[int, int], float] = {}
|
|
265
|
+
rects = [i for i, el in geo.elements.items() if el.tag == "rect"]
|
|
266
|
+
for index, el in geo.elements.items():
|
|
267
|
+
if el.tag != "text" or index not in geo.client:
|
|
268
|
+
continue
|
|
269
|
+
for k, text_box in enumerate(geo.client[index]):
|
|
270
|
+
if text_box is None:
|
|
271
|
+
continue
|
|
272
|
+
container = _container(geo, index, text_box, rects, k)
|
|
273
|
+
if container is None:
|
|
274
|
+
continue
|
|
275
|
+
container_box = geo.client[container][k]
|
|
276
|
+
if container_box is None:
|
|
277
|
+
continue
|
|
278
|
+
excess = _excess(text_box, container_box)
|
|
279
|
+
if excess > TOLERANCE:
|
|
280
|
+
key = (index, container)
|
|
281
|
+
hits.setdefault(key, []).append(k)
|
|
282
|
+
amounts[key] = max(amounts.get(key, 0), excess)
|
|
283
|
+
out = [
|
|
284
|
+
_finding(
|
|
285
|
+
"text-overflow",
|
|
286
|
+
f"{geo.label(text)} overflows its container {geo.label(box)} by up to "
|
|
287
|
+
f"{amounts[(text, box)]:.0f}px at {_fmt_times(_times(geo, ks))}.",
|
|
288
|
+
geo.label(text),
|
|
289
|
+
_times(geo, ks),
|
|
290
|
+
)
|
|
291
|
+
for (text, box), ks in sorted(hits.items())
|
|
292
|
+
]
|
|
293
|
+
html_hits: dict[int, list[int]] = {}
|
|
294
|
+
html_amount: dict[int, tuple[float, float]] = {}
|
|
295
|
+
for k, items in enumerate(geo.html_overflow):
|
|
296
|
+
for index, dx, dy in items:
|
|
297
|
+
html_hits.setdefault(index, []).append(k)
|
|
298
|
+
ox, oy = html_amount.get(index, (0, 0))
|
|
299
|
+
html_amount[index] = (max(ox, dx), max(oy, dy))
|
|
300
|
+
for index, ks in sorted(html_hits.items()):
|
|
301
|
+
dx, dy = html_amount[index]
|
|
302
|
+
out.append(
|
|
303
|
+
_finding(
|
|
304
|
+
"text-overflow",
|
|
305
|
+
f"{geo.label(index)} content is larger than its box ({dx:.0f}px wider, "
|
|
306
|
+
f"{dy:.0f}px taller) at {_fmt_times(_times(geo, ks))}.",
|
|
307
|
+
geo.label(index),
|
|
308
|
+
_times(geo, ks),
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _area(r: Rect) -> float:
|
|
315
|
+
return r[2] * r[3]
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _overlap(a: Rect, b: Rect) -> float:
|
|
319
|
+
w = min(a[0] + a[2], b[0] + b[2]) - max(a[0], b[0])
|
|
320
|
+
h = min(a[1] + a[3], b[1] + b[3]) - max(a[1], b[1])
|
|
321
|
+
return max(0.0, w) * max(0.0, h)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _excess(inner: Rect, outer: Rect) -> float:
|
|
325
|
+
return max(
|
|
326
|
+
outer[0] - inner[0],
|
|
327
|
+
outer[1] - inner[1],
|
|
328
|
+
inner[0] + inner[2] - (outer[0] + outer[2]),
|
|
329
|
+
inner[1] + inner[3] - (outer[1] + outer[3]),
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _container(geo: Geometry, text: int, box: Rect, rects: list[int], k: int) -> int | None:
|
|
334
|
+
"""Smallest rect painted before ``text`` that covers at least 30% of it."""
|
|
335
|
+
best, best_area = None, float("inf")
|
|
336
|
+
for index in rects:
|
|
337
|
+
if index > text or index not in geo.client:
|
|
338
|
+
continue
|
|
339
|
+
rect = geo.client[index][k]
|
|
340
|
+
if rect is None or _area(box) == 0:
|
|
341
|
+
continue
|
|
342
|
+
if _overlap(box, rect) / _area(box) >= 0.3 and _area(rect) < best_area: # noqa: PLR2004
|
|
343
|
+
best, best_area = index, _area(rect)
|
|
344
|
+
return best
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def check_transform_box(geo: Geometry) -> list[Finding]:
|
|
348
|
+
"""CSS transform animations on SVG elements without ``transform-box: fill-box``."""
|
|
349
|
+
out = []
|
|
350
|
+
seen: set[str] = set()
|
|
351
|
+
for anim in geo.animations:
|
|
352
|
+
if anim.transform_box != "view-box" or not anim.target or anim.target in seen:
|
|
353
|
+
continue
|
|
354
|
+
seen.add(anim.target)
|
|
355
|
+
out.append(
|
|
356
|
+
_finding(
|
|
357
|
+
"svg-transform-box",
|
|
358
|
+
f"CSS animation '{anim.name}' on {anim.target} animates transform with "
|
|
359
|
+
"transform-box: view-box (the SVG default), so it rotates/scales around the "
|
|
360
|
+
"SVG origin, not the element. Add transform-box: fill-box; "
|
|
361
|
+
"transform-origin: center.",
|
|
362
|
+
anim.target,
|
|
363
|
+
None,
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
return out
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
CHECKS: list[Callable[[Geometry], list[Finding]]] = [
|
|
370
|
+
check_parked,
|
|
371
|
+
check_outside,
|
|
372
|
+
check_text_overflow,
|
|
373
|
+
check_transform_box,
|
|
374
|
+
]
|
|
375
|
+
"""Render checks run on every inspection, in order. Append to add a check."""
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def run_checks(geo: Geometry) -> list[Finding]:
|
|
379
|
+
findings = [finding for check in CHECKS for finding in check(geo)]
|
|
380
|
+
# An element parked at (0,0) usually pokes out of the top-left corner too: report once.
|
|
381
|
+
parked = {
|
|
382
|
+
(f.element, t) for f in findings if f.code == "parked-at-origin" for t in f.times or []
|
|
383
|
+
}
|
|
384
|
+
return [
|
|
385
|
+
f
|
|
386
|
+
for f in findings
|
|
387
|
+
if not (
|
|
388
|
+
f.code == "outside-bounds"
|
|
389
|
+
and f.times
|
|
390
|
+
and all((f.element, t) in parked for t in f.times)
|
|
391
|
+
)
|
|
392
|
+
]
|
framesheet/checks.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Static (source-level) checks, ported from the svg-animation skill's ``verify_svg.py``.
|
|
2
|
+
|
|
3
|
+
Every check returns :class:`~framesheet.models.Finding` objects with ``check="static"``.
|
|
4
|
+
Render-time checks (geometry over time) live in :mod:`framesheet.analysis`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from html.parser import HTMLParser
|
|
11
|
+
import re
|
|
12
|
+
import xml.etree.ElementTree as ET
|
|
13
|
+
|
|
14
|
+
from framesheet.models import Finding, Severity
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
SVG_NS = "http://www.w3.org/2000/svg"
|
|
18
|
+
LARGE_SVG_KB = 100
|
|
19
|
+
_URL_REF = re.compile(r"url\(\s*['\"]?#([^)'\"]+)['\"]?\s*\)")
|
|
20
|
+
_POSITIVE_CLOCK = re.compile(r"^([0-9]*\.?[0-9]+)(ms|s)?$")
|
|
21
|
+
_KEYFRAMES = re.compile(r"@keyframes[^{]*\{((?:[^{}]*\{[^}]*\})*)[^}]*\}", re.S)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _local(tag: str) -> str:
|
|
25
|
+
return tag.rsplit("}", 1)[-1] if "}" in tag else tag
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _finding(severity: Severity, code: str, message: str, element: str | None = None) -> Finding:
|
|
29
|
+
return Finding(severity=severity, code=code, message=message, check="static", element=element)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _label(tag: str, attrib: dict[str, str]) -> str:
|
|
33
|
+
el_id = attrib.get("id")
|
|
34
|
+
return f"{tag}#{el_id}" if el_id else tag
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def check_css(css: str, *, svg: bool) -> list[Finding]:
|
|
38
|
+
"""Checks on the concatenated text of all ``<style>`` blocks."""
|
|
39
|
+
out: list[Finding] = []
|
|
40
|
+
css = re.sub(r"/\*.*?\*/", "", css, flags=re.S)
|
|
41
|
+
if not css.strip():
|
|
42
|
+
return out
|
|
43
|
+
if re.search(r"@import\s+url\(|https?://", css):
|
|
44
|
+
out.append(
|
|
45
|
+
_finding(
|
|
46
|
+
"warning",
|
|
47
|
+
"css-external",
|
|
48
|
+
"CSS references an external URL/font (blocked when the SVG is used as <img>).",
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
animated = re.search(r"\banimation(-name)?\s*:", css) is not None
|
|
52
|
+
if animated and "prefers-reduced-motion" not in css:
|
|
53
|
+
out.append(
|
|
54
|
+
_finding(
|
|
55
|
+
"warning",
|
|
56
|
+
"no-reduced-motion",
|
|
57
|
+
"CSS animations present without @media (prefers-reduced-motion: reduce).",
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
if svg and "transform-box" not in css:
|
|
61
|
+
has_transform = re.search(r"\btransform\s*:", css) is not None
|
|
62
|
+
if has_transform and "transform-origin" in css:
|
|
63
|
+
out.append(
|
|
64
|
+
_finding(
|
|
65
|
+
"warning",
|
|
66
|
+
"transform-origin-without-box",
|
|
67
|
+
"CSS transform-origin used without transform-box: fill-box; may pivot "
|
|
68
|
+
"unexpectedly across SVG renderers.",
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
elif animated and _keyframes_transform(css):
|
|
72
|
+
out.append(
|
|
73
|
+
_finding(
|
|
74
|
+
"warning",
|
|
75
|
+
"transform-without-box",
|
|
76
|
+
"CSS @keyframes animate transform/rotate/scale but no transform-box is set; "
|
|
77
|
+
"SVG elements then rotate/scale around the SVG origin (0,0). Add "
|
|
78
|
+
"transform-box: fill-box; transform-origin: center.",
|
|
79
|
+
)
|
|
80
|
+
)
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _keyframes_transform(css: str) -> bool:
|
|
85
|
+
return any(
|
|
86
|
+
re.search(r"\b(transform|rotate|scale|translate)\s*:", block)
|
|
87
|
+
for block in _KEYFRAMES.findall(css)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def check_svg_source(raw: str) -> list[Finding]:
|
|
92
|
+
"""Static checks for a standalone SVG document (portability, references, pitfalls)."""
|
|
93
|
+
out: list[Finding] = []
|
|
94
|
+
size_kb = len(raw.encode()) / 1024
|
|
95
|
+
if size_kb > LARGE_SVG_KB:
|
|
96
|
+
out.append(
|
|
97
|
+
_finding(
|
|
98
|
+
"warning",
|
|
99
|
+
"large-file",
|
|
100
|
+
f"Large SVG ({size_kb:.1f} KB); consider simplifying paths or defs.",
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
try:
|
|
104
|
+
root = ET.fromstring(raw)
|
|
105
|
+
except ET.ParseError as exc:
|
|
106
|
+
return [*out, _finding("error", "malformed-xml", f"Malformed XML: {exc}")]
|
|
107
|
+
|
|
108
|
+
if _local(root.tag) != "svg":
|
|
109
|
+
out.append(
|
|
110
|
+
_finding("error", "not-svg", f"Root element is <{_local(root.tag)}>, expected <svg>.")
|
|
111
|
+
)
|
|
112
|
+
if not root.tag.startswith(f"{{{SVG_NS}}}"):
|
|
113
|
+
out.append(
|
|
114
|
+
_finding("error", "missing-xmlns", 'Missing xmlns="http://www.w3.org/2000/svg".')
|
|
115
|
+
)
|
|
116
|
+
if not root.attrib.get("viewBox"):
|
|
117
|
+
out.append(_finding("error", "missing-viewbox", "Missing viewBox attribute on <svg>."))
|
|
118
|
+
has_title = any(_local(el.tag) == "title" for el in root.iter())
|
|
119
|
+
if not (root.attrib.get("aria-label") or has_title):
|
|
120
|
+
out.append(
|
|
121
|
+
_finding("warning", "missing-title", "Missing aria-label or <title> for accessibility.")
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
ids: Counter[str] = Counter()
|
|
125
|
+
refs: set[str] = set()
|
|
126
|
+
css_blocks: list[str] = []
|
|
127
|
+
for el in root.iter():
|
|
128
|
+
tag = _local(el.tag)
|
|
129
|
+
if el_id := el.attrib.get("id"):
|
|
130
|
+
ids[el_id] += 1
|
|
131
|
+
if tag == "script":
|
|
132
|
+
out.append(
|
|
133
|
+
_finding(
|
|
134
|
+
"error",
|
|
135
|
+
"script",
|
|
136
|
+
"Contains <script>, which is stripped by GitHub and blocked in <img>.",
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
if tag == "foreignObject":
|
|
140
|
+
out.append(
|
|
141
|
+
_finding(
|
|
142
|
+
"warning",
|
|
143
|
+
"foreign-object",
|
|
144
|
+
"Contains <foreignObject>, which breaks in many <img>/SVG viewers.",
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
for name, value in el.attrib.items():
|
|
148
|
+
attr = _local(name)
|
|
149
|
+
if attr.startswith("on"):
|
|
150
|
+
out.append(
|
|
151
|
+
_finding(
|
|
152
|
+
"error",
|
|
153
|
+
"event-handler",
|
|
154
|
+
f"Inline event handler '{attr}' on <{tag}> (stripped in <img>).",
|
|
155
|
+
_label(tag, el.attrib),
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
if re.search(r"https?://", value) and attr != "xmlns":
|
|
159
|
+
out.append(
|
|
160
|
+
_finding(
|
|
161
|
+
"warning",
|
|
162
|
+
"external-url",
|
|
163
|
+
f"External URL in {attr}='{value}' on <{tag}> (blocked in GitHub <img>).",
|
|
164
|
+
_label(tag, el.attrib),
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
refs.update(_URL_REF.findall(value))
|
|
168
|
+
if attr == "href" and value.startswith("#"):
|
|
169
|
+
refs.add(value[1:])
|
|
170
|
+
if tag == "animateMotion":
|
|
171
|
+
begin = el.attrib.get("begin", "").strip()
|
|
172
|
+
match = _POSITIVE_CLOCK.match(begin)
|
|
173
|
+
if match and float(match.group(1)) > 0:
|
|
174
|
+
out.append(
|
|
175
|
+
_finding(
|
|
176
|
+
"warning",
|
|
177
|
+
"positive-begin",
|
|
178
|
+
f"<animateMotion begin='{begin}'> uses a positive delay; the parent "
|
|
179
|
+
"shape may park at (0,0) before start. Use a negative begin offset.",
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
if tag == "style" and el.text:
|
|
183
|
+
css_blocks.append(el.text)
|
|
184
|
+
if style := el.attrib.get("style"):
|
|
185
|
+
refs.update(_URL_REF.findall(style))
|
|
186
|
+
|
|
187
|
+
css = "\n".join(css_blocks)
|
|
188
|
+
refs.update(_URL_REF.findall(css))
|
|
189
|
+
out.extend(_id_findings(ids, refs))
|
|
190
|
+
out.extend(check_css(css, svg=True))
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _id_findings(ids: Counter[str], refs: set[str]) -> list[Finding]:
|
|
195
|
+
out = [
|
|
196
|
+
_finding("error", "duplicate-id", f"Duplicate id='{el_id}' ({count} occurrences).")
|
|
197
|
+
for el_id, count in ids.items()
|
|
198
|
+
if count > 1
|
|
199
|
+
]
|
|
200
|
+
out.extend(
|
|
201
|
+
_finding("error", "broken-ref", f"Broken internal reference '#{ref}' (no matching id).")
|
|
202
|
+
for ref in sorted(refs)
|
|
203
|
+
if ref not in ids
|
|
204
|
+
)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class _HTMLCollector(HTMLParser):
|
|
209
|
+
def __init__(self) -> None:
|
|
210
|
+
super().__init__(convert_charrefs=True)
|
|
211
|
+
self.ids: Counter[str] = Counter()
|
|
212
|
+
self.refs: set[str] = set()
|
|
213
|
+
self.css: list[str] = []
|
|
214
|
+
self._in_style = False
|
|
215
|
+
|
|
216
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
217
|
+
self._in_style = tag == "style"
|
|
218
|
+
for name, value in attrs:
|
|
219
|
+
if value is None:
|
|
220
|
+
continue
|
|
221
|
+
if name == "id":
|
|
222
|
+
self.ids[value] += 1
|
|
223
|
+
self.refs.update(_URL_REF.findall(value))
|
|
224
|
+
# Only SVG-style fragment references; HTML <a href="#top"> is navigation.
|
|
225
|
+
if name in {"xlink:href", "href"} and value.startswith("#") and tag in _SVG_REF_TAGS:
|
|
226
|
+
self.refs.add(value[1:])
|
|
227
|
+
|
|
228
|
+
def handle_endtag(self, tag: str) -> None:
|
|
229
|
+
if tag == "style":
|
|
230
|
+
self._in_style = False
|
|
231
|
+
|
|
232
|
+
def handle_data(self, data: str) -> None:
|
|
233
|
+
if self._in_style:
|
|
234
|
+
self.css.append(data)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
_SVG_REF_TAGS = {"use", "mpath", "textpath", "lineargradient", "radialgradient", "pattern"}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def check_html_source(raw: str) -> list[Finding]:
|
|
241
|
+
"""Static checks for an HTML document: ids, internal references, reduced motion."""
|
|
242
|
+
parser = _HTMLCollector()
|
|
243
|
+
parser.feed(raw)
|
|
244
|
+
css = "\n".join(parser.css)
|
|
245
|
+
refs = parser.refs | set(_URL_REF.findall(css))
|
|
246
|
+
return [*_id_findings(parser.ids, refs), *check_css(css, svg="<svg" in raw.lower())]
|