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): retain RGBA alpha with presentation opacity (#321)
Rudy Mizrahi Celekli778bd8bf6fe2
diff --git a/scripts/test-export-svg-standalone.py b/scripts/test-export-svg-standalone.pyindex e7c267e..23c8cf0 100644--- a/scripts/test-export-svg-standalone.py+++ b/scripts/test-export-svg-standalone.py@@ -66,6 +66,40 @@ class ExportSvgStandaloneTests(unittest.TestCase):def setUpClass(cls) -> None:cls.mod = load_helper()+ 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"):+ with self.subTest(prop=prop, selector=selector):+ html = f'<style>{selector}{{{prop}:#000}}</style><svg viewBox="0 0 10 10"><g {prop}="rgba(255,0,0,0.5)"><rect width="5" height="5"/></g></svg>'+ group = ET.fromstring(self.mod.export_svg_document(html, Path("parent.html"))).find("{http://www.w3.org/2000/svg}g")+ self.assertEqual(group.get(prop), "#ff0000")+ self.assertEqual(group.get(prop + "-opacity"), "0.5")++ def test_rgba_parent_retains_alpha_when_page_paint_can_override_children(self) -> None:+ for prop in ("fill", "stroke"):+ for selector in (".paint", "rect", "g > rect", "rect:first-child", "[width]"):+ with self.subTest(prop=prop, selector=selector):+ html = f'<style>{selector}{{{prop}:#000}}</style><svg viewBox="0 0 10 10"><g {prop}="rgba(255,0,0,0.5)"><rect class="paint" width="5" height="5"/></g></svg>'+ group = ET.fromstring(self.mod.export_svg_document(html, Path("parent.html"))).find("{http://www.w3.org/2000/svg}g")+ self.assertEqual(group.get(prop), "rgba(255,0,0,0.5)")+ self.assertNotIn(prop + "-opacity", group.attrib)++ def test_rgba_keeps_alpha_when_css_overrides_the_painted_element(self) -> None:+ for prop in ("fill", "stroke"):+ for tag in ("g", "rect"):+ html = f'<style>.paint{{{prop}:#000}}</style><svg viewBox="0 0 10 10"><{tag} class="paint" {prop}="rgba(255,0,0,0.5)"><rect width="5" height="5"/></{tag}></svg>'+ shape = ET.fromstring(self.mod.export_svg_document(html, Path("parent.html"))).find("{http://www.w3.org/2000/svg}" + tag)+ self.assertEqual(shape.get(prop), "rgba(255,0,0,0.5)")+ self.assertNotIn(prop + "-opacity", shape.attrib)++ def test_rgba_parent_with_unpainted_child_normalizes(self) -> None:+ for prop in ("fill", "stroke"):+ html = f'<svg viewBox="0 0 10 10"><g {prop}="rgba(255,0,0,0.5)" {prop}-opacity="0.5"><rect width="10" height="10"/></g></svg>'+ exported = self.mod.export_svg_document(html, Path("parent.html"))+ root = ET.fromstring(exported)+ group = root.find("{http://www.w3.org/2000/svg}g")+ self.assertEqual(group.get(prop), "#ff0000")+ self.assertEqual(group.get(prop + "-opacity"), "0.25")def test_cli_reports_source_read_errors_without_output(self) -> None:with tempfile.TemporaryDirectory() as directory:source = Path(directory) / "source.html"@@ -180,7 +214,7 @@ class ExportSvgStandaloneTests(unittest.TestCase):match = re.search(r"```python\n(.*?)\n ```", section, re.DOTALL)self.assertIsNotNone(match)recipe = "\n".join(line[3:] if line.startswith(" ") else line for line in match.group(1).splitlines())- for svg in ('<svg><rect fill="rgba(300,-10,20,2)"/></svg>', '<svg><rect stroke="rgba(-4,1,2,-.5)"/></svg>'):+ for svg in ('<svg><rect fill="rgba(255,0,0,0.5)" fill-opacity="0.5" style="fill:#0000ff"/></svg>', '<svg><rect stroke="rgba(255,0,0,0.5)" stroke-opacity="0.5" style="stroke:#0000ff"/></svg>', '<svg><rect fill="rgba(300,-10,20,2)"/></svg>', '<svg><rect stroke="rgba(-4,1,2,-.5)"/></svg>', '<svg><style>.paint{fill:#000}</style><g fill="rgba(255,0,0,0.5)"><rect/></g></svg>', '<svg><style>.paint{fill:#000}</style><g fill="rgba(255,0,0,0.5)"><rect class="paint"/></g></svg>', '<svg><rect fill="rgba(255,0,0,0.5)" fill-opacity="0.5"/></svg>'):with self.subTest(svg=svg):namespace = {"svg": svg}exec(recipe, namespace)@@ -494,6 +528,53 @@ class ExportSvgStandaloneTests(unittest.TestCase):import xml.etree.ElementTree as ETET.fromstring(svg)+ def test_rgba_retains_alpha_with_css_or_inherited_opacity(self) -> None:+ for prop in ("fill", "stroke"):+ paint = f'{prop}="rgba(255,0,0,0.5)"'+ snippets = (+ f'<style>.paint {{ {prop}-opacity:0.5 }}</style><rect class="paint" {paint} {prop}-opacity="0.8"/>',+ f'<g {prop}-opacity="0.5"><rect {paint}/></g>',+ f'<rect {paint} {prop}-opacity="0.8" style="{prop}-opacity:0.5"/>',+ )+ for snippet in snippets:+ with self.subTest(prop=prop, snippet=snippet):+ result = self.mod.export_svg_document(f'<svg viewBox="0 0 10 10">{snippet}</svg>', Path("cascade.html"))+ shape = ET.fromstring(result).find("{http://www.w3.org/2000/svg}rect")+ if shape is None:+ shape = ET.fromstring(result).find(".//{http://www.w3.org/2000/svg}rect")+ self.assertEqual(shape.get(prop), "rgba(255,0,0,0.5)")++ def test_rgba_parent_preserves_independent_child_paints(self) -> None:+ for prop in ("fill", "stroke"):+ html = f'<svg viewBox="0 0 10 10"><g {prop}="rgba(255,0,0,0.5)" {prop}-opacity="0.5"><rect {prop}="#0000ff"/></g></svg>'+ result = ET.fromstring(self.mod.export_svg_document(html, Path("parent.html")))+ group = result.find("{http://www.w3.org/2000/svg}g")+ self.assertEqual(group.get(prop), "rgba(255,0,0,0.5)")+ self.assertEqual(group.get(f"{prop}-opacity"), "0.5")+ self.assertEqual(group[0].get(prop), "#0000ff")++ def test_rgba_keeps_opacity_when_own_inline_paint_overrides_color(self) -> None:+ for prop in ("fill", "stroke"):+ for declaration in (f"{prop}:#0000ff", f"{prop.upper()}:#0000ff", f"/* inline */ {prop}:#0000ff"):+ with self.subTest(paint=prop, declaration=declaration):+ html = (f'<svg viewBox="0 0 10 10"><rect {prop}="rgba(255,0,0,0.5)" '+ f'{prop}-opacity="0.5" style="{declaration}"/></svg>')+ root = ET.fromstring(self.mod.export_svg_document(html, Path("inline.html")))+ rect = root.find("{http://www.w3.org/2000/svg}rect")+ self.assertEqual(rect.get(f"{prop}-opacity"), "0.5")+ self.assertEqual(rect.get(prop), "rgba(255,0,0,0.5)")+ self.assertEqual(rect.get("style"), declaration)++ def test_rgba_css_guard_reads_entities_and_escaped_property_names(self) -> None:+ for prop in ("fill", "stroke"):+ declarations = (f"{prop}-opacity:0.5", f"{prop}\\2d opacity:0.5", f"{prop}\2d opacity:0.5")+ for declaration in declarations:+ html = f'<svg viewBox="0 0 10 10"><rect {prop}="rgba(255,0,0,0.5)" style="{declaration}"/></svg>'+ result = ET.fromstring(self.mod.export_svg_document(html, Path("encoded.html")))+ self.assertEqual(result.find("{http://www.w3.org/2000/svg}rect").get(prop), "rgba(255,0,0,0.5)")+ html = f'<svg viewBox="0 0 10 10"><style>rect {{ {prop}\\2d opacity:0.5 }}</style><rect {prop}="rgba(255,0,0,0.5)"/></svg>'+ result = ET.fromstring(self.mod.export_svg_document(html, Path("escaped.html")))+ self.assertEqual(result.find("{http://www.w3.org/2000/svg}rect").get(prop), "rgba(255,0,0,0.5)")def test_quoted_urls_preserve_delimiters_and_exact_fragment_case(self) -> None:markup = '<svg><defs><linearGradient id="paint)"/></defs><style>.paint { fill:url("#paint)"); }</style></svg>'result = self.mod.namespace_defs_ids(markup, "quoted")@@ -625,6 +706,25 @@ class ExportSvgStandaloneTests(unittest.TestCase):self.assertIn('stroke="none"', svg)self.assertIn('id="rgba-demo-dots"', svg)+ def test_rgba_combines_existing_presentation_opacity(self) -> None:+ for prop in ("fill", "stroke"):+ for quote in ('"', "'"):+ for alpha, original, expected in (("0.5", "0.5", "0.25"), ("0.5", "50%", "0.25"), ("2", "0.5", "0.5")):+ with self.subTest(prop=prop, quote=quote, alpha=alpha, opacity=original):+ source = '<svg viewBox="0 0 40 40"><rect width="40" height="40" '+ source += f'{prop}={quote}rgba(255,0,0,{alpha}){quote} {prop}-opacity="{original}"/></svg>'+ result = self.mod.export_svg_document(source, Path("opacity.html"))+ shape = ET.fromstring(result).find('{http://www.w3.org/2000/svg}rect')+ self.assertEqual(shape.get(prop), '#ff0000')+ self.assertEqual(shape.get(f'{prop}-opacity'), expected)+ source = '<svg viewBox="0 0 10 10"><text>fill="rgba(255,0,0,0.5)"</text>'+ source += '<!-- fill="rgba(255,0,0,0.5)" --><![CDATA[stroke="rgba(255,0,0,0.5)"]]>'+ source += '<rect data-fill="rgba(255,0,0,0.5)" fill="#ff0000"/></svg>'+ result = self.mod.export_svg_document(source, Path("inert.html"))+ self.assertIn('<text>fill="rgba(255,0,0,0.5)"</text>', result)+ self.assertIn('<!-- fill="rgba(255,0,0,0.5)" -->', result)+ self.assertIn('<![CDATA[stroke="rgba(255,0,0,0.5)"]]>', result)+ self.assertIn('data-fill="rgba(255,0,0,0.5)"', result)def test_compound_original_root_does_not_gain_an_ancestor(self) -> None:for selector in ('.diagram#original .paint','svg.diagram#original .paint',@@ -821,7 +921,13 @@ class ExportSvgStandaloneTests(unittest.TestCase):html = source.read_text(encoding="utf-8")slug = source.stemsvg = self.mod.export_svg_document(html, source)- ET.fromstring(svg)+ root = ET.fromstring(svg)+ for element in root.iter():+ for paint in ("fill", "stroke"):+ self.assertNotRegex(+ element.get(paint, ""), r"(?i)^\s*rgba\(",+ f"{source.name}: {paint} presentation paint must export without rgba",+ )css = embedded_css(svg)page_css = re.sub(r"/\*.*?\*/", "", "\n".join(PAGE_STYLE_RE.findall(html)), flags=re.DOTALLdiff --git a/skills/diagram-design/references/export.md b/skills/diagram-design/references/export.mdindex d486a80..1d910bf 100644--- a/skills/diagram-design/references/export.md+++ b/skills/diagram-design/references/export.md@@ -67,10 +67,41 @@ Source read and output write failures return exit 2 with an error diagnostic. Th</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)"`.-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. The transform is lossless (every replacement renders identically to the original in a browser), so apply it to presentation attributes before writing the file:+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:```pythonimport re+ import math+ import html as html_entities+ import xml.etree.ElementTree as ET+ from typing import Callable+++ CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)+++ XML_OPAQUE_OPEN_RE = re.compile(r"<!--|<!\[CDATA\[")+++ START_TAG_RE = re.compile(+ r"<([A-Za-z][\w:.-]*)"+ r"((?:\s+[^\s\"'<>/=]+(?:\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+))?)*)"+ r"(\s*/?)>"+ )+++ TAG_ATTR_RE = re.compile(+ r"(\s+)([^\s\"'<>/=]+)(?:(\s*=\s*)(\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+))?"+ )+++ STYLE_BLOCK_RE = re.compile(r"<style\b[^>]*>(.*?)</style\s*>", re.IGNORECASE | re.DOTALL)+++ CSS_RULE_ATOM = r'''(?:/\*(?:[^*]|\*(?!/))*\*/|\\[\s\S]|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|/(?!\*)|[^{}"'\\/])'''+++ RULE_RE = re.compile(rf"({CSS_RULE_ATOM}+)\{{({CSS_RULE_ATOM}*)\}}", re.DOTALL)RGBA_ATTR_RE = re.compile(@@ -78,22 +109,164 @@ Source read and output write failures return exit 2 with an error diagnostic. Th)- TRANSPARENT_ATTR_RE = re.compile(r'(fill|stroke)="transparent"')+ def _rewrite_start_tags(svg: str, transform: Callable[[re.Match[str]], str]) -> str:+ """Transform actual start tags, preserving comments and CDATA sections."""+ out: list[str] = []+ pos = 0+ while True:+ opener = XML_OPAQUE_OPEN_RE.search(svg, pos)+ text_end = opener.start() if opener else len(svg)+ out.append(START_TAG_RE.sub(transform, svg[pos:text_end]))+ if opener is None:+ break+ closer = "-->" if opener.group(0) == "<!--" else "]]>"+ close_at = svg.find(closer, opener.end())+ stop = len(svg) if close_at == -1 else close_at + len(closer)+ out.append(svg[opener.start() : stop])+ pos = stop+ if close_at == -1:+ break+ return "".join(out)+++ def _decoded_css_property_text(style: str) -> str:+ """Read opacity spellings conservatively without changing carried CSS."""+ style = CSS_COMMENT_RE.sub("", html_entities.unescape(style))++ def escape(match: re.Match[str]) -> str:+ hexadecimal, literal = match.groups()+ if hexadecimal is not None:+ value = int(hexadecimal, 16)+ return chr(value) if 0 < value <= 0x10FFFF and not 0xD800 <= value <= 0xDFFF else "\ufffd"+ return "" if literal in "\r\n\f" else literal++ return re.sub(r"\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\r\n\f])?|([\s\S]))", escape, style)+++ 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(","):+ 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.+ if not re.fullmatch(r"(?:[A-Za-z][\w-]*|\*)?(?:[.#][\w-]+)*", terminal) or not terminal:+ return True+ tag = re.match(r"^[A-Za-z][\w-]*", terminal)+ classes = re.findall(r"\.([\w-]+)", terminal)+ ids = re.findall(r"#([\w-]+)", terminal)+ for child in children:+ if tag and child.tag.rsplit("}", 1)[-1] != tag.group(0):+ continue+ if all(name in child.get("class", "").split() for name in classes) and all(+ name == child.get("id") for name in ids+ ):+ return True+ return Falsedef normalize_rgba_presentation_attrs(svg: str) -> str:- """Split rgba()/transparent presentation attrs for strict SVG 1.1 importers."""-- def repl(match: re.Match[str]) -> str:- prop, r, g, b, a = match.groups()- return '{0}="#{1:02x}{2:02x}{3:02x}" {0}-opacity="{4}"'.format(- prop, max(0, min(255, int(r))), max(0, min(255, int(g))),- max(0, min(255, int(b))), a if 0 <= float(a) <= 1 else "0" if float(a) < 0 else "1"- )-- svg = RGBA_ATTR_RE.sub(repl, svg)- svg = TRANSPARENT_ATTR_RE.sub(r'\1="none"', svg)- return svg+ """Split rgba paint and combine its alpha with existing presentation opacity."""++ # A parent's paint and opacity may be inherited independently. Converting+ # its color alpha into opacity would also change children overriding paint.+ try:+ elements = list(ET.fromstring(svg).iter())+ descendants = {+ index: list(element.iter())[1:]+ for index, element in enumerate(elements) if len(element)+ }+ except ET.ParseError:+ return svg # The existing final XML validator supplies the public error.+ opacity_counts = {"fill-opacity": 0, "stroke-opacity": 0}+ styles = list(STYLE_BLOCK_RE.findall(svg))++ def collect_opacity_context(match: re.Match[str]) -> str:+ for attr in TAG_ATTR_RE.finditer(match.group(2)):+ key, value = attr.group(2), attr.group(4)+ if key in opacity_counts:+ opacity_counts[key] += 1+ elif key == "style" and value is not None:+ styles.append(value[1:-1])+ return match.group(0)++ _rewrite_start_tags(svg, collect_opacity_context)+ css_opacity = {+ key for key in opacity_counts+ if any(re.search(rf"(?:^|[;{{])\s*{key}\s*:", _decoded_css_property_text(style), re.IGNORECASE)+ for style in styles)+ }++ position = 0++ def normalize_tag(match: re.Match[str]) -> str:+ nonlocal position+ children = descendants.get(position, [])+ element = elements[position]+ position += 1+ name, attrs, end = match.groups()+ values = {+ attr.group(2): attr.group(4)[1:-1]+ for attr in TAG_ATTR_RE.finditer(attrs)+ if attr.group(4) is not None+ }+ updates: dict[str, str] = {}+ additions: list[str] = []+ for prop in ("fill", "stroke"):+ value = values.get(prop, "")+ if value == "transparent":+ updates[prop] = "none"+ continue+ rgba = RGBA_ATTR_RE.fullmatch(f'{prop}="{value}"')+ if rgba is None:+ continue+ _, r, g, b, alpha = rgba.groups()+ opacity_name = f"{prop}-opacity"+ # Presentation opacity may be overridden by CSS or inherited from+ # another element. Preserve the color alpha when that cascade is+ # unresolved instead of replacing it with opaque RGB.+ # Converting a parent is safe when descendants inherit its paint.+ # Preserve alpha if a descendant overrides that paint, including+ # a conservatively detected stylesheet or inline declaration.+ inline_paint = re.search(+ rf"(?:^|[;{{])\s*{prop}\s*:",+ _decoded_css_property_text(element.get("style", "")), re.I,+ )+ descendant_paint = any(+ prop in child.attrib+ or re.search(rf"(?:^|[;{{])\s*{prop}\s*:",+ _decoded_css_property_text(child.get("style", "")), re.I)+ for child in children+ )+ stylesheet_paint = any(+ re.search(rf"(?:^|[;{{])\s*{prop}\s*:", _decoded_css_property_text(rule.group(2)), re.I)+ and _css_paint_may_target_descendants(rule.group(1), [element] + children)+ for style in STYLE_BLOCK_RE.findall(svg)+ for rule in RULE_RE.finditer(CSS_COMMENT_RE.sub("", style))+ )+ if inline_paint or descendant_paint or stylesheet_paint or opacity_name in css_opacity or opacity_counts[opacity_name] > int(opacity_name in values):+ continue+ opacity = alpha if 0 <= float(alpha) <= 1 else "0" if float(alpha) < 0 else "1"+ if opacity_name in values:+ try:+ original = values[opacity_name].strip()+ amount = float(original.rstrip("%")) / (100 if original.endswith("%") else 1)+ except ValueError:+ continue # Keep paint intact when the opacity cannot be resolved here.+ if not math.isfinite(amount):+ continue+ opacity = format(min(1, max(0, amount)) * max(0, min(1, float(alpha))), ".12g")+ updates[opacity_name] = opacity+ else:+ additions.append(f' {opacity_name}="{opacity}"')+ updates[prop] = "#{:02x}{:02x}{:02x}".format(*(max(0, min(255, int(c))) for c in (r, g, b)))++ def replace_attr(attr: re.Match[str]) -> str:+ space, key, _equals, _value = attr.groups()+ return f'{space}{key}="{updates[key]}"' if key in updates else attr.group(0)++ return f"<{name}{TAG_ATTR_RE.sub(replace_attr, attrs)}{''.join(additions)}{end}>"++ return _rewrite_start_tags(svg, normalize_tag)svg = normalize_rgba_presentation_attrs(svg)diff --git a/skills/diagram-design/scripts/export_svg.py b/skills/diagram-design/scripts/export_svg.pyindex 737fc15..ddbdc17 100755--- a/skills/diagram-design/scripts/export_svg.py+++ b/skills/diagram-design/scripts/export_svg.py@@ -29,6 +29,7 @@ import reimport sysimport xml.etree.ElementTree as ETfrom pathlib import Path+from typing import CallableGOOGLE_FONTS_IMPORT = ("@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1"@@ -209,17 +210,14 @@ def _xml_start_tag(match: re.Match[str]) -> str:return f"<{name}{TAG_ATTR_RE.sub(attr, attrs)}{end}>"-def xmlify_attributes(svg: str) -> str:- """Rewrite valueless and unquoted HTML attributes as XML (`attr=""`).-- Comments and CDATA sections are copied unchanged.- """+def _rewrite_start_tags(svg: str, transform: Callable[[re.Match[str]], str]) -> str:+ """Transform actual start tags, preserving comments and CDATA sections."""out: list[str] = []pos = 0while True:opener = XML_OPAQUE_OPEN_RE.search(svg, pos)text_end = opener.start() if opener else len(svg)- out.append(START_TAG_RE.sub(_xml_start_tag, svg[pos:text_end]))+ out.append(START_TAG_RE.sub(transform, svg[pos:text_end]))if opener is None:breakcloser = "-->" if opener.group(0) == "<!--" else "]]>"@@ -232,6 +230,11 @@ def xmlify_attributes(svg: str) -> str:return "".join(out)+def xmlify_attributes(svg: str) -> str:+ """Rewrite valueless and unquoted HTML attributes as XML (`attr=""`)."""+ return _rewrite_start_tags(svg, _xml_start_tag)++# HTML named references that browsers decode even without a trailing semicolon.LEGACY_ENTITY_NAMES = tuple(name for name in html_entities.entities.html5 if not name.endswith(";"))@@ -762,19 +765,144 @@ def namespace_defs_ids(svg: str, prefix: str) -> str:return REFERENCE_REGION_RE.sub(rewrite, svg)+def _decoded_css_property_text(style: str) -> str:+ """Read opacity spellings conservatively without changing carried CSS."""+ style = CSS_COMMENT_RE.sub("", html_entities.unescape(style))++ def escape(match: re.Match[str]) -> str:+ hexadecimal, literal = match.groups()+ if hexadecimal is not None:+ value = int(hexadecimal, 16)+ return chr(value) if 0 < value <= 0x10FFFF and not 0xD800 <= value <= 0xDFFF else "\ufffd"+ return "" if literal in "\r\n\f" else literal++ return re.sub(r"\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\r\n\f])?|([\s\S]))", escape, style)+++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(","):+ 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.+ if not re.fullmatch(r"(?:[A-Za-z][\w-]*|\*)?(?:[.#][\w-]+)*", terminal) or not terminal:+ return True+ tag = re.match(r"^[A-Za-z][\w-]*", terminal)+ classes = re.findall(r"\.([\w-]+)", terminal)+ ids = re.findall(r"#([\w-]+)", terminal)+ for child in children:+ if tag and child.tag.rsplit("}", 1)[-1] != tag.group(0):+ continue+ if all(name in child.get("class", "").split() for name in classes) and all(+ name == child.get("id") for name in ids+ ):+ return True+ return False++def normalize_rgba_presentation_attrs(svg: str) -> str:- """Split rgba()/transparent presentation attrs for strict SVG 1.1 importers."""+ """Split rgba paint and combine its alpha with existing presentation opacity."""- def repl(match: re.Match[str]) -> str:- prop, r, g, b, a = match.groups()- return '{0}="#{1:02x}{2:02x}{3:02x}" {0}-opacity="{4}"'.format(- prop, max(0, min(255, int(r))), max(0, min(255, int(g))),- max(0, min(255, int(b))), a if 0 <= float(a) <= 1 else "0" if float(a) < 0 else "1"- )+ # A parent's paint and opacity may be inherited independently. Converting+ # its color alpha into opacity would also change children overriding paint.+ try:+ elements = list(ET.fromstring(svg).iter())+ descendants = {+ index: list(element.iter())[1:]+ for index, element in enumerate(elements) if len(element)+ }+ except ET.ParseError:+ return svg # The existing final XML validator supplies the public error.+ opacity_counts = {"fill-opacity": 0, "stroke-opacity": 0}+ styles = list(STYLE_BLOCK_RE.findall(svg))++ def collect_opacity_context(match: re.Match[str]) -> str:+ for attr in TAG_ATTR_RE.finditer(match.group(2)):+ key, value = attr.group(2), attr.group(4)+ if key in opacity_counts:+ opacity_counts[key] += 1+ elif key == "style" and value is not None:+ styles.append(value[1:-1])+ return match.group(0)++ _rewrite_start_tags(svg, collect_opacity_context)+ css_opacity = {+ key for key in opacity_counts+ if any(re.search(rf"(?:^|[;{{])\s*{key}\s*:", _decoded_css_property_text(style), re.IGNORECASE)+ for style in styles)+ }++ position = 0++ def normalize_tag(match: re.Match[str]) -> str:+ nonlocal position+ children = descendants.get(position, [])+ element = elements[position]+ position += 1+ name, attrs, end = match.groups()+ values = {+ attr.group(2): attr.group(4)[1:-1]+ for attr in TAG_ATTR_RE.finditer(attrs)+ if attr.group(4) is not None+ }+ updates: dict[str, str] = {}+ additions: list[str] = []+ for prop in ("fill", "stroke"):+ value = values.get(prop, "")+ if value == "transparent":+ updates[prop] = "none"+ continue+ rgba = RGBA_ATTR_RE.fullmatch(f'{prop}="{value}"')+ if rgba is None:+ continue+ _, r, g, b, alpha = rgba.groups()+ opacity_name = f"{prop}-opacity"+ # Presentation opacity may be overridden by CSS or inherited from+ # another element. Preserve the color alpha when that cascade is+ # unresolved instead of replacing it with opaque RGB.+ # Converting a parent is safe when descendants inherit its paint.+ # Preserve alpha if a descendant overrides that paint, including+ # a conservatively detected stylesheet or inline declaration.+ inline_paint = re.search(+ rf"(?:^|[;{{])\s*{prop}\s*:",+ _decoded_css_property_text(element.get("style", "")), re.I,+ )+ descendant_paint = any(+ prop in child.attrib+ or re.search(rf"(?:^|[;{{])\s*{prop}\s*:",+ _decoded_css_property_text(child.get("style", "")), re.I)+ for child in children+ )+ stylesheet_paint = any(+ re.search(rf"(?:^|[;{{])\s*{prop}\s*:", _decoded_css_property_text(rule.group(2)), re.I)+ and _css_paint_may_target_descendants(rule.group(1), [element] + children)+ for style in STYLE_BLOCK_RE.findall(svg)+ for rule in RULE_RE.finditer(CSS_COMMENT_RE.sub("", style))+ )+ if inline_paint or descendant_paint or stylesheet_paint or opacity_name in css_opacity or opacity_counts[opacity_name] > int(opacity_name in values):+ continue+ opacity = alpha if 0 <= float(alpha) <= 1 else "0" if float(alpha) < 0 else "1"+ if opacity_name in values:+ try:+ original = values[opacity_name].strip()+ amount = float(original.rstrip("%")) / (100 if original.endswith("%") else 1)+ except ValueError:+ continue # Keep paint intact when the opacity cannot be resolved here.+ if not math.isfinite(amount):+ continue+ opacity = format(min(1, max(0, amount)) * max(0, min(1, float(alpha))), ".12g")+ updates[opacity_name] = opacity+ else:+ additions.append(f' {opacity_name}="{opacity}"')+ updates[prop] = "#{:02x}{:02x}{:02x}".format(*(max(0, min(255, int(c))) for c in (r, g, b)))++ def replace_attr(attr: re.Match[str]) -> str:+ space, key, _equals, _value = attr.groups()+ return f'{space}{key}="{updates[key]}"' if key in updates else attr.group(0)- svg = RGBA_ATTR_RE.sub(repl, svg)- svg = TRANSPARENT_ATTR_RE.sub(r'\1="none"', svg)- return svg+ return f"<{name}{TAG_ATTR_RE.sub(replace_attr, attrs)}{''.join(additions)}{end}>"++ return _rewrite_start_tags(svg, normalize_tag)def has_diagram_stylesheet(svg: str) -> bool:@@ -827,8 +955,8 @@ def export_svg_document(html: str, source_path: Path, system_fonts: bool = Falsediagram_css = diagram_css_from_html(html, root_id, original_root_id)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)+ svg = normalize_rgba_presentation_attrs(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.