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(verifiers): land polarity and accessibility fixes from #315, #328, #334 (#351)

Cathryn Lavery57464d1ceffa
diff --git a/scripts/test-self-check.py b/scripts/test-self-check.py
index 347743c..c14a946 100644
--- a/scripts/test-self-check.py
+++ b/scripts/test-self-check.py
@@ -58,6 +58,22 @@ def main() -> int:
static = STATIC_EXAMPLE.read_text(encoding="utf-8")
animated = EXAMPLE.read_text(encoding="utf-8")
+ for location, markup in (
+ ("heading before SVG", '<h2 id="architecture-title">Monthly traffic summary</h2>'),
+ ("description duplicate", '<p id="architecture-desc">Unrelated description</p>'),
+ ):
+ check_fail(location, static.replace("<body>", "<body>" + markup, 1),
+ "duplicate accessible SVG naming ID")
+ check_fail(
+ "heading after SVG", static.replace("</body>",
+ '<h2 id="architecture-title">Monthly traffic summary</h2></body>', 1),
+ "duplicate accessible SVG naming ID",
+ )
+ check_source_pass("distinct heading ID", static.replace("<body>",
+ '<body><h2 id="monthly-summary">Monthly traffic summary</h2>', 1))
+ check_source_pass("unreferenced duplicate IDs", static.replace("<body>",
+ '<body><span id="unused">One</span><span id="unused">Two</span>', 1))
+
check_fail(
"executable attribute",
static.replace("<body>", '<body onload="fetch(1)">', 1),
diff --git a/scripts/test-verify-skin-polarity.py b/scripts/test-verify-skin-polarity.py
index 464dc15..c00cf95 100644
--- a/scripts/test-verify-skin-polarity.py
+++ b/scripts/test-verify-skin-polarity.py
@@ -136,6 +136,39 @@ def main():
with tempfile.TemporaryDirectory() as raw:
directory = Path(raw)
+ # SVG presentation opacity is multiplicative with the color alpha.
+ for skin, source, ramp, ink, hex_ink in (
+ ("light", light_source, LIGHT_RAMP, LIGHT_INK, "#2d3142"),
+ ("dark", dark_source, DARK_RAMP, DARK_INK, "#f5f5f5"),
+ ):
+ explicit = source
+ for rank, alpha in ramp:
+ explicit = explicit.replace(
+ f'data-share="{rank}" fill="rgba({ink},{alpha})"',
+ f'data-share="{rank}" fill="{hex_ink}" fill-opacity="{float(alpha) * 100:g}%"', 1)
+ code, output = run(write(directory, f"{skin}-fill-opacity.html", explicit))
+ if code:
+ failures.append(f"{skin} explicit fill-opacity ramp failed: {output}")
+ else:
+ print(f"OK: {skin} explicit fill-opacity ramp passes")
+ for attrs, expected in (
+ ('fill="rgba(45,49,66,.8)" fill-opacity=".5" opacity="25%"', .1),
+ ('fill="#2d3142" fill-opacity="200%" opacity=".25"', .25),
+ ):
+ members = COLLECT_MEMBERS(f'<rect x="0" y="0" width="10" height="10" data-share="1" {attrs}/>')
+ found = [m for group in members.values() for m in group]
+ if len(found) != 1 or abs(found[0].alpha - expected) > 1e-9:
+ failures.append(f"presentation opacity measured incorrectly: {attrs}")
+ else:
+ print(f"OK: presentation opacity measures {expected:g}")
+ inverted = light_source.replace('data-share="18.29" fill=',
+ 'data-share="18.29" fill-opacity=".1" fill=', 1)
+ code, output = run(write(directory, "opacity-breaks-order.html", inverted))
+ if code == 0:
+ failures.append("explicit opacity that breaks rank order was accepted")
+ else:
+ print("OK: explicit opacity that breaks rank order is rejected")
+
# SVG accepts both quote styles. Convert every rank-bearing ramp member
# to single-quoted attributes; the checker must still discover all five
# members and verify the shipped claim.
@@ -614,6 +647,87 @@ def main():
else:
print("OK: shipped_wording_binds_as_a_contrast_claim")
+ with tempfile.TemporaryDirectory(prefix="polarity-unreadable-opacity-") as raw:
+ directory = Path(raw)
+ for skin, source, ink, alpha in (
+ ("light", light_source, LIGHT_INK, "0.16"),
+ ("dark", dark_source, DARK_INK, "0.14"),
+ ):
+ for attribute in ("fill-opacity", "opacity"):
+ for value in ("oops", "nan", "inf"):
+ anchor = f'data-share="18.29" fill="rgba({ink},{alpha})"'
+ changed = source.replace(anchor, anchor + f' {attribute}="{value}"', 1)
+ code, output = run(write(directory, f"{skin}-{attribute}-{value}.html", changed))
+ if not code or "unreadable" not in output:
+ failures.append(f"unreadable {skin} {attribute}={value} dropped a ramp member silently: {output}")
+ else:
+ print(f"OK: unreadable {skin} {attribute}={value} is reported")
+
+ with tempfile.TemporaryDirectory(prefix="polarity-zero-opacity-") as raw:
+ directory = Path(raw)
+ for skin, source, ink, alpha in (
+ ("light", light_source, LIGHT_INK, "0.16"),
+ ("dark", dark_source, DARK_INK, "0.14"),
+ ):
+ for attribute in ("fill-opacity", "opacity"):
+ for value in ("0", "-0.25"):
+ anchor = f'data-share="18.29" fill="rgba({ink},{alpha})"'
+ changed = source.replace(anchor, anchor + f' {attribute}="{value}"', 1)
+ code, output = run(write(directory, f"{skin}-{attribute}-{value}.html", changed))
+ if not code or "does not move strictly one way" not in output:
+ failures.append(f"transparent largest {skin} {attribute}={value} omitted from ramp: {output}")
+ else:
+ print(f"OK: transparent largest {skin} {attribute}={value} remains a ramp member")
+ smallest = 'data-share="0.56" fill="rgba(' + ink + ',0.04)"'
+ changed = source.replace(smallest, smallest + ' fill-opacity="0"', 1)
+ code, output = run(write(directory, f"{skin}-zero-smallest.html", changed))
+ if code:
+ failures.append(f"valid zero-alpha smallest {skin} member was rejected: {output}")
+ else:
+ print(f"OK: valid zero-alpha smallest {skin} member passes")
+
+ with tempfile.TemporaryDirectory() as raw:
+ directory = Path(raw)
+ archived = light_source.replace("</body>",
+ "<!-- Archived legend: <p>Other continents · fainter contrast is larger</p> -->\n</body>", 1)
+ code, output = run(write(directory, "commented-legend.html", archived))
+ if code:
+ failures.append(f"commented old legend was treated as visible copy: {output}")
+ else:
+ print("OK: archived HTML comment is not a visible claim")
+ joined = light_source.replace("stronger contrast is larger", "str<!-- editorial note -->onger contrast is larger")
+ code, output = run(write(directory, "inline-comment.html", joined))
+ if code or "1 making a directional tone claim" not in output:
+ failures.append(f"inline comment changed the visible claim: {output}")
+ else:
+ print("OK: inline comment preserves adjacent visible text")
+ incorrect = light_source.replace("stronger contrast is larger", "faint<!-- editorial note -->er contrast is larger")
+ code, output = run(write(directory, "inline-comment-wrong.html", incorrect))
+ if not code or "but the ramp draws larger as stronger" not in output:
+ failures.append(f"wrong visible claim with an inline comment was accepted: {output}")
+ else:
+ print("OK: incorrect visible claim remains rejected across an inline comment")
+ unmatched = archived.replace("stronger contrast is larger", "larger means something stronger eventually")
+ code, output = run(write(directory, "visible-unparsed-with-comment.html", unmatched))
+ if not code:
+ failures.append("unparsed visible claim was excused by the archived comment")
+ else:
+ print("OK: unparsed visible claim remains rejected beside an archived comment")
+
+ with tempfile.TemporaryDirectory() as raw:
+ directory = Path(raw)
+ for label, replacement, wrong in (
+ ("archived-inline-correct", "str<!-- archived <text>old legend</text> -->onger contrast is larger", False),
+ ("archived-inline-wrong", "faint<!-- archived <text>old legend</text> -->er contrast is larger", True),
+ ("archived-inline-unparsed", "larger<!-- archived <text>old legend</text> --> means something stronger eventually", True),
+ ):
+ source = light_source.replace("stronger contrast is larger", replacement)
+ code, output = run(write(directory, label + ".html", source))
+ if bool(code) != wrong or (not wrong and "1 making a directional tone claim" not in output):
+ failures.append(f"{label}: archived closing markup changed visible claim parsing: {output}")
+ else:
+ print(f"OK: {label} preserves complete visible copy")
+
for failure in failures:
print("FAIL: {}".format(failure))
if failures:
diff --git a/scripts/verify-skin-polarity.py b/scripts/verify-skin-polarity.py
index 496d1b2..2d570e8 100644
--- a/scripts/verify-skin-polarity.py
+++ b/scripts/verify-skin-polarity.py
@@ -73,6 +73,7 @@ from __future__ import annotations
import argparse
import html
+import math
import re
import sys
from pathlib import Path
@@ -101,8 +102,11 @@ PAPER_VAR_RE = re.compile(r"--color-paper\s*:\s*(?P<value>[^;}]+)", re.IGNORECAS
# Copy a reader - or a screen reader - actually receives as a statement: rendered
# SVG strings, the accessible description, and the editorial prose the full
# variant wraps around the chart.
+COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
+# A complete inline comment must stay indivisible: its archived closing tags
+# cannot terminate the surrounding visible copy element.
COPY_RE = re.compile(
- r"<(?P<tag>text|desc|p|h1|h2|h3|h4|li|figcaption)\b[^>]*>(?P<body>.*?)</(?P=tag)>",
+ r"<!--.*?-->|<(?P<tag>text|desc|p|h1|h2|h3|h4|li|figcaption)\b[^>]*>(?P<body>(?:<!--.*?-->|(?!<!--).)*?)</(?P=tag)>",
re.IGNORECASE | re.DOTALL,
)
TAG_RE = re.compile(r"<[^>]+>")
@@ -238,7 +242,7 @@ def plain(body):
inside it, would otherwise hide the claim from a substring search while a
reader still receives the whole sentence.
"""
- return " ".join(html.unescape(TAG_RE.sub("", body)).split())
+ return " ".join(html.unescape(TAG_RE.sub("", COMMENT_RE.sub("", body))).split())
def excerpt(text):
@@ -319,6 +323,36 @@ def parse_fill(value):
return parse_rgb(value) or parse_hex_fill(value)
+# A literal fill whose explicit opacity cannot be read. It is reported rather
+# than dropped, because dropping a ranked cell can hide a broken ramp.
+UNREADABLE = object()
+
+
+def painted_fill(attrs):
+ """Literal fill alpha after explicit SVG presentation opacity attributes.
+
+ CSS rules and inherited/group opacity remain outside this source checker.
+ Returns UNREADABLE when a literal fill carries an opacity that is not a
+ finite number.
+ """
+ parsed = parse_fill(attrs.get("fill", ""))
+ if parsed is None:
+ return None
+ ink, alpha = parsed
+ for name in ("fill-opacity", "opacity"):
+ if name not in attrs:
+ continue
+ token = attrs[name].strip()
+ try:
+ value = float(token[:-1]) / 100.0 if token.endswith("%") else float(token)
+ except ValueError:
+ return UNREADABLE
+ if not math.isfinite(value):
+ return UNREADABLE
+ alpha *= max(0.0, min(1.0, value))
+ return ink, alpha
+
+
def srgb_to_linear(channel):
ratio = channel / 255.0
return ratio / 12.92 if ratio <= 0.04045 else ((ratio + 0.055) / 1.055) ** 2.4
@@ -368,7 +402,7 @@ def resolve_paper(source):
return None
-def collect_members(source):
+def collect_members(source, unreadable=None):
"""Rank-bearing translucent fills, grouped by ink triple.
A cell is painted twice - a paper mask, then the body - and the rank
@@ -385,6 +419,7 @@ def collect_members(source):
name = attribute.group("name")
if name not in attrs: # browsers keep the first duplicate attribute
attrs[name] = attribute.group("value")
+ paint = painted_fill(attrs)
signature = (
match.group("tag").lower(),
attrs.get("x"),
@@ -402,7 +437,7 @@ def collect_members(source):
twinnable = any(value is not None for value in signature[1:])
position = index_by_signature.get(signature) if twinnable else None
if position is None:
- merged.append([dict(attrs), match.start()])
+ merged.append([dict(attrs), match.start(), paint])
if twinnable:
index_by_signature[signature] = len(merged) - 1
continue
@@ -410,22 +445,23 @@ def collect_members(source):
for name, value in attrs.items():
# A translucent fill wins over the mask's opaque one, and a rank
# attribute is adopted from whichever twin declared it.
- parsed_fill = parse_fill(value) if name == "fill" else None
+ parsed_fill = paint if name == "fill" else None
if name not in existing[0] or (
- name == "fill" and parsed_fill is not None and 0.0 < parsed_fill[1] < 1.0
+ name == "fill"
+ and (
+ parsed_fill is UNREADABLE
+ or (parsed_fill is not None and 0.0 <= parsed_fill[1] < 1.0)
+ )
):
existing[0][name] = value
+ if name == "fill":
+ existing[2] = paint
existing[1] = min(existing[1], match.start())
groups = {}
- for attrs, offset in merged:
- parsed = parse_fill(attrs.get("fill", ""))
+ for attrs, offset, parsed in merged:
if parsed is None:
continue
- ink, alpha = parsed
- # A fully opaque fill is not a point on an opacity ramp.
- if not 0.0 < alpha < 1.0:
- continue
rank = None
for name in RANK_ATTRS:
if name in attrs:
@@ -437,6 +473,15 @@ def collect_members(source):
# NaN compares unequal to itself and would corrupt every ordering test.
if rank is None or rank != rank:
continue
+ if parsed is UNREADABLE:
+ if unreadable is not None:
+ unreadable.append(offset)
+ continue
+ ink, alpha = parsed
+ # A zero-alpha ranked fill is still a point: it has paper contrast.
+ # A fully opaque fill is not a point on an opacity ramp.
+ if not 0.0 <= alpha < 1.0:
+ continue
groups.setdefault(ink, []).append(Member(rank, alpha, ink, offset))
return groups
@@ -470,6 +515,8 @@ def classify_magnitude(word):
def parse_claims(source):
claims = []
for match in COPY_RE.finditer(source):
+ if match.group("body") is None: # An HTML comment is not a copy element.
+ continue
copy = plain(match.group("body"))
if not copy:
continue
@@ -508,6 +555,8 @@ def find_unparsed(source, claims):
unparsed = []
for match in COPY_RE.finditer(source):
+ if match.group("body") is None: # An HTML comment is not a copy element.
+ continue
copy = plain(match.group("body"))
if not copy:
continue
@@ -552,7 +601,14 @@ def check(path):
)
return findings, True
- groups = collect_members(source)
+ unreadable = []
+ groups = collect_members(source, unreadable)
+ for offset in unreadable:
+ findings.append(
+ "{}:{}: a ranked fill declares an unreadable fill-opacity or opacity, so "
+ "its contrast cannot be composited. Use a finite number or percentage, "
+ "or remove the attribute".format(path.name, line_of(source, offset))
+ )
ramp = max(groups.values(), key=len) if groups else []
if len(ramp) < MIN_RAMP_MEMBERS:
for claim in claims:
diff --git a/skills/diagram-design/references/primitives-core.md b/skills/diagram-design/references/primitives-core.md
index 13b710e..5f0cb47 100644
--- a/skills/diagram-design/references/primitives-core.md
+++ b/skills/diagram-design/references/primitives-core.md
@@ -136,7 +136,7 @@ Every diagram is an accessible figure by default:
1. Its `<svg>` carries `role="img"` and `aria-labelledby` naming the diagram's `<title>` and `<desc>`.
2. `<title>` is the first child of `<svg>`, before `<defs>`. Assistive technology may ignore a title placed later.
-3. The IDs are prefixed per diagram and variant: `<slug>-title` / `<slug>-desc`, where the slug matches the file (`loop`, `loop-dark`, `loop-full`). Bare `title` / `desc` IDs are banned — two inline diagrams would otherwise share one ID, and the second could be announced with the first's name.
+3. The IDs are prefixed per diagram and variant: `<slug>-title` / `<slug>-desc`, where the slug matches the file (`loop`, `loop-dark`, `loop-full`). Bare `title` / `desc` IDs are banned — two inline diagrams would otherwise share one ID, and the second could be announced with the first's name. Each naming ID must also be unique across the whole document, including non-SVG elements; the packaged `scripts/self_check.py` rejects these collisions.
4. `<title>` is the short name of the subject — roughly the page `<h1>`, and about 60 characters or fewer.
5. `<desc>` is one sentence stating what the diagram shows in terms a reader needs without the image. Describe the content, not the geometry: “Org chart showing a command center routing work to specialist agents and escalation owners,” not “A box at the top with five boxes below it.” A shape-by-shape narration is worse than no useful description.
6. Decorative-only SVG, such as the specimen glyphs in `assets/icons.html`, carries `aria-hidden="true"` instead.
diff --git a/skills/diagram-design/references/type-treemap.md b/skills/diagram-design/references/type-treemap.md
index 10c99f8..639b984 100644
--- a/skills/diagram-design/references/type-treemap.md
+++ b/skills/diagram-design/references/type-treemap.md
@@ -19,7 +19,7 @@ Not for: ranked lists where exact values matter more than proportion (use a **ba
- sliver — **no text.** When the cell is at least 12×12px, use a filled `ink` disc, `r=5`, centred in the cell, carrying a paper-coloured `i`, with the cell's name and share spelled out in the legend. Below 12px on either axis, omit the in-cell mark and identify the sliver by position in the legend; a fixed-size disc must never cross the cell boundary. `scripts/verify-treemap.py` checks marker containment. Resist rotating a label to make it fit: a single sideways word among five upright ones reads as a mistake before it reads as data, and its centring is a trap — `text-anchor="middle"` centres along the *baseline*, which a quarter-turn maps to the cell's long axis, leaving nothing centring the cap-height band across the narrow one.
- Never shrink a cell to fit its label. The cell size is the data; the label is commentary.
- **Contrast:** compute the ceiling against the token you actually ship. The 9px value line is `muted`, not `ink`, and `muted` needs a lighter cell than `ink` does: measured against the composited fill, the top of the ramp can go to **0.16 on light paper and 0.14 on dark** before it drops under 4.5:1. (`ink` would tolerate 0.20 — which is exactly the number you will write down if you check the wrong token.) A mid-tone fill — solid accent, or 50% ink — fails against both light and dark text; use the tint-plus-stroke pattern instead. The source line takes `muted` too: `soft` measures 3.48:1 on paper and never reaches AA anywhere on this ramp.
-- **Legend:** the house block (rule, `LEGEND`, keys), naming the focal cell, the direction of the ink ramp, and any cell carrying an info mark. **Name that direction by contrast against the paper — `stronger contrast is larger` — never by lightness.** `darker is larger` is true only on light paper; ship it in the dark variant and the legend states the opposite of what the reader sees, because the ramp's lightness inverts with the skin while its opacity does not. Named by contrast, one sentence serves all three variants and cannot rot apart. `scripts/verify-skin-polarity.py` gates this, checking every directional tone claim against the ramp composited on that file's own paper. The source line rides the same row as `LEGEND`, right-aligned in mono 8px, stating what area encodes plus the dataset and its date.
+- **Legend:** the house block (rule, `LEGEND`, keys), naming the focal cell, the direction of the ink ramp, and any cell carrying an info mark. **Name that direction by contrast against the paper — `stronger contrast is larger` — never by lightness.** `darker is larger` is true only on light paper; ship it in the dark variant and the legend states the opposite of what the reader sees, because the ramp's lightness inverts with the skin while its opacity does not. Named by contrast, one sentence serves all three variants and cannot rot apart. `scripts/verify-skin-polarity.py` gates this, checking every directional tone claim against the ramp composited on that file's own paper. HTML comments are not visible legend copy, including comments between text fragments; contradictory or unverifiable visible wording still fails. Explicit `fill-opacity` and `opacity` presentation attributes multiply the fill color's alpha before that comparison; CSS rules and inherited/group opacity are not resolved by this source checker. Ranked cells with zero effective opacity remain in the comparison at paper contrast. The source line rides the same row as `LEGEND`, right-aligned in mono 8px, stating what area encodes plus the dataset and its date. Archived closing tags inside an inline comment cannot truncate the surrounding visible claim.
### Declaring the share
diff --git a/skills/diagram-design/scripts/self_check.py b/skills/diagram-design/scripts/self_check.py
index bf758a0..7ede778 100644
--- a/skills/diagram-design/scripts/self_check.py
+++ b/skills/diagram-design/scripts/self_check.py
@@ -72,6 +72,7 @@ class DiagramParser(HTMLParser):
self.styles: list[str] = []
self.css_attributes: list[str] = []
self.svgs: list[dict[str, object]] = []
+ self.ids: Counter[str] = Counter()
self.unsafe: list[str] = []
self.references: list[tuple[str, str, str]] = []
self._svg_depth = 0
@@ -89,6 +90,8 @@ class DiagramParser(HTMLParser):
data: dict[str, str] = {}
for key, value in normalized_attrs:
data.setdefault(key, value)
+ if data.get("id"):
+ self.ids[data["id"]] += 1
if tag in {"base", "embed", "object", "iframe"}:
self.unsafe.append(f"<{tag}> is not allowed in a diagram file")
for key, value in normalized_attrs:
@@ -307,6 +310,9 @@ def check_svgs(parser: DiagramParser, errors: list[str]) -> None:
desc_id = desc_attrs.get("id", "")
if title_id in {"", "title"} or desc_id in {"", "desc"}:
errors.append(f"svg {number} title/desc IDs must be diagram-prefixed, never bare")
+ for naming_id in dict.fromkeys((title_id, desc_id)):
+ if parser.ids[naming_id] > 1:
+ errors.append(f"duplicate accessible SVG naming ID {naming_id!r}")
if labelled != [title_id, desc_id]:
errors.append(f"svg {number} aria-labelledby must name title then desc")