Skip to content

Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.

fix(export): preserve stylesheet media conditions (#314)

Rudy Mizrahi Celekli1553bf1df27f
diff --git a/README.md b/README.md
index b416009..70a2f5b 100644
--- a/README.md
+++ b/README.md
@@ -511,7 +511,7 @@ Or just ask in natural language:
"Save my-diagram.html as PNG."
```
-- **SVG** extracts the `<svg>` node and injects Google Fonts so it renders standalone in browsers, Figma, and Illustrator. Pass `--system-fonts` to skip the font import for offline use.
+- **SVG** extracts the `<svg>` node and injects Google Fonts so it renders standalone in browsers, Figma, and Illustrator. Animation bindings follow namespaced keyframes even when property names use CSS escapes. Pass `--system-fonts` to skip the font import for offline use.
- **PNG** rasterizes the diagram via Playwright at 2× by default. One-time setup: `pip install playwright && playwright install chromium`.
Both formats are diagram-only: editorial cards and headers from `-full` variants aren't included. For a screenshot of the full editorial layout, use your browser's print-to-PDF or full-page screenshot. See [`skills/diagram-design/references/export.md`](skills/diagram-design/references/export.md) for the full procedure.
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.py
index 0c58da5..941a1a6 100644
--- a/scripts/test-export-svg-standalone.py
+++ b/scripts/test-export-svg-standalone.py
@@ -10,6 +10,8 @@ from __future__ import annotations
import contextlib
import io
import importlib.util
+import contextlib
+import io
import re
import sys
import tempfile
@@ -66,6 +68,35 @@ class ExportSvgStandaloneTests(unittest.TestCase):
def setUpClass(cls) -> None:
cls.mod = load_helper()
+ def test_nested_rule_groups_preserve_paint_and_animation_bindings(self) -> None:
+ for group in ("@layer base", "@container (min-width: 1px)", "@future-group paint"):
+ with self.subTest(group=group):
+ html = '<style>' + group + ' {@keyframes pulse {from {opacity:0;} to {opacity:1;}} .paint {fill:red;animation:pulse 1s;}}</style>'
+ html += '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ svg = self.mod.export_svg_document(html, Path("group.html"))
+ css = embedded_css(svg)
+ self.assertIn(group + " {", css)
+ self.assertIn("#group-root .paint { fill:red;animation:group-root-pulse 1s; }", css)
+ self.assertIn("@keyframes group-root-pulse { from {opacity:0;} to {opacity:1;} }", css)
+ ET.fromstring(svg)
+
+ def test_stray_page_css_closing_braces_preserve_valid_rules(self) -> None:
+ body = '<svg viewBox="0 0 10 10"><rect class="paint"/><text class="label">x</text></svg>'
+ clean = '<style>.paint {fill:red;}.label {fill:blue;}</style>' + body
+ recovered = '<style>} .paint {fill:red;} } }.label {fill:blue;} }</style>' + body
+ self.assertEqual(self.mod.export_svg_document(recovered, Path("brace.html")),
+ self.mod.export_svg_document(clean, Path("brace.html")))
+
+ def test_unknown_declaration_blocks_warn_without_losing_paint(self) -> None:
+ html = '<style>@property --paint {syntax:"<color>";inherits:false;initial-value:red;}.paint {fill:red;}</style>'
+ html += '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ warning = io.StringIO()
+ with contextlib.redirect_stderr(warning):
+ svg = self.mod.export_svg_document(html, Path("property.html"))
+ self.assertNotIn("@property", embedded_css(svg))
+ self.assertIn("#property-root .paint { fill:red; }", embedded_css(svg))
+ self.assertIn("warning: dropping unsupported CSS block", warning.getvalue())
+
def test_smil_paint_values_follow_namespaced_definitions(self) -> None:
html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/>'
'<linearGradient id="other"/></defs><rect width="10" height="10">'
@@ -560,6 +591,48 @@ class ExportSvgStandaloneTests(unittest.TestCase):
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&#38;B)"])
+ def test_unquoted_data_url_semicolons_preserve_conditional_paint(self) -> None:
+ image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
+ for url in ("data:image/png;base64,AAAA", "data:image/png;base64," + image):
+ for quote in ("", '"'):
+ with self.subTest(url=url, quote=quote):
+ condition = f"@supports (background: url({quote}{url}{quote}))"
+ html = '<style>' + condition + ' { .paint {fill:red;} }</style>'
+ html += '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ css = embedded_css(self.mod.export_svg_document(html, Path("function.html")))
+ self.assertIn(condition + " {", css)
+ self.assertIn("#function-root .paint { fill:red; }", css)
+ self.assertNotIn("#function-root base64", css)
+
+ def test_function_semicolon_keeps_nested_layer_order_and_animation(self) -> None:
+ condition = "@supports (background: url(data:image/png;base64,AAAA))"
+ html = '<style>@keyframes pulse {to{opacity:1}} ' + condition
+ html += ' { @layer second, first; @layer first { .paint {fill:red;animation:pulse 1s;} } }</style>'
+ html += '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ css = embedded_css(self.mod.export_svg_document(html, Path("nested-function.html")))
+ self.assertIn(condition + " {", css)
+ self.assertIn("@layer second, first;", css)
+ self.assertIn("animation:nested-function-root-pulse 1s", css)
+
+ def test_font_face_and_supports_do_not_block_export(self) -> None:
+ html = '<style>@font-face {font-family: Custom; src:url("custom.woff2");}'
+ html += '@supports (display: grid) {.paint {fill:#ff0000;}}</style>'
+ html += '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path("custom-font.html"))
+ css = embedded_css(result)
+ self.assertIn('@font-face', css)
+ self.assertIn('font-family: Custom', css)
+ self.assertIn('@supports (display: grid)', css)
+ self.assertIn('#custom-font-root .paint', css)
+
+ def test_system_fonts_omits_custom_font_face(self) -> None:
+ html = '<style>@supports (display: grid) {@font-face {font-family: Custom; src:url("custom.woff2");} .label {font-family: Custom;}}</style>'
+ html += '<svg viewBox="0 0 10 10"><text class="label">Label</text></svg>'
+ css = embedded_css(self.mod.export_svg_document(html, Path("system-custom.html"), system_fonts=True))
+ self.assertNotIn("@font-face", css)
+ self.assertNotIn("custom.woff2", css)
+ self.assertNotIn("fonts.googleapis.com", css)
+ self.assertIn("#system-custom-root .label", css)
def test_optional_defs_387_template_dots_keep_namespace(self) -> None:
source = ASSETS / "template.html"
exported = self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)
@@ -794,6 +867,215 @@ class ExportSvgStandaloneTests(unittest.TestCase):
html = f'<svg viewBox="0 0 10 10"><style>rect {{ {prop}\\2d opacity:0.5 }}</style><rect {prop}="rgba(255,0,0,0.5)"/></svg>'
result = ET.fromstring(self.mod.export_svg_document(html, Path("escaped.html")))
self.assertEqual(result.find("{http://www.w3.org/2000/svg}rect").get(prop), "rgba(255,0,0,0.5)")
+
+ def test_escaped_animation_properties_keep_keyframe_bindings(self) -> None:
+ properties = (r'anim\61 tion', r'animation\2d name', r'-webkit-anim\61 tion',
+ r'\61 nimation-name', r'\000061nimation', r'ANIM\41 TION')
+ for prop in properties:
+ with self.subTest(prop=prop):
+ value = 'pulse' if 'name' in prop else 'pulse 1s'
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {' + prop + ':' + value + ';}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint" style="' + prop + ':' + value + '"/></svg>'
+ result = self.mod.export_svg_document(html, Path('escaped-property.html'))
+ self.assertIn(prop + ':' + value.replace('pulse', 'escaped-property-root-pulse'), embedded_css(result))
+ shape = next(element for element in ET.fromstring(result).iter() if element.tag.endswith('}rect'))
+ self.assertEqual(shape.get('style'), prop + ':' + value.replace('pulse', 'escaped-property-root-pulse'))
+ self.assertIn('@keyframes escaped-property-root-pulse', embedded_css(result))
+
+ def test_escaped_nested_animation_properties_are_refused(self) -> None:
+ for prop in (r'anim\61 tion', r'animation\2d name', r'-webkit-anim\61 tion'):
+ for nested in ('& {' + prop + ':pulse;}', '& {fill:red;} ' + prop + ':pulse;',
+ '@media print {' + prop + ':pulse;}'):
+ with self.subTest(prop=prop, nested=nested):
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {' + nested + '}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path('nested-escaped.html'))
+
+ def test_escaped_svg_local_animation_properties_are_refused(self) -> None:
+ for prop in (r'anim\61 tion', r'animation\2d name', r'-webkit-anim\61 tion'):
+ with self.subTest(prop=prop):
+ html = '<style>@keyframes pulse {to {opacity:1}}</style><svg viewBox="0 0 40 40">'
+ html += '<style>.paint {' + prop + ':pulse;}</style><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported SVG-local animation stylesheet'):
+ self.mod.export_svg_document(html, Path('local-escaped.html'))
+
+ def test_animation_property_looking_literals_remain_literal(self) -> None:
+ declaration = r'content:";anim\61 tion:pulse;";--anim\61 tion:pulse;anim\;ation:pulse;anim\:ation:pulse;fill:red;'
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {' + declaration + '}</style>'
+ html += '<svg viewBox="0 0 40 40"><style>.paint {' + declaration + '}</style><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path('literal-property.html'))
+ self.assertIn(declaration, embedded_css(result))
+ self.assertIn(declaration, result)
+
+ def test_reserved_animation_values_stay_disabled_or_reset(self) -> None:
+ for value in ("none", "inherit", "initial", "unset", "revert", "revert-layer"):
+ with self.subTest(value=value):
+ html = '<style>@keyframes "' + value + '" {to {opacity:1}}'
+ html += '.paint {animation-name:' + value + '; animation:' + value + ';}'
+ html += '</style><svg viewBox="0 0 40 40"><rect class="paint" style="animation-name:' + value + '"/></svg>'
+ result = self.mod.export_svg_document(html, Path("reserved.html"))
+ css = embedded_css(result)
+ self.assertIn('animation-name:' + value + ';', css)
+ self.assertIn('animation:' + value + ';', css)
+ self.assertIn('style="animation-name:' + value + '"', result)
+ self.assertIn('@keyframes "reserved-root-' + value + '"', css)
+ self.assertEqual(self.mod._animation_declarations('animation-name:' + value.upper(), {value.upper():'prefixed'}), 'animation-name:' + value.upper())
+ for quote in ('"', "'"):
+ body = 'animation-name:' + quote + value + quote + ';animation:' + quote + value + quote + ' 1s'
+ expected = 'animation-name:' + quote + 'reserved-' + value + quote + ';animation:' + quote + 'reserved-' + value + quote + ' 1s'
+ self.assertEqual(self.mod._animation_declarations(body, {value:'reserved-' + value}), expected)
+ self.assertEqual(self.mod._animation_declarations('animation-name:linear', {'linear':'prefixed-linear'}), 'animation-name:prefixed-linear')
+ self.assertEqual(self.mod._animation_declarations('animation:none 1s linear', {'none':'prefixed-none'}), 'animation:none 1s linear')
+
+ def test_nested_animation_bindings_fail_clearly_before_export(self) -> None:
+ for nested in ('& {animation:pulse 1s;}', '@media print {animation-name:pulse;}', '& { & { -webkit-animation:pulse 1s; } }'):
+ with self.subTest(nested=nested):
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {fill:red;' + nested + '}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path("nested.html"))
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {animation:pulse 1s; & {fill:red;content:"animation:pulse; { }";transform:translate(1px, 2px); animation:hover {fill:blue;} }}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path("nested.html"))
+ self.assertIn('animation:nested-root-pulse 1s', embedded_css(result))
+ self.assertIn('content:"animation:pulse; { }"', embedded_css(result))
+ self.assertIn('transform:translate(1px, 2px)', embedded_css(result))
+ with tempfile.TemporaryDirectory() as directory:
+ source = Path(directory) / 'nested.html'
+ output = Path(directory) / 'nested.svg'
+ source.write_text(html.replace('fill:red;content:', 'animation:pulse 1s;content:'), encoding='utf-8')
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors):
+ self.assertEqual(self.mod.main([str(source), str(output)]), 2)
+ self.assertFalse(output.exists())
+ self.assertIn('unsupported nested CSS animation declaration', errors.getvalue())
+ self.assertNotIn('Traceback', errors.getvalue())
+
+ def test_animation_after_nested_block_is_refused(self) -> None:
+ html = '<style>@keyframes pulse {to{opacity:1}} .paint { & {fill:red;} animation:pulse 1s; }</style><svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path("trailing.html"))
+
+ def test_animation_between_nested_blocks_is_refused(self) -> None:
+ html = '<style>@keyframes pulse {to{opacity:1}} .paint { & {fill:red;} animation:pulse 1s; & {stroke:blue;} }</style><svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path("middle.html"))
+
+ def test_animation_before_nested_block_is_namespaced(self) -> None:
+ html = '<style>@keyframes pulse {to{opacity:1}} .paint {animation:pulse 1s; & {fill:red;}}</style><svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path("prefix.html"))
+ self.assertIn('animation:prefix-root-pulse 1s', embedded_css(result))
+
+ def test_important_priority_is_not_a_keyframe_name(self) -> None:
+ html = '<style>@keyframes pulse {to{opacity:1}} @keyframes important {to{opacity:0}} .paint {animation:pulse 1s !important;}</style><svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path("priority.html"))
+ self.assertIn('animation:priority-root-pulse 1s !important', embedded_css(result))
+ self.assertNotIn('!priority-root-important', result)
+
+ def test_comment_prefixed_svg_local_animation_is_refused(self) -> None:
+ html = '<style>@keyframes pulse {to{opacity:1}}</style><svg viewBox="0 0 40 40"><style>#paint {/*note*/animation:pulse 1s;}</style><rect id="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported SVG-local animation stylesheet'):
+ self.mod.export_svg_document(html, Path("local-comment.html"))
+
+ def test_custom_property_value_blocks_are_not_nested_animation_rules(self) -> None:
+ # A custom property's value is token data: semicolons inside its block
+ # do not end the declaration, so animation text there is not rewritten.
+ for value in ('{animation:pulse 1s;}', '{ .nested {animation-name:pulse;} }',
+ '{fill:red;animation:pulse 1s;}', '{ .nested {fill:red;animation-name:pulse;} }'):
+ with self.subTest(value=value):
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {'
+ html += '--unused:' + value + ';fill:red;animation:pulse 1s;}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ result = self.mod.export_svg_document(html, Path("custom-block.html"))
+ css = embedded_css(result)
+ self.assertIn('--unused:' + value, css)
+ self.assertIn('animation:custom-block-root-pulse 1s', css)
+ ET.fromstring(result)
+ html = '<style>@keyframes pulse {to {opacity:1}} .paint {'
+ html += '--unused:{animation:pulse 1s;}; & {animation:pulse 1s;}}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path("custom-block.html"))
+ html = '<style>@keyframes pulse {to {opacity:1}}</style><svg viewBox="0 0 40 40">'
+ html += '<rect style="--unused:{fill:red;animation:pulse 1s;}; animation:pulse 1s"/></svg>'
+ result = self.mod.export_svg_document(html, Path("custom-inline.html"))
+ shape = ET.fromstring(result).find("{http://www.w3.org/2000/svg}rect")
+ self.assertEqual(shape.get("style"), '--unused:{fill:red;animation:pulse 1s;}; animation:custom-inline-root-pulse 1s')
+
+ def test_unbalanced_brackets_do_not_hide_animation_declarations(self) -> None:
+ # A stray closer, or a brace inside url(), must not stop declaration
+ # splitting and leave a later animation bound to the old name.
+ for style in ('--x:}; animation:pulse 1s', '--x:); animation:pulse 1s', 'fill:red}; animation:pulse 1s'):
+ with self.subTest(style=style):
+ html = '<style>@keyframes pulse {to {opacity:1}}</style><svg viewBox="0 0 40 40">'
+ html += f'<rect style="{style}"/></svg>'
+ result = self.mod.export_svg_document(html, Path("unbalanced.html"))
+ shape = ET.fromstring(result).find("{http://www.w3.org/2000/svg}rect")
+ self.assertIn('animation:unbalanced-root-pulse 1s', shape.get("style"))
+ html = '<style>@keyframes pulse {to {opacity:1}} .a {background:url(a{b.png); animation:pulse 1s}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="a"/></svg>'
+ self.assertIn('animation:unbalanced-root-pulse 1s', embedded_css(self.mod.export_svg_document(html, Path("unbalanced.html"))))
+ html = '<style>@keyframes pulse {to {opacity:1}} .a {& {fill:blue} --z:url(a{b); animation:pulse 1s; & {fill:red}}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="a"/></svg>'
+ with self.assertRaisesRegex(ValueError, 'unsupported nested CSS animation declaration'):
+ self.mod.export_svg_document(html, Path("unbalanced.html"))
+
+ def test_nested_layer_statement_does_not_hide_animation_declaration(self) -> None:
+ for declaration in ('animation:pulse 1s;', '-webkit-animation-name:pulse;'):
+ with self.subTest(declaration=declaration), tempfile.TemporaryDirectory() as directory:
+ source = Path(directory) / 'layer-gap.html'
+ output = Path(directory) / 'layer-gap.svg'
+ source.write_text(
+ '<style>@keyframes pulse {to{opacity:1}} .paint {&{@layer first,second;'
+ + declaration + '}}</style><svg viewBox="0 0 10 10"><rect class="paint"/></svg>',
+ encoding='utf-8',
+ )
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors):
+ self.assertEqual(self.mod.main([str(source), str(output)]), 2)
+ self.assertFalse(output.exists())
+ self.assertIn('unsupported nested CSS animation declaration', errors.getvalue())
+ self.assertNotIn('Traceback', errors.getvalue())
+
+ def test_keyframes_and_bindings_are_scoped_together(self) -> None:
+ html = '<style>@keyframes pulse {from {fill:#ff0000} to {fill:#ff0000}}'
+ html += '@-webkit-keyframes other {to {opacity:1}}'
+ html += '.paint {animation:pulse var(--duration) linear, other 2s; animation-name:"pulse", other; content:"pulse; other";}'
+ html += '@media print {.paint {animation:none !important}}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint" style="animation-name:pulse"/></svg>'
+ result = self.mod.export_svg_document(html, Path("frames.html"))
+ css = embedded_css(result)
+ self.assertIn('@keyframes frames-root-pulse { from {fill:#ff0000} to {fill:#ff0000} }', css)
+ self.assertIn('@-webkit-keyframes frames-root-other', css)
+ self.assertIn('animation:frames-root-pulse var(--duration) linear, frames-root-other 2s', css)
+ self.assertIn('animation-name:"frames-root-pulse", frames-root-other', css)
+ self.assertIn('content:"pulse; other"', css)
+ self.assertIn('style="animation-name:frames-root-pulse"', result)
+ self.assertIn('animation:none !important', css)
+ self.assertEqual(self.mod._animation_declarations('animation:pulse 1s steps(2, end)', {'pulse':'frames-pulse','steps':'frames-steps'}), 'animation:frames-pulse 1s steps(2, end)')
+ other = self.mod.export_svg_document(html, Path("second.html"))
+ self.assertNotIn('frames-root-pulse', other)
+ for value in ('var(--name)', 'pulse 1s, var(--other)'):
+ with self.subTest(value=value), self.assertRaisesRegex(ValueError, 'unresolved CSS animation name'):
+ self.mod._animation_declarations(f'animation:{value}', {'pulse':'frames-root-pulse'})
+ with self.assertRaisesRegex(ValueError, 'ambiguous CSS animation name'):
+ self.mod._animation_declarations('animation:linear 1s', {'linear':'frames-root-linear'})
+ with self.assertRaisesRegex(ValueError, 'unsupported SVG-local animation stylesheet'):
+ self.mod.export_svg_document(html.replace('<rect', '<style>.paint {animation:pulse 1s}</style><rect'), Path("local.html"))
+
+ def test_inline_animation_literals_decode_once_and_keep_comments(self) -> None:
+ for attribute in ('style="animation:&quot;linear&quot; 1s both"', "style='animation:\"linear\" 1s both'"):
+ html = '<style>@keyframes "linear" {to {fill:#ff0000}}</style>'
+ html += f'<svg viewBox="0 0 40 40"><rect {attribute}/></svg>'
+ result = self.mod.export_svg_document(html, Path("literal.html"))
+ shape = ET.fromstring(result).find("{http://www.w3.org/2000/svg}rect")
+ self.assertEqual(shape.get("style"), 'animation:"literal-root-linear" 1s both')
+ html = '<style>@keyframes pulse {to {fill:#ff0000}}</style><svg viewBox="0 0 40 40">'
+ html += '<rect style="/*note: retained;*/ animation-name:pulse; content:&quot;&amp;copy;&quot;"/></svg>'
+ result = self.mod.export_svg_document(html, Path("comment.html"))
+ shape = ET.fromstring(result).find("{http://www.w3.org/2000/svg}rect")
+ self.assertEqual(shape.get("style"), '/*note: retained;*/ animation-name:comment-root-pulse; content:"&copy;"')
def test_quoted_urls_preserve_delimiters_and_exact_fragment_case(self) -> None:
markup = '<svg><defs><linearGradient id="paint)"/></defs><style>.paint { fill:url("#paint)"); }</style></svg>'
result = self.mod.namespace_defs_ids(markup, "quoted")
@@ -1176,6 +1458,29 @@ class ExportSvgStandaloneTests(unittest.TestCase):
self.assertIn('<!-- fill="rgba(255,0,0,0.5)" -->', result)
self.assertIn('<![CDATA[stroke="rgba(255,0,0,0.5)"]]>', result)
self.assertIn('data-fill="rgba(255,0,0,0.5)"', result)
+
+ def test_conditional_diagram_css_retains_media_wrappers(self) -> None:
+ html = '<style>.paint {fill: #ff0000;} @media print { .paint {fill: #0000ff;} '
+ html += 'body {padding: 40px;} @media (min-width: 10px) {.edge {stroke: #00ff00;}} }</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="paint" width="40" height="40"/></svg>'
+ result = self.mod.export_svg_document(html, Path("media.html"))
+ css = embedded_css(result)
+ self.assertIn('@media print {', css)
+ self.assertIn('@media (min-width: 10px) {', css)
+ self.assertIn('#media-root .paint { fill: #0000ff; }', css)
+ self.assertNotIn('padding', css)
+ blocks = list(self.mod._css_blocks(css[css.index("');") + 3:]))
+ self.assertEqual(blocks[0][0], '#media-root .paint')
+ self.assertEqual(blocks[1][0], '@media print')
+ self.assertIn('#media-root .paint', blocks[1][1])
+ # Braces inside a string are not a nested block.
+ css = self.mod.diagram_css_from_html('<style>.label {content: "{x}";}</style>', 'root')
+ self.assertIn('content: "{x}"', css)
+ warnings = io.StringIO()
+ with contextlib.redirect_stderr(warnings):
+ css = self.mod.diagram_css_from_html('<style>@unknown {.paint {fill: red;}}</style>', 'root')
+ self.assertEqual(css, "@unknown {\n#root .paint { fill: red; }\n}")
+ self.assertEqual(warnings.getvalue(), "")
def test_compound_original_root_does_not_gain_an_ancestor(self) -> None:
for selector in ('.diagram#original .paint',
'svg.diagram#original .paint',
@@ -1450,6 +1755,115 @@ class ExportSvgStandaloneTests(unittest.TestCase):
with self.assertRaises(ValueError):
self.mod.export_svg_document(source.read_text(encoding="utf-8"), source)
+ def test_deep_css_nesting_cli_fails_cleanly_without_output(self) -> None:
+ css = "@media screen {" * 3000 + ".paint{fill:red}" + "}" * 3000
+ with tempfile.TemporaryDirectory() as folder:
+ source = Path(folder) / "deep.html"
+ output = Path(folder) / "deep.svg"
+ source.write_text('<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>', encoding="utf-8")
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors), contextlib.redirect_stdout(io.StringIO()):
+ result = self.mod.main([str(source), str(output), "--system-fonts"])
+ self.assertEqual(result, 2)
+ self.assertIn("diagram CSS nesting", errors.getvalue())
+ self.assertNotIn("Traceback", errors.getvalue())
+ self.assertFalse(output.exists())
+
+ def test_url_braces_are_value_text_in_css_rule_tree(self) -> None:
+ for url in ("image{.png", "image}.png"):
+ with self.subTest(url=url):
+ css = f'@supports (background: url({url})) {{ .paint {{fill:red;}} }}'
+ html = '<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ rendered = self.mod.export_svg_document(html, Path("url-braces.html"), system_fonts=True)
+ self.assertIn(css.split(" {")[0], rendered)
+ self.assertIn('#url-braces-root .paint', rendered)
+ self.assertIn('fill:red;', rendered)
+ ET.fromstring(rendered)
+
+ def test_unknown_css_group_nesting_scans_source_once(self) -> None:
+ for depth in (200, 400):
+ with self.subTest(depth=depth):
+ css = "@foo {" * depth + '.paint{fill:red;content:"{;}"}' + "}" * depth
+ html = '<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ with patch.object(self.mod, "_css_rule_tree", wraps=self.mod._css_rule_tree) as scans, patch.object(self.mod, "_CssRule", wraps=self.mod._CssRule) as nodes:
+ rendered = self.mod.export_svg_document(html, Path("linear.html"), system_fonts=True)
+ self.assertEqual(scans.call_count, 1)
+ self.assertEqual(sum(len(call.args[0]) for call in scans.call_args_list), len(css))
+ self.assertEqual(nodes.call_count, depth + 1)
+ self.assertEqual(rendered.count("@foo"), depth)
+ self.assertIn('#linear-root .paint', rendered)
+ self.assertIn('content:"{;}"', rendered)
+ ET.fromstring(rendered)
+
+ def test_export_collects_keyframes_once_from_shared_css_tree(self) -> None:
+ css = '@media screen{@foo{@font-face{font-family:Demo;src:url("font.woff2")}@keyframes spin{from{opacity:0}to{opacity:1}}.paint{fill:red;animation:spin 1s}}}@unknown{font-family:Demo}'
+ html = '<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ errors = io.StringIO()
+ with patch.object(self.mod, "_keyframe_names", wraps=self.mod._keyframe_names) as names, contextlib.redirect_stderr(errors):
+ rendered = self.mod.export_svg_document(html, Path("shared.html"))
+ self.assertEqual(names.call_count, 1)
+ self.assertIn('@font-face', rendered)
+ self.assertIn('@keyframes shared-root-spin', rendered)
+ self.assertIn('animation:shared-root-spin 1s', rendered)
+ self.assertNotIn('@unknown', rendered)
+ self.assertIn('dropping unsupported CSS block', errors.getvalue())
+ ET.fromstring(rendered)
+
+ def test_definition_only_css_groups_keep_fonts_and_keyframes(self) -> None:
+ keyframes = '@keyframes pulse{from{opacity:0}to{opacity:1}}'
+ font = '@font-face{font-family:Demo;src:url("demo.woff2")}'
+ for wrapper in ('@scope (svg)', '@future'):
+ for definition in (keyframes, font, '@nested {' + keyframes + font + '}'):
+ with self.subTest(wrapper=wrapper, definition=definition):
+ css = wrapper + '{' + definition + '}.paint{fill:red;animation:pulse 1s;font-family:Demo}'
+ html = '<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors):
+ rendered = self.mod.export_svg_document(html, Path("definitions.html"))
+ self.assertIn(wrapper, rendered)
+ self.assertEqual(errors.getvalue(), "")
+ if keyframes in definition:
+ self.assertIn('@keyframes definitions-root-pulse', rendered)
+ self.assertIn('animation:definitions-root-pulse 1s', rendered)
+ if font in definition:
+ self.assertIn('@font-face', rendered)
+ system_fonts = self.mod.export_svg_document(html, Path("definitions.html"), system_fonts=True)
+ self.assertNotIn('@font-face', system_fonts)
+ ET.fromstring(rendered)
+ html = '<style>@future{font-family:Demo}.paint{fill:red}</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors):
+ rendered = self.mod.export_svg_document(html, Path("declarations.html"))
+ self.assertNotIn('@future', rendered)
+ self.assertIn('dropping unsupported CSS block', errors.getvalue())
+
+ def test_scoped_paint_fails_cleanly_before_output(self) -> None:
+ for css in ('@scope (#original) {.paint{fill:red}}', '@scope (#original) {@scope (.zone) {.paint{fill:red}}}', '@scope (#\\6f riginal) to ([data-label="brace}"]) {.paint{content:"brace}";fill:red}}'):
+ with self.subTest(css=css), tempfile.TemporaryDirectory() as folder:
+ source = Path(folder) / "scope.html"
+ output = Path(folder) / "scope.svg"
+ source.write_text('<style>' + css + '</style><svg id="original" viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>', encoding="utf-8")
+ errors = io.StringIO()
+ with contextlib.redirect_stderr(errors), contextlib.redirect_stdout(io.StringIO()):
+ status = self.mod.main([str(source), str(output), "--system-fonts"])
+ self.assertEqual(status, 2)
+ self.assertIn("unsupported CSS scope with paint rules", errors.getvalue())
+ self.assertNotIn("Traceback", errors.getvalue())
+ self.assertFalse(output.exists())
+
+ def test_layer_order_statements_survive_with_important_blocks(self) -> None:
+ css = '@layer second, first; @layer first { .paint {fill:red!important} } @layer second { .paint {fill:blue!important} }'
+ html = '<style>' + css + '</style><svg viewBox="0 0 10 10"><rect class="paint" width="5" height="5"/></svg>'
+ exported = self.mod.export_svg_document(html, Path("layers.html"), system_fonts=True)
+ self.assertIn('@layer second, first;', exported)
+ self.assertLess(exported.index('@layer second, first;'), exported.index('@layer first {'))
+ self.assertLess(exported.index('@layer first {'), exported.index('@layer second {'))
+ self.assertIn('fill:red!important', exported)
+ self.assertIn('fill:blue!important', exported)
+ nested = self.mod.diagram_css_from_html('<style>@media screen {@layer second, first; @layer first {.paint{fill:red}}}</style>', 'layers-root')
+ self.assertIn('@media screen {\n@layer second, first;', nested)
+ ET.fromstring(exported)
+
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(ExportSvgStandaloneTests)
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index 93aaac0..4b44ef7 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -34,7 +34,7 @@ If the user explicitly asks for "a screenshot of the whole page including the ca
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.
+`--system-fonts` skips the Google Fonts `@import` and carried `@font-face` declarations (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.
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. The selected SVG ends at its own closing tag, so nested icon `<svg>` elements stay inside it. Comments inside the selected SVG remain intact, except that XML forbids `--` inside a comment and a comment ending in `-`: each `--` becomes `- -` and a trailing `-` gets a space. 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.
@@ -51,6 +51,7 @@ Source read and output write failures return exit 2 with an error diagnostic. Th
- Set `id="<slug>-root"` on the opening `<svg>` tag, where `<slug>` is the source basename without extension (e.g. `example-loop.html` → `example-loop`). This ID scopes carried CSS so several inlined figures do not leak rules into each other. When replacing an existing SVG root ID, retarget whole CSS ID tokens for that root in the carried CSS, including escaped identifier spellings; compound selectors such as `.diagram#original` remain bound to the root without adding another ancestor. Descendant IDs and quoted selector values remain unchanged; an unescaped dot belongs to a class selector, not to the ID token.
4. **Carry page CSS into the SVG.** Class-styled diagrams (the loop family, process, medallion, data-flow, and others) declare fills and type in the page `<style>` block — `.station`, `.hub`, `.node-name`, and so on. Extracting the bare `<svg>` without those rules yields black boxes. Copy the page's diagram rules into a `<style>` inside `<defs>`, then:
- Unwrap CDATA sections in SVG stylesheet text before parsing rules, then strip real CSS comments, so neither XML delimiters nor a comment becomes part of a selector. Preserve comment-looking text inside quoted strings and escapes: `[data-label="net/*retained*/revenue"]` must still match the original attribute value. Keep CDATA content as raw text rather than XML-decoding it; the carried copy is XML-escaped below. The original embedded stylesheet stays in the SVG. CDATA-looking text in an HTML stylesheet remains literal, including inside SVG `foreignObject`, `desc`, or `title` elements. A nested `<svg>` inside HTML switches back to SVG stylesheet handling.
+ - Keep diagram rules inside their original `@media` conditions, including nested conditions; print-only paint must not become screen paint. Keyframe bodies remain intact; ordinary identifier names (also quoted) and matching stylesheet/inline `animation` or `animation-name` bindings are prefixed with the SVG root ID so inlined figures cannot share an animation name. Inline style character references are decoded once before inspecting CSS names and escaped once when written as XML; declaration comments are preserved. A custom property's `{ … }` value is token data and stays literal, including any `animation` text inside it. Duration variables with a literal animation name remain supported. Escaped/complex names, unresolved variable animation names, ambiguous shorthand keyword names, SVG-local animation stylesheets, and nested ordinary-rule animation declarations bound to renamed keyframes are refused explicitly rather than silently retargeted. These unsupported animation cases return exit 2 without writing an SVG. Block at-rules containing ordinary rules, including `@layer` and `@container`, retain their grouping and scoped paint. Unsupported declaration-only blocks are dropped with a warning; stray closing braces between rules are ignored, matching browser CSS recovery.
- 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.
- Split selector lists only at top-level commas. Preserve quoted and escaped attribute values, function arguments, and meaningful whitespace while scoping.
@@ -365,4 +366,11 @@ If the target aspect ratio doesn't match the `viewBox` aspect ratio, say so and
- Auto-emits `.svg` or `.png` alongside HTML generation. Manual on every call.
- Embeds an HTML wrapper (cards, headers) into the SVG via `foreignObject`. Too fragile across renderers.
+The exporter preserves `@font-face` and scopes ordinary rules within block at-rules such as `@supports`, `@media`, `@layer`, and `@container` without flattening their conditions. Groups containing only keyframes or font faces are also retained, including nested groups, so references outside the group keep their definitions. Declaration-only unsupported blocks are dropped with a warning rather than aborting the export. System-font mode continues to omit custom font-face declarations. Semicolons inside parenthesized CSS functions, including unquoted data URLs, remain value text instead of ending a statement.
+
+CSS grouping rules are scanned once and preserved without recursively rescanning nested bodies. Exports deeper than 1,024 nested CSS blocks fail with a clear diagnostic (CLI exit 2) before writing output.
+
+`@scope` groups containing ordinary paint rules are refused with a clear exit-2 diagnostic before output is written; definition-only scopes retain their keyframes and font faces. `@layer` order statements remain in source order with their layer blocks, including inside grouping rules, so cascade priority is preserved.
The exporter keeps optional defs in comments namespaced so they can be uncommented later. Only referenceable defs element types have their IDs renamed; live titles and other elements retain their IDs and accessibility references.
+
+Animation property names are compared after CSS escape decoding, while their authored spelling is preserved. Page styles and inline attributes keep their binding to namespaced keyframes, including `anim\61 tion` and vendor-prefixed properties. Nested animation declarations and SVG-local animation stylesheets remain unsupported and fail clearly, including escaped property names.
diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.py
index 0bf43c0..f580f9c 100755
--- a/skills/diagram-design/scripts/export_svg.py
+++ b/skills/diagram-design/scripts/export_svg.py
@@ -111,7 +111,7 @@ DEFS_ID_TAGS = (
"use",
)
-STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style\s*>", re.IGNORECASE | re.DOTALL)
+STYLE_BLOCK_RE = re.compile(r"<style\b(?:[^>\"']|\"[^\"]*\"|'[^']*')*>(.*?)</style\s*>", re.IGNORECASE | re.DOTALL)
# Opening and closing <svg> tags, so nested icon <svg> elements can be
# balanced instead of ending the diagram at the first </svg>.
SVG_TAG_RE = re.compile(
@@ -130,6 +130,7 @@ CDATA_SECTION_RE = re.compile(r"<!\[CDATA\[(.*?)\]\]>", re.DOTALL)
# 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*\)"'
)
@@ -656,40 +657,408 @@ def retarget_root_selector(selector: str, original_id: str, root_id: str) -> str
return "".join(out)
-def diagram_css_from_html(html: str, root_id: str, original_root_id: str = "") -> str:
- """Filter page <style> rules down to diagram rules, scoped under root_id."""
+def _css_blocks(css: str) -> Iterator[tuple[str, str]]:
+ """Yield whole balanced rules without flattening nested conditional blocks."""
+ start = 0
+ opening = -1
+ depth = 0
+ quote = ""
+ escaped = False
+ for index, char in enumerate(css):
+ if escaped:
+ escaped = False
+ continue
+ if char == "\\":
+ escaped = True
+ continue
+ if quote:
+ if char == quote:
+ quote = ""
+ continue
+ if char in "\"'":
+ quote = char
+ elif char == "{":
+ if depth == 0:
+ opening = index
+ depth += 1
+ elif char == "}":
+ if depth == 0:
+ # Browsers ignore stray closing braces between top-level rules.
+ start = index + 1
+ continue
+ depth -= 1
+ if depth == 0:
+ yield css[start:opening].strip(), css[opening + 1:index]
+ start = index + 1
+ elif char == ";" and depth == 0:
+ # Statement at-rules are not diagram paint rules.
+ start = index + 1
+ if depth or quote:
+ raise ValueError("diagram CSS has an unclosed rule or string")
+
+
+class _CssRule:
+ """Source spans plus one cached classification; nested bodies are not copied."""
+ def __init__(self, css: str, start: int, opening: int):
+ self.css = css
+ self.selector = css[start:opening].strip()
+ self.start = opening + 1
+ self.end = opening + 1
+ self.children: list[_CssRule] = []
+ self.group = False
+ self.statement = False
+
+
+def _css_rule_tree(css: str) -> list[_CssRule]:
+ """Scan braces once, then classify each block once in reverse order."""
+ roots: list[_CssRule] = []
+ stack: list[_CssRule] = []
+ nodes: list[_CssRule] = []
+ starts = [0]
+ quote = ""
+ escaped = False
+ parentheses = 0
+ for index, char in enumerate(css):
+ if escaped:
+ escaped = False
+ continue
+ if char == "\\":
+ escaped = True
+ continue
+ if quote:
+ if char == quote:
+ quote = ""
+ continue
+ if char in "\"'":
+ quote = char
+ elif char == "(":
+ parentheses += 1
+ elif char == ")":
+ parentheses = max(0, parentheses - 1)
+ elif char == "{" and parentheses == 0:
+ if len(stack) >= 1024:
+ raise ValueError("diagram CSS nesting exceeds the supported limit of 1024 blocks")
+ rule = _CssRule(css, starts[-1], index)
+ (stack[-1].children if stack else roots).append(rule)
+ nodes.append(rule)
+ stack.append(rule)
+ starts.append(index + 1)
+ elif char == "}" and parentheses == 0:
+ if stack:
+ stack.pop().end = index
+ starts.pop()
+ starts[-1] = index + 1
+ elif char == ";" and parentheses == 0:
+ selector = css[starts[-1]:index].strip()
+ if re.match(r"@layer\b", selector, re.IGNORECASE):
+ rule = _CssRule(css, starts[-1], index)
+ rule.statement = True
+ # Statement terminators occupy the same end position as a closing brace.
+ rule.end = index
+ (stack[-1].children if stack else roots).append(rule)
+ nodes.append(rule)
+ starts[-1] = index + 1
+ if stack or quote:
+ raise ValueError("diagram CSS has an unclosed rule or string")
+ for rule in reversed(nodes):
+ selector = rule.selector
+ if not rule.statement and selector.startswith("@") and not re.match(r"@(?:(?:-webkit-)?keyframes|font-face)\b", selector, re.IGNORECASE):
+ rule.group = bool(re.match(r"@(?:media|supports|layer|container)\b", selector, re.IGNORECASE)) or any(
+ not child.selector.startswith("@") or child.group or child.statement
+ or re.match(r"@(?:(?:-webkit-)?keyframes|font-face)\b", child.selector, re.IGNORECASE) is not None
+ for child in rule.children
+ )
+ return roots
+
+
+def _css_rule_nodes(rules: list[_CssRule]) -> Iterator[_CssRule]:
+ pending = list(reversed(rules))
+ while pending:
+ rule = pending.pop()
+ yield rule
+ if rule.group:
+ pending.extend(reversed(rule.children))
+
+
+def _keyframe_names(rules: list[_CssRule], root_id: str) -> dict[str, str]:
+ names: dict[str, str] = {}
+ for rule in _css_rule_nodes(rules):
+ keyframe = re.fullmatch(r"@(?:-webkit-)?keyframes\s+(.+)", rule.selector, re.IGNORECASE)
+ if keyframe is None:
+ continue
+ name = keyframe.group(1).strip()
+ if name[:1] in ("\"", "'") and name[-1:] == name[:1]:
+ name = name[1:-1]
+ if not re.fullmatch(r"[A-Za-z_][\w-]*", name):
+ raise ValueError(f"unsupported CSS keyframe name in SVG export: {rule.selector}")
+ names[name] = f"{root_id}-{name}"
+ return names
+
+
+def _css_segments(text: str, separator: str) -> list[str]:
+ # Separators inside strings, comments, functions or {} blocks do not split
+ # values; a custom property's {...} value is one token stream. Braces count
+ # only outside functions, as in _css_rule_tree. A stray closer is ignored;
+ # a negative depth would stop all later splitting.
+ pieces: list[str] = []
+ start, parentheses, braces = 0, 0, 0
+ quote = ""
+ escaped = False
+ comment = False
+ index = 0
+ while index < len(text):
+ char = text[index]
+ if comment:
+ if text.startswith("*/", index):
+ comment = False
+ index += 1
+ elif escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif quote:
+ if char == quote:
+ quote = ""
+ elif text.startswith("/*", index):
+ comment = True
+ index += 1
+ elif char in "\"'":
+ quote = char
+ elif char == "(":
+ parentheses += 1
+ elif char == ")":
+ parentheses = max(0, parentheses - 1)
+ elif char == "{" and parentheses == 0:
+ braces += 1
+ elif char == "}" and parentheses == 0:
+ braces = max(0, braces - 1)
+ elif char == separator and parentheses == 0 and braces == 0:
+ pieces.append(text[start:index])
+ start = index + 1
+ index += 1
+ pieces.append(text[start:])
+ return pieces
+
+
+def _animation_component(value: str, names: dict[str, str], shorthand: bool) -> str:
+ tokens = re.compile(r"/\*.*?\*/|\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|(?<![\w.\\-])[-_A-Za-z][\w-]*|[()]", re.DOTALL)
+ depth = 0
+ replacements: list[tuple[int, int, str]] = []
+ found_name = False
+ variable = False
+ keywords = {"linear", "ease", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "infinite", "normal", "reverse", "alternate", "alternate-reverse", "none", "forwards", "backwards", "both", "running", "paused"}
+ for match in tokens.finditer(value):
+ token = match.group(0)
+ if token == "(":
+ depth += 1
+ elif token == ")":
+ depth -= 1
+ elif depth == 0 and not token.startswith("/*"):
+ quote = token[:1] if token[:1] in ("\"", "'") else ""
+ name = token[1:-1] if quote else token
+ function = not quote and re.match(r"\s*\(", value[match.end():]) is not None
+ variable = variable or (function and name.lower() == "var")
+ if function or (not quote and name.lower() == "important"
+ and re.search(r"!\s*$", value[:match.start()])):
+ continue
+ # Unquoted none disables animation; CSS-wide values reset/inherit it.
+ # Quoted spellings are actual keyframe names and must be namespaced.
+ if not quote and name.lower() in {"none", "inherit", "initial", "unset", "revert", "revert-layer"}:
+ continue
+ if name in names:
+ if shorthand and not quote and name.lower() in keywords:
+ raise ValueError("ambiguous CSS animation name in SVG export; use animation-name")
+ replacements.append((match.start(), match.end(), f"{quote}{names[name]}{quote}"))
+ found_name = True
+ if "\\" in strip_css_comments(value) or (variable and not found_name):
+ raise ValueError("unresolved CSS animation name in SVG export")
+ for start, end, replacement in reversed(replacements):
+ value = value[:start] + replacement + value[end:]
+ return value
+
+
+def _animation_property(prop: str) -> str:
+ # Compare decoded identifiers, retaining the authored spelling in output.
+ return decoded_css_url_fragment(strip_css_comments(prop).strip()).lower().removeprefix("-webkit-")
+
+
+def _has_animation_property(css: str) -> bool:
+ # Consume strings before declaration boundaries so property-looking text in
+ # content values remains literal. Hex escapes may include one terminator.
+ escape = r"\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\r\n\f])?|[^\r\n\f])"
+ tokens = re.compile(CSS_COMMENT_OR_LITERAL_RE.pattern
+ + rf"|(?:^|[;{{])\s*(?P<prop>(?:{escape}|[\w-])+)\s*:", re.DOTALL)
+ return any(match.group("prop") is not None
+ and _animation_property(match.group("prop")) in ("animation", "animation-name")
+ for match in tokens.finditer(css))
+
+
+def _animation_declarations(body: str, names: dict[str, str]) -> str:
+ if not names:
+ return body
+ segments = _css_segments(body, ";")
+ for index, segment in enumerate(segments):
+ parts = _css_segments(segment, ":")
+ prop, colon, value = parts[0], ":" if len(parts) > 1 else "", ":".join(parts[1:])
+ key = _animation_property(prop)
+ if colon and key in ("animation", "animation-name"):
+ value = ",".join(_animation_component(part, names, key == "animation") for part in _css_segments(value, ","))
+ segments[index] = prop + colon + value
+ return ";".join(segments)
+
+
+def namespace_inline_animations(svg: str, names: dict[str, str]) -> str:
+ if not names:
+ return svg
+ if any(re.search(r"@(?:-webkit-)?keyframes\b", block, re.IGNORECASE) or _has_animation_property(block)
+ for block in (strip_css_comments(block) for block in STYLE_BLOCK_RE.findall(svg))):
+ raise ValueError("unsupported SVG-local animation stylesheet in SVG export")
+
+ def rewrite_tag(match: re.Match[str]) -> str:
+ tag, attrs, end = match.groups()
+
+ def rewrite_attr(attr: re.Match[str]) -> str:
+ space, key, equals, value = attr.groups()
+ if key == "style" and value is not None:
+ quote = value[0]
+
+ def decode_reference(reference: re.Match[str]) -> str:
+ raw = reference.group(0)
+ if raw.startswith("&#"):
+ return html_entities.unescape(raw)
+ return html_entities.entities.html5.get(raw[1:], raw)
+
+ # The HTML source attribute is decoded by its native parser;
+ # inspect those CSS literals, then encode once for XML output.
+ decoded = re.sub(r"&(?:#(?:[xX][0-9A-Fa-f]+|[0-9]+)|[A-Za-z][A-Za-z0-9]+);", decode_reference, value[1:-1])
+ rewritten = _animation_declarations(decoded, names)
+ encoded = (html_entities.escape(rewritten, quote=True)
+ .replace("\t", "&#9;").replace("\n", "&#10;").replace("\r", "&#13;"))
+ return space + key + equals + quote + encoded + quote
+ return attr.group(0)
+
+ return f"<{tag}{TAG_ATTR_RE.sub(rewrite_attr, attrs)}{end}>"
+
+ return _rewrite_start_tags(svg, rewrite_tag)
+
+
+def _diagram_css_leaf(rule: _CssRule, root_id: str, names: dict[str, str], original_root_id: str, system_fonts: bool) -> str:
kept: list[str] = []
+ selector = rule.selector.strip()
+ if rule.statement:
+ return escape_css_for_xml(selector + ";")
+ body = rule.css[rule.start:rule.end].strip()
+ if not selector or not body:
+ return ""
+ if re.match(r"@(?:-webkit-)?keyframes\b", selector, re.IGNORECASE):
+ prefix, name = selector.rsplit(None, 1)
+ quote = name[:1] if name[:1] in ("\"", "'") else ""
+ original = name[1:-1] if quote else name
+ kept.append(escape_css_for_xml(f"{prefix} {quote}{names[original]}{quote} {{ {body} }}"))
+ return "\n ".join(kept)
+ if re.match(r"@font-face\b", selector, re.IGNORECASE):
+ if not system_fonts:
+ kept.append(escape_css_for_xml(f"{selector} {{ {body} }}"))
+ return "\n ".join(kept)
+ if selector.startswith("@"):
+ print(f"warning: dropping unsupported CSS block in SVG export: {selector}", file=sys.stderr)
+ return "\n ".join(kept)
+ if original_root_id:
+ selector = retarget_root_selector(selector, original_root_id, root_id)
+ # Preserve quoted whitespace and CSS escape terminators.
+ selector = selector.strip()
+ # Nested CSS blocks are carried as text, so their declarations cannot be
+ # namespaced by the flat declaration rewriter. Refuse rather than break
+ # a binding to the keyframes that this export renames.
+ if names:
+ pending_nested = list(rule.children)
+ if any(not re.fullmatch(r"--[\w-]+\s*:", strip_css_comments(child.selector).strip())
+ for child in rule.children):
+ pending_nested.append(rule)
+ while pending_nested:
+ nested = pending_nested.pop()
+ # Braces in a custom property's value carry tokens, not CSS rules.
+ # Do not treat their token subtree as nested animation declarations.
+ if re.fullmatch(r"--[\w-]+\s*:", strip_css_comments(nested.selector).strip()):
+ continue
+ pending_nested.extend(nested.children)
+ # Scan direct declarations once; the last prefix segment is the
+ # next child selector, not a declaration. Descendants are queued.
+ segments: list[str] = []
+ cursor = nested.children[0].end + 1 if nested is rule else nested.start
+ for child in (nested.children[1:] if nested is rule else nested.children):
+ segments.extend(_css_segments(nested.css[cursor:child.start - 1], ";")[:-1])
+ cursor = child.end + 1
+ segments.extend(_css_segments(nested.css[cursor:nested.end], ";"))
+ for segment in segments:
+ parts = _css_segments(segment, ":")
+ key = _animation_property(parts[0])
+ if len(parts) > 1 and key in ("animation", "animation-name"):
+ raise ValueError("unsupported nested CSS animation declaration in SVG export")
+ body = _animation_declarations(body, names)
+ inherited = body_inherited_css(selector, body, root_id)
+ if inherited:
+ kept.append(escape_css_for_xml(inherited))
+ if is_chrome_selector(selector):
+ return "\n ".join(kept)
+ kept.append(escape_css_for_xml(f"{scope_selector(selector, root_id)} {{ {body} }}"))
+ return "\n ".join(kept)
+
+
+def _diagram_css_rules(rules: list[_CssRule], root_id: str, names: dict[str, str], original_root_id: str = "", system_fonts: bool = False) -> str:
+ # Determine empty groups bottom-up, then emit without recursive string copies.
+ nodes = list(_css_rule_nodes(rules))
+ ordinary: dict[_CssRule, bool] = {}
+ for rule in reversed(nodes):
+ ordinary[rule] = any(ordinary[child] for child in rule.children) if rule.group else not rule.selector.startswith("@")
+ for rule in nodes:
+ if rule.group and ordinary[rule] and re.match(r"@scope\b", rule.selector, re.IGNORECASE):
+ raise ValueError("unsupported CSS scope with paint rules in SVG export; move paint outside @scope")
+ leaves = {rule: _diagram_css_leaf(rule, root_id, names, original_root_id, system_fonts)
+ for rule in nodes if not rule.group}
+ retained: dict[_CssRule, bool] = {}
+ for rule in reversed(nodes):
+ retained[rule] = any(retained[child] for child in rule.children) if rule.group else bool(leaves[rule])
+ output: list[str] = []
+
+ def siblings(items: list[_CssRule]) -> list[tuple[_CssRule, str]]:
+ kept = [rule for rule in items if retained[rule]]
+ return list(reversed([(rule, "" if index == 0 else "\n ")
+ for index, rule in enumerate(kept)]))
+
+ pending: list[tuple[_CssRule, str] | str] = siblings(rules)
+ while pending:
+ item = pending.pop()
+ if isinstance(item, str):
+ output.append(item)
+ continue
+ rule, separator = item
+ output.append(separator)
+ if rule.group:
+ output.append(escape_css_for_xml(rule.selector) + " {\n")
+ pending.append("\n}")
+ pending.extend(siblings(rule.children))
+ else:
+ output.append(leaves[rule])
+ return "".join(output)
+
+
+def _html_css_rules(html: str) -> list[_CssRule]:
+ rules: list[_CssRule] = []
for token, in_svg, body_end, _ in html_tokens(html):
if (token.group("tag") or "").lower() != "style" or token.group("close"):
continue
block = html[token.end():body_end]
- # foreignObject/desc/title children are HTML; a nested svg re-enters
- # SVG. CDATA-looking strings in HTML styles must remain literal.
if in_svg:
block = CDATA_SECTION_RE.sub(lambda match: match.group(1), block)
- # A comment before a rule would otherwise become part of its selector
- # (`/* Tokens */ :root` is not recognised as `:root`).
- block = strip_css_comments(block)
- for match in RULE_RE.finditer(block):
- selector = match.group(1).strip()
- if original_root_id:
- selector = retarget_root_selector(selector, original_root_id, root_id)
- # Preserve quoted whitespace and CSS escape terminators: a second
- # space after a hex escape can be a descendant combinator.
- selector = selector.strip()
- 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)
+ rules.extend(_css_rule_tree(strip_css_comments(block)))
+ return rules
+
+
+def diagram_css_from_html(html: str, root_id: str, original_root_id: str = "", system_fonts: bool = False) -> str:
+ """Carry scoped diagram CSS while retaining its existing media conditions."""
+ rules = _html_css_rules(html)
+ return _diagram_css_rules(rules, root_id, _keyframe_names(rules, root_id), original_root_id, system_fonts)
def leading_accessibility_end(svg: str, pos: int) -> int:
@@ -1169,7 +1538,10 @@ def export_svg_document(html: str, source_path: Path, system_fonts: bool = False
"",
)
svg = set_root_id(svg, root_id)
- diagram_css = diagram_css_from_html(html, root_id, original_root_id)
+ rules = _html_css_rules(html)
+ names = _keyframe_names(rules, root_id)
+ diagram_css = _diagram_css_rules(rules, root_id, names, original_root_id, system_fonts)
+ svg = namespace_inline_animations(svg, names)
svg = merge_style_into_defs(svg, diagram_css, system_fonts)
svg = namespace_defs_ids(svg, slug)
svg = xml_safe_comments(svg)
@@ -1217,6 +1589,9 @@ 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 RecursionError:
+ print("error: diagram CSS nesting exceeds the supported export depth", file=sys.stderr)
+ return 2
except (ValueError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 2