Skip to content

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.

refactor(export): package Playwright PNG renderer (#354)

Thomas Chauchefoin5695d3dcd5e9
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bf99da3..9247e7e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -58,7 +58,7 @@ Every validation gate below must pass before a PR is ready. They also run automa
| Every shipped motion template/example | `python3 scripts/verify-motion.py --shipped` |
| Docs/routing sync (description hooks, gallery, README tree, reference links and style-guide anchors, strict-bundler support paths, command/prompt surfaces, font-link parity, template title fallback order, SKILL.md split routing) | `python3 scripts/verify-docs-sync.py && python3 scripts/test-verify-docs-sync.py` |
| Canonical README screenshots match their example HTML sources and recorded PNG digests | `python3 scripts/verify-screenshot-freshness.py` |
-| Export snippet's stalled-webfont fallback (window.stop on timeout, warning, normal load) | `python3 scripts/test-export-wait.py` (requires Playwright; skips without it) |
+| Packaged PNG exporter's stalled-webfont fallback (window.stop on timeout, warning, normal load) | `python3 scripts/test-export-wait.py` (requires Playwright; skips without it) |
| Screenshot freshness checker behaves (CRLF checkout, real source drift, raw PNG digests) | `python3 scripts/test-verify-screenshot-freshness.py` |
| README WebP previews match their PNGs, manifest, dimensions, and full-size links | `python3 scripts/test-build-readme-thumbs.py && python3 scripts/build-readme-thumbs.py --check` (requires `Pillow==12.1.1`) |
| Packaged output self-check behaves (pass + adversarial cases, including `--offline`) | `python3 scripts/test-self-check.py` |
diff --git a/README.md b/README.md
index f3f2eab..974bba8 100644
--- a/README.md
+++ b/README.md
@@ -589,6 +589,7 @@ diagram-design/
│ │ ├── mermaid_extract.py # Mermaid → structured IR
│ │ ├── excalidraw_extract.py # Excalidraw → structured IR
│ │ ├── export_svg.py # standalone SVG export
+│ │ ├── export_png.py # Playwright PNG renderer
│ │ └── self_check.py # packaged output self-check (runs installed)
│ └── assets/
│ ├── index.html # live gallery, tabbed
diff --git a/commands/export-diagram.md b/commands/export-diagram.md
index 6fc2d21..0a25630 100644
--- a/commands/export-diagram.md
+++ b/commands/export-diagram.md
@@ -9,7 +9,7 @@ allowed-tools:
- Glob
---
-Export the diagram HTML at `$1` to `.svg` and/or `.png`, following the procedure documented in [`skills/diagram-design/references/export.md`](../skills/diagram-design/references/export.md). Treat that reference as the source of truth — don't reimplement the logic here. For SVG output, prefer running the packaged helper at `skills/diagram-design/scripts/export_svg.py` when available (it implements the CSS carry-forward and defs ID namespacing steps). If `--registry` is present, also follow [`skills/diagram-design/references/export-registry.md`](../skills/diagram-design/references/export-registry.md) to emit the metadata sidecar — a separate procedure from the SVG/PNG rasterization above.
+Export the diagram HTML at `$1` to `.svg` and/or `.png`, following the procedure documented in [`skills/diagram-design/references/export.md`](../skills/diagram-design/references/export.md). Treat that reference as the source of truth — don't reimplement the logic here. Run the packaged `skills/diagram-design/scripts/export_svg.py` and `skills/diagram-design/scripts/export_png.py` helpers for the requested formats. If `--registry` is present, also follow [`skills/diagram-design/references/export-registry.md`](../skills/diagram-design/references/export-registry.md) to emit the metadata sidecar — a separate procedure from the SVG/PNG rasterization above.
Full argument string: `$ARGUMENTS`
diff --git a/prompts/export-diagram.md b/prompts/export-diagram.md
index 7c20f08..e5d497c 100644
--- a/prompts/export-diagram.md
+++ b/prompts/export-diagram.md
@@ -3,7 +3,7 @@ description: Export a diagram-design HTML file to SVG and PNG
argument-hint: "<html-file> [--svg-only|--png-only] [--scale=N] [--output=<path>] [--registry]"
---
-Export diagram HTML at `$1` to `.svg` or `.png`. Locate available `diagram-design` skill using its `SKILL.md` path advertised by Pi. Read that `SKILL.md`, then read `references/export.md` relative to its directory. Treat that reference as source of truth. For SVG output, prefer `scripts/export_svg.py` relative to the skill directory when available. Do not assume the package lives under the current working directory. If `--registry` is present, also read `references/export-registry.md` relative to the same directory and follow it to emit the metadata sidecar — a separate procedure from the SVG/PNG rasterization above.
+Export diagram HTML at `$1` to `.svg` or `.png`. Locate available `diagram-design` skill using its `SKILL.md` path advertised by Pi. Read that `SKILL.md`, then read `references/export.md` relative to its directory. Treat that reference as source of truth. Run `scripts/export_svg.py` and `scripts/export_png.py` relative to the skill directory for the requested formats. Do not assume the package lives under the current working directory. If `--registry` is present, also read `references/export-registry.md` relative to the same directory and follow it to emit the metadata sidecar — a separate procedure from the SVG/PNG rasterization above.
Full argument string: `$ARGUMENTS`
diff --git a/scripts/lint-render.py b/scripts/lint-render.py
index 1e425c9..4fe8f6e 100755
--- a/scripts/lint-render.py
+++ b/scripts/lint-render.py
@@ -61,9 +61,8 @@ layer. ``--fonts`` excludes exactly the two Google Fonts hostnames from the
resolver block and allows them only over HTTPS on an exact hostname match.
``--self-test`` proves the isolation against a local listener.
-One check sits outside that browser: ``--all`` and ``--self-test`` run the PNG
-rasterize snippet from ``references/export.md`` in a subprocess, the way the doc
-tells a user to, on local fixtures (the shipped templates re-drawn at a wide
+One check sits outside that browser: ``--all`` and ``--self-test`` run the
+packaged PNG renderer in a subprocess, the way the doc tells a user to, on local fixtures (the shipped templates re-drawn at a wide
preset, with every remote ``<link>`` removed). That subprocess's Chromium is not
under the resolver block, which is why the fixtures carry no remote references.
@@ -93,7 +92,7 @@ from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parent.parent
ASSET_DIR = ROOT / "skills/diagram-design/assets"
-EXPORT_DOC = ROOT / "skills/diagram-design/references/export.md"
+EXPORT_PNG = ROOT / "skills/diagram-design/scripts/export_png.py"
VIEWPORT = {"width": 1600, "height": 1000}
TOLERANCE = 1.0 # px of slop before page overflow counts, absorbs subpixel layout
@@ -1171,15 +1170,6 @@ async ([src, probe, viewBoxWidth]) => {
"""
-def export_recipe():
- """The PNG rasterize snippet from export.md, found by heading, not position."""
- text = EXPORT_DOC.read_text(encoding="utf-8")
- match = re.search(r"^### Rasterize[ \t]*\n(.*?)^```python\n(.*?)^```", text, re.M | re.S)
- if match is None or re.search(r"^#{1,3} ", match.group(1), re.M):
- return None
- return match.group(2)
-
-
def wide_preset_fixture(html):
"""Re-draw a template at the widest preset the way output-spec.md says:
viewBox and min-width both at the preset width, plus a probe node at the
@@ -1197,27 +1187,24 @@ def wide_preset_fixture(html):
return re.sub(r"<link\b[^>]*\bhref=\"https?://[^>]*>", "", html)
-def export_png_failures(context, label, html, recipe):
- """Run export.md's rasterize recipe on ``html`` exactly as the doc says
- (snippet in a temp file, ``python <tmp.py> <src.html> <out.png> 1``) and
+def export_png_failures(context, label, html):
+ """Run the packaged PNG renderer on ``html`` exactly as the doc says and
report a PNG that is not the full viewBox width or does not paint the probe."""
with tempfile.TemporaryDirectory() as directory:
directory_path = Path(directory)
- script = directory_path / "rasterize.py"
source = directory_path / "wide-preset.html"
out = directory_path / "wide-preset.png"
- script.write_text(recipe, encoding="utf-8")
source.write_text(html, encoding="utf-8")
try:
run = subprocess.run(
- [sys.executable, str(script), str(source), str(out), "1"],
+ [sys.executable, str(EXPORT_PNG), str(source), str(out), "1"],
capture_output=True, text=True, timeout=EXPORT_TIMEOUT,
)
except subprocess.TimeoutExpired:
- return [f"{label}: template-export: the export.md recipe did not finish in {EXPORT_TIMEOUT}s"]
+ return [f"{label}: template-export: the packaged renderer did not finish in {EXPORT_TIMEOUT}s"]
if run.returncode != 0 or not out.is_file():
tail = (run.stderr.strip().splitlines() or ["no output"])[-1]
- return [f"{label}: template-export: the export.md recipe failed: {tail}"]
+ return [f"{label}: template-export: the packaged renderer failed: {tail}"]
png = out.read_bytes()
page = context.new_page()
try:
@@ -1246,14 +1233,12 @@ def template_export_failures(context, template_paths=None):
min-width equal to the viewBox width makes a 1280 SVG wider than the 1200px
frame, so the local scroller (and the terminal's overflow:hidden chrome)
- clips it on screen. The rasterize recipe screenshots the SVG's box, and
+ clips it on screen. The packaged renderer screenshots the SVG's box, and
whatever an ancestor clipped is simply not in the PNG: full size, blank on
- the right, no error. This runs the recipe from export.md itself, so the
- check follows the doc rather than a copy of it.
+ the right, no error. This runs the packaged helper named by export.md.
"""
- recipe = export_recipe()
- if recipe is None:
- return [f"{display_path(EXPORT_DOC)}: template-export: no ```python block under ### Rasterize"]
+ if not EXPORT_PNG.is_file():
+ return [f"{display_path(EXPORT_PNG)}: template-export: packaged renderer is missing"]
paths = template_paths or sorted(ASSET_DIR.glob("template*.html"))
failures = []
for path in paths:
@@ -1265,7 +1250,7 @@ def template_export_failures(context, template_paths=None):
"(needs one viewBox=\"0 0 W H\" and one `min-width: Wpx`)"
)
continue
- failures += export_png_failures(context, shown_path, fixture, recipe)
+ failures += export_png_failures(context, shown_path, fixture)
return failures
@@ -1540,9 +1525,8 @@ def self_test(context):
# frame, held in a local scroller, must come out whole, and a probe node that
# really is cut off (clip-path, which export does not release) must be reported.
checks += 2
- recipe = export_recipe()
- if recipe is None:
- failures.append("template-export: no python snippet under ### Rasterize in export.md")
+ if not EXPORT_PNG.is_file():
+ failures.append("template-export: packaged PNG renderer is missing")
else:
wide_page = (
'<!DOCTYPE html><html><style>body{{margin:0;padding:32px;background:#f5f5f5}}'
@@ -1556,18 +1540,17 @@ def self_test(context):
+ "</svg></div></div></body></html>"
)
scroller_failures = export_png_failures(
- context, "template-export-scroller-fixture", wide_page.format(clip=""), recipe
+ context, "template-export-scroller-fixture", wide_page.format(clip="")
)
if scroller_failures:
failures.append(
- f"template-export-scroller-fixture: the recipe clipped a {WIDE_PRESET[0]}-wide SVG held in a "
+ f"template-export-scroller-fixture: the renderer clipped a {WIDE_PRESET[0]}-wide SVG held in a "
"local scroller: " + "; ".join(scroller_failures)
)
clipped_failures = export_png_failures(
context,
"template-export-clipped-fixture",
wide_page.format(clip=' style="clip-path:inset(0 160px 0 0)"'),
- recipe,
)
if not any("is missing from the PNG" in f for f in clipped_failures):
failures.append("template-export-clipped-fixture: a cut-off probe node was not reported")
diff --git a/scripts/test-export-wait.py b/scripts/test-export-wait.py
index 315999b..1e257df 100644
--- a/scripts/test-export-wait.py
+++ b/scripts/test-export-wait.py
@@ -1,13 +1,14 @@
#!/usr/bin/env python3
-"""Deterministic tests for the export snippet's stalled-load fallback.
+"""Deterministic tests for the packaged PNG exporter's stalled-load fallback.
-Drives the exact python snippet shipped in
-skills/diagram-design/references/export.md against local fixtures:
+Drives ``skills/diagram-design/scripts/export_png.py`` against local fixtures:
-- a stalled stylesheet request is cancelled with window.stop(), the snippet
+- a stalled stylesheet request is cancelled with window.stop(), the renderer
warns about fallback typography, and capture completes quickly;
- an actual stalled font download is cancelled and font readiness finishes;
- a normal load captures cleanly with no warning;
+- fractional scales produce exact viewBox-sized PNGs; invalid scales and
+ viewBoxes fail;
- non-timeout errors are not swallowed by the fallback.
Requires Playwright (and its Chromium); skips otherwise, matching the export
@@ -17,11 +18,12 @@ procedure's own detection step.
from __future__ import annotations
import contextlib
+import importlib.util
import io
import re
+import struct
import subprocess
import sys
-import struct
import tempfile
import threading
import time
@@ -29,11 +31,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
-EXPORT_DOC = ROOT / "skills/diagram-design/references/export.md"
+EXPORT_PNG = ROOT / "skills/diagram-design/scripts/export_png.py"
-# Fast-but-deterministic substitutes for the snippet's production waits.
-FAST_IDLE_TIMEOUT = "timeout=1500"
-FAST_SETTLE = "wait_for_timeout(150)"
+# Fast-but-deterministic substitutes for the renderer's production waits.
+FAST_IDLE_TIMEOUT_MS = 1_500
+FAST_SETTLE_MS = 150
STALL_HOLD_SECONDS = 30 # must outlast the test's networkidle timeout
WARNING_ANCHOR = "fallback typography"
# The full fallback (fast timeout + settle + capture) must stay far below the
@@ -41,84 +43,29 @@ WARNING_ANCHOR = "fallback typography"
FALLBACK_BUDGET_SECONDS = 15.0
-RASTERIZE_HEADING = re.compile(r"^### Rasterize\b.*$", re.M)
-NEXT_HEADING = re.compile(r"^#{1,3} ", re.M)
-PYTHON_FENCE = re.compile(r"^( *)```python[ \t]*\n(.*?)^\1```[ \t]*$", re.M | re.S)
-
-
-def select_rasterize_block(text: str) -> str:
- """Return the python block under the Rasterize heading.
-
- export.md carries other python blocks (the SVG color normalization, for
- one), so the snippet is located by its section and by the code it runs,
- never by counting blocks in the whole file.
- """
- heading = RASTERIZE_HEADING.search(text)
- if heading is None:
- raise AssertionError(f"{EXPORT_DOC.name} has no '### Rasterize' section")
- section = text[heading.end():]
- following = NEXT_HEADING.search(section)
- if following is not None:
- section = section[: following.start()]
- blocks = [
- "\n".join(line[len(indent):] for line in body.splitlines()) + "\n"
- for indent, body in PYTHON_FENCE.findall(section)
- ]
- if len(blocks) != 1:
- raise AssertionError(
- "expected exactly one python block in the Rasterize section of "
- f"{EXPORT_DOC.name}, found {len(blocks)}"
- )
- if "sync_playwright" not in blocks[0]:
- raise AssertionError(
- "the Rasterize section's python block does not use sync_playwright"
- )
- return blocks[0]
-
-
-def require_block_selection() -> None:
- """The selector must ignore python blocks outside the Rasterize section."""
- rasterize = (
- "### Rasterize\n\nRun this:\n\n```python\n"
- "from playwright.sync_api import sync_playwright\nprint('rasterize')\n"
- "```\n\nAfter the block.\n"
- )
- other = " ```python\n import re\n svg = re.sub('a', 'b', 'a')\n ```\n"
- doc = (
- "# Export\n\n## SVG export procedure\n\n4. Normalize colors:\n\n"
- f"{other}\n## PNG export procedure\n\n{rasterize}\n"
- "### Output naming\n\n```python\nprint('later block')\n```\n"
- )
- selected = select_rasterize_block(doc)
- if "print('rasterize')" not in selected or "re.sub" in selected or "later block" in selected:
- raise AssertionError(f"selector picked the wrong python block:\n{selected}")
- try:
- select_rasterize_block(doc.replace("### Rasterize", "### Capture"))
- except AssertionError:
- pass
- else:
- raise AssertionError("selector accepted a doc with no Rasterize section")
- print("OK: snippet selector finds the Rasterize block among other python blocks")
-
-
-def load_snippet() -> str:
- snippet = select_rasterize_block(EXPORT_DOC.read_text(encoding="utf-8"))
+def load_exporter():
+ source = EXPORT_PNG.read_text(encoding="utf-8")
for anchor in (
"except PlaywrightTimeoutError:",
'page.evaluate("window.stop()")',
- WARNING_ANCHOR,
- "timeout=15000",
+ "NETWORK_IDLE_TIMEOUT_MS = 15_000",
+ "?motion=static",
+ "document.fonts.ready",
+ "[data-motion-root]",
):
- if anchor not in snippet:
- raise AssertionError(
- f"export snippet is missing required anchor {anchor!r}"
- )
- if "except Exception" in snippet or re.search(r"except\s*:", snippet):
+ if anchor not in source:
+ raise AssertionError(f"packaged exporter is missing required anchor {anchor!r}")
+ if "except Exception" in source or "except:" in source:
raise AssertionError(
- "export snippet must not swallow non-timeout errors with a "
+ "packaged exporter must not swallow non-timeout errors with a "
"broad or bare except"
)
- return snippet
+ spec = importlib.util.spec_from_file_location("diagram_export_png", EXPORT_PNG)
+ if spec is None or spec.loader is None:
+ raise AssertionError(f"could not import {EXPORT_PNG}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
class _StallHandler(BaseHTTPRequestHandler):
@@ -142,31 +89,76 @@ def start_stall_server(handler: type[BaseHTTPRequestHandler] = _StallHandler) ->
return server
-def run_snippet(snippet: str, src: Path, out: Path, scale: str | None = None) -> str:
- """Exec the doc snippet with the given argv; return captured stderr."""
+def run_export(exporter, src: Path, out: Path, **kwargs: int) -> str:
+ """Run the packaged renderer and return captured stderr."""
stderr = io.StringIO()
- old_argv, old_stderr = sys.argv, sys.stderr
- sys.argv = ["export", str(src), str(out)] + ([scale] if scale is not None else [])
- try:
- with contextlib.redirect_stderr(stderr):
- exec(compile(snippet, str(EXPORT_DOC), "exec"), {"__name__": "export_snippet"})
- finally:
- sys.argv, sys.stderr = old_argv, old_stderr
+ with contextlib.redirect_stderr(stderr):
+ exporter.rasterize(src, out, 2, **kwargs)
return stderr.getvalue()
+def run_export_with_timeout(src: Path, out: Path) -> str:
+ """Run the packaged renderer with fast waits in a killable subprocess."""
+ runner = """
+import importlib.util
+import pathlib
+import sys
+
+spec = importlib.util.spec_from_file_location("diagram_export_png", sys.argv[1])
+module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+module.rasterize(
+ pathlib.Path(sys.argv[2]),
+ pathlib.Path(sys.argv[3]),
+ 2,
+ network_idle_timeout_ms=int(sys.argv[4]),
+ fallback_settle_ms=int(sys.argv[5]),
+)
+"""
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ runner,
+ str(EXPORT_PNG),
+ str(src),
+ str(out),
+ str(FAST_IDLE_TIMEOUT_MS),
+ str(FAST_SETTLE_MS),
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=FALLBACK_BUDGET_SECONDS,
+ )
+ return result.stderr
+
+
def require_png(out: Path, name: str) -> None:
if not out.exists() or out.stat().st_size == 0:
raise AssertionError(f"{name}: expected a non-empty screenshot at {out}")
-def require_stalled_fallback(snippet: str, tmp: Path) -> None:
- fast = snippet.replace("timeout=15000", FAST_IDLE_TIMEOUT).replace(
- "wait_for_timeout(4000)", FAST_SETTLE
+def run_cli_without_scale(src: Path, out: Path) -> str:
+ run = subprocess.run(
+ [sys.executable, str(EXPORT_PNG), str(src), str(out)],
+ capture_output=True,
+ text=True,
+ timeout=FALLBACK_BUDGET_SECONDS,
)
- if fast == snippet:
- raise AssertionError("could not shorten the snippet's production waits for the test")
+ if run.returncode != 0:
+ raise AssertionError(f"normal-load: packaged renderer failed\n{run.stderr}")
+ return run.stderr
+
+
+def png_dimensions(out: Path) -> tuple[int, int]:
+ png = out.read_bytes()
+ if not png.startswith(b"\x89PNG\r\n\x1a\n") or len(png) < 24:
+ raise AssertionError("normal-load: renderer did not produce a valid PNG header")
+ return struct.unpack(">II", png[16:24])
+
+def require_stalled_fallback(tmp: Path) -> None:
server = start_stall_server()
try:
port = server.server_address[1]
@@ -187,7 +179,7 @@ def require_stalled_fallback(snippet: str, tmp: Path) -> None:
out = tmp / "stall-fixture.png"
started = time.monotonic()
- stderr = run_snippet(fast, src, out)
+ stderr = run_export_with_timeout(src, out)
elapsed = time.monotonic() - started
require_png(out, "stalled-fallback")
@@ -210,10 +202,7 @@ def require_stalled_fallback(snippet: str, tmp: Path) -> None:
server.server_close()
-def require_stalled_font_fallback(snippet: str, tmp: Path) -> None:
- fast = snippet.replace("timeout=15000", FAST_IDLE_TIMEOUT).replace(
- "wait_for_timeout(4000)", FAST_SETTLE
- )
+def require_stalled_font_fallback(tmp: Path) -> None:
font_requested = threading.Event()
class FontStallHandler(_StallHandler):
@@ -238,12 +227,7 @@ def require_stalled_font_fallback(snippet: str, tmp: Path) -> None:
)
out = tmp / "stalled-font.png"
started = time.monotonic()
- result = subprocess.run(
- [sys.executable, "-c", fast, str(src), str(out)],
- capture_output=True, text=True, check=True,
- timeout=FALLBACK_BUDGET_SECONDS,
- )
- stderr = result.stderr
+ stderr = run_export_with_timeout(src, out)
elapsed = time.monotonic() - started
if not font_requested.is_set():
raise AssertionError("stalled-font: fixture never started its font download")
@@ -263,7 +247,7 @@ def require_stalled_font_fallback(snippet: str, tmp: Path) -> None:
server.server_close()
-def require_normal_load(snippet: str, tmp: Path) -> None:
+def require_normal_load(exporter, tmp: Path) -> None:
src = tmp / "normal-fixture.html"
src.write_text(
"<!doctype html>\n<html>\n<head>\n<meta charset='utf-8'>\n</head>\n<body>\n"
@@ -278,15 +262,19 @@ def require_normal_load(snippet: str, tmp: Path) -> None:
)
out = tmp / "normal-fixture.png"
- stderr = run_snippet(snippet, src, out)
+ stderr = run_cli_without_scale(src, out)
require_png(out, "normal-load")
+ if png_dimensions(out) != (800, 480):
+ raise AssertionError(
+ "normal-load: omitted CLI scale did not produce the default 2x dimensions"
+ )
if WARNING_ANCHOR in stderr:
raise AssertionError(f"normal-load: fallback warning fired unexpectedly\n{stderr}")
print("OK: normal load captures with no fallback warning")
-def require_encoded_paths(snippet: str, tmp: Path) -> None:
+def require_encoded_paths(exporter, tmp: Path) -> None:
# Both characters are legal filename content, not a URL fragment/escape.
original = tmp / "normal-fixture.html"
for filename in ("diagram #1.html", "diagram %25.html", "diagram ?draft.html"):
@@ -296,21 +284,32 @@ def require_encoded_paths(snippet: str, tmp: Path) -> None:
source = tmp / filename
source.write_text(original.read_text(encoding="utf-8"), encoding="utf-8")
output = tmp / (filename + ".png")
- stderr = run_snippet(snippet, source, output)
+ stderr = run_export(exporter, source, output)
require_png(output, filename)
if stderr:
raise AssertionError(f"encoded-path capture emitted a warning: {stderr}")
print("OK: legal filename characters are encoded in the file URL")
-def require_fractional_scales(snippet: str, tmp: Path) -> None:
+def run_cli_with_scale(src: Path, out: Path, scale: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, str(EXPORT_PNG), str(src), str(out), scale],
+ capture_output=True,
+ text=True,
+ timeout=FALLBACK_BUDGET_SECONDS,
+ )
+
+
+def require_fractional_scales(exporter, tmp: Path) -> None:
source = tmp / "normal-fixture.html" # 400 by 240 viewBox units
# Page layout must not change dimensions promised by the viewBox contract.
source.write_text(source.read_text(encoding="utf-8").replace("</head>", "<style>svg { width:1200px; min-width:1200px; height:auto; }</style></head>"), encoding="utf-8")
for scale, dimensions in (("1", (400, 240)), ("1.25", (500, 300)),
("1.5", (600, 360)), ("3", (1200, 720)), ("4", (1600, 960))):
output = tmp / f"scale-{scale}.png"
- run_snippet(snippet, source, output, scale)
+ run = run_cli_with_scale(source, output, scale)
+ if run.returncode != 0:
+ raise AssertionError(f"scale {scale}: packaged renderer failed\n{run.stderr}")
require_png(output, scale)
actual = struct.unpack(">II", output.read_bytes()[16:24])
if actual != dimensions:
@@ -320,7 +319,7 @@ def require_fractional_scales(snippet: str, tmp: Path) -> None:
broken.write_text(source.read_text(encoding="utf-8").replace("viewBox='0 0 400 240'", f"viewBox='{viewbox}'"), encoding="utf-8")
output = tmp / "invalid-viewbox.png"
try:
- run_snippet(snippet, broken, output, "2")
+ run_export(exporter, broken, output)
except Exception as exc:
if "viewBox" not in str(exc) or output.exists():
raise AssertionError(f"invalid viewBox failed incorrectly: {exc}")
@@ -328,21 +327,21 @@ def require_fractional_scales(snippet: str, tmp: Path) -> None:
raise AssertionError(f"invalid viewBox {viewbox!r} was accepted")
for scale in ("0.5", "4.1", "nan", "inf", "not-a-number"):
output = tmp / "invalid-scale.png"
- try:
- run_snippet(snippet, source, output, scale)
- except ValueError:
- if output.exists():
- raise AssertionError(f"invalid scale {scale} wrote a PNG")
- else:
+ run = run_cli_with_scale(source, output, scale)
+ if run.returncode == 0:
raise AssertionError(f"invalid scale {scale} was accepted")
+ if "scale" not in run.stderr:
+ raise AssertionError(f"invalid scale {scale} failed without a scale diagnostic\n{run.stderr}")
+ if output.exists():
+ raise AssertionError(f"invalid scale {scale} wrote a PNG")
print("OK: fractional scales produce exact dimensions; invalid scales fail")
-def require_other_errors_propagate(snippet: str, tmp: Path) -> None:
+def require_other_errors_propagate(exporter, tmp: Path) -> None:
missing = tmp / "does-not-exist.html"
out = tmp / "never.png"
try:
- run_snippet(snippet, missing, out)
+ run_export(exporter, missing, out)
except Exception as exc:
if type(exc).__name__ == "TimeoutError":
raise AssertionError(
@@ -355,20 +354,15 @@ def require_other_errors_propagate(snippet: str, tmp: Path) -> None:
-def require_static_motion_frame(snippet: str, tmp: Path) -> None:
+def require_static_motion_frame(exporter, tmp: Path) -> None:
# Exercise the exact shipped controller, avoiding external font requests.
source = (ROOT / "skills/diagram-design/assets/example-policy-trace-animated.html").read_text(encoding="utf-8")
source = re.sub(r"<link\b[^>]*>", "", source, flags=re.I)
src = tmp / "motion-fixture.html"
src.write_text(source, encoding="utf-8")
- observed = snippet.replace(
- " svg.screenshot(path=out, omit_background=True)",
- " assert page.locator('[data-motion-root]').first.get_attribute('data-frame') == 'static', 'motion frame is incomplete'\n"
- " svg.screenshot(path=out, omit_background=True)",
- )
first, second = tmp / "motion-first.png", tmp / "motion-second.png"
- run_snippet(observed, src, first)
- run_snippet(observed, src, second)
+ run_export(exporter, src, first)
+ run_export(exporter, src, second)
require_png(first, "static-motion")
if first.read_bytes() != second.read_bytes():
raise AssertionError("motion captures from the same static source are not identical")
@@ -379,7 +373,7 @@ def require_static_motion_frame(snippet: str, tmp: Path) -> None:
src.write_text(broken, encoding="utf-8")
never = tmp / "incomplete.png"
try:
- run_snippet(snippet, src, never)
+ run_export(exporter, src, never)
except RuntimeError as exc:
if "static" not in str(exc) or never.exists():
raise AssertionError(f"incomplete motion frame failed incorrectly: {exc}")
@@ -391,20 +385,19 @@ def main() -> int:
try:
import playwright # noqa: F401
except ImportError:
- print("SKIP: playwright is not installed; export snippet tests skipped")
+ print("SKIP: playwright is not installed; packaged export tests skipped")
return 0
- require_block_selection()
- snippet = load_snippet()
+ exporter = load_exporter()
with tempfile.TemporaryDirectory(prefix="diagram-export-wait-") as raw_tmp:
tmp = Path(raw_tmp)
- require_stalled_fallback(snippet, tmp)
- require_stalled_font_fallback(snippet, tmp)
- require_normal_load(snippet, tmp)
- require_encoded_paths(snippet, tmp)
- require_fractional_scales(snippet, tmp)
- require_other_errors_propagate(snippet, tmp)
- require_static_motion_frame(snippet, tmp)
+ require_stalled_fallback(tmp)
+ require_stalled_font_fallback(tmp)
+ require_normal_load(exporter, tmp)
+ require_encoded_paths(exporter, tmp)
+ require_fractional_scales(exporter, tmp)
+ require_other_errors_propagate(exporter, tmp)
+ require_static_motion_frame(exporter, tmp)
print("All export-wait cases passed.")
return 0
diff --git a/scripts/verify-docs-sync.py b/scripts/verify-docs-sync.py
index 9c6c284..a8f5f5c 100644
--- a/scripts/verify-docs-sync.py
+++ b/scripts/verify-docs-sync.py
@@ -125,6 +125,7 @@ REQUIRED_PACKAGED_RUNTIME_FILES = frozenset(
"scripts/mermaid_extract.py",
"scripts/excalidraw_extract.py",
"scripts/export_svg.py",
+ "scripts/export_png.py",
"assets/template.html",
"assets/template-dark.html",
"assets/template-full.html",
diff --git a/skills/diagram-design/SKILL.md b/skills/diagram-design/SKILL.md
index 359a320..e1277f1 100644
--- a/skills/diagram-design/SKILL.md
+++ b/skills/diagram-design/SKILL.md
@@ -389,6 +389,6 @@ Every diagram is an accessible figure by default (long form: [primitives-core.md
### Exporting to PNG / SVG
-When the user asks to export, save, rasterize, or convert a generated diagram to `.png` or `.svg`, load [`references/export.md`](references/export.md) and follow the procedure there. For the SVG half, prefer the packaged helper `scripts/export_svg.py` (it carries class-based CSS into the fragment and namespaces `<defs>` IDs so exports stay inline-safe). Both formats deliver the diagram only (the `<svg>` node) — editorial wrappers like cards and headers are dropped by design. Export is **manual** — never produce export files unprompted.
+When the user asks to export, save, rasterize, or convert a generated diagram to `.png` or `.svg`, load [`references/export.md`](references/export.md) and follow the procedure there. Run the packaged helpers `scripts/export_svg.py` and `scripts/export_png.py`; the reference owns their arguments and availability checks. Both formats deliver the diagram only (the `<svg>` node) — editorial wrappers like cards and headers are dropped by design. Export is **manual** — never produce export files unprompted.
For an imported diagram, pixel dimensions come from the `viewBox` × scale factor, so its size decision belongs to §11, not to export. For any diagram that needs an exact frame (an OG card or a slide image), see [`export.md` § Sizing the export](references/export.md).
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index 6ec9df9..93aaac0 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -309,58 +309,17 @@ Don't auto-install. The user asked for one feature, not a system change.
### Rasterize
-Write the snippet below to a temp file and run it with the interpreter that
-passed detection: `python3 <tmp.py> <src.html> <out.png>` or
-`python <tmp.py> <src.html> <out.png>`:
-
-```python
-from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright
-import sys, pathlib, math
-
-src, out = sys.argv[1], sys.argv[2]
-scale = float(sys.argv[3]) if len(sys.argv) > 3 else 2
-if not math.isfinite(scale) or not 1 <= scale <= 4:
- raise ValueError("PNG scale must be a finite number between 1 and 4")
-
-with sync_playwright() as p:
- browser = p.chromium.launch()
- page = browser.new_page(device_scale_factor=scale)
- page.goto(pathlib.Path(src).resolve().as_uri() + "?motion=static", wait_until="domcontentloaded")
- try:
- page.wait_for_load_state("networkidle", timeout=15000)
- except PlaywrightTimeoutError:
- # proxied networks may stall webfont subrequests past any deadline;
- # cancel the outstanding load so the capture below can't block on it again
- page.evaluate("window.stop()")
- page.wait_for_timeout(4000)
- print("warning: webfont request stalled - captured with fallback typography; the PNG may not match the intended fonts", file=sys.stderr)
- page.evaluate("document.fonts.ready")
- if not page.locator("[data-motion-root]").evaluate_all(
- "roots => roots.every(root => root.dataset.frame === 'static')"
- ):
- raise RuntimeError("motion export requires a complete static frame")
- svg = page.locator("svg").first
- # Capture at one CSS pixel per viewBox unit before applying the multiplier.
- svg.evaluate("""el => {
- const box = el.viewBox.baseVal;
- if (![box.width, box.height].every(n => Number.isFinite(n) && n > 0))
- throw new Error('PNG export requires a nonzero finite viewBox');
- for (const [axis, size] of [['width', box.width], ['height', box.height]])
- for (const prefix of ['', 'min-', 'max-'])
- el.style.setProperty(prefix + axis, size + 'px', 'important');
- }""")
- # Release every clipping ancestor (local scroller, overflow:hidden chrome)
- # so an SVG wider than its frame is captured whole.
- svg.evaluate("el => { for (let a = el.parentElement; a; a = a.parentElement) a.style.setProperty('overflow', 'visible', 'important'); }")
- svg.screenshot(path=out, omit_background=True)
- browser.close()
-```
+Keep the user's project directory as the working directory so relative input and
+output paths still resolve there. Invoke the packaged renderer by its absolute
+path under the resolved skill directory with the interpreter that passed
+detection: `python3 <skill-dir>/scripts/export_png.py <src.html> <out.png> [scale]`
+or `python <skill-dir>/scripts/export_png.py <src.html> <out.png> [scale]`.
-If the `networkidle` wait times out (a stalled font or stylesheet behind a proxy), the snippet cancels the outstanding load with `window.stop()` and captures with fallback typography, printing a warning to stderr — pass that warning on to the user. Any other error propagates and fails the export normally. The URL requests the complete static motion frame, waits for font readiness, and rejects a motion root that has not reached `data-frame="static"`; ordinary script-free diagrams need no motion root.
+If the `networkidle` wait times out (a stalled font or stylesheet behind a proxy), the helper cancels the outstanding load with `window.stop()` and captures with fallback typography, printing a warning to stderr — pass that warning on to the user. Any other error propagates and fails the export normally. The helper requests the complete static motion frame, waits for font readiness, and rejects a motion root that has not reached `data-frame="static"`; ordinary script-free diagrams need no motion root.
Default `device_scale_factor=2` for crisp output. Accept `1` for compact assets or `3` for print/retina hero use, passed as a third CLI arg. Fractional scales such as `1.25` are also accepted within the documented 1–4 range for exact pixel sizes.
-The overflow release matters for the wide presets. `min-width` equals the viewBox width (see [`output-spec.md`](output-spec.md)), so a `doc-wide` or `slide-16x9` SVG is 1280px inside a 1200px frame, and its `.diagram-container` scroller clips the last 80px on screen. The screenshot covers the SVG's box but not what an ancestor clipped, so without the release the PNG comes out full size with a blank right edge. This is the screen-side counterpart of the templates' `@media print` rule.
+The helper's overflow release matters for the wide presets. `min-width` equals the viewBox width (see [`output-spec.md`](output-spec.md)), so a `doc-wide` or `slide-16x9` SVG is 1280px inside a 1200px frame, and its `.diagram-container` scroller clips the last 80px on screen. The screenshot covers the SVG's box but not what an ancestor clipped, so without the release the PNG comes out full size with a blank right edge. This is the screen-side counterpart of the templates' `@media print` rule.
### Output naming
diff --git a/skills/diagram-design/scripts/export_png.py b/skills/diagram-design/scripts/export_png.py
new file mode 100755
index 0000000..0bc16e9
--- /dev/null
+++ b/skills/diagram-design/scripts/export_png.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""Rasterize the first SVG in a diagram HTML file with Playwright."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import pathlib
+import sys
+
+from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright
+
+NETWORK_IDLE_TIMEOUT_MS = 15_000
+FALLBACK_SETTLE_MS = 4_000
+
+
+def exact_size_scale(value: str) -> float:
+ try:
+ scale = float(value)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("scale must be a number") from exc
+ if not math.isfinite(scale) or not 1 <= scale <= 4:
+ raise argparse.ArgumentTypeError("scale must be between 1 and 4")
+ return scale
+
+
+def rasterize(
+ src: pathlib.Path,
+ out: pathlib.Path,
+ scale: float = 2,
+ *,
+ network_idle_timeout_ms: int = NETWORK_IDLE_TIMEOUT_MS,
+ fallback_settle_ms: int = FALLBACK_SETTLE_MS,
+) -> None:
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch()
+ try:
+ page = browser.new_page(device_scale_factor=scale)
+ page.goto(
+ src.resolve().as_uri() + "?motion=static",
+ wait_until="domcontentloaded",
+ )
+ try:
+ page.wait_for_load_state("networkidle", timeout=network_idle_timeout_ms)
+ except PlaywrightTimeoutError:
+ # Proxied networks may stall webfont subrequests past any deadline.
+ # Cancel the outstanding load so capture cannot block on it again.
+ page.evaluate("window.stop()")
+ page.wait_for_timeout(fallback_settle_ms)
+ print(
+ "warning: webfont request stalled - captured with fallback "
+ "typography; the PNG may not match the intended fonts",
+ file=sys.stderr,
+ )
+ page.evaluate("document.fonts.ready")
+ if not page.locator("[data-motion-root]").evaluate_all(
+ "roots => roots.every(root => root.dataset.frame === 'static')"
+ ):
+ raise RuntimeError("motion export requires a complete static frame")
+ svg = page.locator("svg").first
+ # Capture at one CSS pixel per viewBox unit before applying the multiplier.
+ svg.evaluate(
+ """el => {
+ const box = el.viewBox.baseVal;
+ if (![box.width, box.height].every(n => Number.isFinite(n) && n > 0))
+ throw new Error('PNG export requires a nonzero finite viewBox');
+ for (const [axis, size] of [['width', box.width], ['height', box.height]])
+ for (const prefix of ['', 'min-', 'max-'])
+ el.style.setProperty(prefix + axis, size + 'px', 'important');
+ }"""
+ )
+ # Release every clipping ancestor so a wide SVG is captured whole.
+ svg.evaluate(
+ "el => { for (let a = el.parentElement; a; a = a.parentElement) "
+ "a.style.setProperty('overflow', 'visible', 'important'); }"
+ )
+ svg.screenshot(path=out, omit_background=True)
+ finally:
+ browser.close()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("src", type=pathlib.Path, help="diagram HTML input")
+ parser.add_argument("out", type=pathlib.Path, help="PNG output")
+ parser.add_argument("scale", nargs="?", type=exact_size_scale, default=2)
+ args = parser.parse_args()
+ rasterize(args.src, args.out, args.scale)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())