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): carry CSS and namespace defs IDs for standalone SVG (#235)
Rufus Hsuea5019e5f153
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9d114ba..bd98f49 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -263,6 +263,11 @@ jobs:id: self_checkrun: python scripts/test-self-check.py+ - name: Verify standalone SVG export (CSS carry + defs IDs)+ if: always()+ id: export_svg+ run: python scripts/test-export-svg-standalone.py+- name: Verify label geometryif: always()id: geometry@@ -475,6 +480,7 @@ jobs:echo "| Screenshot Freshness Checker | ${{ steps.screenshots_tests.outcome == 'success' && '✅ Passed' || (steps.screenshots_tests.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| README Thumbnail Freshness | ${{ steps.readme_thumbs.outcome == 'success' && '✅ Passed' || (steps.readme_thumbs.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Packaged Self-Check | ${{ steps.self_check.outcome == 'success' && '✅ Passed' || (steps.self_check.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY+ echo "| Standalone SVG Export | ${{ steps.export_svg.outcome == 'success' && '✅ Passed' || (steps.export_svg.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Label Geometry | ${{ steps.geometry.outcome == 'success' && '✅ Passed' || (steps.geometry.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Label Geometry Checker | ${{ steps.geometry_tests.outcome == 'success' && '✅ Passed' || (steps.geometry_tests.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Block Registry | ${{ steps.block_registry.outcome == 'success' && '✅ Passed' || (steps.block_registry.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYdiff --git a/.maintainer-policy.json b/.maintainer-policy.jsonindex f53c78d..87d7440 100644--- a/.maintainer-policy.json+++ b/.maintainer-policy.json@@ -68,6 +68,7 @@"python3 scripts/test-build-readme-thumbs.py","python3 scripts/build-readme-thumbs.py --check","python3 scripts/test-self-check.py",+ "python3 scripts/test-export-svg-standalone.py","python3 scripts/verify-geometry.py --all","python3 scripts/test-verify-geometry.py","python3 scripts/verify-block-registry.py --all",diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0615e13..db1a5bd 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -58,6 +58,7 @@ Every validation gate below must pass before a PR is ready. They also run automa| 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) | `python3 scripts/test-self-check.py` |+| Standalone SVG export carries CSS and namespaces defs IDs | `python3 scripts/test-export-svg-standalone.py` || Label masks are never clipped by a node painted after them | `python3 scripts/verify-geometry.py --all` || Label geometry checker behaves (pass + adversarial cases) | `python3 scripts/test-verify-geometry.py` || Traceable block decomposition registries have unique IDs, resolving parents, names, and no cycles | `python3 scripts/verify-block-registry.py --all` |@@ -132,6 +133,7 @@ python3 scripts/test-plugin-package.py \&& python3 scripts/test-build-readme-thumbs.py \&& python3 scripts/build-readme-thumbs.py --check \&& python3 scripts/test-self-check.py \+ && python3 scripts/test-export-svg-standalone.py \&& python3 scripts/verify-geometry.py --all \&& python3 scripts/test-verify-geometry.py \&& python3 scripts/verify-block-registry.py --all \diff --git a/commands/export-diagram.md b/commands/export-diagram.mdindex e09f781..03fc502 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. 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. 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.Full argument string: `$ARGUMENTS`diff --git a/prompts/export-diagram.md b/prompts/export-diagram.mdindex 38b6c82..9610313 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 PNGargument-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. 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. 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.Full argument string: `$ARGUMENTS`diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.pynew file mode 100644index 0000000..66a4a79--- /dev/null+++ b/scripts/test-export-svg-standalone.py@@ -0,0 +1,407 @@+#!/usr/bin/env python3+"""Regression tests for standalone SVG export (CSS carry + defs ID namespace).++Covers the packaged helper at skills/diagram-design/scripts/export_svg.py and+the contract documented in references/export.md (issues #202 and #203).+"""++from __future__ import annotations++import importlib.util+import re+import sys+import tempfile+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+HELPER = ROOT / "skills/diagram-design/scripts/export_svg.py"+EXPORT_MD = ROOT / "skills/diagram-design/references/export.md"+ASSETS = ROOT / "skills/diagram-design/assets"++# Shipped assets the helper refuses (loudly) because their markup is not+# well-formed XML for reasons outside the CSS carry: the first `</svg>` match+# stops at a nested icon <svg>, or a comment contains `--`. Keep this list+# exact so a newly unexportable asset, or a fixed one, shows up here.+KNOWN_UNEXPORTABLE = frozenset(+ {+ # nested icon <svg> truncates the first-</svg> extraction+ "example-datalake.html",+ "example-datalake-dark.html",+ "example-datalake-full.html",+ "example-high-level.html",+ "example-high-level-dark.html",+ "example-high-level-full.html",+ "example-high-level-vertical.html",+ "example-high-level-vertical-dark.html",+ "example-high-level-vertical-full.html",+ # `--` inside an XML comment+ "example-slopegraph.html",+ "example-slopegraph-dark.html",+ "example-slopegraph-full.html",+ "example-streamgraph.html",+ "example-streamgraph-dark.html",+ "example-streamgraph-full.html",+ }+)++# Motion files named in #202; they use valueless HTML attributes.+MOTION_FILES = (+ "template-motion.html",+ "example-policy-trace-animated.html",+ "example-queue-animated.html",+)++PAGE_STYLE_RE = re.compile(r"<style\b[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)+++def exportable_assets() -> list[Path]:+ return sorted(+ path+ for path in ASSETS.glob("*.html")+ if path.name not in {"index.html", "icons.html"}+ and path.name not in KNOWN_UNEXPORTABLE+ )+++def embedded_css(svg: str) -> str:+ match = re.search(r"<style>(.*?)</style>", svg, re.DOTALL)+ return match.group(1) if match else ""+++def load_helper():+ spec = importlib.util.spec_from_file_location("diagram_design_export_svg", HELPER)+ if spec is None or spec.loader is None:+ raise RuntimeError(f"cannot load {HELPER}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class ExportSvgStandaloneTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.mod = load_helper()++ def test_helper_and_docs_exist(self) -> None:+ self.assertTrue(HELPER.is_file())+ self.assertTrue(EXPORT_MD.is_file())++ def test_export_md_documents_helper_css_and_defs(self) -> None:+ text = EXPORT_MD.read_text(encoding="utf-8")+ self.assertIn("scripts/export_svg.py", text)+ self.assertIn("Carry page CSS into the SVG", text)+ self.assertIn("Namespace `<defs>` IDs", text)+ self.assertIn("longest-id-first", text)+ self.assertIn("class=", text)+ self.assertIn("black boxes", text)+ self.assertIn("fonts-only", text)+ self.assertIn("R&D", text)+ self.assertIn("accessible-name guarantee alone is not enough", text)+ self.assertIn("`svg .zone` becomes `#<slug>-root .zone`", text)+ self.assertIn("`stroke=\"currentColor\"` reads `color`", text)+ self.assertIn('`data-motion-item=""`', text)++ def test_loop_export_carries_scoped_css(self) -> None:+ source = ASSETS / "example-loop.html"+ html = source.read_text(encoding="utf-8")+ svg = self.mod.export_svg_document(html, source)+ self.assertTrue(svg.startswith("<?xml version="))+ self.assertIn('id="example-loop-root"', svg)+ self.assertIn("#example-loop-root .station", svg)+ self.assertIn("#example-loop-root .hub", svg)+ self.assertIn("--paper:", svg)+ # Page chrome must not leak into the fragment.+ self.assertNotIn("min-width:", svg)+ self.assertNotRegex(svg, r"#example-loop-root\s+body\b")+ self.assertNotRegex(svg, r"#example-loop-root\s+\.frame\b")+ self.assertNotRegex(svg, r"#example-loop-root\s+\.eyebrow\b")+ self.assertIn("class=\"station\"", svg)+ self.assertIn("<style>", svg)++ def test_loop_export_namespaces_defs_ids_longest_first(self) -> None:+ source = ASSETS / "example-loop.html"+ svg = self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)+ self.assertIn('id="example-loop-arrow-accent"', svg)+ self.assertIn('id="example-loop-arrow"', svg)+ self.assertIn('id="example-loop-arrow-soft"', svg)+ # Loop references arrow / arrow-soft (accent is defined but unused).+ self.assertIn("url(#example-loop-arrow)", svg)+ self.assertIn("url(#example-loop-arrow-soft)", svg)+ self.assertIn('id="example-loop-dots"', svg)+ self.assertIn("url(#example-loop-dots)", svg)+ # Longest-first: accent id must not have been mangled by the arrow rewrite.+ self.assertNotIn('id="example-loop-example-loop-arrow-accent"', svg)+ # Bare shared IDs must be gone — otherwise inlining collides.+ self.assertIsNone(re.search(r'\bid="arrow"', svg))+ self.assertIsNone(re.search(r'\bid="arrow-accent"', svg))+ self.assertIsNone(re.search(r'\bid="dots"', svg))+ self.assertIsNone(re.search(r"url\(#arrow\)", svg))+ self.assertIsNone(re.search(r"url\(#dots\)", svg))++ 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"+ light = self.mod.export_svg_document(light_src.read_text(encoding="utf-8"), light_src)+ dark = self.mod.export_svg_document(dark_src.read_text(encoding="utf-8"), dark_src)+ combined = light + "\n" + dark+ self.assertEqual(combined.count('id="example-architecture-arrow"'), 1)+ self.assertEqual(combined.count('id="example-architecture-dark-arrow"'), 1)+ self.assertIn("url(#example-architecture-arrow)", light)+ self.assertIn("url(#example-architecture-dark-arrow)", dark)+ # Distinct root scopes so token sheets do not overwrite each other.+ self.assertIn('id="example-architecture-root"', light)+ self.assertIn('id="example-architecture-dark-root"', dark)++ def test_class_without_style_gate(self) -> None:+ html = """<!DOCTYPE html><html><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <rect class="station" width="10" height="10"/>+ </svg></body></html>"""+ # No diagram rules: bare class SVG must be refused (fonts-only does not count).+ with self.assertRaises(ValueError) as ctx:+ self.mod.assert_export_gate(+ '<svg viewBox="0 0 1 1"><defs><style>@import url("x");</style></defs>'+ '<rect class="x" width="1" height="1"/></svg>'+ )+ self.assertIn("black boxes", str(ctx.exception))+ self.assertIn("diagram CSS", str(ctx.exception))+ with self.assertRaises(ValueError) as ctx2:+ self.mod.export_svg_document(html, Path("orphan-station.html"))+ self.assertIn("black boxes", str(ctx2.exception))+ # With real diagram rules, the gate passes.+ ok = """<!DOCTYPE html><html><head><style>+ .station { fill: #f00; }+ </style></head><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <rect class="station" width="10" height="10"/>+ </svg></body></html>"""+ svg = self.mod.export_svg_document(ok, Path("styled-station.html"))+ self.assertIn("#styled-station-root .station", svg)+ self.assertTrue(self.mod.has_diagram_stylesheet(svg))++ def test_carried_css_escapes_xml_specials(self) -> None:+ html = """<!DOCTYPE html><html><head><style>+ .label::after { content: "R&D"; }+ .station { fill: #111; }+ </style></head><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <rect class="station" width="10" height="10"/>+ <text class="label">x</text>+ </svg></body></html>"""+ svg = self.mod.export_svg_document(html, Path("rd-label.html"))+ # Raw & would break XML; escaped form must appear in the stylesheet.+ self.assertIn('content: "R&D"', svg)+ self.assertNotRegex(svg, r'content:\s*"R&D"')+ # Document must parse as XML (export already validates; assert explicitly).+ import xml.etree.ElementTree as ET+ ET.fromstring(svg)++ def test_cli_writes_default_path(self) -> None:+ source = ASSETS / "example-loop.html"+ with tempfile.TemporaryDirectory() as tmp:+ staged = Path(tmp) / "example-loop.html"+ staged.write_text(source.read_text(encoding="utf-8"), encoding="utf-8")+ rc = self.mod.main([str(staged)])+ self.assertEqual(rc, 0)+ out = staged.with_suffix(".svg")+ self.assertTrue(out.is_file())+ body = out.read_text(encoding="utf-8")+ self.assertIn("#example-loop-root .station", body)++ def test_rgba_presentation_attrs_still_split(self) -> None:+ html = """<!DOCTYPE html><html><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <defs><pattern id="dots" width="2" height="2"+ patternUnits="userSpaceOnUse">+ <circle cx="1" cy="1" r="0.5" fill="rgba(45,49,66,0.10)"/>+ </pattern></defs>+ <rect width="10" height="10" fill="url(#dots)" stroke="transparent"/>+ </svg></body></html>"""+ svg = self.mod.export_svg_document(html, Path("rgba-demo.html"))+ self.assertIn('fill="#2d3142" fill-opacity="0.10"', svg)+ self.assertIn('stroke="none"', svg)+ self.assertIn('id="rgba-demo-dots"', svg)++ 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.+ source = ASSETS / "example-loop.html"+ css = embedded_css(self.mod.export_svg_document(source.read_text(encoding="utf-8"), source))+ self.assertRegex(css, r"#example-loop-root\s*\{[^}]*--paper\s*:")+ self.assertRegex(css, r"#example-loop-root\s*\{[^}]*--accent\s*:")+ self.assertNotIn(":root", css)+ # A comment in front of the rule (template-full.html) must not hide it.+ html = """<!DOCTYPE html><html><head><style>+ /* Tokens, light */+ :root { --node: #fff; }+ .node { fill: var(--node); }+ </style></head><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <rect class="node" width="1" height="1"/>+ </svg></body></html>"""+ css = embedded_css(self.mod.export_svg_document(html, Path("commented-tokens.html")))+ self.assertIn("#commented-tokens-root { --node: #fff; }", css)+ self.assertNotIn(":root", css)++ def test_svg_descendant_rules_are_kept_and_scoped_to_root(self) -> None:+ # `svg .zone` / `svg text` are diagram rules, not page chrome. The+ # exported root is the <svg> itself, so they must start at the root ID.+ cases = {+ "example-it-state.html": (+ "#example-it-state-root .zone {",+ "#example-it-state-root .node.focal {",+ "#example-it-state-root .zone-mask, #example-it-state-root .node-mask",+ ),+ "example-dp-security-matrix.html": (+ "#example-dp-security-matrix-root .component-head, "+ "#example-dp-security-matrix-root .component {",+ "#example-dp-security-matrix-root .cell {",+ ),+ "example-process.html": ("#example-process-root text {",),+ "example-state-lifecycle.html": ("#example-state-lifecycle-root text {",),+ }+ for name, expected in cases.items():+ with self.subTest(name=name):+ source = ASSETS / name+ slug = source.stem+ css = embedded_css(+ self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)+ )+ for rule in expected:+ self.assertIn(rule, css)+ self.assertNotRegex(css, rf"#{slug}-root\s+svg\b")+ # The bare `svg {{ width; min-width }}` page-layout rule stays out.+ self.assertNotIn("min-width", css)+ html = """<!DOCTYPE html><html><head><style>+ svg { width: 100%; min-width: 900px; }+ svg>.edge { stroke: #111; }+ svg .node, .plain { fill: #fff; }+ </style></head><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <path class="edge" d="M0 0L1 1"/><rect class="node" width="1" height="1"/>+ </svg></body></html>"""+ css = embedded_css(self.mod.export_svg_document(html, Path("svg-prefix.html")))+ self.assertIn("#svg-prefix-root>.edge { stroke: #111; }", css)+ self.assertIn("#svg-prefix-root .node, #svg-prefix-root .plain { fill: #fff; }", css)+ self.assertNotIn("min-width", css)++ def test_body_color_and_font_family_are_carried_onto_root(self) -> None:+ # `stroke="currentColor"` and text without a font rule inherit from+ # body. The body rule is dropped as chrome, so its color and+ # font-family must be bound to the SVG root instead.+ html = """<!DOCTYPE html><html><head><style>+ body { padding: 40px; background: #f5f5f5; color: #2d3142;+ font-family: 'Geist', sans-serif; }+ .edge { fill: none; }+ </style></head><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" role="img"+ aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <path class="edge" d="M0 0L10 10" stroke="currentColor"/>+ <text x="1" y="5">plain</text>+ </svg></body></html>"""+ css = embedded_css(self.mod.export_svg_document(html, Path("body-inherit.html")))+ self.assertRegex(css, r"#body-inherit-root\s*\{[^}]*(?<![\w-])color:\s*#2d3142")+ self.assertRegex(css, r"#body-inherit-root\s*\{[^}]*font-family:\s*'Geist', sans-serif")+ for leaked in ("padding", "background", "40px", "#body-inherit-root body"):+ self.assertNotIn(leaked, css)++ source = ASSETS / "example-dp-integration.html"+ svg = self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)+ self.assertIn('stroke="currentColor"', svg)+ css = embedded_css(svg)+ self.assertRegex(+ css, r"#example-dp-integration-root\s*\{[^}]*(?<![\w-])color:\s*var\(--ink\)"+ )+ self.assertRegex(+ css, r"#example-dp-integration-root\s*\{[^}]*font-family:\s*var\(--sans\)"+ )++ def test_valueless_html_attributes_become_xml(self) -> None:+ for name in MOTION_FILES + ("example-paved-road-animated.html", "example-polar.html"):+ with self.subTest(name=name):+ source = ASSETS / name+ svg = self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)+ ET.fromstring(svg)+ marker = "data-polar-chart" if "polar" in name else "data-motion-item"+ self.assertIn(f'{marker}=""', svg)+ self.assertNotRegex(svg, rf"{marker}(?=[\s/>])")+ html = """<!DOCTYPE html><html><body>+ <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" data-flag+ role="img" aria-labelledby="t d">+ <title id="t">t</title><desc id="d">d</desc>+ <!-- <g data-in-comment> stays as written -->+ <g data-motion-item aria-label="Step 1 > Step 2" data-step=1>+ <rect width="1" height="1" hidden/>+ </g>+ </svg></body></html>"""+ svg = self.mod.export_svg_document(html, Path("valueless.html"))+ ET.fromstring(svg)+ self.assertRegex(svg, r'<svg\b[^>]*\sdata-flag=""')+ self.assertIn('<g data-motion-item="" aria-label="Step 1 > Step 2" data-step="1">', svg)+ self.assertIn('<rect width="1" height="1" hidden=""/>', svg)+ self.assertIn("<!-- <g data-in-comment> stays as written -->", svg)++ def test_shipped_corpus_exports_with_scoped_rules(self) -> None:+ # Every shipped example and template (except the pinned, loudly refused+ # ones) exports; every class the diagram uses that the page styles gets+ # a rule scoped to the root; tokens and body color move to the root.+ for source in exportable_assets():+ with self.subTest(name=source.name):+ html = source.read_text(encoding="utf-8")+ slug = source.stem+ svg = self.mod.export_svg_document(html, source)+ ET.fromstring(svg)+ css = embedded_css(svg)+ page_css = re.sub(+ r"/\*.*?\*/", "", "\n".join(PAGE_STYLE_RE.findall(html)), flags=re.DOTALL+ )+ self.assertNotIn(":root", css)+ self.assertNotRegex(css, rf"#{re.escape(slug)}-root\s+svg\b")+ if re.search(r":root\s*\{[^}]*--", page_css):+ self.assertRegex(css, rf"#{re.escape(slug)}-root\s*\{{[^}}]*--")+ if re.search(r"(?:^|[\s}])body\s*\{[^}]*(?<![\w-])color\s*:", page_css):+ self.assertRegex(+ css, rf"#{re.escape(slug)}-root\s*\{{[^}}]*(?<![\w-])color\s*:"+ )+ used = set()+ for value in re.findall(+ r'\bclass\s*=\s*"([^"]*)"', self.mod.extract_first_svg(html)+ ):+ used.update(value.split())+ for cls in sorted(used):+ if not re.search(rf"\.{re.escape(cls)}(?![\w-])", page_css):+ continue+ self.assertRegex(+ css,+ rf"#{re.escape(slug)}-root[^{{}},]*\.{re.escape(cls)}(?![\w-])",+ f"class {cls!r} is styled on the page but has no scoped rule",+ )++ def test_known_unexportable_assets_are_refused_loudly(self) -> None:+ for name in sorted(KNOWN_UNEXPORTABLE):+ with self.subTest(name=name):+ source = ASSETS / name+ self.assertTrue(source.is_file(), f"{name} is listed but not shipped")+ with self.assertRaises(ValueError):+ self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)+++if __name__ == "__main__":+ suite = unittest.defaultTestLoader.loadTestsFromTestCase(ExportSvgStandaloneTests)+ result = unittest.TextTestRunner(verbosity=2).run(suite)+ sys.exit(0 if result.wasSuccessful() else 1)diff --git a/scripts/verify-docs-sync.py b/scripts/verify-docs-sync.pyindex 0ba4eb4..6487bcc 100644--- a/scripts/verify-docs-sync.py+++ b/scripts/verify-docs-sync.py@@ -117,6 +117,7 @@ REQUIRED_PACKAGED_RUNTIME_FILES = frozenset("scripts/drawio_extract.py","scripts/mermaid_extract.py","scripts/excalidraw_extract.py",+ "scripts/export_svg.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.mdindex e2b7200..e1461fe 100644--- a/skills/diagram-design/SKILL.md+++ b/skills/diagram-design/SKILL.md@@ -383,6 +383,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. 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. 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.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.mdindex 20e2077..d92af04 100644--- a/skills/diagram-design/references/export.md+++ b/skills/diagram-design/references/export.md@@ -20,26 +20,51 @@ The slash command is a thin wrapper that delegates here — both paths run the sBoth formats are **diagram-only** — just the `<svg>` node. Editorial wrappers (header, summary cards, footer in `-full` variants) are intentionally dropped: the export deliverable is the diagram itself, suitable for Figma, slides, social cards, or blog images.-The SVG-only export keeps the source `<title>` and `<desc>` with the diagram. Their per-diagram and per-variant prefixed IDs are what make multiple exported SVGs safe to inline in the same page without one figure resolving to another figure's accessible name.+The SVG-only export keeps the source `<title>` and `<desc>` with the diagram. Their per-diagram and per-variant prefixed IDs keep accessible names unique when several figures share a page.++Inlining several exported SVGs in one host document also requires namespaced `<defs>` IDs (markers, patterns, gradients, filters, clip paths, masks, symbols). The export procedure prefixes those IDs with the source file slug and rewrites matching `url(#…)` / `href="#…"` references, so a light figure next to its `-dark` twin does not silently share arrowheads. The accessible-name guarantee alone is not enough.If the user explicitly asks for "a screenshot of the whole page including the cards", that's a different request — fall back to a normal full-page screenshot via the user's OS or browser.## SVG export procedure+**Prefer the packaged helper.** From this skill's directory run:++```+python3 scripts/export_svg.py <html-file> [<out.svg>]+```++That script is the source of truth for the transform below (CSS carry-forward, defs ID namespacing, rgba normalization, and the class-without-style gate). Reimplement only when the helper is unavailable; keep the behaviour identical.++### Manual algorithm (what the helper does)+1. Read the source HTML file.2. Extract the **first** `<svg ...>...</svg>` block. Use a multiline regex anchored on `<svg` and `</svg>`. Most generated diagrams have only one SVG; if there are multiple, the first is the diagram (gallery files are an exception — see *Edge cases*).3. Make it standalone:- 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.- - Inject Google Fonts `@import` so the SVG renders with correct typography in a browser. **XML-escape the `&` separators as `&`** — 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.)+ - 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.+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.+ - Start selectors that begin at the `<svg>` element at the root instead: `svg .zone` becomes `#<slug>-root .zone` and `svg text` becomes `#<slug>-root text`. The exported root element is the `<svg>` itself, so `#<slug>-root svg .zone` would match nothing.+ - Prefix every other kept selector with `#<slug>-root ` (e.g. `.station` → `#example-loop-root .station`).+ - **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 (`&` → `&`, `<` → `<`) 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 `&`** — 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>`):```svg<defs>- <style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500;600&family=Noto+Serif:ital@0;1&family=Noto+Sans+KR:wght@400;500;600&family=Noto+Serif+KR:wght@400&family=Noto+Sans+TC:wght@400;500;600&family=Noto+Serif+TC:wght@400&display=swap');</style>+ <style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500;600&family=Noto+Serif:ital@0;1&family=Noto+Sans+KR:wght@400;500;600&family=Noto+Serif+KR:wght@400&family=Noto+Sans+TC:wght@400;500;600&family=Noto+Serif+TC:wght@400&display=swap');+ /* …scoped diagram rules… */+ </style>+ <!-- existing markers / patterns stay here --></defs>```- If the SVG already contains a `<defs>` block, **merge** the `<style>` into it (don't add a second `<defs>`).-4. 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 the SVG string extracted in step 2, before writing the file:+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)"`.+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:```pythonimport re@@ -54,9 +79,10 @@ If the user explicitly asks for "a screenshot of the whole page including the casvg = re.sub(r'(fill|stroke)="transparent"', r'\1="none"', svg)```- The `\s*` around each channel tolerates a spaced `rgba(45, 49, 66, 0.03)` as well as the compact `rgba(45,49,66,0.03)` the templates normally use; `\d*\.?\d+` accepts an alpha value with or without a leading zero (both `0.03` and `.03` appear in shipped tokens). Matching is scoped to the `fill="..."` / `stroke="..."` presentation attribute, not the bare `rgba(` string, so nothing else is touched — the shipped templates and examples only ever express color through these two attributes on SVG elements, never a `style="..."` attribute or a `<style>` block. (A brand's onboarded palette in `style-guide.md` could in principle add a third notation such as `hsl()`; none exists in any shipped token today, so this pass doesn't handle it — extend the regex if one is ever introduced.)-5. Prepend `<?xml version="1.0" encoding="UTF-8"?>\n` so the file is well-formed XML.-6. Write to `<basename>.svg` next to the source (e.g. `example-architecture.html` → `example-architecture.svg`). Honour an explicit output path if the user provides one.+ The `\s*` around each channel tolerates a spaced `rgba(45, 49, 66, 0.03)` as well as the compact `rgba(45,49,66,0.03)` the templates normally use; `\d*\.?\d+` accepts an alpha value with or without a leading zero (both `0.03` and `.03` appear in shipped tokens). Matching is scoped to the `fill="..."` / `stroke="..."` presentation attribute. Class-styled diagrams may still carry `rgba(...)` inside the embedded `<style>` block via custom properties (e.g. `--accent-tint`); that form is correct in browsers and in Figma/Illustrator, and is out of scope for this presentation-attribute pass. (A brand's onboarded palette in `style-guide.md` could in principle add a third notation such as `hsl()`; none exists in any shipped token today, so this pass doesn't handle it — extend the regex if one is ever introduced.)+8. **Gate:** if the exported SVG still contains `class=` but no diagram CSS rules, stop and fix the CSS carry step — that fragment will render as black boxes. A fonts-only `<style>` (Google Fonts `@import` with no rules) does **not** satisfy the gate.+9. Prepend `<?xml version="1.0" encoding="UTF-8"?>\n` so the file is well-formed XML.+10. Write to `<basename>.svg` next to the source (e.g. `example-architecture.html` → `example-architecture.svg`). Honour an explicit output path if the user provides one.### Caveat to surface to the userdiff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.pynew file mode 100755index 0000000..ca15f5a--- /dev/null+++ b/skills/diagram-design/scripts/export_svg.py@@ -0,0 +1,418 @@+#!/usr/bin/env python3+"""Export a diagram HTML file to a standalone, inline-safe SVG.++Ships inside the skill so an installed agent can produce a portable SVG without+re-deriving the transform:++ python3 <skill-dir>/scripts/export_svg.py my-diagram.html+ python3 <skill-dir>/scripts/export_svg.py my-diagram.html out.svg++Fixes the export gaps that make a fragment unsafe to open or inline:++1. Class-styled diagrams keep their page ``<style>`` rules by embedding a+ scoped copy inside the SVG (otherwise every shape falls back to black).+2. Referenceable ``<defs>`` IDs (markers, patterns, gradients, …) are prefixed+ with the file slug so several exported figures can share one host document+ without ``url(#arrow)`` resolving to the wrong declaration.+3. HTML-only attribute syntax (``<g data-motion-item>``, ``data-step=1``) is+ rewritten as XML so the standalone file parses.++The algorithm matches ``references/export.md``. No third-party deps.+"""++from __future__ import annotations++import argparse+import re+import sys+import xml.etree.ElementTree as ET+from pathlib import Path++GOOGLE_FONTS_IMPORT = (+ "@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1"+ "&family=Geist:wght@400;500;600"+ "&family=Geist+Mono:wght@400;500;600"+ "&family=Noto+Serif:ital@0;1"+ "&family=Noto+Sans+KR:wght@400;500;600"+ "&family=Noto+Serif+KR:wght@400"+ "&family=Noto+Sans+TC:wght@400;500;600"+ "&family=Noto+Serif+TC:wght@400"+ "&display=swap');"+)++# Page chrome that must not follow a diagram fragment out of its host document.+# The bare `svg { width; min-width }` rule is page layout too (see+# is_chrome_selector); `svg .zone` and `svg text` are diagram rules.+CHROME_SELECTOR_RE = re.compile(+ r"^(?:"+ r"\*|html|body|main|header|footer|h1|h2|h3|p"+ r"|\.frame|\.eyebrow|\.summary|\.cards?|\.card|\.footer|\.header"+ r")(?:\s|:|,|$)",+ re.IGNORECASE,+)+# A selector that starts at the <svg> element: `svg .zone`, `svg text`, `svg>g`.+SVG_TYPE_PREFIX_RE = re.compile(r"^svg(?![\w-])", re.IGNORECASE)+# Inherited properties the page sets on `body` that SVG content relies on:+# `stroke="currentColor"` reads `color`, and text without its own font rule+# reads `font-family`.+BODY_INHERITED_RE = re.compile(r"(?:^|;)\s*(color|font-family)\s*:\s*([^;]+)", re.IGNORECASE)+CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)++# HTML-only attribute syntax that strict XML rejects: a valueless attribute+# (`<g data-motion-item>`) or an unquoted value (`data-step=1`).+XML_OPAQUE_OPEN_RE = re.compile(r"<!--|<!\[CDATA\[")+START_TAG_RE = re.compile(+ r"<([A-Za-z][\w:.-]*)"+ r"((?:\s+[^\s\"'<>/=]+(?:\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+))?)*)"+ r"(\s*/?)>"+)+TAG_ATTR_RE = re.compile(+ r"(\s+)([^\s\"'<>/=]+)(?:(\s*=\s*)(\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+))?"+)++DEFS_ID_TAGS = (+ "marker",+ "pattern",+ "linearGradient",+ "radialGradient",+ "filter",+ "clipPath",+ "mask",+ "symbol",+)++STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)+SVG_BLOCK_RE = re.compile(r"<svg\b[^>]*>.*?</svg>", re.IGNORECASE | re.DOTALL)+RULE_RE = re.compile(r"([^{}]+)\{([^{}]*)\}", re.DOTALL)+RGBA_ATTR_RE = re.compile(+ r'(fill|stroke)="rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d*\.?\d+)\s*\)"'+)+TRANSPARENT_ATTR_RE = re.compile(r'(fill|stroke)="transparent"')+++def slug_for(path: Path) -> str:+ """Stable ID prefix from the source basename (no extension)."""+ slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", path.stem).strip("-")+ if not slug:+ raise ValueError(f"cannot derive an ID slug from {path.name!r}")+ if slug[0].isdigit():+ slug = f"d-{slug}"+ return slug+++def extract_first_svg(html: str) -> str:+ match = SVG_BLOCK_RE.search(html)+ if not match:+ raise ValueError("no <svg> block found in source")+ return match.group(0)+++def _xml_start_tag(match: re.Match[str]) -> str:+ def attr(m: re.Match[str]) -> str:+ space, name, equals, value = m.groups()+ if value is None:+ return f'{space}{name}=""'+ if value[0] in "\"'":+ return m.group(0)+ return f'{space}{name}{equals}"{value}"'++ name, attrs, end = match.groups()+ return f"<{name}{TAG_ATTR_RE.sub(attr, attrs)}{end}>"+++def xmlify_attributes(svg: str) -> str:+ """Rewrite valueless and unquoted HTML attributes as XML (`attr=""`).++ Comments and CDATA sections are copied unchanged.+ """+ out: list[str] = []+ pos = 0+ while True:+ opener = XML_OPAQUE_OPEN_RE.search(svg, pos)+ text_end = opener.start() if opener else len(svg)+ out.append(START_TAG_RE.sub(_xml_start_tag, svg[pos:text_end]))+ if opener is None:+ break+ closer = "-->" if opener.group(0) == "<!--" else "]]>"+ close_at = svg.find(closer, opener.end())+ stop = len(svg) if close_at == -1 else close_at + len(closer)+ out.append(svg[opener.start() : stop])+ pos = stop+ if close_at == -1:+ break+ return "".join(out)+++def ensure_xmlns(svg: str) -> str:+ if re.search(r'\bxmlns\s*=\s*["\']http://www\.w3\.org/2000/svg["\']', svg):+ return svg+ return re.sub(r"<svg\b", '<svg xmlns="http://www.w3.org/2000/svg"', svg, count=1)+++def ensure_viewbox(svg: str) -> None:+ if not re.search(r"\bviewBox\s*=", svg, re.IGNORECASE):+ raise ValueError("SVG is missing a viewBox; refuse to guess")+++def set_root_id(svg: str, root_id: str) -> str:+ """Put `id="{root_id}"` on the opening <svg> tag (replace any existing id)."""++ 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++ return re.sub(r"<svg\b[^>]*>", repl, svg, count=1, flags=re.IGNORECASE)+++def is_chrome_selector(selector: str) -> bool:+ parts = [part.strip() for part in selector.split(",") if part.strip()]+ if not parts:+ return True+ return all(+ part.lower() == "svg" or CHROME_SELECTOR_RE.match(part) is not None for part in parts+ )+++def scope_selector(selector: str, root_id: str) -> str:+ scoped: list[str] = []+ for part in selector.split(","):+ part = part.strip()+ if not part:+ continue+ if part == ":root" or part.startswith(":root"):+ # `: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 part.startswith("#"):+ # Already an ID selector — leave alone (title/desc IDs stay global).+ scoped.append(part)+ elif SVG_TYPE_PREFIX_RE.match(part):+ # The exported root is the <svg> itself, so `svg .zone` becomes+ # `#root .zone` (`#root svg .zone` would match nothing). A bare+ # `svg` in a mixed list is page layout and is dropped.+ rest = part[len("svg") :]+ if rest:+ scoped.append(f"#{root_id}{rest}")+ else:+ scoped.append(f"#{root_id} {part}")+ return ", ".join(scoped)+++def body_inherited_css(selector: str, body: str, root_id: str) -> str:+ """Bind `color` / `font-family` from a dropped `body` rule to the SVG root."""+ parts = [part.strip().lower() for part in selector.split(",")]+ if "body" not in parts:+ return ""+ declarations = [+ f"{name.lower()}: {value.strip()}" for name, value in BODY_INHERITED_RE.findall(body)+ ]+ if not declarations:+ return ""+ return f"#{root_id} {{ {'; '.join(declarations)}; }}"+++def escape_css_for_xml(css: str) -> str:+ """Escape XML-sensitive characters in CSS embedded inside an SVG <style>."""+ # Order matters: amp first so we do not re-escape entities we just wrote.+ return css.replace("&", "&").replace("<", "<")+++def diagram_css_from_html(html: str, 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):+ # A comment before a rule would otherwise become part of its selector+ # (`/* 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())+ body = match.group(2).strip()+ if not selector or not body:+ continue+ inherited = body_inherited_css(selector, body, root_id)+ if inherited:+ kept.append(escape_css_for_xml(inherited))+ if is_chrome_selector(selector):+ continue+ # Escape rule text before it lands in SVG XML (e.g. content:"R&D").+ kept.append(+ escape_css_for_xml(f"{scope_selector(selector, root_id)} {{ {body} }}")+ )+ return "\n ".join(kept)+++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+ if style_css.strip():+ style_inner = f"{GOOGLE_FONTS_IMPORT}\n {style_css.strip()}"+ style_tag = f"<style>{style_inner}</style>"++ defs_match = re.search(r"<defs\b[^>]*>", svg, re.IGNORECASE)+ if defs_match:+ 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).+ open_match = re.match(r"<svg\b[^>]*>", svg, re.IGNORECASE)+ assert open_match is not None+ insert_at = open_match.end()+ return (+ svg[:insert_at]+ + f"\n <defs>\n {style_tag}\n </defs>"+ + svg[insert_at:]+ )+++def find_defs_ids(svg: str) -> list[str]:+ """IDs on referenceable elements living under <defs>."""+ defs_blocks = re.findall(r"<defs\b[^>]*>(.*?)</defs>", svg, re.IGNORECASE | re.DOTALL)+ if not defs_blocks:+ return []+ tag_alt = "|".join(DEFS_ID_TAGS)+ pattern = re.compile(+ rf"<(?:{tag_alt})\b[^>]*\bid\s*=\s*[\"']([^\"']+)[\"']",+ re.IGNORECASE,+ )+ found: list[str] = []+ seen: set[str] = set()+ for block in defs_blocks:+ for match in pattern.finditer(block):+ ident = match.group(1)+ if ident not in seen:+ seen.add(ident)+ found.append(ident)+ return found+++def namespace_defs_ids(svg: str, prefix: str) -> str:+ """Prefix defs IDs and rewrite url(#…)/href="#…" references, longest first."""+ 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 normalize_rgba_presentation_attrs(svg: str) -> str:+ """Split rgba()/transparent presentation attrs for strict SVG 1.1 importers."""++ def repl(match: re.Match[str]) -> str:+ prop, r, g, b, a = match.groups()+ return '{0}="#{1:02x}{2:02x}{3:02x}" {0}-opacity="{4}"'.format(+ prop, int(r), int(g), int(b), a+ )++ svg = RGBA_ATTR_RE.sub(repl, svg)+ svg = TRANSPARENT_ATTR_RE.sub(r'\1="none"', svg)+ return svg+++def has_diagram_stylesheet(svg: str) -> bool:+ """True when a <style> block contains CSS rules beyond the fonts @import."""+ for block in STYLE_BLOCK_RE.findall(svg):+ stripped = re.sub(r"@import\b[^;]*;", "", block, flags=re.IGNORECASE)+ stripped = re.sub(r"/\*.*?\*/", "", stripped, flags=re.DOTALL)+ if RULE_RE.search(stripped):+ return True+ return False+++def assert_export_gate(svg: str) -> None:+ """Refuse a class-styled fragment that shipped without diagram CSS.++ A fonts-only <style> (Google Fonts @import with no rules) does not count —+ class-based fills would still render as black boxes.+ """+ if re.search(r"\bclass\s*=", svg) and not has_diagram_stylesheet(svg):+ raise ValueError(+ "exported SVG uses class= but has no diagram CSS rules; class-based "+ "fills would render as black boxes. Carry the page CSS into the SVG."+ )+++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))+ ensure_viewbox(svg)+ svg = ensure_xmlns(svg)+ svg = set_root_id(svg, root_id)+ diagram_css = diagram_css_from_html(html, root_id)+ svg = merge_style_into_defs(svg, diagram_css)+ svg = namespace_defs_ids(svg, slug)+ svg = normalize_rgba_presentation_attrs(svg)+ assert_export_gate(svg)+ document = '<?xml version="1.0" encoding="UTF-8"?>\n' + svg + "\n"+ # Catch any remaining XML-breaking characters in carried content.+ try:+ ET.fromstring(document)+ except ET.ParseError as exc:+ raise ValueError(f"exported SVG is not well-formed XML: {exc}") from exc+ return document+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Export a diagram-design HTML file to a standalone SVG."+ )+ parser.add_argument("source", type=Path, help="Source .html diagram file")+ parser.add_argument(+ "output",+ type=Path,+ nargs="?",+ help="Output .svg path (default: <source-stem>.svg next to the source)",+ )+ args = parser.parse_args(argv)++ source: Path = args.source+ if not source.is_file():+ print(f"error: source not found: {source}", file=sys.stderr)+ return 2+ if source.name == "index.html" and source.parent.name == "assets":+ print(+ "error: refuse to export the gallery (assets/index.html); "+ "pick a specific diagram file",+ file=sys.stderr,+ )+ return 2++ try:+ html = source.read_text(encoding="utf-8")+ document = export_svg_document(html, source)+ except ValueError as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2++ output = args.output if args.output is not None else source.with_suffix(".svg")+ output.write_text(document, encoding="utf-8")+ print(output)+ return 0+++if __name__ == "__main__":+ sys.exit(main())