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): unwrap SVG CDATA before carrying scoped styles (#417)
Alexc959f97a5258
diff --git a/README.md b/README.mdindex 951c9b0..f0ee83e 100644--- a/README.md+++ b/README.md@@ -455,7 +455,7 @@ What never carries over: source or renderer coordinates, source palette, source## Export to PNG / SVG-Diagrams ship as self-contained HTML, but you can export the diagram itself for Figma, slides, or social cards. Use the slash command for your agent:+Diagrams ship as self-contained HTML, but you can export the diagram itself for Figma, slides, or social cards. SVG export also carries CDATA-wrapped diagram CSS, including selectors bound to the original SVG root. Use the slash command for your agent:**Pi:**diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.pyindex 23c8cf0..274078d 100644--- a/scripts/test-export-svg-standalone.py+++ b/scripts/test-export-svg-standalone.py@@ -678,6 +678,136 @@ class ExportSvgStandaloneTests(unittest.TestCase):self.assertEqual(root[1].text, "Keep description")self.assertEqual(root[2].tag, "{http://www.w3.org/2000/svg}defs")+ def test_cli_carries_cdata_styles_after_root_rename(self) -> None:+ styles = (+ '<![CDATA[#original .paint { fill: red; }]]>',+ '<![CDATA[/* colors */ #original .paint { fill: red; }]]>'+ '<![CDATA[#original .outline { stroke: blue; }]]>',+ '#original .outline { stroke: blue; }'+ '<![CDATA[#original .paint { fill: red; }]]>',+ )+ for style in styles:+ with self.subTest(style=style), tempfile.TemporaryDirectory() as tmp:+ source = Path(tmp) / "cdata.html"+ source.write_text(+ '<svg id="original" viewBox="0 0 10 10">'+ f'<style>{style}</style>'+ '<rect class="paint outline" width="5" height="5"/></svg>',+ encoding="utf-8",+ )+ self.assertEqual(self.mod.main([str(source), "--system-fonts"]), 0)+ document = ET.fromstring(source.with_suffix(".svg").read_text(encoding="utf-8"))+ carried = document.find(+ "{http://www.w3.org/2000/svg}defs/{http://www.w3.org/2000/svg}style"+ ).text+ self.assertIn("#cdata-root .paint { fill: red; }", carried)+ self.assertNotIn("<![CDATA[", carried)+ self.assertNotIn("]]>", carried)+ if ".outline" in style:+ self.assertIn("#cdata-root .outline { stroke: blue; }", carried)++ def test_html_style_cdata_looking_literal_is_not_unwrapped(self) -> None:+ diagram = '<svg viewBox="0 0 10 10"><rect class="paint"/></svg>'+ style = '<style>.paint::after { content: "<![CDATA[literal]]>"; }</style>'+ sources = (+ style + diagram,+ diagram + '<div title="<svg>"></div>' + style,+ diagram + "<div title='<svg>'></div>" + style,+ diagram + '<div title="before > <svg> after"></div>' + style,+ diagram + '<div data-example="<svg>">' + style + '</div>',+ *(diagram + f'<{tag}><svg></{tag}>' + style+ for tag in ("textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript")),+ )+ for html in sources:+ with self.subTest(html=html):+ carried = self.mod.diagram_css_from_html(html, "literal-root")+ self.assertIn('content: "<![CDATA[literal]]>"', carried)+ with tempfile.TemporaryDirectory() as tmp:+ source = Path(tmp) / "literal.html"+ source.write_text(html, encoding="utf-8")+ self.assertEqual(self.mod.main([str(source), "--system-fonts"]), 2)+ self.assertFalse(source.with_suffix(".svg").exists())++ def test_html_text_elements_do_not_supply_svg_or_styles(self) -> None:+ diagram = '<svg id="real" viewBox="0 0 10 10"><rect/></svg>'+ for tag in ("textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript"):+ with self.subTest(tag=tag):+ html = (f'<{tag} title="before > after"><svg id="fake">'+ '<style>.fake { fill: red; }</style></svg>'+ f'</{tag}>' + diagram)+ self.assertEqual(self.mod.extract_first_svg(html), diagram)+ self.assertEqual(self.mod.diagram_css_from_html(html, "scope-root"), "")++ def test_foreign_object_textarea_does_not_change_style_namespace(self) -> None:+ html = ('<svg><foreignObject><textarea><svg></textarea><style>'+ '.paint::after { content: "<![CDATA[literal]]>"; }'+ '</style></foreignObject><style><![CDATA[.paint { fill:red }]]></style></svg>')+ carried = self.mod.diagram_css_from_html(html, "scope-root")+ self.assertIn('content: "<![CDATA[literal]]>"', carried)+ self.assertIn("#scope-root .paint { fill:red }", carried)++ def test_foreign_object_html_style_is_not_unwrapped(self) -> None:+ html = ('<svg id="original" viewBox="0 0 10 10"><foreignObject>'+ '<div xmlns="http://www.w3.org/1999/xhtml"><style>'+ '#original .paint::after { content: "<![CDATA[literal]]>"; }'+ '</style></div></foreignObject></svg>')+ carried = self.mod.diagram_css_from_html(html, "literal-root", "original")+ self.assertIn('content: "<![CDATA[literal]]>"', carried)+ # Preserve the existing refusal of invalid XML rather than silently+ # changing the HTML CSS string so the document can be exported.+ with tempfile.TemporaryDirectory() as tmp:+ source = Path(tmp) / "literal.html"+ source.write_text(html, encoding="utf-8")+ self.assertEqual(self.mod.main([str(source), "--system-fonts"]), 2)+ self.assertFalse(source.with_suffix(".svg").exists())++ def test_nested_svg_styles_inside_foreign_object_are_unwrapped(self) -> None:+ html = ('<svg id="original" viewBox="0 0 10 10"><foreignObject>'+ '<div xmlns="http://www.w3.org/1999/xhtml">'+ '<svg xmlns="http://www.w3.org/2000/svg"><style>'+ '<![CDATA[#original .paint { fill: red; }]]>'+ '</style><rect class="paint" width="5" height="5"/></svg>'+ '<style>.paint::after { content: "<![CDATA[literal]]>"; }</style>'+ '</div></foreignObject><style><![CDATA[.outline { stroke: blue; }]]></style></svg>')+ carried = self.mod.diagram_css_from_html(html, "nested-root", "original")+ self.assertIn("#nested-root .paint { fill: red; }", carried)+ self.assertIn('content: "<![CDATA[literal]]>"', carried)+ self.assertIn("#nested-root .outline { stroke: blue; }", carried)+ valid_html = html.replace(+ '<style>.paint::after { content: "<![CDATA[literal]]>"; }</style>', "")+ exported = self.mod.export_svg_document(valid_html, Path("nested.html"), system_fonts=True)+ document = ET.fromstring(exported)+ carried_style = document.find(+ "{http://www.w3.org/2000/svg}defs/{http://www.w3.org/2000/svg}style"+ ).text+ self.assertIn("#nested-root .paint { fill: red; }", carried_style)+ self.assertIn("#nested-root .outline { stroke: blue; }", carried_style)++ def test_svg_html_integration_points_preserve_style_literals(self) -> None:+ for tag in ("foreignObject", "desc", "title"):+ with self.subTest(tag=tag):+ html = (f'<svg><{tag}><style>'+ '.paint::after { content: "<![CDATA[literal]]>"; }'+ f'</style></{tag}><style><![CDATA[.paint {{ fill:red }}]]></style></svg>')+ carried = self.mod.diagram_css_from_html(html, "scope-root")+ self.assertIn('content: "<![CDATA[literal]]>"', carried)+ self.assertIn("#scope-root .paint { fill:red }", carried)++ def test_cli_carries_svg_styles_after_stray_closing_svg(self) -> None:+ html = ('<div></svg></div><svg id="original" viewBox="0 0 10 10">'+ '<style><![CDATA[#original .paint { fill: red; }]]></style>'+ '<rect class="paint" width="5" height="5"/></svg>')+ with tempfile.TemporaryDirectory() as tmp:+ source = Path(tmp) / "stray.html"+ source.write_text(html, encoding="utf-8")+ self.assertEqual(self.mod.main([str(source), "--system-fonts"]), 0)+ document = ET.fromstring(source.with_suffix(".svg").read_text(encoding="utf-8"))+ carried = document.find(+ "{http://www.w3.org/2000/svg}defs/{http://www.w3.org/2000/svg}style"+ ).text+ self.assertIn("#stray-root .paint { fill: red; }", carried)+ self.assertNotIn("<![CDATA[", carried)+def test_cli_writes_default_path(self) -> None:source = ASSETS / "example-loop.html"with tempfile.TemporaryDirectory() as tmp:diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.mdindex 1d910bf..d830722 100644--- a/skills/diagram-design/references/export.md+++ b/skills/diagram-design/references/export.md@@ -50,7 +50,7 @@ Source read and output write failures return exit 2 with an error diagnostic. Th- Make comments valid XML. Inside each `<!-- ... -->` outside CDATA, turn every `--` into `- -` and add a space after a body that ends in `-`. Refuse a comment that a browser closes before the next `-->` (`<!-->`, `<!--->`, or one containing `--!>`): the markup after it is live, and rewriting the comment would hide it.- Set `id="<slug>-root"` on the opening `<svg>` tag, where `<slug>` is the source basename without extension (e.g. `example-loop.html` → `example-loop`). This ID scopes carried CSS so several inlined figures do not leak rules into each other. When replacing an existing SVG root ID, retarget whole CSS ID tokens for that root in the carried CSS, including escaped identifier spellings; compound selectors such as `.diagram#original` remain bound to the root without adding another ancestor. Descendant IDs and quoted selector values remain unchanged; an unescaped dot belongs to a class selector, not to the ID token.4. **Carry page CSS into the SVG.** Class-styled diagrams (the loop family, process, medallion, data-flow, and others) declare fills and type in the page `<style>` block — `.station`, `.hub`, `.node-name`, and so on. Extracting the bare `<svg>` without those rules yields black boxes. Copy the page's diagram rules into a `<style>` inside `<defs>`, then:- - Strip CSS comments first, so a comment in front of a rule does not become part of its selector.+ - Unwrap CDATA sections in SVG stylesheet text before parsing rules, then strip CSS comments, so neither XML delimiters nor a comment becomes part of a selector. 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.- Re-scope `:root { … }` custom properties onto `#<slug>-root` so the figure keeps its own tokens.- Start selectors that begin at the `<svg>` element at the root instead: `svg .zone` becomes `#<slug>-root .zone` and `svg text` becomes `#<slug>-root text`. The exported root element is the `<svg>` itself, so `#<slug>-root svg .zone` would match nothing.- Prefix every other kept selector with `#<slug>-root ` (e.g. `.station` → `#example-loop-root .station`).diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.pyindex ddbdc17..8d5f159 100755--- a/skills/diagram-design/scripts/export_svg.py+++ b/skills/diagram-design/scripts/export_svg.py@@ -29,7 +29,7 @@ import reimport sysimport xml.etree.ElementTree as ETfrom pathlib import Path-from typing import Callable+from typing import Callable, IteratorGOOGLE_FONTS_IMPORT = ("@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1"@@ -101,6 +101,13 @@ STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style\s*>", re.IGNORECASE | rSVG_TAG_RE = re.compile(r"<svg(?=[\s/>])(?:[^>\"']|\"[^\"]*\"|'[^']*')*>|</svg\s*>", re.IGNORECASE)+# Consume every tag, including quoted attributes, before checking whether it+# changes the namespace of a style. Tag-looking attribute values are literal.+HTML_TOKEN_RE = re.compile(+ r"<!--.*?(?:-->|$)|<!\[CDATA\[.*?(?:\]\]>|$)|"+ r"<(?P<close>/)?(?P<tag>[A-Za-z][^\s/>]*)"+ r"(?:[^>\"']|\"[^\"]*\"|'[^']*')*>", re.IGNORECASE | 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@@ -123,14 +130,60 @@ def slug_for(path: Path) -> str:return slug+def html_tokens(source: str) -> Iterator[tuple[re.Match[str], bool, int, int]]:+ """Yield markup with its SVG context and any opaque text body boundaries.++ HTML text elements consume through their end tag without interpreting the+ contents as markup. SVG title/desc remain HTML integration points instead.+ """+ contexts: list[str] = []+ pos = 0+ while token := HTML_TOKEN_RE.search(source, pos):+ name = (token.group("tag") or "").lower()+ in_svg = bool(contexts and contexts[-1] == "svg")+ body_end = end = token.end()+ self_closing = token.group(0).endswith("/>")+ text_element = name in {"script", "style"} or (+ not in_svg and name in {"textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"}+ )+ if name and not token.group("close") and text_element and not (in_svg and self_closing):+ closing = (None if name == "plaintext" else re.compile(+ r"</" + name + r"(?=[\s/>])(?:[^>\"']|\"[^\"]*\"|'[^']*')*>",+ re.IGNORECASE,+ ).search(source, end))+ body_end = closing.start() if closing else len(source)+ end = closing.end() if closing else len(source)+ elif name in {"svg", "foreignobject", "desc", "title"}:+ if token.group("close"):+ for index in range(len(contexts) - 1, -1, -1):+ if contexts[index] == name:+ del contexts[index:]+ break+ elif not self_closing and (name == "svg" or in_svg):+ contexts.append(name)+ yield token, in_svg, body_end, end+ pos = end++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)+ out: list[str] = []+ pos = 0+ for token, _, _, end in html_tokens(source):+ out.append(source[pos:token.start()])+ name = (token.group("tag") or "").lower()+ if not name or (end > token.end() and (styles or name != "style")):+ out.append(" " * (end - token.start()))+ else:+ # Keep tag names and boundaries, but do not expose markup-looking+ # quoted attribute values to consumers of the masked source.+ suffix = "/>" if token.group(0).endswith("/>") else ">"+ attr_start = token.end("tag")+ out.append(source[token.start():attr_start])+ out.append(" " * (token.end() - len(suffix) - attr_start) + suffix)+ out.append(source[token.end():end])+ pos = end+ out.append(source[pos:])+ return "".join(out)def extract_first_svg(html: str) -> str:@@ -542,7 +595,14 @@ 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(mask_opaque_html(html)):+ 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 = CSS_COMMENT_RE.sub("", block)