chompyy 0.1.0 → 0.3.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.
- package/README.md +79 -6
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/dist/appstate.js +43 -2
- package/dist/away.js +104 -15
- package/dist/board.js +33 -3
- package/dist/claudesettings.js +23 -0
- package/dist/cli.js +409 -27
- package/dist/coldstart.js +207 -0
- package/dist/config.js +36 -1
- package/dist/costs.js +162 -0
- package/dist/gate.js +29 -0
- package/dist/history.js +308 -0
- package/dist/livequota.js +15 -1
- package/dist/pacing.js +189 -0
- package/dist/picture.js +117 -0
- package/dist/projects.js +2 -2
- package/dist/quota.js +31 -5
- package/dist/report.js +38 -21
- package/dist/review.js +47 -4
- package/dist/runner.js +268 -8
- package/dist/taste.js +507 -0
- package/dist/triggers.js +182 -0
- package/dist/verify.js +131 -0
- package/package.json +2 -1
- package/skills/taste/SKILL.md +4 -1
- package/vendor/diagram-design/LICENSE +21 -0
- package/vendor/diagram-design/SKILL.md +399 -0
- package/vendor/diagram-design/UPSTREAM.md +18 -0
- package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
- package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
- package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
- package/vendor/diagram-design/assets/example-architecture.html +183 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
- package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
- package/vendor/diagram-design/assets/example-bar.html +129 -0
- package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
- package/vendor/diagram-design/assets/example-box-plot.html +127 -0
- package/vendor/diagram-design/assets/example-bubble.html +147 -0
- package/vendor/diagram-design/assets/example-bump.html +142 -0
- package/vendor/diagram-design/assets/example-data-flow.html +143 -0
- package/vendor/diagram-design/assets/example-datalake.html +269 -0
- package/vendor/diagram-design/assets/example-db-schema.html +302 -0
- package/vendor/diagram-design/assets/example-dependency.html +224 -0
- package/vendor/diagram-design/assets/example-deployment.html +190 -0
- package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
- package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
- package/vendor/diagram-design/assets/example-er.html +202 -0
- package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
- package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
- package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
- package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
- package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
- package/vendor/diagram-design/assets/example-exploded.html +83 -0
- package/vendor/diagram-design/assets/example-fishbone.html +152 -0
- package/vendor/diagram-design/assets/example-flowchart.html +163 -0
- package/vendor/diagram-design/assets/example-gantt.html +137 -0
- package/vendor/diagram-design/assets/example-heatmap.html +224 -0
- package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
- package/vendor/diagram-design/assets/example-high-level.html +301 -0
- package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
- package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
- package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
- package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
- package/vendor/diagram-design/assets/example-it-state.html +128 -0
- package/vendor/diagram-design/assets/example-journey.html +148 -0
- package/vendor/diagram-design/assets/example-kanban.html +174 -0
- package/vendor/diagram-design/assets/example-layers.html +123 -0
- package/vendor/diagram-design/assets/example-line.html +111 -0
- package/vendor/diagram-design/assets/example-loop.html +100 -0
- package/vendor/diagram-design/assets/example-marimekko.html +148 -0
- package/vendor/diagram-design/assets/example-medallion.html +159 -0
- package/vendor/diagram-design/assets/example-nested.html +136 -0
- package/vendor/diagram-design/assets/example-org-chart.html +45 -0
- package/vendor/diagram-design/assets/example-polar.html +116 -0
- package/vendor/diagram-design/assets/example-process.html +64 -0
- package/vendor/diagram-design/assets/example-pyramid.html +119 -0
- package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
- package/vendor/diagram-design/assets/example-quadrant.html +135 -0
- package/vendor/diagram-design/assets/example-radar.html +139 -0
- package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
- package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
- package/vendor/diagram-design/assets/example-sankey.html +150 -0
- package/vendor/diagram-design/assets/example-sbgn.html +213 -0
- package/vendor/diagram-design/assets/example-scatter.html +141 -0
- package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
- package/vendor/diagram-design/assets/example-sequence.html +222 -0
- package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
- package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
- package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
- package/vendor/diagram-design/assets/example-state.html +147 -0
- package/vendor/diagram-design/assets/example-steps.html +78 -0
- package/vendor/diagram-design/assets/example-story-map.html +184 -0
- package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
- package/vendor/diagram-design/assets/example-swimlane.html +172 -0
- package/vendor/diagram-design/assets/example-timeline.html +135 -0
- package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
- package/vendor/diagram-design/assets/example-tree.html +173 -0
- package/vendor/diagram-design/assets/example-treemap.html +107 -0
- package/vendor/diagram-design/assets/example-uml-class.html +188 -0
- package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
- package/vendor/diagram-design/assets/example-venn.html +110 -0
- package/vendor/diagram-design/assets/example-wardley.html +153 -0
- package/vendor/diagram-design/assets/example-waterfall.html +129 -0
- package/vendor/diagram-design/assets/template-dark.html +99 -0
- package/vendor/diagram-design/assets/template.html +100 -0
- package/vendor/diagram-design/references/layout-budget.md +103 -0
- package/vendor/diagram-design/references/output-spec.md +277 -0
- package/vendor/diagram-design/references/primitive-annotation.md +36 -0
- package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
- package/vendor/diagram-design/references/primitives-core.md +146 -0
- package/vendor/diagram-design/references/semantic-patterns.md +154 -0
- package/vendor/diagram-design/references/style-guide.md +234 -0
- package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
- package/vendor/diagram-design/references/type-architecture.md +117 -0
- package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
- package/vendor/diagram-design/references/type-bar.md +108 -0
- package/vendor/diagram-design/references/type-data-flow.md +371 -0
- package/vendor/diagram-design/references/type-db-schema.md +48 -0
- package/vendor/diagram-design/references/type-dependency.md +113 -0
- package/vendor/diagram-design/references/type-deployment.md +45 -0
- package/vendor/diagram-design/references/type-dp-integration.md +407 -0
- package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
- package/vendor/diagram-design/references/type-er.md +25 -0
- package/vendor/diagram-design/references/type-event-modeling.md +36 -0
- package/vendor/diagram-design/references/type-exploded.md +115 -0
- package/vendor/diagram-design/references/type-fishbone.md +75 -0
- package/vendor/diagram-design/references/type-flowchart.md +23 -0
- package/vendor/diagram-design/references/type-gantt.md +45 -0
- package/vendor/diagram-design/references/type-heatmap.md +80 -0
- package/vendor/diagram-design/references/type-high-level.md +470 -0
- package/vendor/diagram-design/references/type-it-state.md +468 -0
- package/vendor/diagram-design/references/type-journey.md +55 -0
- package/vendor/diagram-design/references/type-kanban.md +49 -0
- package/vendor/diagram-design/references/type-layers.md +26 -0
- package/vendor/diagram-design/references/type-line.md +337 -0
- package/vendor/diagram-design/references/type-loop.md +223 -0
- package/vendor/diagram-design/references/type-medallion.md +356 -0
- package/vendor/diagram-design/references/type-nested.md +22 -0
- package/vendor/diagram-design/references/type-org-chart.md +44 -0
- package/vendor/diagram-design/references/type-polar.md +136 -0
- package/vendor/diagram-design/references/type-process.md +490 -0
- package/vendor/diagram-design/references/type-pyramid.md +33 -0
- package/vendor/diagram-design/references/type-quadrant.md +81 -0
- package/vendor/diagram-design/references/type-radar.md +82 -0
- package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
- package/vendor/diagram-design/references/type-sankey.md +75 -0
- package/vendor/diagram-design/references/type-sbgn.md +80 -0
- package/vendor/diagram-design/references/type-scatter.md +276 -0
- package/vendor/diagram-design/references/type-sequence.md +130 -0
- package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
- package/vendor/diagram-design/references/type-state.md +30 -0
- package/vendor/diagram-design/references/type-steps.md +180 -0
- package/vendor/diagram-design/references/type-story-map.md +46 -0
- package/vendor/diagram-design/references/type-swimlane.md +22 -0
- package/vendor/diagram-design/references/type-timeline.md +20 -0
- package/vendor/diagram-design/references/type-tree.md +24 -0
- package/vendor/diagram-design/references/type-treemap.md +137 -0
- package/vendor/diagram-design/references/type-uml-class.md +65 -0
- package/vendor/diagram-design/references/type-unit-grid.md +63 -0
- package/vendor/diagram-design/references/type-venn.md +26 -0
- package/vendor/diagram-design/references/type-wardley.md +39 -0
- package/vendor/diagram-design/references/type-waterfall.md +75 -0
- package/vendor/diagram-design/scripts/self_check.py +1177 -0
- package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
|
@@ -0,0 +1,1177 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Self-check a generated diagram HTML file, with no third-party deps.
|
|
3
|
+
|
|
4
|
+
Ships inside the skill so an installed agent can verify its own output:
|
|
5
|
+
|
|
6
|
+
python3 <skill-dir>/scripts/self_check.py my-diagram.html
|
|
7
|
+
|
|
8
|
+
Checks the accessible-SVG contract, the single-file safety rules (no remote
|
|
9
|
+
assets beyond the approved Google Fonts stylesheet, no executable attributes,
|
|
10
|
+
no scripts other than the one canonical motion controller), document
|
|
11
|
+
completeness (a truncated or mojibake file is rejected rather than passed),
|
|
12
|
+
painted content
|
|
13
|
+
staying inside each SVG's viewBox, text inside a visible box staying within
|
|
14
|
+
the style-guide width budget, and — when motion markup is present — the
|
|
15
|
+
structural motion contract. This is a distilled
|
|
16
|
+
subset of the repository gates (`lint-skin.py`, `verify-motion.py`), which
|
|
17
|
+
remain the authority for contributions to the repository itself.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import re
|
|
24
|
+
import sys
|
|
25
|
+
import unicodedata
|
|
26
|
+
from collections import Counter
|
|
27
|
+
from html.parser import HTMLParser
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Callable
|
|
30
|
+
from urllib.parse import urlparse
|
|
31
|
+
|
|
32
|
+
SKILL_DIR = Path(__file__).resolve().parent.parent
|
|
33
|
+
MOTION_TEMPLATE = SKILL_DIR / "assets" / "template-motion.html"
|
|
34
|
+
MODES = {"none", "reveal", "step", "loop"}
|
|
35
|
+
ACTIONS = {"play", "pause", "replay", "prev", "next"}
|
|
36
|
+
ASCII_DECIMAL_RE = re.compile(r"^[0-9]+$")
|
|
37
|
+
CSS_ESCAPE_RE = re.compile(
|
|
38
|
+
r"\\(?:([0-9a-fA-F]{1,6})[ \t\r\n\f]?|(.))", re.DOTALL
|
|
39
|
+
)
|
|
40
|
+
CSS_IMPORT_RE = re.compile(r"@import\b", re.IGNORECASE)
|
|
41
|
+
CSS_URL_RE = re.compile(r"url\(\s*([^)]+?)\s*\)", re.IGNORECASE)
|
|
42
|
+
CSS_IMAGE_SET_RE = re.compile(r"(?:-webkit-)?image-set\s*\(", re.IGNORECASE)
|
|
43
|
+
CSS_REMOTE_RE = re.compile(r"(?:https?:)?//", re.IGNORECASE)
|
|
44
|
+
CSS_REFERENCE_ATTRS = {
|
|
45
|
+
"style",
|
|
46
|
+
"fill",
|
|
47
|
+
"stroke",
|
|
48
|
+
"filter",
|
|
49
|
+
"clip-path",
|
|
50
|
+
"mask",
|
|
51
|
+
"marker",
|
|
52
|
+
"marker-start",
|
|
53
|
+
"marker-mid",
|
|
54
|
+
"marker-end",
|
|
55
|
+
"cursor",
|
|
56
|
+
}
|
|
57
|
+
REFERENCE_ATTRS = {
|
|
58
|
+
"src",
|
|
59
|
+
"href",
|
|
60
|
+
"xlink:href",
|
|
61
|
+
"poster",
|
|
62
|
+
"srcset",
|
|
63
|
+
"action",
|
|
64
|
+
"formaction",
|
|
65
|
+
}
|
|
66
|
+
VIEWBOX_TOLERANCE = 2.0
|
|
67
|
+
# Width budget from references/style-guide.md: em per character by face; wide and
|
|
68
|
+
# full-width characters cost 1em.
|
|
69
|
+
SANS_ADVANCE = 0.60
|
|
70
|
+
MONO_ADVANCE = 0.62
|
|
71
|
+
WIDE_ADVANCE = 1.0
|
|
72
|
+
TEXT_FIT_PROPERTIES = ("font-size", "font-family", "text-anchor", "letter-spacing")
|
|
73
|
+
# Weight and style move real glyph widths, but the budget already averages over them.
|
|
74
|
+
TEXT_FIT_IGNORED = {"font-weight", "font-style"}
|
|
75
|
+
PAINT_PROPERTIES = frozenset({"fill", "stroke", "stroke-width", "fill-opacity", "stroke-opacity", "opacity"})
|
|
76
|
+
# Bidi, vertical and preserved-space text lays out in ways the left-to-right budget can't place.
|
|
77
|
+
TEXT_LAYOUT_PROPERTIES = ("direction", "unicode-bidi", "writing-mode", "white-space", "xml:space")
|
|
78
|
+
# Half a narrow glyph. The budget is an average that runs wide of Geist (about 0.52em
|
|
79
|
+
# sans, 0.60em mono drawn), so a smaller overshoot is budget error on a label that
|
|
80
|
+
# draws inside its box; a whole character past the edge is the real defect.
|
|
81
|
+
TEXT_FIT_TOLERANCE_EM = 0.3
|
|
82
|
+
SVG_NUMBER = r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?"
|
|
83
|
+
SVG_NUMBER_RE = re.compile(SVG_NUMBER)
|
|
84
|
+
SVG_PLAIN_NUMBER_RE = re.compile(rf"^\s*{SVG_NUMBER}\s*$")
|
|
85
|
+
TRANSLATE_RE = re.compile(rf"^\s*translate\(\s*({SVG_NUMBER})(?:[\s,]+({SVG_NUMBER}))?\s*\)\s*$")
|
|
86
|
+
REPLACEMENT_CHAR = "\ufffd"
|
|
87
|
+
# Container elements whose end tag HTML requires, so an unmatched count is real damage: a
|
|
88
|
+
# file that stops mid-element, a dropped </text>, a stray </span>. Void elements and the
|
|
89
|
+
# optional-end-tag elements (html, head, body, p, li, ...) stay out, so valid HTML cannot
|
|
90
|
+
# trip the count; the closing </html> of the generated shell is checked separately.
|
|
91
|
+
PAIRED_CONTAINER_TAGS = (
|
|
92
|
+
"title",
|
|
93
|
+
"desc",
|
|
94
|
+
"div",
|
|
95
|
+
"section",
|
|
96
|
+
"main",
|
|
97
|
+
"article",
|
|
98
|
+
"header",
|
|
99
|
+
"footer",
|
|
100
|
+
"figure",
|
|
101
|
+
"figcaption",
|
|
102
|
+
"svg",
|
|
103
|
+
"g",
|
|
104
|
+
"defs",
|
|
105
|
+
"pattern",
|
|
106
|
+
"marker",
|
|
107
|
+
"style",
|
|
108
|
+
"script",
|
|
109
|
+
"span",
|
|
110
|
+
"text",
|
|
111
|
+
"tspan",
|
|
112
|
+
)
|
|
113
|
+
# Their children are not painted where they are declared, or use another coordinate system.
|
|
114
|
+
UNPAINTED_TAGS = {
|
|
115
|
+
"defs",
|
|
116
|
+
"symbol",
|
|
117
|
+
"marker",
|
|
118
|
+
"pattern",
|
|
119
|
+
"clippath",
|
|
120
|
+
"mask",
|
|
121
|
+
"foreignobject",
|
|
122
|
+
"svg",
|
|
123
|
+
}
|
|
124
|
+
# CSS that can move, hide or clip an element, so its painted position is not its attributes.
|
|
125
|
+
UNSTATIC_CSS_PROPERTIES = {
|
|
126
|
+
"transform",
|
|
127
|
+
"translate",
|
|
128
|
+
"rotate",
|
|
129
|
+
"scale",
|
|
130
|
+
"display",
|
|
131
|
+
"visibility",
|
|
132
|
+
"x",
|
|
133
|
+
"y",
|
|
134
|
+
"cx",
|
|
135
|
+
"cy",
|
|
136
|
+
"r",
|
|
137
|
+
"rx",
|
|
138
|
+
"ry",
|
|
139
|
+
"width",
|
|
140
|
+
"height",
|
|
141
|
+
}
|
|
142
|
+
UNSTATIC_CSS_PREFIXES = ("animation", "offset", "clip", "mask")
|
|
143
|
+
CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
|
|
144
|
+
CSS_KEYFRAMES_RE = re.compile(
|
|
145
|
+
r"@(?:-[a-z]+-)?keyframes[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}", re.IGNORECASE
|
|
146
|
+
)
|
|
147
|
+
CSS_RULE_RE = re.compile(r"([^{}]+)\{([^{}]*)\}")
|
|
148
|
+
CSS_STRING_RE = re.compile(r"\"[^\"]*\"|'[^']*'")
|
|
149
|
+
CSS_PARENS_RE = re.compile(r"\([^()]*\)")
|
|
150
|
+
CSS_COMBINATOR_RE = re.compile(r"\s*[>+~]\s*|\s+")
|
|
151
|
+
CSS_TAG_RE = re.compile(r"^[a-zA-Z][\w-]*")
|
|
152
|
+
CSS_CLASS_RE = re.compile(r"\.([\w-]+)")
|
|
153
|
+
CSS_ID_RE = re.compile(r"#([\w-]+)")
|
|
154
|
+
CSS_ATTRIBUTE_RE = re.compile(r"\[\s*([\w:-]+)")
|
|
155
|
+
GEOMETRY_ATTRS = {
|
|
156
|
+
"rect": ("x", "y", "width", "height"),
|
|
157
|
+
"line": ("x1", "y1", "x2", "y2"),
|
|
158
|
+
"circle": ("cx", "cy", "r"),
|
|
159
|
+
"ellipse": ("cx", "cy", "rx", "ry"),
|
|
160
|
+
"polygon": ("points",),
|
|
161
|
+
"polyline": ("points",),
|
|
162
|
+
"text": ("x", "y"),
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class DiagramParser(HTMLParser):
|
|
167
|
+
def __init__(self) -> None:
|
|
168
|
+
super().__init__(convert_charrefs=True)
|
|
169
|
+
self.roots: list[dict[str, str]] = []
|
|
170
|
+
self.items: list[dict[str, str]] = []
|
|
171
|
+
self.actions: set[str] = set()
|
|
172
|
+
self.controls = 0
|
|
173
|
+
self.statuses: list[dict[str, str]] = []
|
|
174
|
+
self.statuses_in_controls = 0
|
|
175
|
+
self.scripts: list[dict[str, object]] = []
|
|
176
|
+
self.styles: list[str] = []
|
|
177
|
+
self.css_attributes: list[str] = []
|
|
178
|
+
self.svgs: list[dict[str, object]] = []
|
|
179
|
+
self.ids: Counter[str] = Counter()
|
|
180
|
+
self.unsafe: list[str] = []
|
|
181
|
+
self.references: list[tuple[str, str, str]] = []
|
|
182
|
+
self._svg_depth = 0
|
|
183
|
+
self._current_svg: dict[str, object] | None = None
|
|
184
|
+
self._capture: str | None = None
|
|
185
|
+
self._current_script: dict[str, object] | None = None
|
|
186
|
+
self._in_style = False
|
|
187
|
+
self._element_stack: list[str] = []
|
|
188
|
+
self._motion_root_depth: int | None = None
|
|
189
|
+
self._controls_depth: int | None = None
|
|
190
|
+
|
|
191
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
192
|
+
tag = tag.casefold()
|
|
193
|
+
normalized_attrs = [(key.casefold(), value or "") for key, value in attrs]
|
|
194
|
+
data: dict[str, str] = {}
|
|
195
|
+
for key, value in normalized_attrs:
|
|
196
|
+
data.setdefault(key, value)
|
|
197
|
+
if data.get("id"):
|
|
198
|
+
self.ids[data["id"]] += 1
|
|
199
|
+
if tag in {"base", "embed", "object", "iframe"}:
|
|
200
|
+
self.unsafe.append(f"<{tag}> is not allowed in a diagram file")
|
|
201
|
+
for key, value in normalized_attrs:
|
|
202
|
+
if key.startswith("on"):
|
|
203
|
+
self.unsafe.append(f"executable attribute {key} on <{tag}>")
|
|
204
|
+
if key == "srcdoc":
|
|
205
|
+
self.unsafe.append(f"srcdoc attribute on <{tag}>")
|
|
206
|
+
if key in REFERENCE_ATTRS:
|
|
207
|
+
self.references.append((tag, data.get("rel", ""), value))
|
|
208
|
+
if key in CSS_REFERENCE_ATTRS:
|
|
209
|
+
self.css_attributes.append(value)
|
|
210
|
+
if "data-motion-root" in data:
|
|
211
|
+
self.roots.append(data)
|
|
212
|
+
if self._motion_root_depth is None:
|
|
213
|
+
self._motion_root_depth = len(self._element_stack)
|
|
214
|
+
if self._motion_root_depth is not None:
|
|
215
|
+
if "data-motion-item" in data:
|
|
216
|
+
self.items.append(data)
|
|
217
|
+
if "data-motion-action" in data:
|
|
218
|
+
self.actions.add(data["data-motion-action"])
|
|
219
|
+
if "data-motion-controls" in data:
|
|
220
|
+
self.controls += 1
|
|
221
|
+
if self._controls_depth is None:
|
|
222
|
+
self._controls_depth = len(self._element_stack)
|
|
223
|
+
if "data-motion-status" in data:
|
|
224
|
+
self.statuses.append(data)
|
|
225
|
+
if self._controls_depth is not None:
|
|
226
|
+
self.statuses_in_controls += 1
|
|
227
|
+
if tag == "script":
|
|
228
|
+
self._current_script = {
|
|
229
|
+
"attrs": data,
|
|
230
|
+
"attr_names": [name for name, _value in normalized_attrs],
|
|
231
|
+
"body": [],
|
|
232
|
+
"closed": False,
|
|
233
|
+
}
|
|
234
|
+
self.scripts.append(self._current_script)
|
|
235
|
+
if tag == "style":
|
|
236
|
+
self._in_style = True
|
|
237
|
+
self._element_stack.append(tag)
|
|
238
|
+
if tag == "svg" and self._svg_depth == 0:
|
|
239
|
+
self._svg_depth = 1
|
|
240
|
+
self._current_svg = {"attrs": data, "first": None, "title": {}, "desc": {}}
|
|
241
|
+
self.svgs.append(self._current_svg)
|
|
242
|
+
return
|
|
243
|
+
if self._svg_depth:
|
|
244
|
+
self._svg_depth += 1
|
|
245
|
+
assert self._current_svg is not None
|
|
246
|
+
if self._svg_depth == 2 and self._current_svg["first"] is None:
|
|
247
|
+
self._current_svg["first"] = tag
|
|
248
|
+
if self._svg_depth == 2 and tag in {"title", "desc"}:
|
|
249
|
+
self._current_svg[tag] = {"attrs": data, "text": ""}
|
|
250
|
+
self._capture = tag
|
|
251
|
+
|
|
252
|
+
def handle_endtag(self, tag: str) -> None:
|
|
253
|
+
tag = tag.casefold()
|
|
254
|
+
if tag == "script" and self._current_script is not None:
|
|
255
|
+
self._current_script["closed"] = True
|
|
256
|
+
self._current_script = None
|
|
257
|
+
if tag == "style":
|
|
258
|
+
self._in_style = False
|
|
259
|
+
if self._svg_depth:
|
|
260
|
+
if tag in {"title", "desc"}:
|
|
261
|
+
self._capture = None
|
|
262
|
+
self._svg_depth -= 1
|
|
263
|
+
if self._svg_depth == 0:
|
|
264
|
+
self._current_svg = None
|
|
265
|
+
for index in range(len(self._element_stack) - 1, -1, -1):
|
|
266
|
+
if self._element_stack[index] == tag:
|
|
267
|
+
del self._element_stack[index:]
|
|
268
|
+
break
|
|
269
|
+
if (
|
|
270
|
+
self._motion_root_depth is not None
|
|
271
|
+
and len(self._element_stack) <= self._motion_root_depth
|
|
272
|
+
):
|
|
273
|
+
self._motion_root_depth = None
|
|
274
|
+
if (
|
|
275
|
+
self._controls_depth is not None
|
|
276
|
+
and len(self._element_stack) <= self._controls_depth
|
|
277
|
+
):
|
|
278
|
+
self._controls_depth = None
|
|
279
|
+
|
|
280
|
+
def handle_data(self, data: str) -> None:
|
|
281
|
+
if self._current_script is not None:
|
|
282
|
+
body = self._current_script["body"]
|
|
283
|
+
assert isinstance(body, list)
|
|
284
|
+
body.append(data)
|
|
285
|
+
if self._in_style:
|
|
286
|
+
self.styles.append(data)
|
|
287
|
+
if self._capture and self._current_svg:
|
|
288
|
+
node = self._current_svg[self._capture]
|
|
289
|
+
assert isinstance(node, dict)
|
|
290
|
+
node["text"] = str(node.get("text", "")) + data
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class SvgExtent:
|
|
294
|
+
def __init__(self, attrs: dict[str, str]) -> None:
|
|
295
|
+
self.attrs = attrs
|
|
296
|
+
self.points: list[tuple[float, float, str]] = []
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def svg_length(attrs: dict[str, str], name: str, default: float | None = None) -> float | None:
|
|
300
|
+
value = attrs.get(name)
|
|
301
|
+
if value is None:
|
|
302
|
+
return default
|
|
303
|
+
return float(value) if SVG_PLAIN_NUMBER_RE.match(value) else None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def painted_points(tag: str, attrs: dict[str, str]) -> list[tuple[float, float]]:
|
|
307
|
+
if tag == "rect":
|
|
308
|
+
x, y = svg_length(attrs, "x", 0.0), svg_length(attrs, "y", 0.0)
|
|
309
|
+
width, height = svg_length(attrs, "width"), svg_length(attrs, "height")
|
|
310
|
+
if x is None or y is None or width is None or height is None:
|
|
311
|
+
return []
|
|
312
|
+
if width <= 0 or height <= 0:
|
|
313
|
+
return []
|
|
314
|
+
return [(x, y), (x + width, y + height)]
|
|
315
|
+
if tag == "line":
|
|
316
|
+
ends = [
|
|
317
|
+
(svg_length(attrs, "x1", 0.0), svg_length(attrs, "y1", 0.0)),
|
|
318
|
+
(svg_length(attrs, "x2", 0.0), svg_length(attrs, "y2", 0.0)),
|
|
319
|
+
]
|
|
320
|
+
return [(x, y) for x, y in ends if x is not None and y is not None]
|
|
321
|
+
if tag in {"circle", "ellipse"}:
|
|
322
|
+
cx, cy = svg_length(attrs, "cx", 0.0), svg_length(attrs, "cy", 0.0)
|
|
323
|
+
rx = svg_length(attrs, "r" if tag == "circle" else "rx")
|
|
324
|
+
ry = svg_length(attrs, "r" if tag == "circle" else "ry")
|
|
325
|
+
if cx is None or cy is None or rx is None or ry is None:
|
|
326
|
+
return []
|
|
327
|
+
if rx <= 0 or ry <= 0:
|
|
328
|
+
return []
|
|
329
|
+
return [(cx - rx, cy - ry), (cx + rx, cy + ry)]
|
|
330
|
+
if tag in {"polygon", "polyline"}:
|
|
331
|
+
numbers = [float(value) for value in SVG_NUMBER_RE.findall(attrs.get("points", ""))]
|
|
332
|
+
return list(zip(numbers[0::2], numbers[1::2]))
|
|
333
|
+
if tag == "text":
|
|
334
|
+
x, y = svg_length(attrs, "x"), svg_length(attrs, "y")
|
|
335
|
+
return [] if x is None or y is None else [(x, y)]
|
|
336
|
+
return []
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def declares_unstatic_css(declarations: str) -> bool:
|
|
340
|
+
for declaration in declarations.split(";"):
|
|
341
|
+
name = declaration.split(":", 1)[0].strip().casefold()
|
|
342
|
+
if name in UNSTATIC_CSS_PROPERTIES or name.startswith(UNSTATIC_CSS_PREFIXES):
|
|
343
|
+
return True
|
|
344
|
+
return False
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def selector_subjects(selector: str) -> list[tuple[str, set[str], set[str], set[str]]]:
|
|
348
|
+
"""Tag, classes, IDs and attribute names a selector's last compound requires."""
|
|
349
|
+
subjects = []
|
|
350
|
+
for alternative in CSS_PARENS_RE.sub("", CSS_STRING_RE.sub("", selector)).split(","):
|
|
351
|
+
parts = [part for part in CSS_COMBINATOR_RE.split(alternative.strip()) if part]
|
|
352
|
+
if not parts:
|
|
353
|
+
continue
|
|
354
|
+
compound = parts[-1].split("::", 1)[0]
|
|
355
|
+
tag = CSS_TAG_RE.match(compound)
|
|
356
|
+
subjects.append((
|
|
357
|
+
tag.group(0).casefold() if tag else "",
|
|
358
|
+
set(CSS_CLASS_RE.findall(compound)),
|
|
359
|
+
set(CSS_ID_RE.findall(compound)),
|
|
360
|
+
{name.casefold() for name in CSS_ATTRIBUTE_RE.findall(compound)},
|
|
361
|
+
))
|
|
362
|
+
return subjects
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def unstatic_css_subjects(source: str) -> list[tuple[str, set[str], set[str], set[str]]]:
|
|
366
|
+
"""Selector subjects of stylesheet rules that move, hide or clip what they match.
|
|
367
|
+
|
|
368
|
+
Matching keeps only the last compound and drops pseudo-classes, so it can match more
|
|
369
|
+
elements than the browser does. That only skips checks; it never adds a finding.
|
|
370
|
+
"""
|
|
371
|
+
styles = re.findall(r"<style\b[^>]*>(.*?)</style\s*>", source, re.IGNORECASE | re.DOTALL)
|
|
372
|
+
sheet = CSS_KEYFRAMES_RE.sub("", CSS_COMMENT_RE.sub("", "\n".join(styles)))
|
|
373
|
+
subjects = []
|
|
374
|
+
for selector, declarations in CSS_RULE_RE.findall(sheet):
|
|
375
|
+
if declares_unstatic_css(declarations):
|
|
376
|
+
subjects.extend(selector_subjects(selector))
|
|
377
|
+
return subjects
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def matches_subject(
|
|
381
|
+
tag: str, attrs: dict[str, str], subject: tuple[str, set[str], set[str], set[str]]
|
|
382
|
+
) -> bool:
|
|
383
|
+
subject_tag, classes, ids, attribute_names = subject
|
|
384
|
+
if subject_tag not in {"", "*", tag}:
|
|
385
|
+
return False
|
|
386
|
+
if not classes <= set(attrs.get("class", "").split()):
|
|
387
|
+
return False
|
|
388
|
+
if not ids <= {attrs.get("id", "")}:
|
|
389
|
+
return False
|
|
390
|
+
return attribute_names <= set(attrs)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def child_offset(
|
|
394
|
+
tag: str,
|
|
395
|
+
attrs: dict[str, str],
|
|
396
|
+
parent: tuple[float, float] | None,
|
|
397
|
+
css_subjects: list[tuple[str, set[str], set[str], set[str]]],
|
|
398
|
+
) -> tuple[float, float] | None:
|
|
399
|
+
"""Offset of an element in viewBox units, or None when its paint is not static."""
|
|
400
|
+
if parent is None or tag in UNPAINTED_TAGS:
|
|
401
|
+
return None
|
|
402
|
+
if declares_unstatic_css(attrs.get("style", "")):
|
|
403
|
+
return None
|
|
404
|
+
if attrs.get("display", "").strip().casefold() == "none":
|
|
405
|
+
return None
|
|
406
|
+
if attrs.get("visibility", "").strip().casefold() in {"hidden", "collapse"}:
|
|
407
|
+
return None
|
|
408
|
+
if attrs.get("clip-path", "none").strip().casefold() != "none":
|
|
409
|
+
return None
|
|
410
|
+
if attrs.get("mask", "none").strip().casefold() != "none":
|
|
411
|
+
return None
|
|
412
|
+
if any(matches_subject(tag, attrs, subject) for subject in css_subjects):
|
|
413
|
+
return None
|
|
414
|
+
transform = attrs.get("transform")
|
|
415
|
+
if transform is None:
|
|
416
|
+
return parent
|
|
417
|
+
match = TRANSLATE_RE.match(transform)
|
|
418
|
+
if match is None:
|
|
419
|
+
return None
|
|
420
|
+
return parent[0] + float(match.group(1)), parent[1] + float(match.group(2) or 0)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
class ViewBoxParser(HTMLParser):
|
|
424
|
+
def __init__(self, css_subjects: list[tuple[str, set[str], set[str], set[str]]]) -> None:
|
|
425
|
+
super().__init__(convert_charrefs=True)
|
|
426
|
+
self.svgs: list[SvgExtent] = []
|
|
427
|
+
self._css_subjects = css_subjects
|
|
428
|
+
self._frames: list[tuple[str, tuple[float, float] | None]] = []
|
|
429
|
+
|
|
430
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
431
|
+
tag = tag.casefold()
|
|
432
|
+
data = {key.casefold(): value or "" for key, value in attrs}
|
|
433
|
+
if not self._frames:
|
|
434
|
+
if tag == "svg":
|
|
435
|
+
self.svgs.append(SvgExtent(data))
|
|
436
|
+
self._frames.append((tag, (0.0, 0.0)))
|
|
437
|
+
return
|
|
438
|
+
offset = child_offset(tag, data, self._frames[-1][1], self._css_subjects)
|
|
439
|
+
self._frames.append((tag, offset))
|
|
440
|
+
if offset is None:
|
|
441
|
+
return
|
|
442
|
+
label = " ".join(
|
|
443
|
+
[f"<{tag}"]
|
|
444
|
+
+ [f'{name}="{data[name]}"' for name in GEOMETRY_ATTRS.get(tag, ()) if name in data]
|
|
445
|
+
) + ">"
|
|
446
|
+
for x, y in painted_points(tag, data):
|
|
447
|
+
self.svgs[-1].points.append((x + offset[0], y + offset[1], label))
|
|
448
|
+
|
|
449
|
+
def handle_endtag(self, tag: str) -> None:
|
|
450
|
+
tag = tag.casefold()
|
|
451
|
+
for index in range(len(self._frames) - 1, -1, -1):
|
|
452
|
+
if self._frames[index][0] == tag:
|
|
453
|
+
del self._frames[index:]
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def normalized_controller(body: str) -> str:
|
|
458
|
+
return body.replace("\r\n", "\n").replace("\r", "\n").strip()
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def parsed_document(source: str) -> DiagramParser:
|
|
462
|
+
parser = DiagramParser()
|
|
463
|
+
parser.feed(source)
|
|
464
|
+
parser.close()
|
|
465
|
+
return parser
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def is_approved_google_fonts_stylesheet(value: str) -> bool:
|
|
469
|
+
try:
|
|
470
|
+
parsed = urlparse(value)
|
|
471
|
+
except ValueError:
|
|
472
|
+
return False
|
|
473
|
+
return (
|
|
474
|
+
parsed.scheme == "https"
|
|
475
|
+
and parsed.hostname is not None
|
|
476
|
+
and parsed.hostname.casefold() == "fonts.googleapis.com"
|
|
477
|
+
and parsed.port is None
|
|
478
|
+
and parsed.path == "/css2"
|
|
479
|
+
and not parsed.fragment
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def reference_error(tag: str, rel: str, value: str) -> str | None:
|
|
484
|
+
stripped = value.strip()
|
|
485
|
+
lowered = stripped.casefold()
|
|
486
|
+
if not stripped or stripped.startswith("#"):
|
|
487
|
+
return None
|
|
488
|
+
if lowered.startswith("javascript:") or lowered.startswith("data:text/html"):
|
|
489
|
+
return f"executable URL on <{tag}>: {stripped[:80]}"
|
|
490
|
+
remote = lowered.startswith(("http://", "https://", "//")) or (
|
|
491
|
+
":" in stripped.split("/", 1)[0] and not lowered.startswith("data:")
|
|
492
|
+
)
|
|
493
|
+
if not remote:
|
|
494
|
+
if lowered.startswith("data:") and not lowered.startswith("data:image/"):
|
|
495
|
+
return f"non-image data URL on <{tag}>: {stripped[:80]}"
|
|
496
|
+
return None
|
|
497
|
+
if tag == "link" and "stylesheet" in rel.casefold().split():
|
|
498
|
+
if is_approved_google_fonts_stylesheet(stripped):
|
|
499
|
+
return None
|
|
500
|
+
return f"remote stylesheet is not the approved Google Fonts /css2 URL: {stripped[:80]}"
|
|
501
|
+
return f"remote reference on <{tag}>: {stripped[:80]}"
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def normalize_css_escapes(source: str) -> str:
|
|
505
|
+
source = source.replace("\r\n", "\n").replace("\r", "\n").replace("\f", "\n")
|
|
506
|
+
|
|
507
|
+
def replace(match: re.Match[str]) -> str:
|
|
508
|
+
if match.group(1) is None:
|
|
509
|
+
escaped = match.group(2)
|
|
510
|
+
return "" if escaped == "\n" else escaped
|
|
511
|
+
codepoint = int(match.group(1), 16)
|
|
512
|
+
if codepoint == 0 or codepoint > 0x10FFFF:
|
|
513
|
+
return "\N{REPLACEMENT CHARACTER}"
|
|
514
|
+
return chr(codepoint)
|
|
515
|
+
|
|
516
|
+
return CSS_ESCAPE_RE.sub(replace, source)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def check_css_references(parser: DiagramParser, errors: list[str]) -> None:
|
|
520
|
+
# Match the repository linter's fail-closed treatment of CSS loader syntax.
|
|
521
|
+
source = normalize_css_escapes("\n".join(parser.styles + parser.css_attributes))
|
|
522
|
+
found_loader = False
|
|
523
|
+
if CSS_IMPORT_RE.search(source):
|
|
524
|
+
errors.append("CSS @import is not allowed")
|
|
525
|
+
found_loader = True
|
|
526
|
+
for match in CSS_URL_RE.finditer(source):
|
|
527
|
+
value = match.group(1).strip().strip("'\"").strip()
|
|
528
|
+
if not value.startswith("#"):
|
|
529
|
+
errors.append("non-fragment CSS url() is not allowed")
|
|
530
|
+
found_loader = True
|
|
531
|
+
if CSS_IMAGE_SET_RE.search(source):
|
|
532
|
+
errors.append("CSS image-set() is not allowed")
|
|
533
|
+
found_loader = True
|
|
534
|
+
if CSS_REMOTE_RE.search(source) and not found_loader:
|
|
535
|
+
errors.append("remote reference in CSS is not allowed")
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def canonical_controller() -> str:
|
|
539
|
+
if not MOTION_TEMPLATE.is_file():
|
|
540
|
+
raise RuntimeError(
|
|
541
|
+
f"cannot find the canonical controller at {MOTION_TEMPLATE}; "
|
|
542
|
+
"run self_check.py from its shipped location inside the skill"
|
|
543
|
+
)
|
|
544
|
+
parser = parsed_document(MOTION_TEMPLATE.read_text(encoding="utf-8"))
|
|
545
|
+
if len(parser.scripts) != 1 or not parser.scripts[0]["closed"]:
|
|
546
|
+
raise RuntimeError("template-motion.html must contain one closed controller")
|
|
547
|
+
body = parser.scripts[0]["body"]
|
|
548
|
+
assert isinstance(body, list)
|
|
549
|
+
return normalized_controller("".join(body))
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
class BalanceParser(HTMLParser):
|
|
553
|
+
"""Counts start and end tags as parsed, so attribute values and CDATA stay opaque.
|
|
554
|
+
|
|
555
|
+
Reading the raw source with a regular expression instead would count tag-like text
|
|
556
|
+
inside a quoted attribute or a stylesheet as markup, and report an imbalance the
|
|
557
|
+
document does not have. A self-closing tag arrives as both a start and an end tag,
|
|
558
|
+
so it balances itself.
|
|
559
|
+
|
|
560
|
+
Titles and text areas are RCDATA: `<title>Using <span> labels</title>` is literal
|
|
561
|
+
text, not a span element. `HTMLParser` only separates RCDATA from markup from
|
|
562
|
+
Python 3.13 on, so on the versions the skill supports the inner tag arrives here as
|
|
563
|
+
a real one; this class ignores markup until the matching end tag instead.
|
|
564
|
+
"""
|
|
565
|
+
|
|
566
|
+
RCDATA_ELEMENTS = ("title", "textarea")
|
|
567
|
+
|
|
568
|
+
def __init__(self) -> None:
|
|
569
|
+
super().__init__(convert_charrefs=True)
|
|
570
|
+
self.opens: Counter[str] = Counter()
|
|
571
|
+
self.closes: Counter[str] = Counter()
|
|
572
|
+
self.rcdata = ""
|
|
573
|
+
|
|
574
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
575
|
+
if self.rcdata:
|
|
576
|
+
return
|
|
577
|
+
self.opens[tag] += 1
|
|
578
|
+
if tag in self.RCDATA_ELEMENTS:
|
|
579
|
+
self.rcdata = tag
|
|
580
|
+
|
|
581
|
+
def handle_endtag(self, tag: str) -> None:
|
|
582
|
+
if self.rcdata:
|
|
583
|
+
if tag == self.rcdata:
|
|
584
|
+
self.rcdata = ""
|
|
585
|
+
self.closes[tag] += 1
|
|
586
|
+
return
|
|
587
|
+
self.closes[tag] += 1
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def ends_with_shell_close(source: str) -> bool:
|
|
591
|
+
"""True when the last markup in the document is `</html>`.
|
|
592
|
+
|
|
593
|
+
HTML allows comments and whitespace after the `</html>` end tag, so stripping only
|
|
594
|
+
whitespace would reject valid files; a document that really stopped early has no
|
|
595
|
+
closing tag left once trailing comments are removed.
|
|
596
|
+
"""
|
|
597
|
+
tail = source.rstrip()
|
|
598
|
+
while True:
|
|
599
|
+
start = tail.rfind("<!--")
|
|
600
|
+
if start < 0:
|
|
601
|
+
break
|
|
602
|
+
end = tail.find("-->", start + 4)
|
|
603
|
+
if end < 0 or tail[end + 3 :].strip():
|
|
604
|
+
break
|
|
605
|
+
tail = tail[:start].rstrip()
|
|
606
|
+
return re.search(r"</html\s*>\Z", tail, re.IGNORECASE) is not None
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def check_document_completeness(source: str, errors: list[str]) -> None:
|
|
610
|
+
"""Reject a document that is not whole: truncation, mojibake, unbalanced markup.
|
|
611
|
+
|
|
612
|
+
The other checks read a document's contents; none of them notices that the document
|
|
613
|
+
stopped early. A generated file that was cut off mid-write still satisfies the
|
|
614
|
+
accessible-SVG contract for the part that survived, so this check reads the shape of
|
|
615
|
+
the whole file instead.
|
|
616
|
+
"""
|
|
617
|
+
if not ends_with_shell_close(source):
|
|
618
|
+
errors.append("document does not end with </html>; the file looks truncated")
|
|
619
|
+
|
|
620
|
+
replacements = source.count(REPLACEMENT_CHAR)
|
|
621
|
+
if replacements:
|
|
622
|
+
line = source[: source.index(REPLACEMENT_CHAR)].count("\n") + 1
|
|
623
|
+
errors.append(
|
|
624
|
+
f"contains {replacements} U+FFFD replacement character(s), first on line {line}:"
|
|
625
|
+
" the file has mojibake or a truncated multi-byte character"
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
parser = BalanceParser()
|
|
629
|
+
parser.feed(source)
|
|
630
|
+
parser.close()
|
|
631
|
+
if parser.rcdata:
|
|
632
|
+
# Everything after an unterminated RCDATA element is text, so the tag counts
|
|
633
|
+
# below describe the damage rather than the cause; report the cause alone.
|
|
634
|
+
errors.append(
|
|
635
|
+
f"<{parser.rcdata}> is never closed; the rest of the document reads as its text"
|
|
636
|
+
)
|
|
637
|
+
return
|
|
638
|
+
for tag in PAIRED_CONTAINER_TAGS:
|
|
639
|
+
opens, closes = parser.opens[tag], parser.closes[tag]
|
|
640
|
+
if opens != closes:
|
|
641
|
+
errors.append(
|
|
642
|
+
f"<{tag}> opens {opens} time(s) and closes {closes} time(s);"
|
|
643
|
+
" the document is not balanced"
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def check_svgs(parser: DiagramParser, errors: list[str]) -> None:
|
|
648
|
+
checkable = [
|
|
649
|
+
svg
|
|
650
|
+
for svg in parser.svgs
|
|
651
|
+
if isinstance(svg["attrs"], dict)
|
|
652
|
+
and str(svg["attrs"].get("aria-hidden", "")).casefold() != "true"
|
|
653
|
+
]
|
|
654
|
+
if not checkable:
|
|
655
|
+
errors.append("diagram file needs at least one accessible (non-aria-hidden) SVG")
|
|
656
|
+
for number, svg in enumerate(checkable, 1):
|
|
657
|
+
attrs = svg["attrs"]
|
|
658
|
+
assert isinstance(attrs, dict)
|
|
659
|
+
if attrs.get("role") != "img":
|
|
660
|
+
errors.append(f"svg {number} needs role=img")
|
|
661
|
+
labelled = attrs.get("aria-labelledby", "").split()
|
|
662
|
+
title = svg["title"]
|
|
663
|
+
desc = svg["desc"]
|
|
664
|
+
assert isinstance(title, dict) and isinstance(desc, dict)
|
|
665
|
+
title_attrs = title.get("attrs", {})
|
|
666
|
+
desc_attrs = desc.get("attrs", {})
|
|
667
|
+
assert isinstance(title_attrs, dict) and isinstance(desc_attrs, dict)
|
|
668
|
+
if svg["first"] != "title":
|
|
669
|
+
errors.append(f"svg {number} title must be its first child")
|
|
670
|
+
if not str(title.get("text", "")).strip() or not str(desc.get("text", "")).strip():
|
|
671
|
+
errors.append(f"svg {number} needs non-empty title and desc")
|
|
672
|
+
title_id = title_attrs.get("id", "")
|
|
673
|
+
desc_id = desc_attrs.get("id", "")
|
|
674
|
+
if title_id in {"", "title"} or desc_id in {"", "desc"}:
|
|
675
|
+
errors.append(f"svg {number} title/desc IDs must be diagram-prefixed, never bare")
|
|
676
|
+
for naming_id in dict.fromkeys((title_id, desc_id)):
|
|
677
|
+
if parser.ids[naming_id] > 1:
|
|
678
|
+
errors.append(f"duplicate accessible SVG naming ID {naming_id!r}")
|
|
679
|
+
if labelled != [title_id, desc_id]:
|
|
680
|
+
errors.append(f"svg {number} aria-labelledby must name title then desc")
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def check_viewbox(source: str, errors: list[str]) -> None:
|
|
684
|
+
parser = ViewBoxParser(unstatic_css_subjects(source))
|
|
685
|
+
parser.feed(source)
|
|
686
|
+
parser.close()
|
|
687
|
+
checkable = [
|
|
688
|
+
svg for svg in parser.svgs if svg.attrs.get("aria-hidden", "").casefold() != "true"
|
|
689
|
+
]
|
|
690
|
+
for number, svg in enumerate(checkable, 1):
|
|
691
|
+
box = [float(value) for value in SVG_NUMBER_RE.findall(svg.attrs.get("viewbox", ""))]
|
|
692
|
+
if len(box) != 4 or box[2] <= 0 or box[3] <= 0:
|
|
693
|
+
continue
|
|
694
|
+
left, top, width, height = box
|
|
695
|
+
worst: dict[str, tuple[float, str]] = {}
|
|
696
|
+
for x, y, label in svg.points:
|
|
697
|
+
for side, overshoot in (
|
|
698
|
+
("left", left - x),
|
|
699
|
+
("top", top - y),
|
|
700
|
+
("right", x - (left + width)),
|
|
701
|
+
("bottom", y - (top + height)),
|
|
702
|
+
):
|
|
703
|
+
if overshoot > VIEWBOX_TOLERANCE and overshoot > worst.get(side, (0.0, ""))[0]:
|
|
704
|
+
worst[side] = (overshoot, label)
|
|
705
|
+
for side, (overshoot, label) in worst.items():
|
|
706
|
+
errors.append(
|
|
707
|
+
f"svg {number}: {label} paints {overshoot:g}px past the viewBox {side} edge "
|
|
708
|
+
"and is clipped; grow the viewBox or move the content inside it"
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def declaring_css_subjects(
|
|
713
|
+
source: str, declares: Callable[[str], bool]
|
|
714
|
+
) -> list[tuple[str, set[str], set[str], set[str]]]:
|
|
715
|
+
"""Selector subjects of stylesheet rules that declare a property `declares` accepts."""
|
|
716
|
+
styles = re.findall(r"<style\b[^>]*>(.*?)</style\s*>", source, re.IGNORECASE | re.DOTALL)
|
|
717
|
+
sheet = CSS_KEYFRAMES_RE.sub("", CSS_COMMENT_RE.sub("", "\n".join(styles)))
|
|
718
|
+
subjects = []
|
|
719
|
+
for selector, declarations in CSS_RULE_RE.findall(sheet):
|
|
720
|
+
names = {part.split(":", 1)[0].strip().casefold() for part in declarations.split(";")}
|
|
721
|
+
if any(declares(name) for name in names):
|
|
722
|
+
subjects.extend(selector_subjects(selector))
|
|
723
|
+
return subjects
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def inline_paint(attrs: dict[str, str]) -> dict[str, str]:
|
|
727
|
+
values = {name: attrs[name].strip().casefold() for name in PAINT_PROPERTIES if name in attrs}
|
|
728
|
+
for declaration in attrs.get("style", "").split(";"):
|
|
729
|
+
name, _, value = declaration.partition(":")
|
|
730
|
+
name = name.strip().casefold()
|
|
731
|
+
if name in PAINT_PROPERTIES:
|
|
732
|
+
values[name] = value.strip().casefold()
|
|
733
|
+
return values
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def inline_text_style(attrs: dict[str, str]) -> dict[str, str]:
|
|
737
|
+
values = {name: attrs[name] for name in TEXT_FIT_PROPERTIES if name in attrs}
|
|
738
|
+
values.update({name: "" for name in TEXT_LAYOUT_PROPERTIES if name in attrs})
|
|
739
|
+
for declaration in attrs.get("style", "").split(";"):
|
|
740
|
+
name, _, value = declaration.partition(":")
|
|
741
|
+
name = name.strip().casefold()
|
|
742
|
+
if restyles_text_width(name):
|
|
743
|
+
values[name] = value.strip() if name in TEXT_FIT_PROPERTIES else ""
|
|
744
|
+
return values
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def restyles_text_width(name: str) -> bool:
|
|
748
|
+
if name in TEXT_FIT_IGNORED:
|
|
749
|
+
return False
|
|
750
|
+
return (
|
|
751
|
+
name.startswith(("font", "letter-spacing", "word-spacing"))
|
|
752
|
+
or name == "text-anchor"
|
|
753
|
+
or name in TEXT_LAYOUT_PROPERTIES
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def zero_alpha(value: str) -> bool | None:
|
|
758
|
+
"""True for an opacity or colour that paints nothing; None when it can't be read."""
|
|
759
|
+
value = value.strip().casefold()
|
|
760
|
+
if value in {"none", "transparent"}:
|
|
761
|
+
return True
|
|
762
|
+
number = re.fullmatch(rf"({SVG_NUMBER})(%?)", value)
|
|
763
|
+
if number:
|
|
764
|
+
return float(number.group(1)) <= 0
|
|
765
|
+
if re.fullmatch(r"#[0-9a-f]{4}|#[0-9a-f]{8}", value):
|
|
766
|
+
return int(value[4] if len(value) == 5 else value[7:], 16) == 0
|
|
767
|
+
function = re.fullmatch(r"(?:rgba?|hsla?)\((.*)\)", value)
|
|
768
|
+
if function:
|
|
769
|
+
parts = [part for part in re.split(r"[\s,/]+", function.group(1).strip()) if part]
|
|
770
|
+
return zero_alpha(parts[3]) if len(parts) == 4 else False
|
|
771
|
+
return False if value.startswith("#") or value.isalpha() else None
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def text_advance(text: str, mono: bool) -> float:
|
|
775
|
+
"""Text advance in em under the style-guide width budget."""
|
|
776
|
+
narrow = MONO_ADVANCE if mono else SANS_ADVANCE
|
|
777
|
+
advance = 0.0
|
|
778
|
+
for char in text:
|
|
779
|
+
if unicodedata.category(char) in {"Mn", "Me"}:
|
|
780
|
+
continue
|
|
781
|
+
advance += WIDE_ADVANCE if unicodedata.east_asian_width(char) in {"W", "F"} else narrow
|
|
782
|
+
return advance
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def font_size_px(style: dict[str, str]) -> float | None:
|
|
786
|
+
match = re.fullmatch(rf"\s*({SVG_NUMBER})\s*(?:px)?\s*", style.get("font-size", ""))
|
|
787
|
+
return float(match.group(1)) if match else None
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def text_run_width(text: str, style: dict[str, str]) -> float | None:
|
|
791
|
+
"""Estimated width in px of one run, or None when its style cannot be read statically."""
|
|
792
|
+
size = font_size_px(style)
|
|
793
|
+
if size is None:
|
|
794
|
+
return None
|
|
795
|
+
spacing = style.get("letter-spacing", "normal").strip().casefold()
|
|
796
|
+
spacing_match = re.fullmatch(rf"({SVG_NUMBER})\s*(em|px)?", spacing)
|
|
797
|
+
if spacing == "normal":
|
|
798
|
+
tracking = 0.0
|
|
799
|
+
elif spacing_match is None:
|
|
800
|
+
return None
|
|
801
|
+
else:
|
|
802
|
+
tracking = float(spacing_match.group(1)) * (size if spacing_match.group(2) == "em" else 1)
|
|
803
|
+
glyphs = sum(1 for char in text if unicodedata.category(char) not in {"Mn", "Me"})
|
|
804
|
+
mono = "mono" in style.get("font-family", "").casefold()
|
|
805
|
+
return text_advance(text, mono) * size + tracking * glyphs
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
class TextFitParser(HTMLParser):
|
|
809
|
+
"""Collects static rects and text lines per top-level SVG, in paint order."""
|
|
810
|
+
|
|
811
|
+
def __init__(self, source: str) -> None:
|
|
812
|
+
super().__init__(convert_charrefs=True)
|
|
813
|
+
self.svgs: list[dict[str, object]] = []
|
|
814
|
+
self._css_subjects = unstatic_css_subjects(source)
|
|
815
|
+
self._text_subjects = declaring_css_subjects(source, restyles_text_width)
|
|
816
|
+
self._paint_subjects = declaring_css_subjects(source, PAINT_PROPERTIES.__contains__)
|
|
817
|
+
# (tag, offset, inherited text style, inherited paint); a style or paint is None
|
|
818
|
+
# once a stylesheet rule can change it, since its value is then unknown here.
|
|
819
|
+
self._frames: list[
|
|
820
|
+
tuple[str, tuple[float, float] | None, dict[str, str] | None, dict[str, str] | None]
|
|
821
|
+
] = []
|
|
822
|
+
self._text: dict[str, object] | None = None
|
|
823
|
+
|
|
824
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
825
|
+
tag = tag.casefold()
|
|
826
|
+
data = {key.casefold(): value or "" for key, value in attrs}
|
|
827
|
+
if not self._frames:
|
|
828
|
+
if tag == "svg":
|
|
829
|
+
self.svgs.append({"attrs": data, "rects": [], "lines": [], "papers": set()})
|
|
830
|
+
style, paint = self._inherit(tag, data, {}, {})
|
|
831
|
+
self._frames.append((tag, (0.0, 0.0), style, paint))
|
|
832
|
+
return
|
|
833
|
+
_parent_tag, parent_offset, parent_style, parent_paint = self._frames[-1]
|
|
834
|
+
offset = child_offset(tag, data, parent_offset, self._css_subjects)
|
|
835
|
+
style, paint = self._inherit(tag, data, parent_style, parent_paint)
|
|
836
|
+
self._frames.append((tag, offset, style, paint))
|
|
837
|
+
svg = self.svgs[-1]
|
|
838
|
+
if offset is None:
|
|
839
|
+
if tag in {"text", "tspan"} and self._text is not None:
|
|
840
|
+
self._text["static"] = False
|
|
841
|
+
return
|
|
842
|
+
if tag == "rect" and self._text is None:
|
|
843
|
+
fill: str | None = None
|
|
844
|
+
stroked = False
|
|
845
|
+
if paint is not None:
|
|
846
|
+
fill = paint.get("fill", "black")
|
|
847
|
+
stroke = paint.get("stroke", "none")
|
|
848
|
+
stroked = stroke not in {"none", "transparent"} and paint.get("stroke-width") != "0"
|
|
849
|
+
faded = [
|
|
850
|
+
zero_alpha(value) for value in (
|
|
851
|
+
paint["opacity"], fill, paint.get("fill-opacity", "1"),
|
|
852
|
+
stroke, paint.get("stroke-opacity", "1"),
|
|
853
|
+
)
|
|
854
|
+
]
|
|
855
|
+
if None in faded:
|
|
856
|
+
fill, stroked = None, False
|
|
857
|
+
else:
|
|
858
|
+
if faded[0] or faded[1] or faded[2]:
|
|
859
|
+
fill = "none"
|
|
860
|
+
stroked = stroked and not (faded[0] or faded[3] or faded[4])
|
|
861
|
+
if data.get("width", "").strip() == "100%":
|
|
862
|
+
papers = svg["papers"]
|
|
863
|
+
assert isinstance(papers, set)
|
|
864
|
+
papers.add(fill)
|
|
865
|
+
points = painted_points(tag, data)
|
|
866
|
+
if points and (fill not in {"none", "transparent"} or stroked):
|
|
867
|
+
(x0, y0), (x1, y1) = points
|
|
868
|
+
rects = svg["rects"]
|
|
869
|
+
assert isinstance(rects, list)
|
|
870
|
+
rects.append(
|
|
871
|
+
(x0 + offset[0], y0 + offset[1], x1 + offset[0], y1 + offset[1], fill, stroked)
|
|
872
|
+
)
|
|
873
|
+
elif tag == "text" and self._text is None:
|
|
874
|
+
x, y = svg_length(data, "x"), svg_length(data, "y")
|
|
875
|
+
shifted = any(name in data for name in ("dx", "dy", "rotate", "textlength"))
|
|
876
|
+
self._text = {"static": x is not None and y is not None and not shifted, "lines": []}
|
|
877
|
+
if x is not None and y is not None:
|
|
878
|
+
self._start_line(x + offset[0], y + offset[1], style)
|
|
879
|
+
elif tag == "tspan" and self._text is not None:
|
|
880
|
+
if any(name in data for name in ("dx", "rotate", "textlength")):
|
|
881
|
+
self._text["static"] = False
|
|
882
|
+
x = svg_length(data, "x")
|
|
883
|
+
lines = self._text["lines"]
|
|
884
|
+
assert isinstance(lines, list)
|
|
885
|
+
if "x" in data:
|
|
886
|
+
if x is None:
|
|
887
|
+
self._text["static"] = False
|
|
888
|
+
return
|
|
889
|
+
dy = svg_length(data, "dy", 0.0)
|
|
890
|
+
y = svg_length(data, "y")
|
|
891
|
+
previous_y = lines[-1]["y"] if lines else 0.0
|
|
892
|
+
line_y = (y + offset[1]) if y is not None else previous_y + (dy or 0.0)
|
|
893
|
+
self._start_line(x + offset[0], line_y, style)
|
|
894
|
+
elif "y" in data or "dy" in data:
|
|
895
|
+
self._text["static"] = False
|
|
896
|
+
|
|
897
|
+
def _inherit(
|
|
898
|
+
self,
|
|
899
|
+
tag: str,
|
|
900
|
+
data: dict[str, str],
|
|
901
|
+
parent_style: dict[str, str] | None,
|
|
902
|
+
parent_paint: dict[str, str] | None,
|
|
903
|
+
) -> tuple[dict[str, str] | None, dict[str, str] | None]:
|
|
904
|
+
style: dict[str, str] | None = None
|
|
905
|
+
if parent_style is not None and not any(
|
|
906
|
+
matches_subject(tag, data, subject) for subject in self._text_subjects
|
|
907
|
+
):
|
|
908
|
+
own = inline_text_style(data)
|
|
909
|
+
style = None if "" in own.values() else {**parent_style, **own}
|
|
910
|
+
paint: dict[str, str] | None = None
|
|
911
|
+
if parent_paint is not None and not any(
|
|
912
|
+
matches_subject(tag, data, subject) for subject in self._paint_subjects
|
|
913
|
+
):
|
|
914
|
+
own = inline_paint(data)
|
|
915
|
+
hidden = parent_paint.get("opacity") == "0" or zero_alpha(own.get("opacity", "1"))
|
|
916
|
+
paint = {**parent_paint, **own, "opacity": "0" if hidden else "1"}
|
|
917
|
+
if hidden is None:
|
|
918
|
+
paint = None
|
|
919
|
+
return style, paint
|
|
920
|
+
|
|
921
|
+
def _start_line(self, x: float, y: float, style: dict[str, str] | None) -> None:
|
|
922
|
+
assert self._text is not None
|
|
923
|
+
lines = self._text["lines"]
|
|
924
|
+
assert isinstance(lines, list)
|
|
925
|
+
rects = self.svgs[-1]["rects"]
|
|
926
|
+
assert isinstance(rects, list)
|
|
927
|
+
anchor = (style or {}).get("text-anchor", "start").strip().casefold()
|
|
928
|
+
lines.append({"x": x, "y": y, "anchor": anchor, "runs": [], "rects": len(rects)})
|
|
929
|
+
|
|
930
|
+
def handle_data(self, data: str) -> None:
|
|
931
|
+
if self._text is None or not self._frames:
|
|
932
|
+
return
|
|
933
|
+
lines = self._text["lines"]
|
|
934
|
+
assert isinstance(lines, list)
|
|
935
|
+
if not lines:
|
|
936
|
+
return
|
|
937
|
+
style = self._frames[-1][2]
|
|
938
|
+
if style is None:
|
|
939
|
+
self._text["static"] = False
|
|
940
|
+
return
|
|
941
|
+
lines[-1]["runs"].append((data, style))
|
|
942
|
+
|
|
943
|
+
def handle_endtag(self, tag: str) -> None:
|
|
944
|
+
tag = tag.casefold()
|
|
945
|
+
for index in range(len(self._frames) - 1, -1, -1):
|
|
946
|
+
if self._frames[index][0] == tag:
|
|
947
|
+
del self._frames[index:]
|
|
948
|
+
break
|
|
949
|
+
if tag == "text" and self._text is not None:
|
|
950
|
+
if self._text["static"] and self.svgs:
|
|
951
|
+
svg_lines = self.svgs[-1]["lines"]
|
|
952
|
+
assert isinstance(svg_lines, list)
|
|
953
|
+
svg_lines.extend(self._text["lines"])
|
|
954
|
+
self._text = None
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def rect_area(rect: tuple) -> float:
|
|
958
|
+
return (rect[2] - rect[0]) * (rect[3] - rect[1])
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def check_text_fit(source: str, errors: list[str]) -> None:
|
|
962
|
+
"""Flag text whose budgeted width runs past the rect it sits in.
|
|
963
|
+
|
|
964
|
+
A line's box is the smallest rect painted before it that contains the line's
|
|
965
|
+
anchor point; a rect whose opacity, fill and stroke draw nothing is no box.
|
|
966
|
+
Text with no such rect (a free label, a caption), text on a paper-coloured
|
|
967
|
+
mask, bidi, vertical or space-preserving text, and text whose size, spacing,
|
|
968
|
+
layout or position CSS can change are not checked.
|
|
969
|
+
"""
|
|
970
|
+
parser = TextFitParser(source)
|
|
971
|
+
parser.feed(source)
|
|
972
|
+
parser.close()
|
|
973
|
+
checkable = [
|
|
974
|
+
svg for svg in parser.svgs
|
|
975
|
+
if isinstance(svg["attrs"], dict) and svg["attrs"].get("aria-hidden", "").casefold() != "true"
|
|
976
|
+
]
|
|
977
|
+
for number, svg in enumerate(checkable, 1):
|
|
978
|
+
rects, lines, papers = svg["rects"], svg["lines"], svg["papers"]
|
|
979
|
+
assert isinstance(rects, list) and isinstance(lines, list) and isinstance(papers, set)
|
|
980
|
+
for line in lines:
|
|
981
|
+
runs = [(re.sub(r"\s+", " ", run), style) for run, style in line["runs"]]
|
|
982
|
+
text = "".join(run for run, _style in runs)
|
|
983
|
+
if not text.strip():
|
|
984
|
+
continue
|
|
985
|
+
runs[0] = (runs[0][0].lstrip(), runs[0][1])
|
|
986
|
+
runs[-1] = (runs[-1][0].rstrip(), runs[-1][1])
|
|
987
|
+
widths = [text_run_width(run, style) for run, style in runs]
|
|
988
|
+
if any(width is None for width in widths):
|
|
989
|
+
continue
|
|
990
|
+
width = sum(widths)
|
|
991
|
+
size = max(font_size_px(style) or 0.0 for _run, style in runs)
|
|
992
|
+
x, y = line["x"], line["y"]
|
|
993
|
+
behind = [
|
|
994
|
+
rect for rect in rects[: line["rects"]]
|
|
995
|
+
if rect[0] <= x <= rect[2] and rect[1] <= y <= rect[3]
|
|
996
|
+
]
|
|
997
|
+
# A paper-coloured mask has no visible edge to overflow; text past it shows
|
|
998
|
+
# only where something crosses behind, which is a collision, not a fit problem.
|
|
999
|
+
# Nodes paint such a mask under their tinted body, so it only decides when it
|
|
1000
|
+
# is strictly smaller than every visible rect around the anchor.
|
|
1001
|
+
visible = [
|
|
1002
|
+
rect for rect in behind
|
|
1003
|
+
if rect[5] or (rect[4] is not None and rect[4] not in papers)
|
|
1004
|
+
]
|
|
1005
|
+
if not visible:
|
|
1006
|
+
continue
|
|
1007
|
+
box = min(visible, key=rect_area)
|
|
1008
|
+
if min(rect_area(rect) for rect in behind) < rect_area(box) or box[4] is None:
|
|
1009
|
+
continue
|
|
1010
|
+
left, right = box[0], box[2]
|
|
1011
|
+
anchor = line["anchor"]
|
|
1012
|
+
start = x - width / 2 if anchor == "middle" else x - width if anchor == "end" else x
|
|
1013
|
+
overshoot = max(left - start, start + width - right)
|
|
1014
|
+
if overshoot > TEXT_FIT_TOLERANCE_EM * size:
|
|
1015
|
+
errors.append(
|
|
1016
|
+
f"svg {number}: text {text.strip()!r} at ({x:g}, {y:g}) is budgeted at "
|
|
1017
|
+
f"{width:.0f}px and overflows its {right - left:g}px box by {overshoot:.0f}px; "
|
|
1018
|
+
"widen the box or shorten the label (budget: 0.60em sans, 0.62em mono per char)"
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def check_scripts(parser: DiagramParser, errors: list[str]) -> None:
|
|
1023
|
+
if not parser.scripts:
|
|
1024
|
+
return
|
|
1025
|
+
if len(parser.scripts) > 1:
|
|
1026
|
+
errors.append(f"at most one script is allowed; found {len(parser.scripts)}")
|
|
1027
|
+
for number, script in enumerate(parser.scripts, 1):
|
|
1028
|
+
attrs = script["attrs"]
|
|
1029
|
+
attr_names = script["attr_names"]
|
|
1030
|
+
body = script["body"]
|
|
1031
|
+
assert isinstance(attrs, dict) and isinstance(attr_names, list) and isinstance(body, list)
|
|
1032
|
+
if not script["closed"]:
|
|
1033
|
+
errors.append(f"script {number} must have a closing script tag")
|
|
1034
|
+
if attr_names != ["data-diagram-controls"] or attrs.get("data-diagram-controls") != "":
|
|
1035
|
+
errors.append(f"script {number} must carry only the canonical data-diagram-controls attribute")
|
|
1036
|
+
continue
|
|
1037
|
+
try:
|
|
1038
|
+
if normalized_controller("".join(body)) != canonical_controller():
|
|
1039
|
+
errors.append(f"script {number} must exactly match the controller in template-motion.html")
|
|
1040
|
+
except RuntimeError as exc:
|
|
1041
|
+
errors.append(str(exc))
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
def check_motion(parser: DiagramParser, source: str, errors: list[str]) -> None:
|
|
1045
|
+
has_motion_markup = bool(parser.roots or parser.items or parser.scripts)
|
|
1046
|
+
if not has_motion_markup:
|
|
1047
|
+
return
|
|
1048
|
+
if len(parser.roots) != 1:
|
|
1049
|
+
errors.append(f"expected exactly one data-motion-root; found {len(parser.roots)}")
|
|
1050
|
+
return
|
|
1051
|
+
root = parser.roots[0]
|
|
1052
|
+
mode = root.get("data-motion-mode", "")
|
|
1053
|
+
if mode not in MODES:
|
|
1054
|
+
errors.append(f"data-motion-mode must be one of {sorted(MODES)}; got {mode!r}")
|
|
1055
|
+
raw_count = root.get("data-step-count", "")
|
|
1056
|
+
if not ASCII_DECIMAL_RE.fullmatch(raw_count):
|
|
1057
|
+
count = -1
|
|
1058
|
+
errors.append("data-step-count must be an ASCII decimal integer")
|
|
1059
|
+
else:
|
|
1060
|
+
count = int(raw_count)
|
|
1061
|
+
minimum_count = 0 if mode == "none" else 1
|
|
1062
|
+
if count < minimum_count or count > 8:
|
|
1063
|
+
errors.append(f"semantic step count must be {minimum_count}..8; got {count}")
|
|
1064
|
+
|
|
1065
|
+
if len(parser.items) > 12:
|
|
1066
|
+
errors.append(f"motion item budget is 12; found {len(parser.items)}")
|
|
1067
|
+
semantic_steps: list[int] = []
|
|
1068
|
+
for index, item in enumerate(parser.items, 1):
|
|
1069
|
+
raw_step = item.get("data-step", "")
|
|
1070
|
+
if not ASCII_DECIMAL_RE.fullmatch(raw_step):
|
|
1071
|
+
errors.append(f"motion item {index} has a non-ASCII-decimal data-step")
|
|
1072
|
+
continue
|
|
1073
|
+
step = int(raw_step)
|
|
1074
|
+
decorative = "data-motion-decorative" in item
|
|
1075
|
+
if not decorative:
|
|
1076
|
+
semantic_steps.append(step)
|
|
1077
|
+
if not item.get("aria-label", "").strip():
|
|
1078
|
+
errors.append(f"semantic motion item {index} needs a non-color aria-label")
|
|
1079
|
+
elif item.get("aria-hidden") != "true" or item.get("focusable") != "false":
|
|
1080
|
+
errors.append(f"decorative motion item {index} needs aria-hidden=true and focusable=false")
|
|
1081
|
+
inline = item.get("style", "").replace(" ", "").lower()
|
|
1082
|
+
if any(token in inline for token in ("display:none", "visibility:hidden", "opacity:0")):
|
|
1083
|
+
errors.append(f"motion item {index} is hidden in source; the fallback must be visible")
|
|
1084
|
+
|
|
1085
|
+
expected = set(range(1, count + 1)) if count > 0 else set()
|
|
1086
|
+
if set(semantic_steps) != expected:
|
|
1087
|
+
errors.append(f"semantic steps must be contiguous 1..{count}; found {sorted(set(semantic_steps))}")
|
|
1088
|
+
crowded = {step: n for step, n in Counter(semantic_steps).items() if n > 2}
|
|
1089
|
+
if crowded:
|
|
1090
|
+
errors.append(f"no more than two semantic items may share a step; found {crowded}")
|
|
1091
|
+
|
|
1092
|
+
if mode in {"none", "loop"} and parser.scripts:
|
|
1093
|
+
errors.append(f"{mode} mode must be script-free")
|
|
1094
|
+
if mode in {"none", "loop"} and (parser.controls or parser.actions or parser.statuses):
|
|
1095
|
+
errors.append(f"{mode} mode must not expose playback controls or live status")
|
|
1096
|
+
controlled = mode == "step" or (mode == "reveal" and bool(parser.scripts))
|
|
1097
|
+
if controlled:
|
|
1098
|
+
if parser.controls != 1:
|
|
1099
|
+
errors.append(f"controlled mode needs one in-root control group; found {parser.controls}")
|
|
1100
|
+
missing = ACTIONS - parser.actions
|
|
1101
|
+
if missing:
|
|
1102
|
+
errors.append(f"controlled mode is missing actions: {', '.join(sorted(missing))}")
|
|
1103
|
+
if not parser.statuses:
|
|
1104
|
+
errors.append("controlled mode needs data-motion-status")
|
|
1105
|
+
else:
|
|
1106
|
+
status = parser.statuses[0]
|
|
1107
|
+
if (
|
|
1108
|
+
status.get("role") != "status"
|
|
1109
|
+
or status.get("aria-live") != "polite"
|
|
1110
|
+
or status.get("aria-atomic") != "true"
|
|
1111
|
+
):
|
|
1112
|
+
errors.append("motion status needs role=status, aria-live=polite, aria-atomic=true")
|
|
1113
|
+
if parser.statuses_in_controls:
|
|
1114
|
+
errors.append("motion status must sit outside data-motion-controls")
|
|
1115
|
+
if not parser.scripts:
|
|
1116
|
+
errors.append("controlled mode needs the scoped control script")
|
|
1117
|
+
|
|
1118
|
+
style_source = "".join(parser.styles)
|
|
1119
|
+
if parser.scripts:
|
|
1120
|
+
if re.search(r"prefers-reduced-motion\s*:\s*reduce", style_source, re.IGNORECASE) is None:
|
|
1121
|
+
errors.append("missing reduced-motion CSS fallback (prefers-reduced-motion)")
|
|
1122
|
+
if re.search(r"@media\s+print\b", style_source, re.IGNORECASE) is None:
|
|
1123
|
+
errors.append("missing print CSS fallback (@media print)")
|
|
1124
|
+
if "<noscript" not in source.casefold():
|
|
1125
|
+
errors.append("motion file needs a <noscript> explanation of the complete static frame")
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def verify(path: Path, offline: bool = False) -> list[str]:
|
|
1129
|
+
source = path.read_text(encoding="utf-8")
|
|
1130
|
+
parser = parsed_document(source)
|
|
1131
|
+
errors: list[str] = []
|
|
1132
|
+
errors.extend(parser.unsafe)
|
|
1133
|
+
check_document_completeness(source, errors)
|
|
1134
|
+
check_css_references(parser, errors)
|
|
1135
|
+
for tag, rel, value in parser.references:
|
|
1136
|
+
finding = reference_error(tag, rel, value)
|
|
1137
|
+
if finding:
|
|
1138
|
+
errors.append(finding)
|
|
1139
|
+
elif offline and is_approved_google_fonts_stylesheet(value.strip()):
|
|
1140
|
+
errors.append(
|
|
1141
|
+
"offline: file loads Google Fonts; remove the font <link> to use system fonts"
|
|
1142
|
+
)
|
|
1143
|
+
check_svgs(parser, errors)
|
|
1144
|
+
check_viewbox(source, errors)
|
|
1145
|
+
check_text_fit(source, errors)
|
|
1146
|
+
check_scripts(parser, errors)
|
|
1147
|
+
check_motion(parser, source, errors)
|
|
1148
|
+
return errors
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
def main() -> int:
|
|
1152
|
+
argument_parser = argparse.ArgumentParser(description=__doc__)
|
|
1153
|
+
argument_parser.add_argument("files", nargs="+", type=Path)
|
|
1154
|
+
argument_parser.add_argument(
|
|
1155
|
+
"--offline",
|
|
1156
|
+
action="store_true",
|
|
1157
|
+
help="also fail on the Google Fonts link, for system-font output that makes no network requests",
|
|
1158
|
+
)
|
|
1159
|
+
args = argument_parser.parse_args()
|
|
1160
|
+
failed = False
|
|
1161
|
+
for path in args.files:
|
|
1162
|
+
try:
|
|
1163
|
+
errors = verify(path, offline=args.offline)
|
|
1164
|
+
except (OSError, UnicodeError) as exc:
|
|
1165
|
+
errors = [str(exc)]
|
|
1166
|
+
if errors:
|
|
1167
|
+
failed = True
|
|
1168
|
+
print(f"FAIL {path}")
|
|
1169
|
+
for error in errors:
|
|
1170
|
+
print(f" - {error}")
|
|
1171
|
+
else:
|
|
1172
|
+
print(f"OK {path}")
|
|
1173
|
+
return 1 if failed else 0
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
if __name__ == "__main__":
|
|
1177
|
+
sys.exit(main())
|