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.

fix(export): land export and doctor fixes from #301, #313, #319, #320, #323, #326, #329 (#348)

Cathryn Lavery4fc224238ddb
diff --git a/scripts/lint-render.py b/scripts/lint-render.py
index 3d03333..94fe5b9 100755
--- a/scripts/lint-render.py
+++ b/scripts/lint-render.py
@@ -500,7 +500,9 @@ def measure(page):
def check(page, path):
findings = []
watch(page, findings)
- page.goto(path.resolve().as_uri(), wait_until="load")
+ # CSS animation disabling does not stop the controller's JavaScript timer.
+ # Both overflow captures must observe the same complete diagram.
+ page.goto(path.resolve().as_uri() + "?motion=static", wait_until="load")
return measure(page) + findings
@@ -1205,6 +1207,32 @@ def self_test(context):
checks += 1
failures += network_isolation_failures(context)
+ # Exercise the real reveal controller through the public file entry point.
+ # Its timers must stay stopped throughout the paired clipping screenshots.
+ for asset in ("example-exploded-phone-animated.html", "example-axonometric-plan-coffee-shop-animated.html"):
+ checks += 1
+ motion_page = context.new_page()
+ try:
+ findings = check(motion_page, ASSET_DIR / asset)
+ state = motion_page.locator("[data-motion-root]").first.evaluate(
+ "el => [el.dataset.frame, el.dataset.motionState, el.dataset.stepCurrent === el.dataset.stepCount]"
+ )
+ if findings or state != ["static", "static", True]:
+ failures.append(f"{asset}: static capture failed: {state}, {findings}")
+ finally:
+ motion_page.close()
+
+ checks += 1
+ with tempfile.TemporaryDirectory() as directory:
+ clipped_path = Path(directory) / "static-clipped.html"
+ clipped_path.write_text(fixture_html(SVG_CASES[0][1]), encoding="utf-8")
+ clipped_page = context.new_page()
+ try:
+ if not any(category == "clipped" for category, _ in check(clipped_page, clipped_path)):
+ failures.append("static file entry point stopped detecting actual clipping")
+ finally:
+ clipped_page.close()
+
checks += 1
failures += gallery_mobile_failures(context)
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.py
index 66a4a79..dda67d8 100644
--- a/scripts/test-export-svg-standalone.py
+++ b/scripts/test-export-svg-standalone.py
@@ -140,6 +140,28 @@ class ExportSvgStandaloneTests(unittest.TestCase):
self.assertIsNone(re.search(r"url\(#arrow\)", svg))
self.assertIsNone(re.search(r"url\(#dots\)", svg))
+ def test_quoted_local_paint_urls_follow_namespaced_defs(self) -> None:
+ references = (
+ 'url(#paint)', 'url("#paint")', "url('#paint')",
+ 'url( "#paint" )', 'url("#paint")', 'url('#paint')',
+ )
+ for reference in references:
+ with self.subTest(reference=reference):
+ markup = '<svg><defs><linearGradient id="paint"/></defs>'
+ markup += '<rect style="fill: ' + reference.replace('"', '&quot;') + '"/>'
+ markup += '<style>.node { fill: ' + reference + '; }</style></svg>'
+ exported = self.mod.namespace_defs_ids(markup, "quoted")
+ self.assertIn('id="quoted-paint"', exported)
+ expected = reference.replace('#paint', '#quoted-paint').replace(' ', '')
+ self.assertIn(expected, exported)
+ self.assertIn(expected.replace('"', '&quot;'), exported)
+ self.assertEqual(exported.count('#quoted-paint'), 2)
+ untouched = '<svg><defs><linearGradient id="paint"/></defs>'
+ untouched += '<rect fill="url(#paint-other)" stroke="url(other.svg#paint)"/></svg>'
+ result = self.mod.namespace_defs_ids(untouched, "quoted")
+ self.assertIn('url(#paint-other)', result)
+ self.assertIn('url(other.svg#paint)', result)
+
def test_light_and_dark_architecture_do_not_collide_when_inlined(self) -> None:
light_src = ASSETS / "example-architecture.html"
dark_src = ASSETS / "example-architecture-dark.html"
@@ -204,6 +226,109 @@ class ExportSvgStandaloneTests(unittest.TestCase):
import xml.etree.ElementTree as ET
ET.fromstring(svg)
+ def test_quoted_urls_preserve_delimiters_and_exact_fragment_case(self) -> None:
+ markup = '<svg><defs><linearGradient id="paint)"/></defs><style>.paint { fill:url("#paint)"); }</style></svg>'
+ result = self.mod.namespace_defs_ids(markup, "quoted")
+ self.assertIn('url("#quoted-paint)")', result)
+ markup = '<svg><defs><linearGradient id="A"/><linearGradient id="a"/></defs>'
+ markup += '<style>.paint { fill:URL("#a"); stroke:url("#A"); }</style><use HREF="#a"/></svg>'
+ result = self.mod.namespace_defs_ids(markup, "quoted")
+ self.assertIn('url("#quoted-a")', result)
+ self.assertIn('url("#quoted-A")', result)
+ self.assertIn('HREF="#quoted-a"', result)
+
+ def test_root_selector_retarget_preserves_literals_and_escapes(self) -> None:
+ selector = r"""#original .paint[data-label="#original"], [data-label='#original'], .\#original, #original-child, #original\:child, #originalé"""
+ expected = r"""#export-root .paint[data-label="#original"], [data-label='#original'], .\#original, #original-child, #original\:child, #originalé"""
+ self.assertEqual(self.mod.retarget_root_selector(selector, "original", "export-root"), expected)
+ escaped_quote = r' .paint[data-label="escaped\"#original"] #original'
+ self.assertEqual(self.mod.retarget_root_selector(escaped_quote, "original", "export-root"),
+ r' .paint[data-label="escaped\"#original"] #export-root')
+ html = '<style>.paint[data-label="#original"] { fill:#00ff00 } #original .paint { stroke:#0000ff }</style>'
+ html += '<svg id="original" viewBox="0 0 40 40"><rect class="paint" data-label="#original" width="40" height="40"/></svg>'
+ svg = self.mod.export_svg_document(html, Path("literal.html"))
+ self.assertIn('#literal-root .paint[data-label="#original"]', svg)
+ self.assertIn('#literal-root .paint { stroke:#0000ff }', svg)
+
+ def test_named_html_entities_retain_readable_text(self) -> None:
+ html = '<svg viewBox="0 0 40 40"><title>R&nbsp;D &copy;</title><desc>&LT;literal&GT;</desc>'
+ html += '<text data-label="&quot;A&nbsp;B&quot;">R&nbsp;D &amp;nbsp; &copy; &#160;</text></svg>'
+ result = self.mod.export_svg_document(html, Path("entities.html"))
+ root = ET.fromstring(result)
+ text = root.find("{http://www.w3.org/2000/svg}text")
+ self.assertEqual(text.text, "R\u00a0D &nbsp; © \u00a0")
+ self.assertEqual(text.get("data-label"), '"A\u00a0B"')
+ self.assertEqual(root.find("{http://www.w3.org/2000/svg}desc").text, "<literal>")
+ opaque = '<!-- &nbsp; --><![CDATA[&nbsp;]]><style>.label {content:"&nbsp;"}</style>'
+ self.assertEqual(self.mod.normalize_html_entities(opaque), opaque)
+ self.assertEqual(self.mod.normalize_html_entities('&notARealEntity;'), '&notARealEntity;')
+
+ def test_defs_reference_rewrite_leaves_visible_text_alone(self) -> None:
+ markup = ('<svg><defs><linearGradient id="paint"/></defs>'
+ '<style>.a { fill:url("#paint") } .b { stroke:url(#paint) }</style>'
+ '<rect fill="url(#paint)"/><use href="#paint"/>'
+ '<text>Use url("#paint"), url(#paint) or href="#paint"</text>'
+ '<title>id="paint"</title><!-- url(#paint) --></svg>')
+ result = self.mod.namespace_defs_ids(markup, "diagram")
+ self.assertIn('<linearGradient id="diagram-paint"/>', result)
+ self.assertIn('.a { fill:url("#diagram-paint") } .b { stroke:url(#diagram-paint) }', result)
+ self.assertIn('<rect fill="url(#diagram-paint)"/><use href="#diagram-paint"/>', result)
+ self.assertIn('<text>Use url("#paint"), url(#paint) or href="#paint"</text>', result)
+ self.assertIn('<title>id="paint"</title>', result)
+ # Comments are not visible text; a commented-out block stays consistent.
+ self.assertIn('<!-- url(#diagram-paint) -->', result)
+
+ def test_legacy_entities_without_semicolon_follow_html_contexts(self) -> None:
+ html = '<svg viewBox="0 0 40 40"><title>Copyright &copy 2026</title>'
+ html += '<text data-label="&copy 2026">A&nbsp B &amp C &lt D</text></svg>'
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("legacy.html")))
+ self.assertEqual(root.find("{http://www.w3.org/2000/svg}title").text, "Copyright \u00a9 2026")
+ text = root.find("{http://www.w3.org/2000/svg}text")
+ self.assertEqual(text.text, "A\u00a0 B & C < D")
+ self.assertEqual(text.get("data-label"), "\u00a9 2026")
+ # In attribute values HTML leaves a legacy name followed by an
+ # alphanumeric or "=" undecoded; text content decodes the prefix.
+ self.assertEqual(self.mod.normalize_html_entities('<a data-q="x&copy=1&notit">'),
+ '<a data-q="x&copy=1&notit">')
+ self.assertEqual(self.mod.normalize_html_entities("<b>&notit</b>"), "<b>\u00acit</b>")
+
+ def test_escaped_root_id_keeps_retargeted_styles(self) -> None:
+ html = '<style>#a\\&b .paint { fill:#ff0000 }</style>'
+ html += '<svg id="a&amp;b" viewBox="0 0 40 40"><rect class="paint" width="40" height="40"/></svg>'
+ svg = self.mod.export_svg_document(html, Path("escaped.html"))
+ self.assertIn("#escaped-root .paint { fill:#ff0000 }", svg)
+ # A legacy name HTML leaves literal in an attribute stays literal here too.
+ for source_id, css_id in (("x&copy2026", "x\\&copy2026"), ("n&#38;m", "n\\&m"),
+ ("a&#128;b", "a\u20acb"), ("c&#x80;d", "c\u20acd"), ("e&#38f", "e\\&f")):
+ html = f'<style>#{css_id} .paint {{ fill:#ff0000 }}</style>'
+ html += f'<svg id="{source_id}" viewBox="0 0 40 40"><rect class="paint" width="40" height="40"/></svg>'
+ svg = self.mod.export_svg_document(html, Path("literal-id.html"))
+ self.assertIn("#literal-id-root .paint { fill:#ff0000 }", svg)
+
+ def test_raw_text_opening_attributes_normalize_entities(self) -> None:
+ for tag in ("style", "script"):
+ raw = f'<{tag} title="Copyright &copy; > literal">raw &copy; content</{tag}>'
+ expected = f'<{tag} title="Copyright © > literal">raw &copy; content</{tag}>'
+ self.assertEqual(self.mod.normalize_html_entities(raw), expected)
+ html = '<svg viewBox="0 0 10 10"><style title="Copyright &copy; > literal">.label {fill:red}</style><rect class="label" width="10" height="10"/></svg>'
+ result = ET.fromstring(self.mod.export_svg_document(html, Path("style-attribute.html")))
+ style = result.find("{http://www.w3.org/2000/svg}style")
+ self.assertEqual(style.get("title"), "Copyright © > literal")
+ self.assertEqual(style.text, ".label {fill:red}")
+
+ def test_new_defs_preserve_leading_accessible_title(self) -> None:
+ for asset in ("example-journey.html", "example-polar.html"):
+ source = ASSETS / asset
+ root = ET.fromstring(self.mod.export_svg_document(source.read_text(encoding="utf-8"), source))
+ self.assertEqual(root[0].tag, "{http://www.w3.org/2000/svg}title")
+ self.assertEqual(root[1].tag, "{http://www.w3.org/2000/svg}desc")
+ html = '<svg viewBox="0 0 40 40"><!-- before title --><title><![CDATA[Literal </title> text]]></title>'
+ html += '<desc>Keep description</desc><rect width="40" height="40"/></svg>'
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("title.html")))
+ self.assertEqual(root[0].text, "Literal </title> text")
+ self.assertEqual(root[1].text, "Keep description")
+ self.assertEqual(root[2].tag, "{http://www.w3.org/2000/svg}defs")
+
def test_cli_writes_default_path(self) -> None:
source = ASSETS / "example-loop.html"
with tempfile.TemporaryDirectory() as tmp:
@@ -232,6 +357,69 @@ class ExportSvgStandaloneTests(unittest.TestCase):
self.assertIn('stroke="none"', svg)
self.assertIn('id="rgba-demo-dots"', svg)
+ def test_compound_original_root_does_not_gain_an_ancestor(self) -> None:
+ for selector in ('.diagram#original .paint',
+ 'svg.diagram#original .paint',
+ '[data-mode="active"]#original.diagram .paint'):
+ with self.subTest(selector=selector):
+ source = '<style>' + selector + ' {fill:#ff0000}</style>'
+ source += '<svg id="original" class="diagram" data-mode="active" viewBox="0 0 40 40">'
+ source += '<rect class="paint" width="40" height="40"/></svg>'
+ result = self.mod.export_svg_document(source, Path('compound.html'))
+ expected = selector.replace('#original', '#compound-root')
+ self.assertIn(expected + ' { fill:#ff0000 }', embedded_css(result))
+ self.assertNotIn('#compound-root ' + expected, embedded_css(result))
+
+ def test_hex_root_escape_retains_descendant_separator(self) -> None:
+ source = r'<style>.paint {fill:#00ff00} #\31 .paint {fill:#ff0000}</style>'
+ source += '<svg id="1" viewBox="0 0 40 40"><rect class="paint" width="40" height="40"/></svg>'
+ result = self.mod.export_svg_document(source, Path('single-hex.html'))
+ self.assertIn('#single-hex-root .paint { fill:#ff0000 }', embedded_css(result))
+ self.assertNotIn('#single-hex-root.paint', embedded_css(result))
+
+ def test_root_retarget_compares_whole_decoded_css_id_tokens(self) -> None:
+ cases = (
+ (r'#panel.v1 .paint', 'panel.v1', r'#panel.v1 .paint'),
+ (r'#panel\.v1 .paint', 'panel.v1', '#export-root .paint'),
+ (r'#panel\2e v1 .paint', 'panel.v1', '#export-root .paint'),
+ (r'#panel\00002Ev1 .paint', 'panel.v1', '#export-root .paint'),
+ (r'#panel\:v1 .paint', 'panel:v1', '#export-root .paint'),
+ (r'#panel\.v1-child .paint', 'panel.v1', r'#panel\.v1-child .paint'),
+ ('#123 .paint', '123', '#123 .paint'),
+ (r'#\31 23 .paint', '123', '#export-root .paint'),
+ (r'#\-123 .paint', '-123', '#export-root .paint'),
+ ('#-123 .paint', '-123', '#-123 .paint'),
+ ('#面板 .paint', '面板', '#export-root .paint'),
+ )
+ for selector, original, expected in cases:
+ with self.subTest(selector=selector):
+ self.assertEqual(self.mod.retarget_root_selector(selector, original, 'export-root'), expected)
+ self.assertEqual(self.mod.scope_selector('.paint[data-label="#export-root"]', 'export-root'),
+ '#export-root .paint[data-label="#export-root"]')
+ self.assertEqual(self.mod.scope_selector('.paint:is(#export-root)', 'export-root'),
+ '#export-root .paint:is(#export-root)')
+
+ def test_original_svg_root_selectors_follow_replaced_id(self) -> None:
+ for quote in ('"', "'"):
+ with self.subTest(quote=quote):
+ html = '<style>#original .paint {fill: #ff0000;} '
+ html += '#original-child {stroke: #00ff00;}</style>'
+ html += '<svg id=' + quote + 'original' + quote + ' viewBox="0 0 40 40">'
+ html += '<rect id="original-child" class="paint" width="40" height="40"/></svg>'
+ result = self.mod.export_svg_document(html, Path("renamed.html"))
+ css = embedded_css(result)
+ self.assertIn('#renamed-root .paint { fill: #ff0000; }', css)
+ self.assertIn('#original-child { stroke: #00ff00; }', css)
+ self.assertIn('id="original-child"', result)
+ self.assertNotIn('#original .paint', css)
+ # An unrelated attribute that contains the word id is not the root id.
+ source = '<style>#original .paint {fill: #f00;}</style>'
+ source += '<svg data-id="original" viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(source, Path("data-id.html"))
+ self.assertIn('#original .paint', embedded_css(result))
+ self.assertIn('data-id="original"', result)
+ self.assertEqual(ET.fromstring(result).get('id'), 'data-id-root')
+
def test_root_tokens_bind_to_svg_root(self) -> None:
# Without the :root re-scope the tokens land on `#root :root`, which
# matches nothing, and every var(--token) fill falls back to black.
diff --git a/scripts/test-export-wait.py b/scripts/test-export-wait.py
index 9484510..735e2a8 100644
--- a/scripts/test-export-wait.py
+++ b/scripts/test-export-wait.py
@@ -6,6 +6,7 @@ skills/diagram-design/references/export.md against local fixtures:
- a stalled stylesheet request is cancelled with window.stop(), the snippet
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;
- non-timeout errors are not swallowed by the fallback.
@@ -18,6 +19,7 @@ from __future__ import annotations
import contextlib
import io
import re
+import subprocess
import sys
import tempfile
import threading
@@ -132,8 +134,8 @@ class _StallHandler(BaseHTTPRequestHandler):
pass
-def start_stall_server() -> ThreadingHTTPServer:
- server = ThreadingHTTPServer(("127.0.0.1", 0), _StallHandler)
+def start_stall_server(handler: type[BaseHTTPRequestHandler] = _StallHandler) -> ThreadingHTTPServer:
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
@@ -207,6 +209,59 @@ 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
+ )
+ font_requested = threading.Event()
+
+ class FontStallHandler(_StallHandler):
+ def do_GET(self) -> None: # noqa: N802 - stdlib naming
+ if self.path == "/stall.woff2":
+ font_requested.set()
+ super().do_GET()
+
+ server = start_stall_server(FontStallHandler)
+ try:
+ port = server.server_address[1]
+ src = tmp / "stalled-font.html"
+ src.write_text(
+ "<!doctype html><meta charset='utf-8'><style>"
+ "@font-face{font-family:OwnedStalledFont;src:url("
+ f"http://127.0.0.1:{port}/stall.woff2) format('woff2')}}"
+ "</style><svg xmlns='http://www.w3.org/2000/svg' "
+ "viewBox='0 0 400 240' width='400' height='240'>"
+ "<text x='20' y='120' font-family='OwnedStalledFont,sans-serif'>"
+ "stalled font fixture</text></svg>",
+ encoding="utf-8",
+ )
+ 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
+ elapsed = time.monotonic() - started
+ if not font_requested.is_set():
+ raise AssertionError("stalled-font: fixture never started its font download")
+ require_png(out, "stalled-font")
+ if not out.read_bytes().startswith(b"\x89PNG\r\n\x1a\n"):
+ raise AssertionError("stalled-font: output is not a PNG")
+ if WARNING_ANCHOR not in stderr:
+ raise AssertionError(f"stalled-font: fallback warning did not fire\n{stderr}")
+ if elapsed > FALLBACK_BUDGET_SECONDS:
+ raise AssertionError(
+ f"stalled-font: capture took {elapsed:.1f}s, over the "
+ f"{FALLBACK_BUDGET_SECONDS:.0f}s budget after font cancellation"
+ )
+ print(f"OK: actual stalled font cancels, fonts.ready finishes, and PNG captures in {elapsed:.1f}s")
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
def require_normal_load(snippet: str, tmp: Path) -> None:
src = tmp / "normal-fixture.html"
src.write_text(
@@ -230,6 +285,23 @@ def require_normal_load(snippet: str, tmp: Path) -> None:
print("OK: normal load captures with no fallback warning")
+def require_encoded_paths(snippet: str, 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"):
+ # Question marks are not valid Windows filename characters.
+ if "?" in filename and sys.platform == "win32":
+ continue
+ 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)
+ 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_other_errors_propagate(snippet: str, tmp: Path) -> None:
missing = tmp / "does-not-exist.html"
out = tmp / "never.png"
@@ -246,6 +318,39 @@ def require_other_errors_propagate(snippet: str, tmp: Path) -> None:
raise AssertionError("missing-source: expected goto on a missing file to raise")
+
+def require_static_motion_frame(snippet: str, 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)
+ require_png(first, "static-motion")
+ if first.read_bytes() != second.read_bytes():
+ raise AssertionError("motion captures from the same static source are not identical")
+
+ # A broken controller must fail rather than silently capture hidden steps.
+ broken = re.sub(r"<script\b[^>]*>.*?</script>", "", source, flags=re.I | re.S)
+ broken = broken.replace('data-frame="static" data-static-frame=', 'data-frame="start" data-static-frame=', 1)
+ src.write_text(broken, encoding="utf-8")
+ never = tmp / "incomplete.png"
+ try:
+ run_snippet(snippet, src, never)
+ except RuntimeError as exc:
+ if "static" not in str(exc) or never.exists():
+ raise AssertionError(f"incomplete motion frame failed incorrectly: {exc}")
+ else:
+ raise AssertionError("incomplete motion frame was exported without an error")
+ print("OK: motion exports show the complete static frame, repeat identically, and reject incomplete roots")
+
def main() -> int:
try:
import playwright # noqa: F401
@@ -258,8 +363,11 @@ def main() -> int:
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_other_errors_propagate(snippet, tmp)
+ require_static_motion_frame(snippet, tmp)
print("All export-wait cases passed.")
return 0
diff --git a/scripts/test-verify-doctor.py b/scripts/test-verify-doctor.py
index 27c9e17..07296bf 100644
--- a/scripts/test-verify-doctor.py
+++ b/scripts/test-verify-doctor.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import contextlib
import importlib.util
import io
+import os
import sys
import tempfile
from pathlib import Path
@@ -201,6 +202,37 @@ def main() -> int:
raise AssertionError(f"expected no python command, got {python_cmd!r}")
print("OK: an empty PATH fails without naming a command")
+ # Exercise the probe through a real subprocess against Playwright's
+ # import contract: the package need not expose a __version__ attribute.
+ fake_package = root / "import-probe" / "playwright"
+ touch(fake_package / "__init__.py", "# No __version__ attribute.\n")
+ browser_path = root / "import-probe" / "chromium"
+ touch(browser_path)
+ touch(fake_package / "sync_api.py", (
+ "from types import SimpleNamespace\n"
+ "class sync_playwright:\n"
+ " def __enter__(self):\n"
+ f" return SimpleNamespace(chromium=SimpleNamespace(executable_path={str(browser_path)!r}))\n"
+ " def __exit__(self, *args): pass\n"
+ ))
+ original_pythonpath = os.environ.get("PYTHONPATH")
+ os.environ["PYTHONPATH"] = str(fake_package.parent)
+ try:
+ expect_status(verify.check_playwright(sys.executable), verify.PASS,
+ "Playwright is installed and Chromium is present")
+ browser_path.unlink()
+ expect_status(verify.check_playwright(sys.executable), verify.WARN,
+ "Chromium is not ready")
+ touch(fake_package / "__init__.py", "raise ModuleNotFoundError('playwright unavailable')\n")
+ expect_status(verify.check_playwright(sys.executable), verify.WARN,
+ "Playwright package is not available")
+ finally:
+ if original_pythonpath is None:
+ os.environ.pop("PYTHONPATH", None)
+ else:
+ os.environ["PYTHONPATH"] = original_pythonpath
+ print("OK: real import probe does not require Playwright version metadata")
+
summary_checks = [
verify.CheckResult("a", verify.PASS, "ok"),
verify.CheckResult("b", verify.WARN, "warn", "fix warn"),
diff --git a/scripts/verify-doctor.py b/scripts/verify-doctor.py
index 8b90b1b..a941f62 100644
--- a/scripts/verify-doctor.py
+++ b/scripts/verify-doctor.py
@@ -199,7 +199,7 @@ def check_playwright(python_cmd: str | None) -> CheckResult:
fix="Provision an approved Playwright renderer after resolving Python, then re-run this check.",
)
- import_probe = run_command([python_cmd, "-c", "import playwright; print(playwright.__version__)"])
+ import_probe = run_command([python_cmd, "-c", "import playwright"])
if import_probe.returncode != 0:
return CheckResult(
name="Playwright PNG export readiness",
diff --git a/skills/diagram-design/references/animation.md b/skills/diagram-design/references/animation.md
index 640b2a0..bc642b9 100644
--- a/skills/diagram-design/references/animation.md
+++ b/skills/diagram-design/references/animation.md
@@ -108,7 +108,7 @@ One scoped exception to the translation limit: a part in an exploded axonometric
Declare `data-step-count`; do not infer steps from transition events. Set `--motion-total` to step count × `--motion-hold` and keep it within the 8-second budget. Use one `setTimeout` chain per root, derive its hold from `--motion-hold`, clear it on Pause/Replay/page hide and immediately after rendering the final step, and never use `setInterval` for semantic playback. Pause when `document.visibilityState` becomes hidden and do not catch up later. `?motion=step&step=N` may expose an exact zero-duration frame for visual regression only when `N` is a non-negative base-10 integer from 0 through `data-step-count`; missing, fractional, negative, and over-budget values leave normal playback in place.
-The final-state capture contract is synchronous: `?motion=static`, `<html data-motion="static">`, or mode `none` exposes every semantic item, hides controls and decorative overlays, and sets `data-frame="static"`. Wait for `document.fonts.ready` before capture. Two captures from the same URL, viewport, fonts, and device scale must be pixel-identical; random delays, generated IDs, clocks, and runtime path measurement are forbidden.
+The final-state capture contract is synchronous: `?motion=static`, `<html data-motion="static">`, or mode `none` exposes every semantic item, hides controls and decorative overlays, and sets `data-frame="static"`. Wait for `document.fonts.ready` before capture. The rendered clipping verifier uses this same static URL before comparing authored and overflow-released paint. Two captures from the same URL, viewport, fonts, and device scale must be pixel-identical; random delays, generated IDs, clocks, and runtime path measurement are forbidden.
## Export and verification
diff --git a/skills/diagram-design/references/doctor.md b/skills/diagram-design/references/doctor.md
index c899e46..7c70105 100644
--- a/skills/diagram-design/references/doctor.md
+++ b/skills/diagram-design/references/doctor.md
@@ -41,7 +41,7 @@ Run all checks in this order and report each as `pass`, `warn`, or `fail`.
- `fail` if version is below 3.10.
2. Playwright availability for PNG export
-- Check whether Playwright import works in the active Python interpreter (`import playwright`).
+- Check whether Playwright import works in the active Python interpreter (`import playwright`); an optional package version attribute is not required.
- Check whether Chromium is installed for Playwright (`playwright install --help` availability is sufficient for command presence; prefer also checking browser cache when practical).
- If missing, mark `warn` and report that the host environment must provision
an approved Playwright installation and compatible browser.
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index 4a1a2d5..155de4c 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -44,8 +44,8 @@ That script is the source of truth for the transform below (CSS carry-forward, d
- Ensure the opening tag has `xmlns="http://www.w3.org/2000/svg"`. Add it if missing.
- Ensure a `viewBox` is present. The skill's templates always include one; warn the user if absent rather than guessing.
- Preserve `role="img"`, `aria-labelledby`, and the first-child `<title>` / `<desc>` exactly as authored.
- - Rewrite HTML-only attribute syntax as XML: a valueless attribute (`<g data-motion-item>`) becomes `data-motion-item=""`, and an unquoted value gets double quotes. Comments and CDATA sections stay as written.
- - Set `id="<slug>-root"` on the opening `<svg>` tag, where `<slug>` is the source basename without extension (e.g. `example-loop.html` → `example-loop`). This ID scopes carried CSS so several inlined figures do not leak rules into each other.
+ - Rewrite HTML-only attribute syntax as XML: a valueless attribute (`<g data-motion-item>`) becomes `data-motion-item=""`, and an unquoted value gets double quotes. Known named HTML character references in labels and attributes become equivalent XML-safe text (for example, `&nbsp;` becomes a nonbreaking space). HTML's legacy names such as `&copy` and `&nbsp` also decode without the semicolon, except inside an attribute value when the next character is a letter, digit, or `=`, as browsers do. Decode once and escape XML delimiters; already escaped references remain escaped. Comments, CDATA and raw style/script content stay as written; style/script opening-tag attributes follow the same reference conversion as other attributes.
+ - Set `id="<slug>-root"` on the opening `<svg>` tag, where `<slug>` is the source basename without extension (e.g. `example-loop.html` → `example-loop`). This ID scopes carried CSS so several inlined figures do not leak rules into each other. When replacing an existing SVG root ID, retarget whole CSS ID tokens for that root in the carried CSS, including escaped identifier spellings; compound selectors such as `.diagram#original` remain bound to the root without adding another ancestor. Descendant IDs and quoted selector values remain unchanged; an unescaped dot belongs to a class selector, not to the ID token.
4. **Carry page CSS into the SVG.** Class-styled diagrams (the loop family, process, medallion, data-flow, and others) declare fills and type in the page `<style>` block — `.station`, `.hub`, `.node-name`, and so on. Extracting the bare `<svg>` without those rules yields black boxes. Copy the page's diagram rules into a `<style>` inside `<defs>`, then:
- Strip CSS comments first, so a comment in front of a rule does not become part of its selector.
- Re-scope `:root { … }` custom properties onto `#<slug>-root` so the figure keeps its own tokens.
@@ -54,7 +54,7 @@ That script is the source of truth for the transform below (CSS carry-forward, d
- **Drop** page chrome: `*`, `html`, `body`, `main`, `h1`/`h2`/`h3`, `p`, `.frame`, `.eyebrow`, `.summary`, `.card(s)`, `.footer`, `.header`, and the bare `svg { min-width: … }` layout rule. Only the bare `svg` selector is layout; `svg .zone` and `svg text` are diagram rules (see above). Those must not follow a fragment.
- Carry `color` and `font-family` from the dropped `body` rule onto `#<slug>-root`. SVG content inherits both: `stroke="currentColor"` reads `color`, and text without its own font rule reads `font-family`.
- **XML-escape** the carried CSS text (`&` → `&amp;`, `<` → `&lt;`) before inserting it into the SVG. Rule bodies can contain XML-sensitive characters (e.g. `content: "R&D"`); a bare `&` makes the standalone file fail to parse.
-5. Inject Google Fonts `@import` so the SVG renders with correct typography in a browser. **XML-escape the `&` separators as `&amp;`** — a standalone `.svg` is parsed as strict XML, where a bare `&` starts an entity reference and makes the whole file fail to parse. (Don't copy the raw URL from the HTML `<link href>`; that ampersand form is only valid in HTML.) Merge into the same `<defs>` `<style>` as the carried rules (don't add a second `<defs>`):
+5. Inject Google Fonts `@import` so the SVG renders with correct typography in a browser. **XML-escape the `&` separators as `&amp;`** — a standalone `.svg` is parsed as strict XML, where a bare `&` starts an entity reference and makes the whole file fail to parse. (Don't copy the raw URL from the HTML `<link href>`; that ampersand form is only valid in HTML.) Merge into the same `<defs>` `<style>` as the carried rules (don't add a second `<defs>`). If a new `<defs>` is needed, insert it after the existing leading `<title>` and `<desc>` so the first-child accessible-title contract is preserved:
```svg
<defs>
<style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=Geist:wght@400;500;600&amp;family=Geist+Mono:wght@400;500;600&amp;family=Noto+Serif:ital@0;1&amp;family=Noto+Sans+KR:wght@400;500;600&amp;family=Noto+Serif+KR:wght@400&amp;family=Noto+Sans+TC:wght@400;500;600&amp;family=Noto+Serif+TC:wght@400&amp;display=swap');
@@ -63,7 +63,7 @@ That script is the source of truth for the transform below (CSS carry-forward, d
<!-- existing markers / patterns stay here -->
</defs>
```
-6. **Namespace `<defs>` IDs.** Prefix every referenceable defs ID — on `marker`, `pattern`, `linearGradient`, `radialGradient`, `filter`, `clipPath`, `mask`, and `symbol` — with `<slug>-`, and rewrite matching `url(#…)` and `href="#…"` / `xlink:href="#…"` references. Rewrite **longest-id-first** so `arrow-accent` is not clipped by a shorter `arrow` rule. Example: `id="arrow"` in `example-loop.html` becomes `id="example-loop-arrow"` with `marker-end="url(#example-loop-arrow)"`.
+6. **Namespace `<defs>` IDs.** Prefix every referenceable defs ID — on `marker`, `pattern`, `linearGradient`, `radialGradient`, `filter`, `clipPath`, `mask`, and `symbol` — with `<slug>-`, and rewrite matching `url(#…)` and `href="#…"` / `xlink:href="#…"` references. Preserve URL quotes and match fragment IDs case-sensitively (the CSS `url` keyword remains case-insensitive). Rewrite **longest-id-first** so `arrow-accent` is not clipped by a shorter `arrow` rule. Quoted local URLs (`url("#arrow")`, `url('#arrow')`, including XML-escaped quotes in attributes) follow the same rewrite as unquoted URLs. Unrelated fragment IDs and non-local URLs remain unchanged. Example: `id="arrow"` in `example-loop.html` becomes `id="example-loop-arrow"` with `marker-end="url(#example-loop-arrow)"`.
7. Normalize colors for strict SVG 1.1 consumers. This design system's tokens are authored as `rgba(...)` (see `style-guide.md`) and render correctly wherever colors are read as CSS — browsers, Figma, Illustrator. PowerPoint's SVG importer does not: it treats `rgba(...)` and `transparent` as unrecognized and paints them **opaque black**, turning a barely-there tint into a solid block that swallows the label inside it. The transform is lossless (every replacement renders identically to the original in a browser), so apply it to presentation attributes before writing the file:
```python
@@ -129,7 +129,7 @@ scale = int(sys.argv[3]) if len(sys.argv) > 3 else 2
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(device_scale_factor=scale)
- page.goto(f"file://{pathlib.Path(src).resolve()}", wait_until="domcontentloaded")
+ page.goto(pathlib.Path(src).resolve().as_uri() + "?motion=static", wait_until="domcontentloaded")
try:
page.wait_for_load_state("networkidle", timeout=15000)
except PlaywrightTimeoutError:
@@ -138,6 +138,11 @@ with sync_playwright() as p:
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
# Release every clipping ancestor (local scroller, overflow:hidden chrome)
# so an SVG wider than its frame is captured whole.
@@ -146,7 +151,7 @@ with sync_playwright() as p:
browser.close()
```
-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.
+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.
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.
@@ -154,7 +159,7 @@ The overflow release matters for the wide presets. `min-width` equals the viewBo
### Output naming
-`example-architecture.html` → `example-architecture.png`, written next to the source. Honour explicit user-provided paths.
+`example-architecture.html` → `example-architecture.png`, written next to the source. Honour explicit user-provided paths. The rasterizer encodes the absolute source path as a file URI, so literal `#` and `%` characters in filenames remain filename content.
## Sizing the export
diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.py
index ca15f5a..ef71dab 100755
--- a/skills/diagram-design/scripts/export_svg.py
+++ b/skills/diagram-design/scripts/export_svg.py
@@ -23,6 +23,7 @@ The algorithm matches ``references/export.md``. No third-party deps.
from __future__ import annotations
import argparse
+import html as html_entities
import re
import sys
import xml.etree.ElementTree as ET
@@ -143,6 +144,89 @@ def xmlify_attributes(svg: str) -> str:
return "".join(out)
+# HTML named references that browsers decode even without a trailing semicolon.
+LEGACY_ENTITY_NAMES = tuple(name for name in html_entities.entities.html5 if not name.endswith(";"))
+
+
+def normalize_html_entities(svg: str) -> str:
+ """Convert named HTML references to XML-safe text without decoding markup."""
+ opaque = re.compile(
+ r"<!--.*?-->|<!\[CDATA\[.*?\]\]>|"
+ r"(?P<opening><(?P<tag>style|script)\b(?:[^>\"']|\"[^\"]*\"|'[^']*')*>)"
+ r".*?</(?P=tag)\s*>", re.DOTALL | re.IGNORECASE,
+ )
+ # Terminated names first; then HTML's legacy names, which also decode
+ # without a semicolon (longest first, so "&notin" is not read as "&not").
+ named = re.compile(
+ r"&(?:[A-Za-z][A-Za-z0-9]+;|(?P<legacy>"
+ + "|".join(sorted((re.escape(name) for name in LEGACY_ENTITY_NAMES), key=len, reverse=True))
+ + r"))"
+ )
+ tag = re.compile(r"<[A-Za-z/!?](?:[^>\"']|\"[^\"]*\"|'[^']*')*>")
+
+ def replace_entity(match: re.Match[str], in_attribute: bool = False) -> str:
+ original = match.group(0)
+ if original in ("&amp;", "&lt;", "&gt;", "&apos;", "&quot;"):
+ return original
+ if match.group("legacy") is not None:
+ following = match.string[match.end() : match.end() + 1]
+ # HTML leaves these undecoded inside attribute values.
+ if in_attribute and (following == "=" or following.isalnum()):
+ return original
+ decoded = html_entities.entities.html5[match.group("legacy")]
+ else:
+ decoded = html_entities.entities.html5.get(original[1:])
+ if decoded is None:
+ return original
+ return (html_entities.escape(decoded, quote=True)
+ .replace("\t", "&#9;").replace("\n", "&#10;").replace("\r", "&#13;"))
+
+ def replace_in_attribute(match: re.Match[str]) -> str:
+ return replace_entity(match, in_attribute=True)
+
+ def normalize_region(region: str) -> str:
+ parts: list[str] = []
+ cursor = 0
+ for token in tag.finditer(region):
+ parts.append(named.sub(replace_entity, region[cursor : token.start()]))
+ parts.append(named.sub(replace_in_attribute, token.group(0)))
+ cursor = token.end()
+ parts.append(named.sub(replace_entity, region[cursor:]))
+ return "".join(parts)
+
+ out: list[str] = []
+ pos = 0
+ for match in opaque.finditer(svg):
+ out.append(normalize_region(svg[pos:match.start()]))
+ opening = match.group("opening")
+ if opening is not None:
+ out.append(named.sub(replace_in_attribute, opening) + match.group(0)[len(opening):])
+ else:
+ out.append(match.group(0))
+ pos = match.end()
+ out.append(normalize_region(svg[pos:]))
+ return "".join(out)
+
+
+XML_REFERENCE_RE = re.compile(r"&(?:(amp|lt|gt|quot|apos);|#[0-9]+;?|#[xX][0-9A-Fa-f]+;?)")
+XML_NAMED = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}
+
+
+def decode_xml_references(value: str) -> str:
+ """Decode the references left after normalize_html_entities has run.
+
+ Numeric references follow HTML (so &#128; is the euro sign); legacy names
+ that HTML leaves literal in attributes stay literal.
+ """
+ def replace(match: re.Match[str]) -> str:
+ name = match.group(1)
+ if name:
+ return XML_NAMED[name]
+ return html_entities.unescape(match.group(0))
+
+ return XML_REFERENCE_RE.sub(replace, value)
+
+
def ensure_xmlns(svg: str) -> str:
if re.search(r'\bxmlns\s*=\s*["\']http://www\.w3\.org/2000/svg["\']', svg):
return svg
@@ -155,17 +239,23 @@ def ensure_viewbox(svg: str) -> None:
def set_root_id(svg: str, root_id: str) -> str:
- """Put `id="{root_id}"` on the opening <svg> tag (replace any existing id)."""
+ """Put the scoped ID on the actual root id attribute, preserving other data."""
+ opening = START_TAG_RE.match(svg)
+ assert opening is not None
+ name, attrs, end = opening.groups()
+ replaced = False
- def repl(match: re.Match[str]) -> str:
- tag = match.group(0)
- if re.search(r"\bid\s*=", tag, re.IGNORECASE):
- tag = re.sub(r'\bid\s*=\s*("[^"]*"|\'[^\']*\')', f'id="{root_id}"', tag, count=1)
- else:
- tag = tag[:-1] + f' id="{root_id}">'
- return tag
+ def replace_attr(attr: re.Match[str]) -> str:
+ nonlocal replaced
+ if attr.group(2) != "id":
+ return attr.group(0)
+ replaced = True
+ return f'{attr.group(1)}id="{root_id}"'
- return re.sub(r"<svg\b[^>]*>", repl, svg, count=1, flags=re.IGNORECASE)
+ attrs = TAG_ATTR_RE.sub(replace_attr, attrs)
+ if not replaced:
+ attrs += f' id="{root_id}"'
+ return f"<{name}{attrs}{end}>" + svg[opening.end():]
def is_chrome_selector(selector: str) -> bool:
@@ -177,6 +267,84 @@ def is_chrome_selector(selector: str) -> bool:
)
+def css_escape(text: str, pos: int) -> tuple[str, int] | None:
+ """Read one CSS identifier escape, including its optional hex terminator."""
+ end = pos + 1
+ if end == len(text) or text[end] in "\n\r\f":
+ return None
+ start = end
+ while end < min(start + 6, len(text)) and text[end] in "0123456789abcdefABCDEF":
+ end += 1
+ if end == start:
+ return text[end], end + 1
+ code = int(text[start:end], 16)
+ value = chr(code) if 0 < code <= 0x10FFFF and not 0xD800 <= code <= 0xDFFF else "\ufffd"
+ if end < len(text) and text[end] in " \t\n\r\f":
+ end += 2 if text[end:end + 2] == "\r\n" else 1
+ return value, end
+
+
+def css_id_token(text: str, pos: int) -> tuple[str, int] | None:
+ """Read a whole valid CSS ID selector after '#', decoding identifier escapes."""
+ def starts_name(index: int) -> bool:
+ char = text[index:index + 1]
+ return bool(char) and (char in "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ or ord(char) >= 128
+ or (char == "\\" and css_escape(text, index) is not None))
+
+ if not starts_name(pos) and not (text[pos:pos + 1] == "-"
+ and (starts_name(pos + 1) or text[pos + 1:pos + 2] == "-")):
+ return None
+ out: list[str] = []
+ while pos < len(text):
+ char = text[pos]
+ if char == "\\":
+ escaped = css_escape(text, pos)
+ if escaped is None:
+ break
+ value, pos = escaped
+ out.append(value)
+ elif char in "_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" or ord(char) >= 128:
+ out.append(char)
+ pos += 1
+ else:
+ break
+ return "".join(out), pos
+
+
+def root_bound_compound(selector: str, root_id: str) -> bool:
+ """Whether the first compound names this root outside attributes/functions."""
+ pos = 0
+ depth = 0
+ quote = ""
+ while pos < len(selector):
+ char = selector[pos]
+ if char == "\\":
+ escaped = css_escape(selector, pos)
+ pos = escaped[1] if escaped else pos + 1
+ continue
+ if quote:
+ if char == quote:
+ quote = ""
+ elif char in "\"'":
+ quote = char
+ elif char in "[(":
+ depth += 1
+ elif char in "])":
+ depth -= 1
+ elif depth == 0 and (char.isspace() or char in ">+~"):
+ break
+ elif depth == 0 and char == "#":
+ token = css_id_token(selector, pos + 1)
+ if token:
+ value, pos = token
+ if value == root_id:
+ return True
+ continue
+ pos += 1
+ return False
+
+
def scope_selector(selector: str, root_id: str) -> str:
scoped: list[str] = []
for part in selector.split(","):
@@ -187,6 +355,9 @@ def scope_selector(selector: str, root_id: str) -> str:
# `:root { … }` and rare `:root .x` → bind tokens to the SVG root.
remainder = part[len(":root") :].strip()
scoped.append(f"#{root_id}" + (f" {remainder}" if remainder else ""))
+ elif root_bound_compound(part, root_id):
+ # A compound such as `.diagram#root` already names the SVG itself.
+ scoped.append(part)
elif part.startswith("#"):
# Already an ID selector — leave alone (title/desc IDs stay global).
scoped.append(part)
@@ -221,7 +392,41 @@ def escape_css_for_xml(css: str) -> str:
return css.replace("&", "&amp;").replace("<", "&lt;")
-def diagram_css_from_html(html: str, root_id: str) -> str:
+def retarget_root_selector(selector: str, original_id: str, root_id: str) -> str:
+ """Retarget whole decoded ID tokens, preserving unrelated escapes and literals."""
+ out: list[str] = []
+ quote = ""
+ pos = 0
+ while pos < len(selector):
+ char = selector[pos]
+ if char == "\\":
+ escaped = css_escape(selector, pos)
+ end = escaped[1] if escaped else pos + 1
+ out.append(selector[pos:end])
+ pos = end
+ continue
+ if quote:
+ out.append(char)
+ if char == quote:
+ quote = ""
+ elif char in "\"'":
+ quote = char
+ out.append(char)
+ elif char == "#":
+ token = css_id_token(selector, pos + 1)
+ if token:
+ value, end = token
+ out.append(f"#{root_id}" if value == original_id else selector[pos:end])
+ pos = end
+ continue
+ out.append(char)
+ else:
+ out.append(char)
+ pos += 1
+ return "".join(out)
+
+
+def diagram_css_from_html(html: str, root_id: str, original_root_id: str = "") -> str:
"""Filter page <style> rules down to diagram rules, scoped under root_id."""
kept: list[str] = []
for block in STYLE_BLOCK_RE.findall(html):
@@ -229,7 +434,12 @@ def diagram_css_from_html(html: str, root_id: str) -> str:
# (`/* Tokens */ :root` is not recognised as `:root`).
block = CSS_COMMENT_RE.sub("", block)
for match in RULE_RE.finditer(block):
- selector = " ".join(match.group(1).split())
+ selector = match.group(1).strip()
+ if original_root_id:
+ selector = retarget_root_selector(selector, original_root_id, root_id)
+ # Retarget before collapsing whitespace: a hex escape consumes one
+ # terminator, so a second space may be the descendant combinator.
+ selector = " ".join(selector.split())
body = match.group(2).strip()
if not selector or not body:
continue
@@ -245,6 +455,27 @@ def diagram_css_from_html(html: str, root_id: str) -> str:
return "\n ".join(kept)
+def leading_accessibility_end(svg: str, pos: int) -> int:
+ """Keep leading title/desc and comments ahead of a newly inserted defs."""
+ token = re.compile(r"<!--.*?-->|<title\b[^>]*>|<desc\b[^>]*>", re.DOTALL | re.IGNORECASE)
+ while True:
+ start = re.match(r"\s*", svg[pos:])
+ assert start is not None
+ next_pos = pos + start.end()
+ opening = token.match(svg, next_pos)
+ if opening is None:
+ return pos
+ if opening.group(0).startswith("<!--"):
+ pos = opening.end()
+ continue
+ name = "title" if opening.group(0).lower().startswith("<title") else "desc"
+ endings = re.compile(rf"<!--.*?-->|<!\[CDATA\[.*?\]\]>|</{name}\s*>", re.DOTALL | re.IGNORECASE)
+ close = next((match for match in endings.finditer(svg, opening.end()) if match.group(0).startswith("</")), None)
+ if close is None:
+ return pos
+ pos = close.end()
+
+
def merge_style_into_defs(svg: str, style_css: str) -> str:
"""Ensure one <defs> and place a <style> with fonts + diagram CSS first."""
style_inner = GOOGLE_FONTS_IMPORT
@@ -257,11 +488,10 @@ def merge_style_into_defs(svg: str, style_css: str) -> str:
insert_at = defs_match.end()
return svg[:insert_at] + "\n " + style_tag + svg[insert_at:]
- # No defs yet — insert one right after the opening svg tag (after title/desc
- # would also be fine; putting defs first keeps markers available).
+ # Keep the authored first-child title/desc ahead of a newly created defs.
open_match = re.match(r"<svg\b[^>]*>", svg, re.IGNORECASE)
assert open_match is not None
- insert_at = open_match.end()
+ insert_at = leading_accessibility_end(svg, open_match.end())
return (
svg[:insert_at]
+ f"\n <defs>\n {style_tag}\n </defs>"
@@ -290,31 +520,51 @@ def find_defs_ids(svg: str) -> list[str]:
return found
+# Markup that can carry defs references: <style> blocks, tags (attribute
+# values), and comments, which may hold an optional commented-out block.
+# CDATA and <script> are matched so they are skipped, not rewritten.
+REFERENCE_REGION_RE = re.compile(
+ r"(?P<skip><!\[CDATA\[.*?\]\]>|<script\b.*?</script\s*>)"
+ r"|<!--.*?-->|<style\b[^>]*>.*?</style\s*>"
+ r"|<[A-Za-z/?!](?:[^>\"']|\"[^\"]*\"|'[^']*')*>",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
def namespace_defs_ids(svg: str, prefix: str) -> str:
- """Prefix defs IDs and rewrite url(#…)/href="#…" references, longest first."""
+ """Prefix defs IDs and rewrite url(#…)/href="#…" references, longest first.
+
+ Only tags and <style> blocks are rewritten; visible text keeps its wording.
+ """
ids = find_defs_ids(svg)
if not ids:
return svg
- for old in sorted(ids, key=len, reverse=True):
- new = f"{prefix}-{old}"
- svg = re.sub(
- rf'(\bid\s*=\s*[\'"]){re.escape(old)}([\'"])',
- rf"\1{new}\2",
- svg,
- )
- svg = re.sub(
- rf"url\(\s*#\s*{re.escape(old)}\s*\)",
- f"url(#{new})",
- svg,
- flags=re.IGNORECASE,
- )
- svg = re.sub(
- rf"""((?:xlink:)?href\s*=\s*['"])#{re.escape(old)}(['"])""",
- rf"\1#{new}\2",
- svg,
- flags=re.IGNORECASE,
- )
- return svg
+
+ def rewrite(region: str) -> str:
+ for old in sorted(ids, key=len, reverse=True):
+ new = f"{prefix}-{old}"
+ region = re.sub(
+ rf'(\bid\s*=\s*[\'"]){re.escape(old)}([\'"])',
+ rf"\1{new}\2",
+ region,
+ )
+ region = re.sub(
+ rf"(?i:url)\(\s*(?P<quote>[\"']|&quot;|&apos;|)\s*#\s*"
+ rf"{re.escape(old)}\s*(?P=quote)\s*\)",
+ lambda match: f"url({match.group('quote')}#{new}{match.group('quote')})",
+ region,
+ )
+ region = re.sub(
+ rf"""((?i:(?:xlink:)?href)\s*=\s*['"])#{re.escape(old)}(['"])""",
+ rf"\1#{new}\2",
+ region,
+ )
+ return region
+
+ return REFERENCE_REGION_RE.sub(
+ lambda match: match.group(0) if match.group("skip") else rewrite(match.group(0)),
+ svg,
+ )
def normalize_rgba_presentation_attrs(svg: str) -> str:
@@ -358,11 +608,19 @@ def export_svg_document(html: str, source_path: Path) -> str:
"""Transform source HTML into a standalone SVG document string."""
slug = slug_for(source_path)
root_id = f"{slug}-root"
- svg = xmlify_attributes(extract_first_svg(html))
+ svg = normalize_html_entities(xmlify_attributes(extract_first_svg(html)))
ensure_viewbox(svg)
svg = ensure_xmlns(svg)
+ opening = START_TAG_RE.match(svg)
+ assert opening is not None
+ # Compare the decoded ID: CSS escapes resolve to characters, not to markup.
+ original_root_id = next(
+ (decode_xml_references(attr.group(4)[1:-1]) for attr in TAG_ATTR_RE.finditer(opening.group(2))
+ if attr.group(2) == "id" and attr.group(4) is not None),
+ "",
+ )
svg = set_root_id(svg, root_id)
- diagram_css = diagram_css_from_html(html, root_id)
+ diagram_css = diagram_css_from_html(html, root_id, original_root_id)
svg = merge_style_into_defs(svg, diagram_css)
svg = namespace_defs_ids(svg, slug)
svg = normalize_rgba_presentation_attrs(svg)