stocks / scripts /check-shadow-css.py
user
python version
ee446e8
Raw History Blame Contribute Delete
8.32 kB
#!/usr/bin/env python3
"""
check-shadow-css.py β€” guardrail 13.9: the shadow root is not invisible.
`<stock-chart-card>` renders in a shadow root, so the 700-odd lines of CSS in
its `<style>` blocks are invisible to stylelint (which only walks .css files),
to check-tokens.py, and to every other rule in this lane. That is how it got
to 104 raw hex values, 29 raw colour functions, 12 z-index literals and two
competing font stacks: none of it was ever in scope for a lint.
The guardrail is a ratchet. The counts below are measured, not inherited;
the script fails when any of them GROWS. STY-3.4a moved the CSS to
static/css/chart-card.css and STY-3.4b repainted it onto tokens, so the
ratchet now reads the extracted file (EXTRACTED_BASELINE) and stylelint owns
the same file on top of it.
`var()` reads are the one metric that growing is good news, so they are
reported and never gated.
Usage:
.venv/bin/python scripts/check-shadow-css.py # report, exit 1 on growth
.venv/bin/python scripts/check-shadow-css.py --strict # also fail while the debt stands
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _css_scan import CSS_DIR, REPO # noqa: E402
from _css_scan import SHADOW_CSS as EXTRACTED
from _css_scan import SHADOW_HOST as HOST
# Measured 2026-10-03 on the tree this landed with (comment-stripped CSS lines;
# the audit's 756 counts the <style> tags and the comments between them).
BASELINE = {
"blocks": 2,
"lines": 704,
"hex": 104,
"px": 104,
"z-index": 12,
"font stacks": 2,
"colour functions": 29,
"!important": 21,
}
# var() reads are progress, not debt.
PROGRESS = "var() reads"
# The same ratchet, measured on the extracted file just before STY-3.4b
# repainted it. It gates growth, never the debt that is left.
EXTRACTED_BASELINE = {
"hex": 104,
"px": 104,
"z-index": 12,
"font stacks": 2,
"colour functions": 29,
"!important": 21,
}
RE_COMMENT = re.compile(r"/\*.*?\*/", re.S)
RE_HEX = re.compile(r"#[0-9a-fA-F]{3,8}\b")
RE_PX = re.compile(r"(?<![\w.-])\d+(?:\.\d+)?px")
RE_Z = re.compile(r"z-index:(?!\s*var\()[^;]*")
RE_FONT = re.compile(r"font-family:\s*([^;]+)")
RE_COLOUR_FN = re.compile(r"\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([^)]*\d[^)]*\)")
RE_IMPORTANT = re.compile(r"!important")
RE_VAR = re.compile(r"var\((--[\w-]+)")
RE_TOKEN_DEF = re.compile(r"(--[\w-]+)\s*:\s*([^;]+);")
RE_BLOCK = re.compile(r"([^{}]*)\{([^{}]*)\}", re.S)
def shadow_blocks() -> list[tuple[int, int, str]]:
"""(first_line, last_line, css) for each <style> block, 1-indexed."""
if not HOST.exists():
return []
lines = HOST.read_text(encoding="utf8").split("\n")
out: list[tuple[int, int, str]] = []
i = 0
while i < len(lines):
if lines[i].strip() == "<style>":
j = i
while "</style>" not in lines[j]:
j += 1
out.append((i + 1, j + 1, RE_COMMENT.sub("", "\n".join(lines[i + 1 : j]))))
i = j
i += 1
return out
def token_colours() -> dict[str, str]:
"""hex -> token, from the design tokens, for the "a token was available"
list. Only literal colours count; an alias cannot be compared."""
out: dict[str, str] = {}
for path in sorted(CSS_DIR.glob("*.css")):
src = RE_COMMENT.sub("", path.read_text(encoding="utf8"))
for m in RE_BLOCK.finditer(src):
parts = [p.strip().split(";")[-1].strip() for p in m.group(1).split(",")]
if not any(p == ":root" or p.startswith(":root ") or p.startswith("body[data-page") for p in parts):
continue
for token, value in RE_TOKEN_DEF.findall(m.group(2)):
if RE_HEX.fullmatch(value.strip()):
out.setdefault(value.strip().lower(), token)
return out
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--strict", action="store_true", help="fail while any baseline debt stands")
args = parser.parse_args()
if not HOST.exists():
print(f"host file gone: {HOST} β€” STY-3.4a may have landed; check BASELINE", file=sys.stderr)
return 1
blocks = shadow_blocks()
css = "\n".join(css for _, _, css in blocks)
if not css.strip():
# STY-3.4a: the blocks live in static/css/chart-card.css now. The
# guardrail follows them there instead of stopping, because the debt
# they carry is still debt until the repaint (STY-3.4b) pays it.
if not EXTRACTED.exists():
print(f"no <style> block in {HOST.name} and no {EXTRACTED.name}: the CSS is lost", file=sys.stderr)
return 1
print(f"no <style> block left in {HOST.name}; the shadow CSS now lives in {EXTRACTED.relative_to(REPO)}")
css = RE_COMMENT.sub("", EXTRACTED.read_text(encoding="utf8"))
counts = {
"hex": len(RE_HEX.findall(css)),
"px": len(RE_PX.findall(css)),
"z-index": len(RE_Z.findall(css)),
"font stacks": len({f.strip() for f in RE_FONT.findall(css)}),
"colour functions": len(RE_COLOUR_FN.findall(css)),
"!important": len(RE_IMPORTANT.findall(css)),
}
print(f" {PROGRESS:<18} {len(RE_VAR.findall(css)):>4}")
grown = []
for metric, value in counts.items():
baseline = EXTRACTED_BASELINE[metric]
mark = "ok " if value == baseline else ("GREW" if value > baseline else "shrank")
print(f" {mark:<6} {metric:<18} {value:>4} (baseline {baseline})")
if value > baseline:
grown.append(f"{metric} {value} (baseline {baseline})")
if RE_HEX.findall(css):
print(
f" note: {EXTRACTED.name} still carries raw hex -- STY-3.4b repaints it onto tokens.",
file=sys.stderr,
)
if grown:
for row in grown:
print(f"{EXTRACTED.name}: {row} β€” lower EXTRACTED_BASELINE or repaint it", file=sys.stderr)
return 1
return 1 if args.strict else 0
fonts = sorted({f.strip() for f in RE_FONT.findall(css)})
counts = {
"blocks": len(blocks),
"lines": len(css.splitlines()),
"hex": len(RE_HEX.findall(css)),
"px": len(RE_PX.findall(css)),
"z-index": len(RE_Z.findall(css)),
"font stacks": len(fonts),
"colour functions": len(RE_COLOUR_FN.findall(css)),
"!important": len(RE_IMPORTANT.findall(css)),
}
var_reads = len(RE_VAR.findall(css))
print(
f"{HOST.relative_to(REPO)}: {len(blocks)} <style> block(s) at lines "
+ ", ".join(f"{a}-{b}" for a, b, _ in blocks)
)
grown: list[str] = []
shrank: list[str] = []
for metric, baseline in BASELINE.items():
actual = counts[metric]
delta = actual - baseline
mark = "ok " if delta == 0 else ("GREW" if delta > 0 else "shrank")
print(f" {mark:<6} {metric:<18} {actual:>4} (baseline {baseline})")
(grown if delta > 0 else shrank if delta < 0 else []).append(f"{metric} {actual} (baseline {baseline})")
print(f" {PROGRESS:<18} {var_reads:>4}")
for font in fonts:
print(f" font stack: {font}")
# Debt detail: a raw hex that a token already defines is the whole point of
# 13.1, applied to the one file stylelint cannot see.
available = token_colours()
reusable = sorted({h for h in RE_HEX.findall(css) if h.lower() in available})
if reusable:
print(f" hex whose value a token also defines ({len(reusable)} distinct):")
for value in reusable:
print(f" {value} is also the value of {available[value.lower()]}")
for row in grown:
print(f"{HOST.name}: {row} β€” the shadow root is supposed to shrink (STY-3.4a)", file=sys.stderr)
for row in shrank:
print(f"note: {row} β€” lower BASELINE in scripts/check-shadow-css.py in this commit")
if grown or args.strict:
return 1
print("check-shadow-css: no growth; shadow CSS is on its way out")
return 0
if __name__ == "__main__":
sys.exit(main())