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): export nested icon SVGs and comments with double hyphens (#414)

Cathryn Lavery489dbd574d7d
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.py
index b1165fc..9b1bf7a 100644
--- a/scripts/test-export-svg-standalone.py
+++ b/scripts/test-export-svg-standalone.py
@@ -23,31 +23,10 @@ HELPER = ROOT / "skills/diagram-design/scripts/export_svg.py"
EXPORT_MD = ROOT / "skills/diagram-design/references/export.md"
ASSETS = ROOT / "skills/diagram-design/assets"
-# Shipped assets the helper refuses (loudly) because their markup is not
-# well-formed XML for reasons outside the CSS carry: the first `</svg>` match
-# stops at a nested icon <svg>, or a comment contains `--`. Keep this list
-# exact so a newly unexportable asset, or a fixed one, shows up here.
-KNOWN_UNEXPORTABLE = frozenset(
- {
- # nested icon <svg> truncates the first-</svg> extraction
- "example-datalake.html",
- "example-datalake-dark.html",
- "example-datalake-full.html",
- "example-high-level.html",
- "example-high-level-dark.html",
- "example-high-level-full.html",
- "example-high-level-vertical.html",
- "example-high-level-vertical-dark.html",
- "example-high-level-vertical-full.html",
- # `--` inside an XML comment
- "example-slopegraph.html",
- "example-slopegraph-dark.html",
- "example-slopegraph-full.html",
- "example-streamgraph.html",
- "example-streamgraph-dark.html",
- "example-streamgraph-full.html",
- }
-)
+# Shipped assets the helper refuses (loudly). Empty since #407: nested icon
+# <svg> elements and `--` inside comments both export. Keep this list exact so
+# a newly unexportable asset shows up here instead of in a user's export.
+KNOWN_UNEXPORTABLE: frozenset[str] = frozenset()
# Motion files named in #202; they use valueless HTML attributes.
MOTION_FILES = (
@@ -842,6 +821,43 @@ class ExportSvgStandaloneTests(unittest.TestCase):
f"class {cls!r} is styled on the page but has no scoped rule",
)
+ def test_nested_icon_svg_does_not_end_the_extraction(self) -> None:
+ html = ('<p>intro</p><svg viewBox="0 0 100 50"><g><svg x="2" y="2" width="8" height="8" viewBox="0 0 8 8">'
+ '<path d="M0 0h8v8z"/></svg><svg x="12" y="2" width="8" height="8"/></g>'
+ '<rect id="after" width="10" height="10"/></svg><svg viewBox="0 0 1 1"><rect id="second"/></svg>')
+ extracted = self.mod.extract_first_svg(html)
+ self.assertTrue(extracted.startswith('<svg viewBox="0 0 100 50">'))
+ self.assertTrue(extracted.endswith('<rect id="after" width="10" height="10"/></svg>'))
+ self.assertNotIn('id="second"', extracted)
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("nested.html")))
+ self.assertTrue(any(element.get("id") == "after" for element in root.iter()))
+
+ def test_comments_with_double_hyphens_export_as_xml(self) -> None:
+ html = ('<svg viewBox="0 0 10 10"><!-- focal -- and worse --><!-- trailing dash--->'
+ '<!-- fine --><style><![CDATA[.a { --x: 1; }]]></style><rect class="a"/></svg>')
+ svg = self.mod.export_svg_document(html, Path("comments.html"))
+ ET.fromstring(svg)
+ self.assertIn("<!-- fine -->", svg)
+ self.assertIn("<!-- focal - - and worse -->", svg)
+ self.assertIn("<!-- trailing dash- -->", svg)
+ self.assertIn("<![CDATA[.a { --x: 1; }]]>", svg)
+ for comment in re.findall(r"<!--(.*?)-->", svg, flags=re.DOTALL):
+ self.assertNotIn("--", comment)
+ self.assertFalse(comment.endswith("-"), comment)
+
+ def test_svg_extraction_reads_quoted_attributes_and_whole_tag_names(self) -> None:
+ html = ('<svg-icon name="x"></svg-icon><svg viewBox="0 0 9 9" aria-label="in/out />">'
+ '<svg viewBox="0 0 8 8"><path id="icon"/></svg><rect id="after"/></svg>')
+ extracted = self.mod.extract_first_svg(html)
+ self.assertTrue(extracted.startswith('<svg viewBox="0 0 9 9"'), extracted)
+ self.assertTrue(extracted.endswith('<rect id="after"/></svg>'), extracted)
+
+ def test_comments_browsers_close_early_are_refused(self) -> None:
+ for comment in ("<!-- a --!>", "<!-->", "<!--->"):
+ html = '<svg viewBox="0 0 9 9">' + comment + '<rect id="live"/><!-- x --></svg>'
+ with self.subTest(comment=comment), self.assertRaises(ValueError):
+ self.mod.export_svg_document(html, Path("comment.html"))
+
def test_known_unexportable_assets_are_refused_loudly(self) -> None:
for name in sorted(KNOWN_UNEXPORTABLE):
with self.subTest(name=name):
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index 5c6a605..d486a80 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -36,17 +36,18 @@ 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.
-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.
+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.
### 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*).
+2. Extract the **first** top-level `<svg ...>...</svg>` element. Skip HTML comments, `<script>` and `<style>` content, then count `<svg` openings and `</svg>` closings (a self-closing `<svg .../>` does not open one) and stop when the count returns to zero. Read quoted attribute values whole so a `>` or `/>` inside one does not end the tag. A non-greedy regex stops at a nested icon's `</svg>` and truncates the diagram. Most generated diagrams have only one top-level 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. 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, `&nbsp;` becomes a nonbreaking space). HTML's legacy names such as `&copy` and `&nbsp` also decode without the semicolon, except inside an attribute value when the next character is a letter, digit, or `=`, as browsers do. Decode once and escape XML delimiters; already escaped references remain escaped. Comments, CDATA and raw style/script content stay as written; style/script opening-tag attributes follow the same reference conversion as other attributes.
+ - 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.
diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.py
index 648a10b..c245b5a 100755
--- a/skills/diagram-design/scripts/export_svg.py
+++ b/skills/diagram-design/scripts/export_svg.py
@@ -95,7 +95,11 @@ DEFS_ID_TAGS = (
)
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)
+# 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(
+ r"<svg(?=[\s/>])(?:[^>\"']|\"[^\"]*\"|'[^']*')*>|</svg\s*>", re.IGNORECASE
+)
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
@@ -129,10 +133,67 @@ def mask_opaque_html(source: str, *, styles: bool = False) -> str:
def extract_first_svg(html: str) -> str:
- match = SVG_BLOCK_RE.search(mask_opaque_html(html, styles=True))
- if not match:
- raise ValueError("no <svg> block found in source")
- return html[match.start():match.end()]
+ """Return the first top-level <svg> element, including nested <svg> icons."""
+ start = None
+ depth = 0
+ for tag in SVG_TAG_RE.finditer(mask_opaque_html(html, styles=True)):
+ token = tag.group(0)
+ if token.startswith("</"):
+ if start is None:
+ continue
+ depth -= 1
+ if depth == 0:
+ return html[start:tag.end()]
+ elif not token.endswith("/>"):
+ if start is None:
+ start = tag.start()
+ depth += 1
+ raise ValueError("no <svg> block found in source")
+
+
+def xml_safe_comments(svg: str) -> str:
+ """Make HTML comments valid XML comments; CDATA is copied unchanged.
+
+ HTML allows `--` inside a comment and a body ending in `-`; XML allows
+ neither. Each `--` becomes `- -` and a trailing `-` gets a space, so the
+ comment text stays readable. Comments that are already valid XML are
+ copied byte for byte.
+ """
+ out: list[str] = []
+ pos = 0
+ while True:
+ opener = XML_OPAQUE_OPEN_RE.search(svg, pos)
+ if opener is None:
+ out.append(svg[pos:])
+ break
+ out.append(svg[pos:opener.start()])
+ if opener.group(0) == "<!--":
+ close_at = svg.find("-->", opener.end())
+ if close_at == -1:
+ out.append(svg[opener.start():])
+ break
+ body = svg[opener.end():close_at]
+ # Browsers end these comments earlier than the next "-->", so the
+ # markup after them is live; rewriting would silently drop it.
+ if body.startswith((">", "->")) or "--!>" in body:
+ raise ValueError(
+ "exported SVG has a comment a browser closes early "
+ "(<!-->, <!--->, or --!>); fix the comment in the source"
+ )
+ while "--" in body:
+ body = body.replace("--", "- -")
+ if body.endswith("-"):
+ body += " "
+ out.append("<!--" + body + "-->")
+ pos = close_at + 3
+ else:
+ close_at = svg.find("]]>", opener.end())
+ stop = len(svg) if close_at == -1 else close_at + 3
+ out.append(svg[opener.start():stop])
+ pos = stop
+ if close_at == -1:
+ break
+ return "".join(out)
def _xml_start_tag(match: re.Match[str]) -> str:
@@ -765,6 +826,7 @@ def export_svg_document(html: str, source_path: Path, system_fonts: bool = False
svg = merge_style_into_defs(svg, diagram_css, system_fonts)
svg = namespace_defs_ids(svg, slug)
svg = normalize_rgba_presentation_attrs(svg)
+ svg = xml_safe_comments(svg)
assert_export_gate(svg)
document = '<?xml version="1.0" encoding="UTF-8"?>\n' + svg + "\n"
# Catch any remaining XML-breaking characters in carried content.