Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.
fix(self-check): flag content painted outside the viewBox (#408)
O. Riastanjung1a6a6fc90750
diff --git a/scripts/test-self-check.py b/scripts/test-self-check.pyindex 96194b8..06bb020 100644--- a/scripts/test-self-check.py+++ b/scripts/test-self-check.py@@ -254,6 +254,74 @@ def main() -> int:"ASCII decimal",)+ # Content past the viewBox is clipped silently in the render (#406).+ clipped_legend = static.replace('viewBox="0 0 1000 480"', 'viewBox="0 0 1000 400"', 1)+ check_fail("legend below the viewBox", clipped_legend, "past the viewBox bottom edge")+ for label, markup, needle in (+ ("rect past the right edge", '<rect x="980" y="10" width="40" height="10"/>',+ "past the viewBox right edge"),+ ("translated text above the top edge",+ '<g transform="translate(10, -30)"><text x="5" y="10">Late</text></g>',+ "past the viewBox top edge"),+ ("line past the left edge", '<line x1="-20" y1="5" x2="10" y2="5"/>',+ "past the viewBox left edge"),+ ("circle past the bottom edge", '<circle cx="500" cy="478" r="10"/>',+ "past the viewBox bottom edge"),+ ("polygon past the right edge", '<polygon points="990,10 1010,20 990,30"/>',+ "past the viewBox right edge"),+ ("square-cornered rect past the right edge",+ '<rect x="1100" y="20" width="10" height="10" rx="0" ry="0"/>',+ "past the viewBox right edge"),+ ):+ check_fail(label, static.replace("</svg>", markup + "</svg>", 1), needle)+ for label, markup in (+ ("rect on the viewBox edges", '<rect x="0" y="0" width="1000" height="480"/>'),+ ("overhang within tolerance", '<rect x="990" y="0" width="12" height="5"/>'),+ ("definitions off-canvas", '<defs><rect x="5000" y="5000" width="1" height="1"/></defs>'),+ ("rotated group", '<g transform="rotate(90)"><rect x="5000" y="0" width="1" height="1"/></g>'),+ ("percentage size", '<rect x="0" y="0" width="200%" height="200%"/>'),+ ("display none group", '<g display="none"><rect x="1100" y="20" width="10" height="10"/></g>'),+ ("inline display none", '<rect style="display: none" x="1100" y="20" width="10" height="10"/>'),+ ("visibility hidden group", '<g visibility="hidden"><rect x="1100" y="20" width="10" height="10"/></g>'),+ ("oversized artwork clipped inside the canvas",+ '<clipPath id="inside"><rect x="10" y="10" width="200" height="100"/></clipPath>'+ '<g clip-path="url(#inside)"><rect x="-100" y="20" width="1200" height="40"/></g>'),+ ("masked group", '<g mask="url(#m)"><rect x="1100" y="20" width="10" height="10"/></g>'),+ ("zero-width rect placeholder", '<rect x="1100" y="20" width="0" height="10"/>'),+ ("zero-height rect placeholder", '<rect x="1100" y="20" width="10" height="0"/>'),+ ("zero-radius circle placeholder", '<circle cx="1100" cy="20" r="0"/>'),+ ("zero-radius ellipse placeholder", '<ellipse cx="1100" cy="20" rx="0" ry="5"/>'),+ ):+ check_source_pass(label, static.replace("</svg>", markup + "</svg>", 1))+ def styled(rule: str, markup: str) -> str:+ return static.replace("</style>", rule + "</style>", 1).replace("</svg>", markup + "</svg>", 1)++ placed_rect = '<rect class="placed" x="1100" y="20" width="10" height="10"/>'+ check_source_pass("stylesheet transform moves it inside",+ styled(".placed { transform: translateX(-200px); }", placed_rect))+ check_source_pass("stylesheet display none on an ancestor",+ styled("g.off { display: none; }",+ '<g class="off"><rect x="1100" y="20" width="10" height="10"/></g>'))+ check_source_pass("stylesheet transform under a combinator",+ styled(".motion-ready svg > .placed:hover { transform: none; }", placed_rect))+ check_fail("stylesheet rule that only colors it",+ styled(".placed { fill: #bf4520; }", placed_rect), "past the viewBox right edge")+ check_fail("transform keyframes alone do not exempt it",+ styled("@keyframes slide { 0% { transform: translateX(0); } }", placed_rect),+ "past the viewBox right edge")+ check_source_pass("aria-hidden decorative SVG", static.replace("</body>",+ '<svg aria-hidden="true" viewBox="0 0 10 10"><rect x="50" y="50" width="5" height="5"/></svg></body>', 1))+ outside_assets = []+ for asset in sorted(ASSET_DIR.glob("*.html")):+ viewbox_errors: list[str] = []+ module.check_viewbox(asset.read_text(encoding="utf-8"), viewbox_errors)+ if viewbox_errors:+ outside_assets.append(f"{asset.name}: {viewbox_errors}")+ if outside_assets:+ failures.append(f"shipped assets reported outside their viewBox: {outside_assets}")+ else:+ print("OK: every shipped asset stays inside its viewBox")+# --offline: system-font output must make no network request, so the one# remote stylesheet the default contract allows becomes a failure.if module.verify(STATIC_EXAMPLE, offline=False):diff --git a/skills/diagram-design/SKILL.md b/skills/diagram-design/SKILL.mdindex abc51b6..45dc9ea 100644--- a/skills/diagram-design/SKILL.md+++ b/skills/diagram-design/SKILL.md@@ -297,7 +297,7 @@ Run before producing any diagram.- [ ] `viewBox` expanded for the legend strip (~60px)?- [ ] **`min-width` equals the viewBox width, and the SVG sits in a local `overflow-x: auto` wrapper? (Otherwise a phone scrolls the whole page — or an `overflow: hidden` ancestor clips the diagram with no scrollbar at all. See [output-spec.md](references/output-spec.md).)**- [ ] Node origins, dimensions, gaps, padding on the 4px grid; type sizes on the role ramp?-- [ ] From the installed skill directory, did `python3 scripts/self_check.py <file>` pass? (Accessible-SVG contract, single-file safety, motion basics.)+- [ ] From the installed skill directory, did `python3 scripts/self_check.py <file>` pass? (Accessible-SVG contract, single-file safety, content inside the viewBox, motion basics.)- [ ] If animated, does the complete static/no-JS frame work, does reduced motion hide/disable playback, and is the controller copied verbatim from `assets/template-motion.html`? From a repository checkout, also run `python3 <repo-root>/scripts/verify-motion.py path/to/generated.html` plus the skin linter; from an installed skill, manually check print and static-query states on top of the self-check.**Typography:**diff --git a/skills/diagram-design/scripts/self_check.py b/skills/diagram-design/scripts/self_check.pyindex 46182e2..11cd103 100644--- a/skills/diagram-design/scripts/self_check.py+++ b/skills/diagram-design/scripts/self_check.py@@ -7,8 +7,9 @@ Ships inside the skill so an installed agent can verify its own output:Checks the accessible-SVG contract, the single-file safety rules (no remoteassets beyond the approved Google Fonts stylesheet, no executable attributes,-no scripts other than the one canonical motion controller), and — when motion-markup is present — the structural motion contract. This is a distilled+no scripts other than the one canonical motion controller), painted content+staying inside each SVG's viewBox, and — when motion markup is present — the+structural motion contract. This is a distilledsubset of the repository gates (`lint-skin.py`, `verify-motion.py`), whichremain the authority for contributions to the repository itself."""@@ -57,6 +58,62 @@ REFERENCE_ATTRS = {"action","formaction",}+VIEWBOX_TOLERANCE = 2.0+SVG_NUMBER = r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?"+SVG_NUMBER_RE = re.compile(SVG_NUMBER)+SVG_PLAIN_NUMBER_RE = re.compile(rf"^\s*{SVG_NUMBER}\s*$")+TRANSLATE_RE = re.compile(rf"^\s*translate\(\s*({SVG_NUMBER})(?:[\s,]+({SVG_NUMBER}))?\s*\)\s*$")+# Their children are not painted where they are declared, or use another coordinate system.+UNPAINTED_TAGS = {+ "defs",+ "symbol",+ "marker",+ "pattern",+ "clippath",+ "mask",+ "foreignobject",+ "svg",+}+# CSS that can move, hide or clip an element, so its painted position is not its attributes.+UNSTATIC_CSS_PROPERTIES = {+ "transform",+ "translate",+ "rotate",+ "scale",+ "display",+ "visibility",+ "x",+ "y",+ "cx",+ "cy",+ "r",+ "rx",+ "ry",+ "width",+ "height",+}+UNSTATIC_CSS_PREFIXES = ("animation", "offset", "clip", "mask")+CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)+CSS_KEYFRAMES_RE = re.compile(+ r"@(?:-[a-z]+-)?keyframes[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}", re.IGNORECASE+)+CSS_RULE_RE = re.compile(r"([^{}]+)\{([^{}]*)\}")+CSS_STRING_RE = re.compile(r"\"[^\"]*\"|'[^']*'")+CSS_PARENS_RE = re.compile(r"\([^()]*\)")+CSS_COMBINATOR_RE = re.compile(r"\s*[>+~]\s*|\s+")+CSS_TAG_RE = re.compile(r"^[a-zA-Z][\w-]*")+CSS_CLASS_RE = re.compile(r"\.([\w-]+)")+CSS_ID_RE = re.compile(r"#([\w-]+)")+CSS_ATTRIBUTE_RE = re.compile(r"\[\s*([\w:-]+)")+GEOMETRY_ATTRS = {+ "rect": ("x", "y", "width", "height"),+ "line": ("x1", "y1", "x2", "y2"),+ "circle": ("cx", "cy", "r"),+ "ellipse": ("cx", "cy", "rx", "ry"),+ "polygon": ("points",),+ "polyline": ("points",),+ "text": ("x", "y"),+}class DiagramParser(HTMLParser):@@ -186,6 +243,170 @@ class DiagramParser(HTMLParser):node["text"] = str(node.get("text", "")) + data+class SvgExtent:+ def __init__(self, attrs: dict[str, str]) -> None:+ self.attrs = attrs+ self.points: list[tuple[float, float, str]] = []+++def svg_length(attrs: dict[str, str], name: str, default: float | None = None) -> float | None:+ value = attrs.get(name)+ if value is None:+ return default+ return float(value) if SVG_PLAIN_NUMBER_RE.match(value) else None+++def painted_points(tag: str, attrs: dict[str, str]) -> list[tuple[float, float]]:+ if tag == "rect":+ x, y = svg_length(attrs, "x", 0.0), svg_length(attrs, "y", 0.0)+ width, height = svg_length(attrs, "width"), svg_length(attrs, "height")+ if x is None or y is None or width is None or height is None:+ return []+ if width <= 0 or height <= 0:+ return []+ return [(x, y), (x + width, y + height)]+ if tag == "line":+ ends = [+ (svg_length(attrs, "x1", 0.0), svg_length(attrs, "y1", 0.0)),+ (svg_length(attrs, "x2", 0.0), svg_length(attrs, "y2", 0.0)),+ ]+ return [(x, y) for x, y in ends if x is not None and y is not None]+ if tag in {"circle", "ellipse"}:+ cx, cy = svg_length(attrs, "cx", 0.0), svg_length(attrs, "cy", 0.0)+ rx = svg_length(attrs, "r" if tag == "circle" else "rx")+ ry = svg_length(attrs, "r" if tag == "circle" else "ry")+ if cx is None or cy is None or rx is None or ry is None:+ return []+ if rx <= 0 or ry <= 0:+ return []+ return [(cx - rx, cy - ry), (cx + rx, cy + ry)]+ if tag in {"polygon", "polyline"}:+ numbers = [float(value) for value in SVG_NUMBER_RE.findall(attrs.get("points", ""))]+ return list(zip(numbers[0::2], numbers[1::2]))+ if tag == "text":+ x, y = svg_length(attrs, "x"), svg_length(attrs, "y")+ return [] if x is None or y is None else [(x, y)]+ return []+++def declares_unstatic_css(declarations: str) -> bool:+ for declaration in declarations.split(";"):+ name = declaration.split(":", 1)[0].strip().casefold()+ if name in UNSTATIC_CSS_PROPERTIES or name.startswith(UNSTATIC_CSS_PREFIXES):+ return True+ return False+++def selector_subjects(selector: str) -> list[tuple[str, set[str], set[str], set[str]]]:+ """Tag, classes, IDs and attribute names a selector's last compound requires."""+ subjects = []+ for alternative in CSS_PARENS_RE.sub("", CSS_STRING_RE.sub("", selector)).split(","):+ parts = [part for part in CSS_COMBINATOR_RE.split(alternative.strip()) if part]+ if not parts:+ continue+ compound = parts[-1].split("::", 1)[0]+ tag = CSS_TAG_RE.match(compound)+ subjects.append((+ tag.group(0).casefold() if tag else "",+ set(CSS_CLASS_RE.findall(compound)),+ set(CSS_ID_RE.findall(compound)),+ {name.casefold() for name in CSS_ATTRIBUTE_RE.findall(compound)},+ ))+ return subjects+++def unstatic_css_subjects(source: str) -> list[tuple[str, set[str], set[str], set[str]]]:+ """Selector subjects of stylesheet rules that move, hide or clip what they match.++ Matching keeps only the last compound and drops pseudo-classes, so it can match more+ elements than the browser does. That only skips checks; it never adds a finding.+ """+ styles = re.findall(r"<style\b[^>]*>(.*?)</style\s*>", source, re.IGNORECASE | re.DOTALL)+ sheet = CSS_KEYFRAMES_RE.sub("", CSS_COMMENT_RE.sub("", "\n".join(styles)))+ subjects = []+ for selector, declarations in CSS_RULE_RE.findall(sheet):+ if declares_unstatic_css(declarations):+ subjects.extend(selector_subjects(selector))+ return subjects+++def matches_subject(+ tag: str, attrs: dict[str, str], subject: tuple[str, set[str], set[str], set[str]]+) -> bool:+ subject_tag, classes, ids, attribute_names = subject+ if subject_tag not in {"", "*", tag}:+ return False+ if not classes <= set(attrs.get("class", "").split()):+ return False+ if not ids <= {attrs.get("id", "")}:+ return False+ return attribute_names <= set(attrs)+++def child_offset(+ tag: str,+ attrs: dict[str, str],+ parent: tuple[float, float] | None,+ css_subjects: list[tuple[str, set[str], set[str], set[str]]],+) -> tuple[float, float] | None:+ """Offset of an element in viewBox units, or None when its paint is not static."""+ if parent is None or tag in UNPAINTED_TAGS:+ return None+ if declares_unstatic_css(attrs.get("style", "")):+ return None+ if attrs.get("display", "").strip().casefold() == "none":+ return None+ if attrs.get("visibility", "").strip().casefold() in {"hidden", "collapse"}:+ return None+ if attrs.get("clip-path", "none").strip().casefold() != "none":+ return None+ if attrs.get("mask", "none").strip().casefold() != "none":+ return None+ if any(matches_subject(tag, attrs, subject) for subject in css_subjects):+ return None+ transform = attrs.get("transform")+ if transform is None:+ return parent+ match = TRANSLATE_RE.match(transform)+ if match is None:+ return None+ return parent[0] + float(match.group(1)), parent[1] + float(match.group(2) or 0)+++class ViewBoxParser(HTMLParser):+ def __init__(self, css_subjects: list[tuple[str, set[str], set[str], set[str]]]) -> None:+ super().__init__(convert_charrefs=True)+ self.svgs: list[SvgExtent] = []+ self._css_subjects = css_subjects+ self._frames: list[tuple[str, tuple[float, float] | None]] = []++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ tag = tag.casefold()+ data = {key.casefold(): value or "" for key, value in attrs}+ if not self._frames:+ if tag == "svg":+ self.svgs.append(SvgExtent(data))+ self._frames.append((tag, (0.0, 0.0)))+ return+ offset = child_offset(tag, data, self._frames[-1][1], self._css_subjects)+ self._frames.append((tag, offset))+ if offset is None:+ return+ label = " ".join(+ [f"<{tag}"]+ + [f'{name}="{data[name]}"' for name in GEOMETRY_ATTRS.get(tag, ()) if name in data]+ ) + ">"+ for x, y in painted_points(tag, data):+ self.svgs[-1].points.append((x + offset[0], y + offset[1], label))++ def handle_endtag(self, tag: str) -> None:+ tag = tag.casefold()+ for index in range(len(self._frames) - 1, -1, -1):+ if self._frames[index][0] == tag:+ del self._frames[index:]+ return++def normalized_controller(body: str) -> str:return body.replace("\r\n", "\n").replace("\r", "\n").strip()@@ -317,6 +538,35 @@ def check_svgs(parser: DiagramParser, errors: list[str]) -> None:errors.append(f"svg {number} aria-labelledby must name title then desc")+def check_viewbox(source: str, errors: list[str]) -> None:+ parser = ViewBoxParser(unstatic_css_subjects(source))+ parser.feed(source)+ parser.close()+ checkable = [+ svg for svg in parser.svgs if svg.attrs.get("aria-hidden", "").casefold() != "true"+ ]+ for number, svg in enumerate(checkable, 1):+ box = [float(value) for value in SVG_NUMBER_RE.findall(svg.attrs.get("viewbox", ""))]+ if len(box) != 4 or box[2] <= 0 or box[3] <= 0:+ continue+ left, top, width, height = box+ worst: dict[str, tuple[float, str]] = {}+ for x, y, label in svg.points:+ for side, overshoot in (+ ("left", left - x),+ ("top", top - y),+ ("right", x - (left + width)),+ ("bottom", y - (top + height)),+ ):+ if overshoot > VIEWBOX_TOLERANCE and overshoot > worst.get(side, (0.0, ""))[0]:+ worst[side] = (overshoot, label)+ for side, (overshoot, label) in worst.items():+ errors.append(+ f"svg {number}: {label} paints {overshoot:g}px past the viewBox {side} edge "+ "and is clipped; grow the viewBox or move the content inside it"+ )++def check_scripts(parser: DiagramParser, errors: list[str]) -> None:if not parser.scripts:return@@ -438,6 +688,7 @@ def verify(path: Path, offline: bool = False) -> list[str]:"offline: file loads Google Fonts; remove the font <link> to use system fonts")check_svgs(parser, errors)+ check_viewbox(source, errors)check_scripts(parser, errors)check_motion(parser, source, errors)return errors