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 live references alongside commented defs (#387)
Rudy Mizrahi Celekliefcdcaff704a
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.pyindex f1c3684..8ce611f 100644--- a/scripts/test-export-svg-standalone.py+++ b/scripts/test-export-svg-standalone.py@@ -367,6 +367,11 @@ 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&B)"])+ 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)+ self.assertIn('id="template-dots"', exported)+ self.assertIn('url(#template-dots)', exported)def test_metadata_defs_382_ignores_data_id_inside_defs(self) -> None:markup = '<svg><defs><marker id="arrow"/><g data-id="ghost"/></defs><g data-id="arrow" data-href="#arrow"/><use href="#arrow"/></svg>'@@ -841,6 +846,91 @@ class ExportSvgStandaloneTests(unittest.TestCase):body = out.read_text(encoding="utf-8")self.assertIn("#example-loop-root .station", body)+ def test_optional_defs_387_preserve_live_reusable_shape_ids(self) -> None:+ svg = '<svg><defs><path id="live" d="M0 0"/></defs><g id="dots"/><!-- <defs><pattern id="dots"/><g id="optional-shape"/></defs> --><use href="#live"/></svg>'+ result = self.mod.namespace_defs_ids(svg, "demo")+ self.assertIn('<g id="dots"/>', result)+ self.assertIn('<pattern id="demo-dots"/>', result)+ self.assertIn('<g id="optional-shape"/>', result)+ self.assertIn('<path id="demo-live"', result)+ self.assertIn('href="#demo-live"', result)++ def test_optional_defs_387_preserve_live_title_ids(self) -> None:+ svg = '<svg aria-labelledby="name"><title id="name">Title</title><!-- <defs><marker id="name"/></defs> --></svg>'+ self.assertEqual(self.mod.find_defs_ids(svg), ["name"])+ result = self.mod.namespace_defs_ids(svg, "demo")+ self.assertIn('aria-labelledby="name"><title id="name">Title</title>', result)+ self.assertIn('<marker id="demo-name"/>', result)++ def test_optional_defs_387_cdata_text_is_not_a_live_id_collision(self) -> None:+ svg = ('<svg viewBox="0 0 10 10"><metadata><![CDATA[<g id="dots"/>]]></metadata>'+ '<defs><!-- <pattern id="dots"><rect width="1" height="1"/></pattern> --></defs>'+ '<rect width="10" height="10" fill="url(#dots)"/></svg>')+ result = self.mod.export_svg_document(svg, Path("cdata-pattern.html"))+ self.assertIn('<![CDATA[<g id="dots"/>]]>', result)+ self.assertIn('<pattern id="cdata-pattern-dots">', result)+ root = ET.fromstring(result)+ rect = root.find("{http://www.w3.org/2000/svg}rect")+ self.assertEqual(rect.get("fill"), "url(#cdata-pattern-dots)")+ restored = ET.fromstring(result.replace('<!--', '').replace('-->', ''))+ pattern = restored.find('.//{http://www.w3.org/2000/svg}pattern')+ self.assertEqual(pattern.get('id'), 'cdata-pattern-dots')++ def test_optional_defs_387_opaque_delimiters_keep_real_id_ownership(self) -> None:+ for metadata in ('<![CDATA[<!-- literal]]>', '<!-- <, but export never injects another controller.- 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 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.diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.pyindex a324e09..a9f5506 100755--- a/skills/diagram-design/scripts/export_svg.py+++ b/skills/diagram-design/scripts/export_svg.py@@ -749,10 +749,35 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:Only tags, comments and <style> blocks are rewritten; visible text keepsits wording. ID selectors in <style> rules follow the renamed IDs."""- ids = find_defs_ids(svg)+ # Match opaque regions in one pass: a comment opener inside CDATA is text.+ live_svg = re.sub(r"<!\[CDATA\[.*?\]\]>|<!--.*?-->", "", svg, flags=re.DOTALL)+ commented_defs_tags = {"marker", "pattern", "lineargradient", "radialgradient", "filter", "clippath", "mask", "symbol"}++ def markup_ids(markup: str, allowed: set[str] | None = None) -> set[str]:+ found: set[str] = set()+ for tag in START_TAG_RE.finditer(markup):+ if allowed is not None and tag.group(1).lower() not in allowed:+ continue+ for attribute in TAG_ATTR_RE.finditer(tag.group(2)):+ _, name, _, quoted = attribute.groups()+ if name == "id" and quoted is not None and quoted[0] in "\"'":+ found.add(decode_xml_references(quoted[1:-1]))+ return found++ live_defs_tags = {kind.lower() for kind in DEFS_ID_TAGS}+ live_ids = set().union(*(markup_ids(block, live_defs_tags)+ for block in re.findall(r"<defs\b[^>]*>(.*?)</defs>", live_svg, re.IGNORECASE | re.DOTALL)))+ commented_ids = set().union(*(markup_ids(comment, commented_defs_tags)+ for comment in re.findall(r"<!--.*?-->", svg, re.DOTALL)))+ # An optional commented definition must not redirect references to a live+ # element whose ID is left unchanged, even if both happen to use one name.+ unrenamed_live_ids = markup_ids(live_svg) - live_ids+ live_reference_ids = live_ids | (commented_ids - unrenamed_live_ids)+ ids = live_ids | commented_idsif not ids:return svgreplacements = {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>[\"']|"|'|)\s*#\s*"r"(?P<ident>.*?)\s*(?P=quote)\s*\)", re.DOTALL,@@ -765,29 +790,35 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:def rewrite_raw_url(match: re.Match[str]) -> 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 ids:+ if match.group("ident") not in 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]) -> str:- new = replacements.get(decode_xml_references(match.group("ident")))+ 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")))if new is None:return match.group(0)return f"url({match.group('quote')}#{new}{match.group('quote')})"- def rewrite_tag(tag: re.Match[str]) -> str:+ def rewrite_tag(tag: re.Match[str], commented: bool = False) -> str:+ mapping = replacements if commented else live_replacements+def attribute(match: re.Match[str]) -> str:space, name, equals, quoted = match.groups()if quoted is None or quoted[0] not in "\"'":return match.group(0)raw = quoted[1:-1]value = decode_xml_references(raw)- if name == "id" and value in replacements:+ if name == "id" and value in replacements and (+ tag.group(1).lower() in commented_defs_tags if commented+ else value in live_ids and tag.group(1).lower() in live_defs_tags+ ):raw = replacements[value]- elif name.lower() in {"href", "xlink:href"} and value.startswith("#") and value[1:] in replacements:- raw = "#" + replacements[value[1:]]+ elif name.lower() in {"href", "xlink:href"} and value.startswith("#") and value[1:] in mapping:+ raw = "#" + mapping[value[1:]]else:- raw = url_ref.sub(rewrite_url, raw)+ raw = url_ref.sub(lambda reference: rewrite_url(reference, commented), raw)return space + name + equals + quoted[0] + raw + quoted[-1]name, attrs, end = tag.groups()@@ -800,7 +831,7 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:def rewrite_comment_token(match: re.Match[str]) -> str:token = match.group(0)tag = START_TAG_RE.fullmatch(token)- return rewrite_tag(tag) if tag is not None else rewrite_url(url_ref.fullmatch(token))+ return rewrite_tag(tag, commented=True) if tag is not None else rewrite_url(url_ref.fullmatch(token), commented=True)def retarget_style_selectors(region: str) -> str:# IDs are already decoded once, so CSS selectors compare against the@@ -810,7 +841,7 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:return url_ref.sub(rewrite_url, region)def retarget(css: str) -> str:- for old in sorted(ids, key=len, reverse=True):+ for old in sorted(live_reference_ids, key=len, reverse=True):escaped_new = "".join(char if char.isalnum() or char in "_-" or ord(char) >= 128else f"\\{ord(char):x} " if ord(char) < 32 or ord(char) == 127