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 CSS selector literals while scoping (#423)

Rudy Mizrahi Celeklie794452d3fef
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.py
index 274078d..f1c3684 100644
--- a/scripts/test-export-svg-standalone.py
+++ b/scripts/test-export-svg-standalone.py
@@ -66,6 +66,27 @@ class ExportSvgStandaloneTests(unittest.TestCase):
def setUpClass(cls) -> None:
cls.mod = load_helper()
+ def test_selector_lists_preserve_quoted_and_escaped_literals(self) -> None:
+ selectors = [
+ 'rect[data-label="Revenue, net"]',
+ 'rect[data-label="Revenue net"]',
+ "rect[data-label='Revenue, net']",
+ r'rect[data-label="a\"b, c"]',
+ r'.revenue\,net',
+ r'.revenue\2c net',
+ ':is(rect, circle):not([data-label="a,b"])',
+ ':where(rect, :is(circle, path))',
+ ]
+ for selector in selectors:
+ with self.subTest(selector=selector):
+ html = '<style>' + selector + ', .other {fill:red}</style>'
+ html += '<svg viewBox="0 0 40 40"><rect class="other"/></svg>'
+ css = embedded_css(self.mod.export_svg_document(html, Path("literal.html")))
+ self.assertIn('#literal-root ' + selector + ', #literal-root .other { fill:red }', css)
+ # Hex escape terminator plus descendant whitespace must remain distinct.
+ css = self.mod.diagram_css_from_html('<style>.\\31 rect {fill:red}</style>', 'literal-root')
+ self.assertIn('#literal-root .\\31 rect', css)
+
def test_rgba_parent_normalizes_with_unrelated_page_paint(self) -> None:
for prop in ("fill", "stroke"):
for selector in (".paint", "rect.paint", "#unrelated", ".unused .paint"):
@@ -836,6 +857,23 @@ class ExportSvgStandaloneTests(unittest.TestCase):
self.assertIn('stroke="none"', svg)
self.assertIn('id="rgba-demo-dots"', svg)
+ def test_escaped_selector_keeps_parent_alpha_from_overriding_child_paint(self) -> None:
+ for selector in (r'.revenue\,net\31 foo', r'.revenue\2c net\31 foo'):
+ with self.subTest(selector=selector):
+ html = '<style>' + selector + ' {fill:blue}</style>'
+ html += '<svg viewBox="0 0 10 10"><g fill="rgba(255,0,0,0.5)">'
+ html += '<rect class="revenue,net1foo" width="10" height="10"/></g></svg>'
+ result = self.mod.export_svg_document(html, Path("escaped-paint.html"))
+ group = ET.fromstring(result).find('.//{http://www.w3.org/2000/svg}g')
+ self.assertEqual(group.get('fill'), 'rgba(255,0,0,0.5)')
+ self.assertIsNone(group.get('fill-opacity'))
+ html = '<style>.other {fill:blue}</style>'
+ html += '<svg viewBox="0 0 10 10"><g fill="rgba(255,0,0,0.5)">'
+ html += '<rect class="paint" width="10" height="10"/></g></svg>'
+ group = ET.fromstring(self.mod.export_svg_document(html, Path("ordinary-paint.html"))).find('.//{http://www.w3.org/2000/svg}g')
+ self.assertEqual(group.get('fill'), '#ff0000')
+ self.assertEqual(group.get('fill-opacity'), '0.5')
+
def test_rgba_combines_existing_presentation_opacity(self) -> None:
for prop in ("fill", "stroke"):
for quote in ('"', "'"):
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index d830722..5de9c0b 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -53,6 +53,7 @@ Source read and output write failures return exit 2 with an error diagnostic. Th
- 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.
+ - Split selector lists only at top-level commas. Preserve quoted and escaped attribute values, function arguments, and meaningful whitespace while scoping.
- Prefix every other kept selector with `#<slug>-root ` (e.g. `.station` → `#example-loop-root .station`).
- **Drop** page chrome: `*`, `html`, `body`, `main`, `h1`/`h2`/`h3`, `p`, `.frame`, `.eyebrow`, `.summary`, `.card(s)`, `.footer`, `.header`, and the bare `svg { min-width: … }` layout rule. Only the bare `svg` selector is layout; `svg .zone` and `svg text` are diagram rules (see above). Those must not follow a fragment.
- Carry `color` and `font-family` from the dropped `body` rule onto `#<slug>-root`. SVG content inherits both: `stroke="currentColor"` reads `color`, and text without its own font rule reads `font-family`.
diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.py
index 8d5f159..a324e09 100755
--- a/skills/diagram-design/scripts/export_svg.py
+++ b/skills/diagram-design/scripts/export_svg.py
@@ -424,8 +424,39 @@ def set_root_id(svg: str, root_id: str) -> str:
return f"<{name}{attrs}{end}>" + svg[opening.end():]
+def selector_list_parts(selector: str) -> list[str]:
+ """Split only selector-list commas, preserving quoted and escaped literals."""
+ parts: list[str] = []
+ start = 0
+ depth = 0
+ quote = ""
+ pos = 0
+ while pos < len(selector):
+ char = selector[pos]
+ if char == "\\":
+ escape = css_escape(selector, pos)
+ if escape:
+ pos = escape[1]
+ continue
+ if quote:
+ if char == quote:
+ quote = ""
+ elif char in "\"'":
+ quote = char
+ elif char in "([":
+ depth += 1
+ elif char in ")]":
+ depth -= 1
+ elif char == "," and depth == 0:
+ parts.append(selector[start:pos])
+ start = pos + 1
+ pos += 1
+ parts.append(selector[start:])
+ return parts
+
+
def is_chrome_selector(selector: str) -> bool:
- parts = [part.strip() for part in selector.split(",") if part.strip()]
+ parts = [part.strip() for part in selector_list_parts(selector) if part.strip()]
if not parts:
return True
return all(
@@ -513,7 +544,7 @@ def root_bound_compound(selector: str, root_id: str) -> bool:
def scope_selector(selector: str, root_id: str) -> str:
scoped: list[str] = []
- for part in selector.split(","):
+ for part in selector_list_parts(selector):
part = part.strip()
if not part:
continue
@@ -541,7 +572,7 @@ def scope_selector(selector: str, root_id: str) -> str:
def body_inherited_css(selector: str, body: str, root_id: str) -> str:
"""Bind `color` / `font-family` from a dropped `body` rule to the SVG root."""
- parts = [part.strip().lower() for part in selector.split(",")]
+ parts = [part.strip().lower() for part in selector_list_parts(selector)]
if "body" not in parts:
return ""
declarations = [
@@ -610,9 +641,9 @@ def diagram_css_from_html(html: str, root_id: str, original_root_id: str = "") -
selector = match.group(1).strip()
if original_root_id:
selector = retarget_root_selector(selector, original_root_id, root_id)
- # Retarget before collapsing whitespace: a hex escape consumes one
- # terminator, so a second space may be the descendant combinator.
- selector = " ".join(selector.split())
+ # 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
@@ -841,7 +872,11 @@ def _decoded_css_property_text(style: str) -> str:
def _css_paint_may_target_descendants(selector: str, children: list[ET.Element]) -> bool:
"""Exclude provably unrelated simple selectors; preserve unknown CSS cascades."""
- for branch in selector.split(","):
+ for branch in selector_list_parts(selector):
+ # A hex escape's whitespace terminator belongs to its identifier.
+ # Keep escaped branches conservative before splitting combinators.
+ if "\\" in branch:
+ return True
terminal = re.split(r"[\s>+~]+", branch.strip())[-1]
# Unsupported selectors remain conservative, including escaped names,
# attribute selectors and pseudo-classes that can affect descendant paint.