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(containment): honor important inline declaration priority (#427)
Rudy Mizrahi Celekli4ebfd0c322a4
diff --git a/scripts/test-verify-architecture-containment.py b/scripts/test-verify-architecture-containment.pyindex 8b9bdfb..07c7688 100644--- a/scripts/test-verify-architecture-containment.py+++ b/scripts/test-verify-architecture-containment.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport importlib.utilimport os+import reimport subprocessimport sysimport tempfile@@ -355,6 +356,135 @@ class ContractTests(unittest.TestCase):self.assertNotEqual(traffic, GOOD)self.clean(traffic)+ def test_important_dasharray_wins_over_later_normal_declaration(self):+ for style in (+ "stroke-dasharray:none!important;stroke-dasharray:4,4",+ "stroke-dasharray:none ! IMPORTANT;stroke-dasharray:4,4",+ ):+ with self.subTest(style=style):+ self.rejects(GOOD.replace('stroke-dasharray="4,4"',+ f'style="{style}"', 1),+ "admin band must use a dashed stroke")+ for style in (+ "stroke-dasharray:4,4!important;stroke-dasharray:none",+ "stroke-dasharray:4,4 ! IMPORTANT;stroke-dasharray:none",+ ):+ with self.subTest(style=style):+ self.clean(GOOD.replace('stroke-dasharray="4,4"',+ f'style="{style}"', 1))++ def test_equal_dasharray_priority_keeps_later_declaration(self):+ for style in (+ "stroke-dasharray:none;stroke-dasharray:4,4",+ "stroke-dasharray:none!important;stroke-dasharray:4,4!important",+ ):+ with self.subTest(style=style):+ self.clean(GOOD.replace('stroke-dasharray="4,4"',+ f'style="{style}"', 1))+ for style in (+ "stroke-dasharray:4,4;stroke-dasharray:none",+ "stroke-dasharray:4,4!important;stroke-dasharray:none!important",+ ):+ with self.subTest(style=style):+ self.rejects(GOOD.replace('stroke-dasharray="4,4"',+ f'style="{style}"', 1),+ "admin band must use a dashed stroke")++ def test_invalid_literal_values_do_not_acquire_declaration_priority(self):+ invalid = ("", " ", "/**/", "nope", "-1", "4,-1", "4,,4", ",4", "4,")+ for value in invalid:+ for style in (+ f"stroke-dasharray:{value}!important;stroke-dasharray:4,4",+ f"stroke-dasharray:4,4!important;stroke-dasharray:{value}!important",+ f"stroke-dasharray:4,4;stroke-dasharray:{value}",+ ):+ with self.subTest(style=style, scope="admin"):+ self.clean(GOOD.replace('stroke-dasharray="4,4"', f'style="{style}"', 1))+ with self.subTest(style=style, scope="traffic"):+ traffic = GOOD.replace(+ 'data-scope-id="hub" data-scope-kind="traffic"',+ f'data-scope-id="hub" data-scope-kind="traffic" style="{style}"', 1,+ )+ self.rejects(traffic, "traffic box must use a solid stroke")++ def test_unresolved_dash_values_fail_closed_only_when_they_win(self):+ for value in ("var(--dash, 4)", "calc(2px + 2px)", "4cap", r"n\6f ne"):+ with self.subTest(value=value):+ self.rejects(GOOD.replace(+ 'stroke-dasharray="4,4"',+ f'style="stroke-dasharray:{value}!important;stroke-dasharray:4,4"', 1,+ ), "unsupported stroke-dasharray value")+ self.clean(GOOD.replace(+ 'stroke-dasharray="4,4"',+ f'style="stroke-dasharray:4,4!important;stroke-dasharray:{value}"', 1,+ ))++ def test_css_wide_dash_keywords_are_retained_in_priority_resolution(self):+ for value in ("inherit", "initial", "unset", "revert", "revert-layer"):+ with self.subTest(value=value):+ self.assertEqual(checker.declarations(+ f"stroke-dasharray:{value}!important;stroke-dasharray:4,4"+ )["stroke-dasharray"], value)++ def test_css_wide_dash_priority_matches_attribute_and_parent_inheritance(self):+ for value in ("inherit", "initial", "unset", "revert", "revert-layer"):+ style = f"stroke-dasharray:{value}!important;stroke-dasharray:4,4"+ with self.subTest(value=value, source="presentation attribute"):+ source = GOOD.replace('stroke-dasharray="4,4"',+ f'stroke-dasharray="4,4" style="{style}"', 1)+ if value == "revert-layer":+ self.clean(source)+ else:+ self.rejects(source, "admin band must use a dashed stroke")+ with self.subTest(value=value, source="dashed parent"):+ source = GOOD.replace('stroke-dasharray="4,4"', f'style="{style}"', 1)+ source = re.sub(+ r'<rect\b[^>]*data-scope-id="subscription"[^>]*/>',+ lambda match: '<g stroke-dasharray="4,4">' + match.group() + '</g>',+ source, count=1,+ )+ if value == "initial":+ self.rejects(source, "admin band must use a dashed stroke")+ else:+ self.clean(source)++ def test_comments_do_not_fabricate_dash_keywords_units_or_priority(self):+ for style in (+ "stroke-dasharray:no/**/ne!important;stroke-dasharray:4,4",+ "stroke-dasharray:in/**/herit!important;stroke-dasharray:4,4",+ "stroke-dasharray:none!im/**/portant;stroke-dasharray:4,4",+ "stroke-dasharray:4/**/4!important;stroke-dasharray:none",+ ):+ with self.subTest(style=style, scope="admin"):+ self.clean(GOOD.replace('stroke-dasharray="4,4"', f'style="{style}"', 1))+ with self.subTest(style=style, scope="traffic"):+ self.rejects(GOOD.replace(+ 'data-scope-id="hub" data-scope-kind="traffic"',+ f'data-scope-id="hub" data-scope-kind="traffic" style="{style}"', 1,+ ), "traffic box must use a solid stroke")+ for style in (+ "stroke-dasharray:4/**/px!important;stroke-dasharray:none",+ "stroke-dasharray:none!/**/important;stroke-dasharray:4,4",+ ):+ with self.subTest(style=style, scope="admin"):+ self.rejects(GOOD.replace('stroke-dasharray="4,4"', f'style="{style}"', 1),+ "admin band must use a dashed stroke")+ with self.subTest(style=style, scope="traffic"):+ self.clean(GOOD.replace(+ 'data-scope-id="hub" data-scope-kind="traffic"',+ f'data-scope-id="hub" data-scope-kind="traffic" style="{style}"', 1,+ ))++ def test_comment_scanning_preserves_quoted_strings_escapes_and_rule_bodies(self):+ source = r'label:"escaped\"/*literal;{}*/";stroke-dasharray:4/**/4!important;stroke-dasharray:none'+ values = checker.declarations(source)+ self.assertEqual(values["label"], r'"escaped\"/*literal;{}*/"')+ self.assertEqual(values["stroke-dasharray"], "4 4")+ rules = checker.css_rules('rect/**/.bounds {' + source + '}')+ self.assertEqual(rules, [("rect.bounds", values)])+ self.assertEqual(checker.declarations("stroke-dasharray:4,4;/* unterminated"),+ {"stroke-dasharray": "4,4"})+def test_dasharray_resolves_style_and_inheritance(self):self.rejects(GOOD.replace(' stroke-dasharray="4,4"', ' stroke-dasharray="4,4" style="stroke-dasharray: none"', 1),"admin band must use a dashed stroke")diff --git a/scripts/verify-architecture-containment.py b/scripts/verify-architecture-containment.pyindex 6c8e190..cc12db4 100644--- a/scripts/verify-architecture-containment.py+++ b/scripts/verify-architecture-containment.py@@ -3,8 +3,9 @@Checks unique IDs, resolving parents, no cycles, geometric containment,innermost-scope parents (only the outermost scope may omit data-parent),-<rect> bounds, admin-band vs traffic-box shapes with stroke-dasharray resolved-as rendered, PaaS placement, endpoint targets, declared peerings, sibling axes+<rect> bounds, admin-band vs traffic-box shapes with supported literal+stroke-dasharray declarations resolved by priority (unresolved computed values+are findings), PaaS placement, endpoint targets, declared peerings, sibling axes(nested children perpendicular to their parent's), and the 4px grid. Geometryis read from raw x/y/width/height, so a transform, moving inline CSS, nested<svg> viewport, matching <style> rule, or geometry animation on a checked@@ -166,10 +167,49 @@ def identity_ok(raw: str) -> bool:return bool(raw) and ID_RE.fullmatch(raw) is not None+def css_without_comments(text: str, *, replacement: str = " ", mask: bool = False) -> str:+ """Remove actual comments without joining tokens or touching strings.++ A width-preserving mask lets the rule scanner find delimiters while keeping+ indices into the original declaration body, where comment boundaries matter.+ """+ output, quote, index = [], "", 0+ while index < len(text):+ char = text[index]+ if char == "\\":+ output.append(text[index:index + 2])+ index += 2+ continue+ if quote:+ output.append(char)+ if char == quote:+ quote = ""+ elif char in "\"'":+ quote = char+ output.append(char)+ elif text.startswith("/*", index):+ close = text.find("*/", index + 2)+ end = len(text) if close < 0 else close + 2+ output.append(" " * (end - index) if mask else replacement)+ index = end+ continue+ else:+ output.append(char)+ index += 1+ return "".join(output)++def split_top(text: str, separators: str) -> list[str]:"""Split on separators outside quotes, brackets and parentheses."""parts, depth, quote, start = [], 0, "", 0+ escaped = Falsefor index, char in enumerate(text):+ if escaped:+ escaped = False+ continue+ if char == "\\":+ escaped = True+ continueif quote:if char == quote:quote = ""@@ -186,14 +226,56 @@ def split_top(text: str, separators: str) -> list[str]:return parts+DASH_KEYWORDS = {"none", "inherit", "initial", "unset", "revert", "revert-layer"}+DASH_UNITS = {"", "px", "%", "em", "rem", "ex", "ch", "pt", "pc", "mm", "cm", "in", "vw", "vh"}+++def dash_declaration_valid(raw: str) -> bool | None:+ """True for supported literals, False for invalid ones, None if unresolved.++ A valid computed value (for example var() or calc()) must not be discarded+ as though it were a syntactically invalid declaration. Keep it in the+ cascade and report that the checker cannot resolve it if it wins.+ """+ value = raw.strip().lower()+ if value in DASH_KEYWORDS:+ return True+ if any(char in value for char in "()\\"):+ return None+ if not value or re.search(r"^,|,$|,\s*,", value):+ return False+ unresolved = False+ for token in re.split(r"[\s,]+", value):+ match = re.fullmatch(f"({NUMBER})([a-z%]*)", token)+ if match is None:+ return False+ amount = float(match.group(1))+ if amount < 0:+ return False+ if not math.isfinite(amount) or match.group(2) not in DASH_UNITS:+ unresolved = True+ return None if unresolved else True++def declarations(text: str) -> dict[str, str]:- """Parse a CSS declaration block; later declarations win, as in CSS."""+ """Resolve declarations by importance, then by their order in the block."""result = {}- for part in split_top(re.sub(r"/\*.*?\*/", "", text, flags=re.S), ";"):+ important = set()+ for part in split_top(css_without_comments(text), ";"):name, colon, value = part.partition(":")name = name.strip().lower()if colon and name and not name.startswith("--"):- result[name] = re.sub(r"!\s*important\s*$", "", value.strip(), flags=re.I).strip()+ priority = re.search(r"!\s*important\s*$", value, flags=re.I)+ value = value[:priority.start()].strip() if priority else value.strip()+ # Invalid declarations must not hide a later valid value or erase+ # an earlier one merely because they carry !important.+ if (not value+ or (name == "stroke-dasharray" and dash_declaration_valid(value) is False)+ or (name in important and priority is None)):+ continue+ result[name] = value+ if priority:+ important.add(name)return result@@ -203,11 +285,15 @@ GROUP_AT_RULES = {"media", "supports", "layer", "container", "scope", "document"def css_rules(text: str) -> list[tuple[str, dict[str, str]]]:"""Return (selector list, declarations) for every style rule, recursing intoconditional group at-rules and skipping @keyframes, @font-face and the like."""- text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)+ original = text+ text = css_without_comments(text, mask=True)rules: list[tuple[str, dict[str, str]]] = []index, start, quote = 0, 0, ""while index < len(text):char = text[index]+ if char == "\\":+ index += 2+ continueif quote:if char == quote:quote = ""@@ -219,6 +305,9 @@ def css_rules(text: str) -> list[tuple[str, dict[str, str]]]:depth, close, inner_quote = 1, index + 1, ""while close < len(text) and depth:inner = text[close]+ if inner == "\\":+ close += 2+ continueif inner_quote:if inner == inner_quote:inner_quote = ""@@ -229,7 +318,8 @@ def css_rules(text: str) -> list[tuple[str, dict[str, str]]]:elif inner == "}":depth -= 1close += 1- prelude, body = text[start:index].strip(), text[index + 1:close - 1]+ prelude = css_without_comments(original[start:index], replacement="").strip()+ body = original[index + 1:close - 1]if prelude.startswith("@"):name = prelude[1:].split(None, 1)[0].lower() if len(prelude) > 1 else ""if name in GROUP_AT_RULES:@@ -465,9 +555,9 @@ def rule_may_match(selector: str, node: Node, parent_of) -> bool:def dash_value(raw: str) -> bool | None:"""True dashed, False solid, None when unspecified, inherited or invalid."""value = raw.strip().lower()- if value in ("", "inherit"):+ if value in ("", "inherit", "unset", "revert", "revert-layer"):return None- if value in ("none", "initial", "unset", "revert"):+ if value in ("none", "initial"):return Falselengths = []for token in re.split(r"[\s,]+", value):@@ -483,9 +573,22 @@ def is_dashed(node: Node, root: Node) -> bool:and the property inherits from ancestors up to the diagram SVG."""current: Node | None = nodewhile current is not None:- for raw in (declarations(current.attrs.get("style", "")).get("stroke-dasharray"),- current.attrs.get("stroke-dasharray")):+ inline = declarations(current.attrs.get("style", "")).get("stroke-dasharray")+ keyword = inline.strip().lower() if inline is not None else ""+ if keyword in {"inherit", "unset", "revert"}:+ # These inherit the parent's computed value rather than resurrect+ # this element's lower-priority presentation attribute.+ values = ()+ elif keyword == "revert-layer":+ # Matching stylesheet rules are refused below, so reverting the+ # inline layer exposes the presentation attribute or inheritance.+ values = (current.attrs.get("stroke-dasharray"),)+ else:+ values = (inline, current.attrs.get("stroke-dasharray"))+ for raw in values:if raw is not None:+ if dash_declaration_valid(raw) is None:+ raise ValueError(f"unsupported stroke-dasharray value: {raw!r}")resolved = dash_value(raw)if resolved is not None:return resolved