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-escaped local paint references (#432)

Rudy Mizrahi Celeklida999a1a2fd2
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.py
index 1817b6d..0c58da5 100644
--- a/scripts/test-export-svg-standalone.py
+++ b/scripts/test-export-svg-standalone.py
@@ -66,6 +66,90 @@ class ExportSvgStandaloneTests(unittest.TestCase):
def setUpClass(cls) -> None:
cls.mod = load_helper()
+ 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">'
+ '<set attributeName="fill" to="url(#paint)" begin="0s"/>'
+ '<animate attributeName="str&#111;ke" from="url(#paint)" '
+ 'to="url(#other)" values="url(#paint); url(#other)" by="url(#paint)"/>'
+ '</rect></svg>')
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("smil.html")))
+ animation = next(element for element in root.iter() if element.tag.endswith("}set"))
+ self.assertEqual(animation.get("to"), "url(#smil-paint)")
+ animation = next(element for element in root.iter() if element.tag.endswith("}animate"))
+ for name, expected in {"from": "url(#smil-paint)", "to": "url(#smil-other)",
+ "values": "url(#smil-paint); url(#smil-other)",
+ "by": "url(#smil-paint)"}.items():
+ self.assertEqual(animation.get(name), expected, name)
+
+ def test_smil_reference_values_preserve_css_escapes_and_literals(self) -> None:
+ for target in ("fill", "stroke", "filter", "clip-path", "mask", "marker-end"):
+ with self.subTest(target=target):
+ html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/></defs>'
+ '<animate attributeName="' + target + '" '
+ 'from="URL(&quot;#pa\\69 nt&quot;)" to="url(#missing)" '
+ 'values="url(#paint);url(#pa\\69 nt);none" '
+ 'by="url(#paint)" data-label="url(#paint)"/></svg>')
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("smil.html")))
+ actual = next(node for node in root.iter() if node.tag.endswith("}animate"))
+ self.assertEqual(actual.get("from"), 'url("#smil-pa\\69 nt")')
+ self.assertEqual(actual.get("to"), "url(#missing)")
+ self.assertEqual(actual.get("values"), "url(#smil-paint);url(#smil-pa\\69 nt);none")
+ self.assertEqual(actual.get("by"), "url(#smil-paint)")
+ self.assertEqual(actual.get("data-label"), "url(#paint)")
+
+ def test_only_applicable_animation_attributes_carry_paint_urls(self) -> None:
+ for markup in ('<g attributeName="fill" to="url(#paint)"/>',
+ '<animateTransform attributeName="fill" to="url(#paint)"/>',
+ '<set attributeName="fill" from="url(#paint)" '
+ 'values="url(#paint)" by="url(#paint)"/>',
+ '<animate attributename="fill" to="url(#paint)"/>'):
+ with self.subTest(markup=markup):
+ html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/>'
+ '</defs>' + markup + '</svg>')
+ svg = self.mod.export_svg_document(html, Path("smil.html"))
+ self.assertIn(markup, svg)
+
+ def test_unchanged_inline_css_keeps_original_attribute_spelling(self) -> None:
+ style = "font-family:'Foo\\&#10;Bar'; --literal:&amp;#10;;fill:url(#external)"
+ html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/>'
+ '</defs><text style="' + style + '">Label</text></svg>')
+ svg = self.mod.export_svg_document(html, Path("space.html"))
+ self.assertIn('style="' + style + '"', svg)
+
+ def test_animation_looking_metadata_remains_literal(self) -> None:
+ for element in ("set", "animate", "animateTransform", "g"):
+ for target in ("data-label", "Fill", "style"):
+ with self.subTest(element=element, target=target):
+ html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/>'
+ '</defs><' + element + ' attributeName="' + target + '" '
+ 'to="url(#paint)" from="url(#paint)" '
+ 'values="url(#paint);url(#paint)" by="url(#paint)"/></svg>')
+ root = ET.fromstring(self.mod.export_svg_document(html, Path("smil.html")))
+ actual = next(node for node in root.iter() if node.get("attributeName"))
+ for name in ("to", "from", "by"):
+ self.assertEqual(actual.get(name), "url(#paint)")
+ self.assertEqual(actual.get("values"), "url(#paint);url(#paint)")
+
+ def test_inline_css_attribute_whitespace_keeps_xml_semantics(self) -> None:
+ whitespace = ("&#9;", "&#10;", "&#13;", "&#x9;", "&#xA;", "&#xD;",
+ "\t", "\n", "\r", "\r\n", "&amp;#10;")
+ for spelling in whitespace:
+ for rewrite in (False, True):
+ with self.subTest(spelling=repr(spelling), rewrite=rewrite):
+ style = "font-family:'Foo\\" + spelling + "Bar'; --quoted:'a" + spelling + "b'"
+ if rewrite:
+ style += ";fill:url(#paint)"
+ html = ('<svg viewBox="0 0 10 10"><defs><linearGradient id="paint"/>'
+ '</defs><text style="' + style + '">Label</text></svg>')
+ original = next(node for node in ET.fromstring(html).iter() if node.tag == "text")
+ exported = ET.fromstring(self.mod.export_svg_document(html, Path("space.html")))
+ actual = next(node for node in exported.iter() if node.tag.endswith("}text"))
+ expected = original.get("style")
+ if rewrite:
+ expected = expected.replace("url(#paint)", "url(#space-paint)")
+ self.assertEqual(actual.get("style"), expected)
+
def test_css_comment_delimiters_inside_literals_survive_export(self) -> None:
selectors = [
'rect[data-label="net/*retained*/revenue"]',
@@ -111,6 +195,91 @@ class ExportSvgStandaloneTests(unittest.TestCase):
css = self.mod.diagram_css_from_html('<style>.\\31 rect {fill:red}</style>', 'literal-root')
self.assertIn('#literal-root .\\31 rect', css)
+ def test_css_escaped_local_paint_fragments_follow_namespaced_defs(self) -> None:
+ references = [r'url(#\70 aint)', r"url('#\70 aint')", r'url(&quot;#\70 aint&quot;)']
+ for reference in references:
+ with self.subTest(reference=reference):
+ source = '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ source += '<rect fill="' + reference + '" width="20" height="20"/></svg>'
+ root = ET.fromstring(self.mod.export_svg_document(source, Path("literal.html"), system_fonts=True))
+ gradient = root.find('.//{http://www.w3.org/2000/svg}linearGradient')
+ rectangle = root.find('{http://www.w3.org/2000/svg}rect')
+ self.assertEqual(gradient.get('id'), 'literal-paint')
+ self.assertIn(r'#literal-\70 aint', rectangle.get('fill'))
+
+ def test_url_looking_metadata_and_css_strings_remain_literal(self) -> None:
+ for fragment in (r'#\70 aint', '#paint'):
+ with self.subTest(fragment=fragment):
+ literal = 'url(' + fragment + ')'
+ selector_value = literal.replace('\\', '\\\\')
+ source = '<style>rect[data-label="' + selector_value + '"]{fill:red}</style>'
+ source += '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ source += '<rect data-label="' + literal + '" width="20" height="20"/></svg>'
+ exported = self.mod.export_svg_document(source, Path("literal.html"), system_fonts=True)
+ rectangle = ET.fromstring(exported).find('{http://www.w3.org/2000/svg}rect')
+ self.assertEqual(rectangle.get('data-label'), literal)
+ self.assertIn('[data-label="' + selector_value + '"]', embedded_css(exported))
+ for carrier in ('stylesheet', 'inline'):
+ with self.subTest(carrier=carrier):
+ declaration = r'--note:"url(#\70 aint)";fill:url(#\70 aint)'
+ source = '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ if carrier == 'stylesheet':
+ source += '<style>.paint {' + declaration + '}</style><rect class="paint"/>'
+ else:
+ source += "<rect style='" + declaration + "'/>"
+ exported = self.mod.export_svg_document(source + '</svg>', Path("literal.html"), system_fonts=True)
+ if carrier == 'stylesheet':
+ css = ''.join(node.text or '' for node in ET.fromstring(exported).iter() if node.tag.endswith('}style'))
+ else:
+ css = ET.fromstring(exported).find('{http://www.w3.org/2000/svg}rect').get('style')
+ self.assertIn(r'--note:"url(#\70 aint)"', css)
+ self.assertIn(r'fill:url(#literal-\70 aint)', css)
+
+ def test_commented_inline_paint_keeps_its_optional_definition_binding(self) -> None:
+ source = '<svg viewBox="0 0 20 20"><defs><!-- <pattern id="paint"/> --></defs>'
+ source += '<symbol id="paint"><rect width="10" height="10"/></symbol>'
+ source += '<!-- <rect style="fill:url(#paint)"/> --><use href="#paint"/></svg>'
+ exported = self.mod.export_svg_document(source, Path("literal.html"), system_fonts=True)
+ self.assertIn('<pattern id="literal-paint"/>', exported)
+ self.assertIn('<rect style="fill:url(#literal-paint)"/>', exported)
+ self.assertEqual(ET.fromstring(exported).find('{http://www.w3.org/2000/svg}use').get('href'), '#paint')
+
+ def test_longer_css_function_names_are_not_local_url_functions(self) -> None:
+ for function in ('noturl', 'vendor-url', '-url', '_url', '💡url'):
+ for carrier in ('stylesheet', 'inline'):
+ with self.subTest(function=function, carrier=carrier):
+ declaration = '--note:' + function + r'(#\70 aint);fill:red'
+ source = '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ if carrier == 'stylesheet':
+ source += '<style>.paint {' + declaration + '}</style><rect class="paint"/>'
+ else:
+ source += "<rect style='" + declaration + "'/>"
+ root = ET.fromstring(self.mod.export_svg_document(source + '</svg>', Path("literal.html"), system_fonts=True))
+ css = ''.join(node.text or '' for node in root.iter() if node.tag.endswith('}style')) if carrier == 'stylesheet' else root.find('{http://www.w3.org/2000/svg}rect').get('style')
+ self.assertIn(declaration, css)
+
+ def test_escaped_function_identifiers_are_consumed_before_url_matching(self) -> None:
+ functions = [r'my\31 url', r'my\000031url', r'my\0031 url', r'my\31 URL', r'my\31' + '\turl']
+ for function in functions:
+ for carrier in ('stylesheet', 'inline'):
+ with self.subTest(function=function, carrier=carrier):
+ declaration = '--note:' + function + r'(#\70 aint);fill:red'
+ source = '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ if carrier == 'stylesheet':
+ source += '<style>.paint {' + declaration + '}</style><rect class="paint"/>'
+ else:
+ source += "<rect style='" + declaration + "'/>"
+ root = ET.fromstring(self.mod.export_svg_document(source + '</svg>', Path("literal.html"), system_fonts=True))
+ css = ''.join(node.text or '' for node in root.iter() if node.tag.endswith('}style')) if carrier == 'stylesheet' else root.find('{http://www.w3.org/2000/svg}rect').get('style')
+ self.assertIn(declaration.replace('\t', ' ') if carrier == 'inline' else declaration, css)
+
+ def test_second_space_after_an_identifier_escape_starts_a_real_url(self) -> None:
+ declaration = r'--note:my\31 url(#\70 aint);fill:red'
+ source = '<svg viewBox="0 0 20 20"><defs><linearGradient id="paint"/></defs>'
+ source += '<style>.paint {' + declaration + '}</style><rect class="paint"/></svg>'
+ exported = self.mod.export_svg_document(source, Path("literal.html"), system_fonts=True)
+ self.assertIn(r'--note:my\31 url(#literal-\70 aint);fill:red', exported)
+
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"):
diff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.md
index c64c6d4..6ec9df9 100644
--- a/skills/diagram-design/references/export.md
+++ b/skills/diagram-design/references/export.md
@@ -67,7 +67,7 @@ Source read and output write failures return exit 2 with an error diagnostic. Th
<!-- existing markers / patterns stay here -->
</defs>
```
-6. **Namespace `<defs>` IDs.** Prefix every referenceable defs ID — on `marker`, `pattern`, `linearGradient`, `radialGradient`, `filter`, `clipPath`, `mask`, `symbol`, and reusable graphics (`g`, `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `text`, `image`, and `use`) — with `<slug>-`, and rewrite matching `url(#…)` and `href="#…"` / `xlink:href="#…"` references. Compare ID and fragment values after XML character-reference decoding, so equivalent named and numeric references stay connected. Retarget ID selectors in embedded style rules while leaving declaration colors and unrelated IDs unchanged. Preserve URL quotes and match fragment IDs case-sensitively (the CSS `url` keyword remains case-insensitive). Rewrite **longest-id-first** so `arrow-accent` is not clipped by a shorter `arrow` rule. Quoted local URLs (`url("#arrow")`, `url('#arrow')`, including XML-escaped quotes in attributes) follow the same rewrite as unquoted URLs. Unrelated fragment IDs and non-local URLs remain unchanged. Example: `id="arrow"` in `example-loop.html` becomes `id="example-loop-arrow"` with `marker-end="url(#example-loop-arrow)"`.
+6. **Namespace `<defs>` IDs.** Prefix every referenceable defs ID — on `marker`, `pattern`, `linearGradient`, `radialGradient`, `filter`, `clipPath`, `mask`, `symbol`, and reusable graphics (`g`, `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `text`, `image`, and `use`) — with `<slug>-`, and rewrite matching `url(#…)` and `href="#…"` / `xlink:href="#…"` references. Compare ID and fragment values after XML character-reference decoding, so equivalent named and numeric references stay connected. For recognized local CSS URL forms (literal `url(...)`, case-insensitive) in paint/reference attributes, inline styles, and stylesheets, decode hex escapes before comparing fragment identity, and preserve the original escape spelling when adding the prefix; `url(#\70 aint)` must stay connected to the namespaced `paint` definition. URL-looking metadata and quoted CSS string contents remain literal. Retarget ID selectors in embedded style rules while leaving declaration colors and unrelated IDs unchanged. Preserve URL quotes and match fragment IDs case-sensitively (the CSS `url` keyword remains case-insensitive). Rewrite **longest-id-first** so `arrow-accent` is not clipped by a shorter `arrow` rule. Quoted local URLs (`url("#arrow")`, `url('#arrow')`, including XML-escaped quotes in attributes) follow the same rewrite as unquoted URLs. Unrelated fragment IDs and non-local URLs remain unchanged. Example: `id="arrow"` in `example-loop.html` becomes `id="example-loop-arrow"` with `marker-end="url(#example-loop-arrow)"`.
7. Normalize colors for strict SVG 1.1 consumers. This design system's tokens are authored as `rgba(...)` (see `style-guide.md`) and render correctly wherever colors are read as CSS — browsers, Figma, Illustrator. PowerPoint's SVG importer does not: it treats `rgba(...)` and `transparent` as unrecognized and paints them **opaque black**, turning a barely-there tint into a solid block that swallows the label inside it. Normalize presentation paint only when its alpha can be preserved: combine a local presentation opacity, but retain RGBA when a CSS or inherited opacity, or a paint override on the element or its children, makes splitting unsafe. An unrelated simple CSS rule does not prevent normalization. Apply this full recipe before writing the file:
```python
diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.py
index 6da88fa..0bf43c0 100755
--- a/skills/diagram-design/scripts/export_svg.py
+++ b/skills/diagram-design/scripts/export_svg.py
@@ -84,6 +84,11 @@ TAG_ATTR_RE = re.compile(
r"(\s+)([^\s\"'<>/=]+)(?:(\s*=\s*)(\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+))?"
)
+CSS_URL_ATTRIBUTES = {
+ "fill", "stroke", "filter", "clip-path", "mask", "cursor", "marker",
+ "marker-start", "marker-mid", "marker-end",
+}
+
DEFS_ID_TAGS = (
"marker",
"pattern",
@@ -492,6 +497,23 @@ def css_escape(text: str, pos: int) -> tuple[str, int] | None:
return value, end
+def decoded_css_url_fragment(fragment: str) -> str:
+ """Decode valid CSS escapes before comparing a local fragment with an ID."""
+ decoded: list[str] = []
+ pos = 0
+ while pos < len(fragment):
+ if fragment[pos] == "\\":
+ escaped = css_escape(fragment, pos)
+ if escaped is None:
+ return fragment
+ value, pos = escaped
+ decoded.append(value)
+ else:
+ decoded.append(fragment[pos])
+ pos += 1
+ return "".join(decoded)
+
+
def css_id_token(text: str, pos: int) -> tuple[str, int] | None:
"""Read a whole valid CSS ID selector after '#', decoding identifier escapes."""
def starts_name(index: int) -> bool:
@@ -790,30 +812,86 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:
replacements = {old: html_entities.escape(f"{prefix}-{old}", quote=True) for old in ids}
live_replacements = {old: replacements[old] for old in live_reference_ids}
url_ref = re.compile(
- r"(?i:url)\(\s*(?P<quote>[\"']|&quot;|&apos;|)\s*#\s*"
+ r"(?<![A-Za-z0-9_\\\-\u0080-\U0010ffff])(?i:url)\(\s*(?P<quote>[\"']|&quot;|&apos;|)\s*#\s*"
r"(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,
)
raw_url_ref = re.compile(
- r"(?i:url)\(\s*(?P<quote>[\"']|)\s*#\s*(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,
+ r"(?<![A-Za-z0-9_\\\-\u0080-\U0010ffff])(?i:url)\(\s*(?P<quote>[\"']|)\s*#\s*(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,
)
- def rewrite_raw_url(match: re.Match[str]) -> str:
+ css_string = re.compile(
+ r'''(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*')''', re.DOTALL,
+ )
+
+ def rewrite_css_urls(css: str, commented: bool = False) -> str:
+ """Consume complete identifiers before considering literal URL functions."""
+ out: list[str] = []
+ pos = 0
+ while pos < len(css):
+ if css[pos] in "\"'":
+ literal = css_string.match(css, pos)
+ end = literal.end() if literal else len(css)
+ elif css.startswith("/*", pos):
+ closing = css.find("*/", pos + 2)
+ end = closing + 2 if closing >= 0 else len(css)
+ else:
+ token = css_id_token(css, pos)
+ if token is not None:
+ _, end = token
+ # Only literal ASCII url(...) is in the supported grammar.
+ # Escape terminator whitespace is part of the identifier.
+ if css[pos:end].lower() == "url" and css[end:end + 1] == "(":
+ reference = raw_url_ref.match(css, pos)
+ if reference is not None:
+ out.append(rewrite_raw_url(reference, commented))
+ pos = reference.end()
+ continue
+ else:
+ escaped = css_escape(css, pos) if css[pos] == "\\" else None
+ end = escaped[1] if escaped else pos + 1
+ out.append(css[pos:end])
+ pos = end
+ return "".join(out)
+
+ def rewrite_raw_url(match: re.Match[str], commented: bool = False) -> str:
# CSS text with XML references already resolved (or CDATA, which has
- # none): compare and write the ID unescaped; the caller escapes.
- if match.group("ident") not in live_reference_ids:
+ # none): compare the decoded CSS identity, preserving its escape
+ # spelling when prefixing the reference. The caller XML-escapes.
+ ident = decoded_css_url_fragment(match.group("ident"))
+ if ident not in (ids if commented else live_reference_ids):
return match.group(0)
return f"url({match.group('quote')}#{prefix}-{match.group('ident')}{match.group('quote')})"
def rewrite_url(match: re.Match[str], commented: bool = False) -> str:
mapping = replacements if commented else live_replacements
- new = mapping.get(decode_xml_references(match.group("ident")))
+ new = mapping.get(decoded_css_url_fragment(decode_xml_references(match.group("ident"))))
if new is None:
return match.group(0)
- return f"url({match.group('quote')}#{new}{match.group('quote')})"
+ return f"url({match.group('quote')}#{prefix}-{match.group('ident')}{match.group('quote')})"
def rewrite_tag(tag: re.Match[str], commented: bool = False) -> str:
mapping = replacements if commented else live_replacements
+ # SMIL values describe the animated attribute, not the animation tag's
+ # own paint. Only supported paint/reference targets carry CSS URLs.
+ animation_values = {"set": {"to"}, "animate": {"from", "to", "values", "by"}}
+ target = next((decode_xml_references(attr.group(4)[1:-1])
+ for attr in TAG_ATTR_RE.finditer(tag.group(2))
+ if attr.group(2) == "attributeName" and attr.group(4) is not None
+ and attr.group(4)[0] in "\"'"), "")
+ animated_attributes = (animation_values.get(tag.group(1), set())
+ if target in CSS_URL_ATTRIBUTES else set())
+
+ def rewrite_css_attribute(raw: str) -> str:
+ # XML normalizes original literal whitespace before expanding
+ # character references. References to controls must survive the
+ # next parse; an amp-escaped reference must stay literal text.
+ value = decode_xml_references(re.sub(r"\r\n?|[\n\t]", " ", raw))
+ rewritten = rewrite_css_urls(value, commented)
+ if rewritten == value:
+ return raw
+ return (escape_css_for_xml(rewritten).replace('"', "&quot;").replace("'", "&apos;")
+ .replace("\t", "&#9;").replace("\n", "&#10;").replace("\r", "&#13;"))
def attribute(match: re.Match[str]) -> str:
space, name, equals, quoted = match.groups()
@@ -828,7 +906,9 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:
raw = replacements[value]
elif name.lower() in {"href", "xlink:href"} and value.startswith("#") and value[1:] in mapping:
raw = "#" + mapping[value[1:]]
- else:
+ elif name.lower() == "style" or name in animated_attributes:
+ raw = rewrite_css_attribute(raw)
+ elif name.lower() in CSS_URL_ATTRIBUTES:
raw = url_ref.sub(lambda reference: rewrite_url(reference, commented), raw)
return space + name + equals + quoted[0] + raw + quoted[-1]
@@ -864,7 +944,7 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:
+ "{" + rule.group(2) + "}",
css,
)
- return raw_url_ref.sub(rewrite_raw_url, css)
+ return rewrite_css_urls(css)
# CDATA content is raw text: rewrite it inside its markers without XML
# decoding or escaping. Only the text outside CDATA is XML-decoded and