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 SVG and PNG export fixes from ten PRs (#411)
Cathryn Lavery09c1428533cc
diff --git a/commands/export-diagram.md b/commands/export-diagram.mdindex 03fc502..6fc2d21 100644--- a/commands/export-diagram.md+++ b/commands/export-diagram.md@@ -23,7 +23,7 @@ Full argument string: `$ARGUMENTS`- `--svg-only` — emit only the SVG. Skip Playwright entirely.- `--png-only` — emit only the PNG.-- `--scale=1` / `--scale=2` / `--scale=3` — override the PNG device scale factor. Default `2`.+- `--scale=N` — override the PNG device scale factor with a finite number from `1` to `4`, including fractional values such as `1.25`. Default `2`.- `--output=<path>` — override the output base path; the format extension is appended. Applies to both formats when both are produced.- `--registry` — emit `<basename>.registry.json`, a metadata sidecar of every block's `data-block-*` attributes. Follows [`skills/diagram-design/references/export-registry.md`](../skills/diagram-design/references/export-registry.md), a procedure independent of the SVG/PNG rasterization above — it never needs Playwright. Used alone (see Defaults), it is the *only* output produced. Combine with `--svg-only` and/or `--png-only` to also produce an image in the same call.@@ -33,7 +33,7 @@ Full argument string: `$ARGUMENTS`2. **Source is `assets/index.html`** (the gallery, multiple SVGs in one file) → refuse and ask which specific diagram file. Per the reference's edge-case section.3. **Source has no `<svg>` block** → refuse and tell the user; don't write anything.4. **PNG requested but Playwright not installed** → surface the install instruction from the reference verbatim and stop. Do **not** auto-install.-5. **PNG requested with `--scale` outside {1,2,3}** → reject; valid values are 1, 2, 3.+5. **PNG requested with a non-numeric or non-finite `--scale`, or a value outside the inclusive 1–4 range** → reject. Fractional values within that range are valid.6. **`--registry` requested but source has no `data-block-id` attributes** → refuse and tell the user; don't emit an empty or partial registry file. Per the export-registry reference's edge-case section.7. **`--registry` is the only flag given** (no `--svg-only`/`--png-only`) → emit only the registry JSON. Do not also produce SVG/PNG, and do not check for Playwright — a registry-only call must succeed on a host that doesn't have it installed at all.diff --git a/prompts/export-diagram.md b/prompts/export-diagram.mdindex 9610313..7c20f08 100644--- a/prompts/export-diagram.md+++ b/prompts/export-diagram.md@@ -17,7 +17,7 @@ Full argument string: `$ARGUMENTS`- `--svg-only` — emit SVG only. Skip Playwright.- `--png-only` — emit PNG only.-- `--scale=1`, `--scale=2`, or `--scale=3` — override PNG device scale factor.+- `--scale=N` — override PNG device scale factor with a finite number from `1` to `4`, including fractional values such as `1.25`. Default `2`.- `--output=<path>` — override output base path; append format extension.- `--registry` — emit `<basename>.registry.json`, a metadata sidecar of every block's `data-block-*` attributes. Never needs Playwright. Used alone (see Defaults) it is the only output; combine with `--svg-only` and/or `--png-only` to also produce an image.@@ -27,7 +27,7 @@ Full argument string: `$ARGUMENTS`2. Source is `assets/index.html` → refuse; ask for specific diagram file.3. Source lacks `<svg>` → refuse; write nothing.4. PNG requested without Playwright → show install instruction from reference verbatim; stop. Do not auto-install.-5. `--scale` outside {1, 2, 3} → reject.+5. PNG requested with a non-numeric or non-finite `--scale`, or a value outside the inclusive 1–4 range → reject. Fractional values within that range are valid.6. Both `--svg-only` and `--png-only` supplied → reject them as mutually exclusive.7. `--registry` requested but source has no `data-block-id` attributes → refuse; write nothing. Per the export-registry reference's edge-case section.8. `--registry` is the only flag given (no `--svg-only`/`--png-only`) → emit only the registry JSON; do not also produce SVG/PNG and do not check for Playwright.diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.pyindex dac92be..b1165fc 100644--- a/scripts/test-export-svg-standalone.py+++ b/scripts/test-export-svg-standalone.py@@ -7,6 +7,8 @@ the contract documented in references/export.md (issues #202 and #203).from __future__ import annotations+import contextlib+import ioimport importlib.utilimport reimport sys@@ -14,6 +16,7 @@ import tempfileimport unittestimport xml.etree.ElementTree as ETfrom pathlib import Path+from unittest.mock import patchROOT = Path(__file__).resolve().parent.parentHELPER = ROOT / "skills/diagram-design/scripts/export_svg.py"@@ -84,6 +87,253 @@ class ExportSvgStandaloneTests(unittest.TestCase):def setUpClass(cls) -> None:cls.mod = load_helper()+ def test_cli_reports_source_read_errors_without_output(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ source = Path(directory) / "source.html"+ source.write_text('<svg viewBox="0 0 10 10"></svg>', encoding="utf-8")+ output = Path(directory) / "output.svg"+ stderr = io.StringIO()+ with patch.object(Path, "read_text", side_effect=PermissionError("source denied")):+ with contextlib.redirect_stderr(stderr):+ result = self.mod.main([str(source), str(output)])+ self.assertEqual(result, 2)+ self.assertIn("error: source denied", stderr.getvalue())+ self.assertNotIn("Traceback", stderr.getvalue())+ self.assertFalse(output.exists())++ def test_cli_reports_output_io_errors_without_traceback(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ source = Path(directory) / "source.html"+ source.write_text('<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>', encoding="utf-8")+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ result = self.mod.main([str(source), directory])+ self.assertEqual(result, 2)+ self.assertIn("error:", stderr.getvalue())+ self.assertNotIn("Traceback", stderr.getvalue())++ def test_nested_namespace_does_not_replace_root_namespace(self) -> None:+ markup = '<svg viewBox="0 0 10 10"><g xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10"/></g></svg>'+ result = self.mod.ensure_xmlns(markup)+ self.assertEqual(ET.fromstring(result).tag, "{http://www.w3.org/2000/svg}svg")+ with self.assertRaisesRegex(ValueError, "root namespace"):+ self.mod.ensure_xmlns('<svg xmlns="https://example.invalid/other"/>')++ def test_viewbox_has_four_finite_values_and_positive_extents(self) -> None:+ for value in ("0 0 0 10", "0 0 -10 10", "0 0 nan 10", "0 0 1e309 10", "0 0 10", "0,,0,10,10", "٠ ٠ ١٠ ١٠"):+ with self.subTest(value=value), self.assertRaisesRegex(ValueError, "viewBox"):+ self.mod.ensure_viewbox(f'<svg viewBox="{value}"/>')+ for value in ("-10,+10,100.5,50", "0 0 1e2 1e-2", "0 0 10 10"):+ self.mod.ensure_viewbox(f'<svg viewBox="{value}"/>')++ def test_viewbox_reads_exact_root_attribute(self) -> None:+ html = '<svg data-viewBox="preview" data-note=\'viewBox="preview"\' viewBox="0 0 100 100"></svg>'+ root = ET.fromstring(self.mod.export_svg_document(html, Path("viewport.html")))+ self.assertEqual(root.get("viewBox"), "0 0 100 100")+ for svg in (+ '<svg data-viewBox="0 0 100 100" viewBox="0 0 0 100"></svg>',+ '<svg data-viewBox="0 0 100 100"></svg>',+ '<svg><g viewBox="0 0 100 100"/></svg>',+ ):+ with self.subTest(svg=svg), self.assertRaisesRegex(ValueError, "viewBox"):+ self.mod.export_svg_document(svg, Path("viewport.html"))++ def test_viewbox_refuses_non_svg_whitespace(self) -> None:+ for value in ("0 0 100 100", " 0 0 100 100", "0 0 100 100 "):+ with self.subTest(value=value), self.assertRaisesRegex(ValueError, "viewBox"):+ self.mod.export_svg_document(f'<svg viewBox="{value}"></svg>', Path("viewport.html"))++ def test_css_gate_ignores_non_class_and_empty_attributes(self) -> None:+ for markup in (+ '<svg data-class="metadata"><rect fill="#fff"/></svg>',+ '<svg><!-- class="archived" --><rect fill="#fff"/></svg>',+ '<svg class=" "><rect fill="#fff"/></svg>',+ '<svg><text>class="example"</text></svg>',+ ):+ with self.subTest(markup=markup):+ self.mod.assert_export_gate(markup)+ with self.assertRaisesRegex(ValueError, "no diagram CSS"):+ self.mod.assert_export_gate('<svg><rect class="paint"/></svg>')++ def test_export_uses_live_svg_and_live_styles(self) -> None:+ html = '<!-- <svg viewBox="0 0 1 1"></svg> --><script>const sample = "<svg viewBox=\"0 0 2 2\"></svg>";</script>'+ html += '<!-- <style>.paint {fill:red;}</style> -->'+ html += '<style>.paint {fill:blue;}</style><svg viewBox="0 0 10 10"><!-- archived </svg> --><rect class="paint" width="10" height="10"/></svg>'+ document = self.mod.export_svg_document(html, Path("live.html"))+ root = ET.fromstring(document)+ self.assertEqual(root.get("viewBox"), "0 0 10 10")+ self.assertIn("fill:blue", document)+ self.assertNotIn("fill:red", document)+ self.assertIn("<!-- archived </svg> -->", document)++ def test_live_css_comment_markers_and_strings_are_preserved(self) -> None:+ css = '.x { fill:red; /* <!-- */ stroke:blue; /* --> */ } .x::before { content:"<!-- note -->"; }'+ html = f'<style>{css}</style><svg viewBox="0 0 10 10"><rect class="x" width="10" height="10"/></svg>'+ root = ET.fromstring(self.mod.export_svg_document(html, Path("live-style.html")))+ styles = "".join(element.text or "" for element in root.iter() if element.tag.endswith("}style"))+ self.assertIn("stroke:blue", styles)+ self.assertIn('content:"<!-- note -->"', styles)++ def test_svg_cdata_comment_marker_does_not_hide_closing_svg(self) -> None:+ html = '<svg viewBox="0 0 10 10"><text><![CDATA[<!--]]></text></svg><!-- footer -->'+ document = self.mod.export_svg_document(html, Path("cdata.html"))+ root = ET.fromstring(document)+ self.assertEqual(root.get("viewBox"), "0 0 10 10")+ text = next(element for element in root.iter() if element.tag.endswith("}text"))+ self.assertEqual(text.text, "<!--")+ self.assertNotIn("footer", document)++ def test_rgba_normalization_clamps_channels_and_alpha(self) -> None:+ for value, paint, opacity in (+ ("rgba(300,0,0,0.5)", "#ff0000", "0.5"),+ ("rgba(-12,300,10,0.5)", "#00ff0a", "0.5"),+ ("rgba(45,49,66,-0.1)", "#2d3142", "0"),+ ("rgba(45,49,66,1.5)", "#2d3142", "1"),+ ):+ with self.subTest(value=value):+ normalized = self.mod.normalize_rgba_presentation_attrs(f'<svg><rect fill="{value}"/></svg>')+ rect = ET.fromstring(normalized)[0]+ self.assertEqual(rect.get("fill"), paint)+ self.assertEqual(rect.get("fill-opacity"), opacity)++ def test_manual_paint_recipe_retains_css_clamping(self) -> None:+ section = EXPORT_MD.read_text(encoding="utf-8").split("7. Normalize colors", 1)[1]+ match = re.search(r"```python\n(.*?)\n ```", section, re.DOTALL)+ self.assertIsNotNone(match)+ recipe = "\n".join(line[3:] if line.startswith(" ") else line for line in match.group(1).splitlines())+ for svg in ('<svg><rect fill="rgba(300,-10,20,2)"/></svg>', '<svg><rect stroke="rgba(-4,1,2,-.5)"/></svg>'):+ with self.subTest(svg=svg):+ namespace = {"svg": svg}+ exec(recipe, namespace)+ self.assertEqual(namespace["svg"], self.mod.normalize_rgba_presentation_attrs(svg))++ def test_defs_id_selectors_follow_namespaced_ids(self) -> None:+ markup = '<svg><defs><linearGradient id="abc"><stop/></linearGradient></defs><style>#abc stop { stop-color:#abc; } #abc-other { fill:#fff; }</style></svg>'+ result = self.mod.namespace_defs_ids(markup, "diagram")+ self.assertIn('#diagram-abc stop { stop-color:#abc; }', result)+ self.assertIn('#abc-other { fill:#fff; }', result)+ escaped = r'<svg><defs><linearGradient id="paint.v1"/></defs><style>#paint\.v1 stop { stop-color:#fff; }</style></svg>'+ result = self.mod.namespace_defs_ids(escaped, "diagram")+ self.assertIn(r'#diagram-paint\.v1 stop', result)++ def test_defs_selector_retarget_keeps_cdata_stylesheets(self) -> None:+ css = '.paint { fill:red; } #abc stop { stop-color:#fff; }'+ markup = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="abc"><stop/></linearGradient></defs>'+ '<style><![CDATA[' + css + ']]></style><rect class="paint" width="5" height="5"/></svg>')+ result = self.mod.namespace_defs_ids(markup, "diagram")+ self.assertIn('<style><![CDATA[.paint { fill:red; } #diagram-abc stop { stop-color:#fff; }]]></style>', result)+ self.assertNotIn('<![CDATA[', result)+ root = ET.fromstring(self.mod.export_svg_document(markup, Path("diagram.html")))+ texts = [element.text or "" for element in root.iter() if element.tag.endswith("}style")]+ # The SVG's own <style> keeps working CSS after the defs rename.+ self.assertIn('.paint { fill:red; } #diagram-abc stop { stop-color:#fff; }', texts)++ def test_defs_selector_retarget_survives_quotes_in_css_comments(self) -> None:+ for wrap in (lambda css: css, lambda css: "<![CDATA[" + css + "]]>"):+ css = "#shape { /* user's color */ fill:red; }"+ markup = ('<svg><defs><g id="shape"/></defs><style>' + wrap(css) + '</style>'+ '<use href="#shape"/></svg>')+ with self.subTest(markup=markup):+ result = self.mod.namespace_defs_ids(markup, "diagram")+ self.assertIn("#diagram-shape { /* user's color */ fill:red; }", result)++ def test_cdata_url_references_stay_raw_after_defs_rename(self) -> None:+ markup = ('<svg><defs><linearGradient id="A&B"/></defs>'+ '<style><![CDATA[.paint { fill:url(#A&B); }]]></style></svg>')+ result = self.mod.namespace_defs_ids(markup, "diagram")+ self.assertIn('id="diagram-A&B"', result)+ self.assertIn("<![CDATA[.paint { fill:url(#diagram-A&B); }]]>", result)+ plain = ('<svg><defs><linearGradient id="A&B"/></defs>'+ '<style>.paint { fill:url(#A&B); }</style></svg>')+ self.assertIn(".paint { fill:url(#diagram-A&B); }", self.mod.namespace_defs_ids(plain, "diagram"))++ def test_unfinished_rule_with_repeated_comments_does_not_stall(self) -> None:+ import subprocess+ markup = ('<svg><defs><g id="shape"/></defs><style>.paint { fill:red;'+ + "/*x*/" * 40 + '</style><use href="#shape"/></svg>')+ code = ("import importlib.util, sys; spec = importlib.util.spec_from_file_location('e', sys.argv[1]); "+ "mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod); "+ "print(mod.namespace_defs_ids(sys.stdin.read(), 'diagram'))")+ try:+ result = subprocess.run([sys.executable, "-c", code, str(HELPER)], input=markup,+ capture_output=True, text=True, timeout=10)+ except subprocess.TimeoutExpired:+ self.fail("an unfinished rule followed by repeated CSS comments stalled the rule matcher")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn('id="diagram-shape"', result.stdout)++ def test_style_closing_tag_whitespace_keeps_selectors_retargeted(self) -> None:+ markup = '<svg><defs><g id="shape"/></defs><style>#shape { fill:red; }</style ><use href="#shape"/></svg>'+ self.assertIn("#diagram-shape { fill:red; }", self.mod.namespace_defs_ids(markup, "diagram"))++ def test_defs_selectors_decode_xml_and_preserve_escaped_braces(self) -> None:+ for ident, selector, expected_id, expected_selector in (+ ("p.v", r"#p\.v", "diagram-p.v", r"#diagram-p\.v"),+ ("paint{v", r"#paint\{v", "diagram-paint{v", r"#diagram-paint\{v"),+ ("A&B", r"#A\&B", "diagram-A&B", r"#diagram-A\&B"),+ ):+ with self.subTest(ident=ident):+ html = '<svg viewBox="0 0 10 10"><defs><linearGradient id="' + ident + '"/></defs>'+ html += '<style>' + selector + ' stop { stop-color:#fff; }</style></svg>'+ root = ET.fromstring(self.mod.export_svg_document(html, Path("diagram.html")))+ gradient = next(element for element in root.iter() if element.tag.endswith("}linearGradient"))+ self.assertEqual(gradient.get("id"), expected_id)+ css = "".join(element.text or "" for element in root.iter() if element.tag.endswith("}style"))+ self.assertIn(expected_selector + " stop { stop-color:#fff; }", css)++ def test_reusable_defs_shapes_are_namespaced(self) -> None:+ for tag in ("g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "image", "use"):+ with self.subTest(tag=tag):+ markup = f'<svg><defs><{tag} id="shape"/></defs><use href="#shape"/><use xlink:href="#shape"/></svg>'+ result = self.mod.namespace_defs_ids(markup, "diagram")+ self.assertIn('id="diagram-shape"', result)+ self.assertIn('href="#diagram-shape"', result)+ self.assertIn('xlink:href="#diagram-shape"', result)++ def test_reusable_shapes_keep_css_id_styles_after_public_export(self) -> None:+ html = '<style>#abc { fill:#abc; } #holder > path { stroke:red; }</style>'+ html += '<svg viewBox="0 0 10 10"><defs><g id="holder"><path id="abc" d="M0 0H10V10H0Z"/></g></defs>'+ html += '<use href="#holder"/></svg>'+ root = ET.fromstring(self.mod.export_svg_document(html, Path("diagram.html")))+ css = "".join(element.text or "" for element in root.iter() if element.tag.endswith("}style"))+ self.assertIn("#diagram-abc { fill:#abc; }", css)+ self.assertIn("#diagram-holder > path { stroke:red; }", css)+ self.assertEqual(next(element for element in root.iter() if element.tag.endswith("}path")).get("id"), "diagram-abc")+ self.assertEqual(next(element for element in root.iter() if element.tag.endswith("}use")).get("href"), "#diagram-holder")++ def test_defs_references_compare_decoded_xml_ids(self) -> None:+ markup = '<svg><defs><linearGradient id="A&B"/></defs><use href="#A&B"/><rect fill="url(#A&B)"/></svg>'+ result = self.mod.namespace_defs_ids(markup, "diagram")+ root = ET.fromstring(result)+ self.assertEqual(root[0][0].get("id"), "diagram-A&B")+ self.assertEqual(root[1].get("href"), "#diagram-A&B")+ self.assertEqual(root[2].get("fill"), "url(#diagram-A&B)")++ def test_distinct_once_decoded_ids_keep_distinct_definitions_and_references(self) -> None:+ markup = '<svg><defs><linearGradient id="A&B"/><linearGradient id="A&#38;B"/></defs>'+ markup += '<use href="#A&B"/><use href="#A&#38;B"/>'+ markup += '<rect fill="url(#A&B)"/><rect fill="url(#A&#38;B)"/></svg>'+ root = ET.fromstring(self.mod.namespace_defs_ids(markup, "diagram"))+ self.assertEqual([element.get("id") for element in root.find("defs")],+ ["diagram-A&B", "diagram-A&B"])+ self.assertEqual([element.get("href") for element in root.findall("use")],+ ["#diagram-A&B", "#diagram-A&B"])+ self.assertEqual([element.get("fill") for element in root.findall("rect")],+ ["url(#diagram-A&B)", "url(#diagram-A&B)"])++ def test_style_selectors_follow_once_decoded_distinct_defs_ids(self) -> None:+ # #376 selector retargeting combined with #381 single-decode IDs:+ # A&B and A&#38;B are different IDs and keep different rules.+ html = r'<svg viewBox="0 0 10 10"><defs><linearGradient id="A&B"/><linearGradient id="A&#38;B"/></defs>'+ html += r'<style>#A\&B stop { stop-color:red; } #A\&\#38\;B stop { stop-color:blue; }</style>'+ html += '<rect fill="url(#A&B)"/><rect fill="url(#A&#38;B)"/></svg>'+ root = ET.fromstring(self.mod.export_svg_document(html, Path("diagram.html")))+ css = "".join(element.text or "" for element in root.iter() if element.tag.endswith("}style"))+ self.assertIn(r"#diagram-A\&B stop { stop-color:red; }", css)+ self.assertIn(r"#diagram-A\&\#38\;B stop { stop-color:blue; }", css)+ self.assertEqual([element.get("fill") for element in root.iter() if element.tag.endswith("}rect")],+ ["url(#diagram-A&B)", "url(#diagram-A&B)"])+def test_helper_and_docs_exist(self) -> None:self.assertTrue(HELPER.is_file())self.assertTrue(EXPORT_MD.is_file())diff --git a/scripts/test-export-wait.py b/scripts/test-export-wait.pyindex 735e2a8..315999b 100644--- a/scripts/test-export-wait.py+++ b/scripts/test-export-wait.py@@ -21,6 +21,7 @@ import ioimport reimport subprocessimport sys+import structimport tempfileimport threadingimport time@@ -141,11 +142,11 @@ def start_stall_server(handler: type[BaseHTTPRequestHandler] = _StallHandler) ->return server-def run_snippet(snippet: str, src: Path, out: Path) -> str:+def run_snippet(snippet: str, src: Path, out: Path, scale: str | None = None) -> str:"""Exec the doc snippet with the given argv; return captured stderr."""stderr = io.StringIO()old_argv, old_stderr = sys.argv, sys.stderr- sys.argv = ["export", str(src), str(out)]+ sys.argv = ["export", str(src), str(out)] + ([scale] if scale is not None else [])try:with contextlib.redirect_stderr(stderr):exec(compile(snippet, str(EXPORT_DOC), "exec"), {"__name__": "export_snippet"})@@ -302,6 +303,41 @@ def require_encoded_paths(snippet: str, tmp: Path) -> None:print("OK: legal filename characters are encoded in the file URL")+def require_fractional_scales(snippet: str, tmp: Path) -> None:+ source = tmp / "normal-fixture.html" # 400 by 240 viewBox units+ # Page layout must not change dimensions promised by the viewBox contract.+ source.write_text(source.read_text(encoding="utf-8").replace("</head>", "<style>svg { width:1200px; min-width:1200px; height:auto; }</style></head>"), encoding="utf-8")+ for scale, dimensions in (("1", (400, 240)), ("1.25", (500, 300)),+ ("1.5", (600, 360)), ("3", (1200, 720)), ("4", (1600, 960))):+ output = tmp / f"scale-{scale}.png"+ run_snippet(snippet, source, output, scale)+ require_png(output, scale)+ actual = struct.unpack(">II", output.read_bytes()[16:24])+ if actual != dimensions:+ raise AssertionError(f"scale {scale}: expected {dimensions}, got {actual}")+ for viewbox in ("0 0 0 240", "0 0 400 0", "not-a-viewbox"):+ broken = tmp / "invalid-viewbox.html"+ broken.write_text(source.read_text(encoding="utf-8").replace("viewBox='0 0 400 240'", f"viewBox='{viewbox}'"), encoding="utf-8")+ output = tmp / "invalid-viewbox.png"+ try:+ run_snippet(snippet, broken, output, "2")+ except Exception as exc:+ if "viewBox" not in str(exc) or output.exists():+ raise AssertionError(f"invalid viewBox failed incorrectly: {exc}")+ else:+ raise AssertionError(f"invalid viewBox {viewbox!r} was accepted")+ for scale in ("0.5", "4.1", "nan", "inf", "not-a-number"):+ output = tmp / "invalid-scale.png"+ try:+ run_snippet(snippet, source, output, scale)+ except ValueError:+ if output.exists():+ raise AssertionError(f"invalid scale {scale} wrote a PNG")+ else:+ raise AssertionError(f"invalid scale {scale} was accepted")+ print("OK: fractional scales produce exact dimensions; invalid scales fail")++def require_other_errors_propagate(snippet: str, tmp: Path) -> None:missing = tmp / "does-not-exist.html"out = tmp / "never.png"@@ -366,6 +402,7 @@ def main() -> int:require_stalled_font_fallback(snippet, tmp)require_normal_load(snippet, tmp)require_encoded_paths(snippet, tmp)+ require_fractional_scales(snippet, tmp)require_other_errors_propagate(snippet, tmp)require_static_motion_frame(snippet, tmp)print("All export-wait cases passed.")diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.mdindex ba180ab..5c6a605 100644--- a/skills/diagram-design/references/export.md+++ b/skills/diagram-design/references/export.md@@ -36,14 +36,14 @@ python3 scripts/export_svg.py <html-file> [<out.svg>] [--system-fonts]`--system-fonts` skips the Google Fonts `@import` (step 5) so the SVG makes no network request; use it when the skin's font source is `system` (see [style-guide.md § Font source](style-guide.md#font-source)). The diagram CSS still carries over.-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.+Source read and output write failures return exit 2 with an error diagnostic. The viewport must contain four finite SVG numbers with positive width and height; empty or disabled viewports are refused. The class-without-style gate inspects nonempty actual `class` attributes; comments, visible text, empty class values, and `data-class` metadata do not require a stylesheet. Export selects a live SVG and carries live style blocks; HTML comments and script literals do not contribute diagrams or CSS. Comments inside the selected SVG remain intact. 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 the opening tag has `xmlns="http://www.w3.org/2000/svg"`. Add it if missing. The SVG namespace must belong to the root SVG element; a namespace on a descendant does not satisfy it. An explicit incompatible root namespace is refused.- 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. Known named HTML character references in labels and attributes become equivalent XML-safe text (for example, ` ` becomes a nonbreaking space). HTML's legacy names such as `©` and ` ` 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.@@ -65,23 +65,40 @@ 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. 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)"`.+6. **Namespace `<defs>` IDs.** Prefix every referenceable defs ID — on `marker`, `pattern`, `linearGradient`, `radialGradient`, `filter`, `clipPath`, `mask`, `symbol`, and reusable graphics (`g`, `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `text`, `image`, and `use`) — with `<slug>-`, and rewrite matching `url(#…)` and `href="#…"` / `xlink:href="#…"` references. Compare ID and fragment values after XML character-reference decoding, so equivalent named and numeric references stay connected. Retarget ID selectors in embedded style rules while leaving declaration colors and unrelated IDs unchanged. 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:```pythonimport re- svg = re.sub(- r'(fill|stroke)="rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d*\.?\d+)\s*\)"',- lambda m: '{0}="#{1:02x}{2:02x}{3:02x}" {0}-opacity="{4}"'.format(- m.group(1), int(m.group(2)), int(m.group(3)), int(m.group(4)), m.group(5)- ),- svg,++ RGBA_ATTR_RE = re.compile(+ r'(fill|stroke)="rgba\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d*\.?\d+)\s*\)"')- svg = re.sub(r'(fill|stroke)="transparent"', r'\1="none"', svg)+++ TRANSPARENT_ATTR_RE = re.compile(r'(fill|stroke)="transparent"')+++ 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, max(0, min(255, int(r))), max(0, min(255, int(g))),+ max(0, min(255, int(b))), a if 0 <= float(a) <= 1 else "0" if float(a) < 0 else "1"+ )++ svg = RGBA_ATTR_RE.sub(repl, svg)+ svg = TRANSPARENT_ATTR_RE.sub(r'\1="none"', svg)+ return svg+++ svg = normalize_rgba_presentation_attrs(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. 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.)+ Channels and alpha are clamped to the CSS ranges 0–255 and 0–1 so out-of-range rgba values retain their browser paint when converted. 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.@@ -123,10 +140,12 @@ passed detection: `python3 <tmp.py> <src.html> <out.png>` or```pythonfrom playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright-import sys, pathlib+import sys, pathlib, mathsrc, out = sys.argv[1], sys.argv[2]-scale = int(sys.argv[3]) if len(sys.argv) > 3 else 2+scale = float(sys.argv[3]) if len(sys.argv) > 3 else 2+if not math.isfinite(scale) or not 1 <= scale <= 4:+ raise ValueError("PNG scale must be a finite number between 1 and 4")with sync_playwright() as p:browser = p.chromium.launch()@@ -146,6 +165,15 @@ with sync_playwright() as p:):raise RuntimeError("motion export requires a complete static frame")svg = page.locator("svg").first+ # Capture at one CSS pixel per viewBox unit before applying the multiplier.+ svg.evaluate("""el => {+ const box = el.viewBox.baseVal;+ if (![box.width, box.height].every(n => Number.isFinite(n) && n > 0))+ throw new Error('PNG export requires a nonzero finite viewBox');+ for (const [axis, size] of [['width', box.width], ['height', box.height]])+ for (const prefix of ['', 'min-', 'max-'])+ el.style.setProperty(prefix + axis, size + 'px', 'important');+ }""")# Release every clipping ancestor (local scroller, overflow:hidden chrome)# so an SVG wider than its frame is captured whole.svg.evaluate("el => { for (let a = el.parentElement; a; a = a.parentElement) a.style.setProperty('overflow', 'visible', 'important'); }")@@ -155,7 +183,7 @@ with sync_playwright() as p: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.+Default `device_scale_factor=2` for crisp output. Accept `1` for compact assets or `3` for print/retina hero use, passed as a third CLI arg. Fractional scales such as `1.25` are also accepted within the documented 1–4 range for exact pixel sizes.The overflow release matters for the wide presets. `min-width` equals the viewBox width (see [`output-spec.md`](output-spec.md)), so a `doc-wide` or `slide-16x9` SVG is 1280px inside a 1200px frame, and its `.diagram-container` scroller clips the last 80px on screen. The screenshot covers the SVG's box but not what an ancestor clipped, so without the release the PNG comes out full size with a blank right edge. This is the screen-side counterpart of the templates' `@media print` rule.@@ -165,7 +193,7 @@ The overflow release matters for the wide presets. `min-width` equals the viewBo## Sizing the export-The PNG's pixel dimensions are the SVG's `viewBox` × `device_scale_factor`. So the size decision was already made when the diagram was drawn — see [`output-spec.md` §2](output-spec.md) for the presets. Export only picks the multiplier.+The PNG's pixel dimensions are the SVG's `viewBox` × `device_scale_factor`. The rasterizer establishes the capture viewport from the finite, nonzero viewBox dimensions so page CSS cannot enlarge or shrink the promised output. So the size decision was already made when the diagram was drawn — see [`output-spec.md` §2](output-spec.md) for the presets. Export only picks the multiplier.| Destination | Scale | Result from a 1280×720 `viewBox` ||---|---|---|diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.pyindex 1fcc679..648a10b 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 annotationsimport argparse+import mathimport html as html_entitiesimport reimport sys@@ -80,13 +81,29 @@ DEFS_ID_TAGS = ("clipPath","mask","symbol",+ "g",+ "path",+ "rect",+ "circle",+ "ellipse",+ "line",+ "polyline",+ "polygon",+ "text",+ "image",+ "use",)-STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)+STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style\s*>", re.IGNORECASE | re.DOTALL)SVG_BLOCK_RE = re.compile(r"<svg\b[^>]*>.*?</svg>", re.IGNORECASE | re.DOTALL)-RULE_RE = re.compile(r"([^{}]+)\{([^{}]*)\}", re.DOTALL)+CDATA_SECTION_RE = re.compile(r"<!\[CDATA\[(.*?)\]\]>", re.DOTALL)+# Each alternative starts on a different character, and a comment cannot run+# past its first "*/", so a failed match backtracks linearly, not+# exponentially (an unfinished final rule followed by many comments).+CSS_RULE_ATOM = r'''(?:/\*(?:[^*]|\*(?!/))*\*/|\\[\s\S]|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|/(?!\*)|[^{}"'\\/])'''+RULE_RE = re.compile(rf"({CSS_RULE_ATOM}+)\{{({CSS_RULE_ATOM}*)\}}", re.DOTALL)RGBA_ATTR_RE = re.compile(- r'(fill|stroke)="rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d*\.?\d+)\s*\)"'+ 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"')@@ -101,11 +118,21 @@ def slug_for(path: Path) -> str:return slug+def mask_opaque_html(source: str, *, styles: bool = False) -> str:+ tags = "script|style"+ pattern = re.compile(r"<!\[CDATA\[.*?\]\]>|<!--.*?-->|<(?P<raw>" + tags + r")\b[^>]*>.*?</(?P=raw)\s*>", re.IGNORECASE | re.DOTALL)+ def mask(match: re.Match[str]) -> str:+ if not styles and (match.group("raw") or "").lower() == "style":+ return match.group(0)+ return " " * len(match.group(0))+ return pattern.sub(mask, source)++def extract_first_svg(html: str) -> str:- match = SVG_BLOCK_RE.search(html)+ match = SVG_BLOCK_RE.search(mask_opaque_html(html, styles=True))if not match:raise ValueError("no <svg> block found in source")- return match.group(0)+ return html[match.start():match.end()]def _xml_start_tag(match: re.Match[str]) -> str:@@ -228,14 +255,36 @@ def decode_xml_references(value: str) -> str:def ensure_xmlns(svg: str) -> str:- if re.search(r'\bxmlns\s*=\s*["\']http://www\.w3\.org/2000/svg["\']', svg):- return svg+ opening = START_TAG_RE.match(svg)+ if opening is None or opening.group(1) != "svg":+ raise ValueError("cannot identify SVG root namespace")+ for attribute in TAG_ATTR_RE.finditer(opening.group(2)):+ if attribute.group(2) == "xmlns":+ value = attribute.group(4)+ if value is not None and decode_xml_references(value[1:-1]) == "http://www.w3.org/2000/svg":+ return svg+ raise ValueError("SVG root namespace must be http://www.w3.org/2000/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):+ opening = START_TAG_RE.match(svg)+ raw = next(+ (attr.group(4) for attr in TAG_ATTR_RE.finditer(opening.group(2))+ if attr.group(2) == "viewBox"),+ None,+ ) if opening is not None and opening.group(1).lower() == "svg" else None+ if raw is None:raise ValueError("SVG is missing a viewBox; refuse to guess")+ value = decode_xml_references(raw[1:-1] if raw[0] in "\"'" else raw).strip(" \t\r\n")+ number = r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?"+ separator = r"(?:[ \t\r\n]*,[ \t\r\n]*|[ \t\r\n]+)"+ parsed = re.fullmatch(separator.join([f"({number})"] * 4), value)+ if parsed is None:+ raise ValueError("SVG viewBox must contain four finite numbers")+ coordinates = [float(token) for token in parsed.groups()]+ if not all(math.isfinite(token) for token in coordinates) or min(coordinates[2:]) <= 0:+ raise ValueError("SVG viewBox must be finite with positive width and height")def set_root_id(svg: str, root_id: str) -> str:@@ -429,7 +478,7 @@ def retarget_root_selector(selector: str, original_id: str, root_id: str) -> strdef 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):+ for block in STYLE_BLOCK_RE.findall(mask_opaque_html(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)@@ -519,7 +568,7 @@ def find_defs_ids(svg: str) -> list[str]:seen: set[str] = set()for block in defs_blocks:for match in pattern.finditer(block):- ident = match.group(1)+ ident = decode_xml_references(match.group(1))if ident not in seen:seen.add(ident)found.append(ident)@@ -538,40 +587,117 @@ REFERENCE_REGION_RE = re.compile(def namespace_defs_ids(svg: str, prefix: str) -> str:- """Prefix defs IDs and rewrite url(#…)/href="#…" references, longest first.+ """Prefix defs IDs and compare each reference after exactly one XML decode.- Only tags and <style> blocks are rewritten; visible text keeps its wording.+ Only tags, comments and <style> blocks are rewritten; visible text keeps+ its wording. ID selectors in <style> rules follow the renamed IDs."""ids = find_defs_ids(svg)if not ids:return svg+ replacements = {old: html_entities.escape(f"{prefix}-{old}", quote=True) for old in ids}+ url_ref = re.compile(+ r"(?i:url)\(\s*(?P<quote>[\"']|"|'|)\s*#\s*"+ r"(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,+ )- 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>[\"']|"|'|)\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,+ raw_url_ref = re.compile(+ r"(?i:url)\(\s*(?P<quote>[\"']|)\s*#\s*(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,)+ def rewrite_raw_url(match: re.Match[str]) -> str:+ # CSS text with XML references already resolved (or CDATA, which has+ # none): compare and write the ID unescaped; the caller escapes.+ if match.group("ident") not in ids:+ return match.group(0)+ return f"url({match.group('quote')}#{prefix}-{match.group('ident')}{match.group('quote')})"++ def rewrite_url(match: re.Match[str]) -> str:+ new = replacements.get(decode_xml_references(match.group("ident")))+ if new is None:+ return match.group(0)+ return f"url({match.group('quote')}#{new}{match.group('quote')})"++ def rewrite_tag(tag: re.Match[str]) -> str:+ def attribute(match: re.Match[str]) -> str:+ space, name, equals, quoted = match.groups()+ if quoted is None or quoted[0] not in "\"'":+ return match.group(0)+ raw = quoted[1:-1]+ value = decode_xml_references(raw)+ if name == "id" and value in replacements:+ raw = replacements[value]+ elif name.lower() in {"href", "xlink:href"} and value.startswith("#") and value[1:] in replacements:+ raw = "#" + replacements[value[1:]]+ else:+ raw = url_ref.sub(rewrite_url, raw)+ return space + name + equals + quoted[0] + raw + quoted[-1]++ name, attrs, end = tag.groups()+ return "<" + name + TAG_ATTR_RE.sub(attribute, attrs) + end + ">"++ # A complete tag consumes all quoted values before any URL-like metadata+ # can be considered separately. Every original reference is visited once.+ comment_tokens = re.compile(START_TAG_RE.pattern + "|" + url_ref.pattern, re.DOTALL)++ def rewrite_comment_token(match: re.Match[str]) -> str:+ token = match.group(0)+ tag = START_TAG_RE.fullmatch(token)+ return rewrite_tag(tag) if tag is not None else rewrite_url(url_ref.fullmatch(token))++ def retarget_style_selectors(region: str) -> str:+ # IDs are already decoded once, so CSS selectors compare against the+ # same value; the renamed token is CSS-escaped, then XML-escaped.+ style = STYLE_BLOCK_RE.fullmatch(region)+ if style is None:+ return url_ref.sub(rewrite_url, region)++ def retarget(css: str) -> str:+ for old in sorted(ids, key=len, reverse=True):+ escaped_new = "".join(+ char if char.isalnum() or char in "_-" or ord(char) >= 128+ else f"\\{ord(char):x} " if ord(char) < 32 or ord(char) == 127+ else "\\" + char+ for char in f"{prefix}-{old}"+ )+ css = RULE_RE.sub(+ lambda rule, old=old, new=escaped_new: retarget_root_selector(rule.group(1), old, new)+ + "{" + rule.group(2) + "}",+ css,+ )+ return raw_url_ref.sub(rewrite_raw_url, css)++ # CDATA content is raw text: rewrite it inside its markers without XML+ # decoding or escaping. Only the text outside CDATA is XML-decoded and+ # re-escaped.+ content = style.group(1)+ parts: list[str] = []+ pos = 0+ for cdata in CDATA_SECTION_RE.finditer(content):+ parts.append(escape_css_for_xml(retarget(decode_xml_references(content[pos:cdata.start()]))))+ parts.append("<![CDATA[" + retarget(cdata.group(1)) + "]]>")+ pos = cdata.end()+ parts.append(escape_css_for_xml(retarget(decode_xml_references(content[pos:]))))+ # URLs in the style body were rewritten per segment above; only the+ # tags around it still go through the XML-level rewrite.+ return (url_ref.sub(rewrite_url, region[:style.start(1)]) + "".join(parts)+ + url_ref.sub(rewrite_url, region[style.end(1):]))++ def rewrite(region: re.Match[str]) -> str:+ token = region.group(0)+ if region.group("skip"):+ return token+ tag = START_TAG_RE.fullmatch(token)+ if tag is not None:+ return rewrite_tag(tag)+ if token.startswith("<!--"):+ return comment_tokens.sub(rewrite_comment_token, token)+ if token[:6].lower() == "<style":+ return retarget_style_selectors(token)+ return url_ref.sub(rewrite_url, token)++ return REFERENCE_REGION_RE.sub(rewrite, svg)+def normalize_rgba_presentation_attrs(svg: str) -> str:"""Split rgba()/transparent presentation attrs for strict SVG 1.1 importers."""@@ -579,7 +705,8 @@ def normalize_rgba_presentation_attrs(svg: str) -> str: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+ prop, max(0, min(255, int(r))), max(0, min(255, int(g))),+ max(0, min(255, int(b))), a if 0 <= float(a) <= 1 else "0" if float(a) < 0 else "1")svg = RGBA_ATTR_RE.sub(repl, svg)@@ -603,7 +730,15 @@ def assert_export_gate(svg: str) -> None: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):+ uses_classes = False+ for region in REFERENCE_REGION_RE.finditer(svg):+ tag = START_TAG_RE.fullmatch(region.group(0))+ if tag is None:+ continue+ for attribute in TAG_ATTR_RE.finditer(tag.group(2)):+ if attribute.group(2) == "class" and attribute.group(4) is not None:+ uses_classes |= bool(decode_xml_references(attribute.group(4)[1:-1]).strip())+ if uses_classes 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."@@ -673,12 +808,16 @@ def main(argv: list[str] | None = None) -> int:try:html = source.read_text(encoding="utf-8")document = export_svg_document(html, source, system_fonts=args.system_fonts)- except ValueError as exc:+ except (ValueError, OSError) as exc:print(f"error: {exc}", file=sys.stderr)return 2output = args.output if args.output is not None else source.with_suffix(".svg")- output.write_text(document, encoding="utf-8")+ try:+ output.write_text(document, encoding="utf-8")+ except OSError as exc:+ print(f"error: cannot write {output}: {exc}", file=sys.stderr)+ return 2print(output)return 0