#!/usr/bin/python3 # -*- coding: utf-8 -*- """图标可读名称普查(只读,**不进退出码**):页面上每一只 `.anticon` 与它所在控件的名称来源。 常驻闸门只回答「有没有缺陷」(`semanticcheck.GLYPH` 数外泄、`classaudit` 数出口形状), 回答不了「这一族缺陷原来有多大、现在缩到多小」。这条脚本量三组数: A 组 字形码对辅助技术可见的图标(按字形聚合)——S-2 改前 900 只 / 改后 80 只; 两条口径分开数:**包围盒口径**(有尺寸 ≠ AT 读得到)与 **AT 可读口径** (再排除 `visibility:hidden` 的祖先)。S-2 立项时两者差 6 只: rc-tabs 的「…」在 1440 下是 `visibility:hidden`,包围盒有值但读屏念不到, 真实溢出只在窄视口出现(`reports/ui_evidence/nex-s2/PROBE3.txt`)。 常驻闸 `semanticcheck.GLYPH` 从一开始就按 AT 可读口径判(`semanticcheck.py:227`), 这条普查脚本原来只按包围盒——补上 `vis` 之后两者口径一致,别再拿裸数当结论。 B 组 **「图标是宿主唯一语义」**:宿主既没有 `aria-label` 也没有 `title`、又没有文字, 去掉图标这个控件就没名字 → 这一组才是必须显式具名的位置(S-2 改后 0 条); D 组 控件的可读名称里混进了字形 token(`aria-label` / `title` / 正文文本撞表)—— 这一组包含假阳性(正文里真写着 `/api/meta`),所以只打印、不立案。 用法(跑完把 stdout 存进证据目录,两份 JSON 是逐条取证): NEX_BASE=http://127.0.0.1:5199 NEX_CENSUS_OUT=reports/ui_evidence/nex-s2 \ .venv/bin/python scripts/ui/census-icons.py 环境变量:`NEX_WIDTH`(默认 1440)、`NEX_THEME`(默认 both)、`NEX_CENSUS_OUT`(默认 /tmp/nex_census)。 """ import json, os, pathlib, re, sys from collections import Counter from playwright.sync_api import sync_playwright BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5199") WIDTH = int(os.environ.get("NEX_WIDTH", "1440")) THEMES = ["dark", "light"] if os.environ.get("NEX_THEME", "both") == "both" else [os.environ["NEX_THEME"]] OUT = os.environ.get("NEX_CENSUS_OUT", "/tmp/nex_census") ROOT = str(pathlib.Path(__file__).resolve().parents[2]) src = open(ROOT + "/frontend/src/components/icons/index.ts", encoding="utf8").read() pairs = [] for glyph, alias in re.findall(r"export\s*\{\s*(\w+)\s+as\s+(Icon\w+)\s*\}", src): pairs.append((glyph, alias)) for alias, glyph in re.findall(r"export\s+const\s+(Icon\w+)\s*=\s*decorative\(\s*(\w+)\s*,", src): pairs.append((glyph, alias)) GLYPHS = {} for glyph_component, alias in pairs: token = re.sub(r"(Outlined|Filled|TwoTone)$", "", glyph_component) token = re.sub(r"(? { const out = []; const txt = (n) => (n || '').replace(/\s+/g, ' ').trim(); const INTERACTIVE = 'a,button,input,select,textarea,[role=button],[role=link],[role=checkbox],[role=radio],[role=switch],[role=combobox],[role=tab],[role=menuitem],[role=option],[role=searchbox]'; for (const el of document.querySelectorAll('.anticon')) { const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue; const host = el.closest(INTERACTIVE); let hiddenAncestor = false, anc = el.parentElement; while (anc) { if (anc.getAttribute && anc.getAttribute('aria-hidden') === 'true') { hiddenAncestor = true; break } anc = anc.parentElement; } let textHost = host ? txt(host.innerText || '') : ''; if (!host) { let p = el.parentElement, depth = 0; while (p && depth < 5) { const t = txt(p.innerText || ''); if (t) { textHost = t; break } p = p.parentElement; depth++; } } out.push({ cls: txt(el.className), label: el.getAttribute('aria-label') || '', role: el.getAttribute('role') || '', hidden: el.getAttribute('aria-hidden') || '', hiddenAncestor, // visibility 是继承来的:祖先 visibility:hidden 时包围盒照样有值,AT 却读不到 // (页签溢出那颗就是这么被算进改前 42 只的)——所以另外记一笔计算后的 visibility。 vis: getComputedStyle(el).visibility, box: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)], host: host ? (host.tagName.toLowerCase() + (host.className ? '.' + txt(host.className).split(' ').slice(0, 3).join('.') : '')) : '', hostLabel: host ? (host.getAttribute('aria-label') || '') : '', hostTitle: host ? (host.getAttribute('title') || '') : '', hostText: textHost.slice(0, 60), hostIconOnly: host ? !txt(host.innerText || '') : false, }); } return out; }""" NAMES_JS = r"""() => { const out = []; const txt = (n) => (n || '').replace(/\s+/g, ' ').trim(); const sel = 'a,button,[role=button],[role=link],[role=switch],[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=combobox]'; for (const el of document.querySelectorAll(sel)) { const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue; out.push({ tag: el.tagName.toLowerCase(), cls: txt(el.className).slice(0, 90), aria: el.getAttribute('aria-label') || '', title: el.getAttribute('title') || '', text: txt(el.innerText || '').slice(0, 60), axName: (el.getAttribute('aria-label') || el.getAttribute('title') || txt(el.innerText || '')).slice(0, 60) }); } return out; }""" def main(): os.makedirs(OUT, exist_ok=True) records, ctl_names = [], [] with sync_playwright() as pw: browser = pw.chromium.launch() page = browser.new_page(viewport={"width": WIDTH, "height": 1000}) for theme in THEMES: page.add_init_script("try{localStorage.setItem('nex-the','%s')}catch(e){}" % theme) page.goto(BASE + "/login", wait_until="networkidle") if page.locator("#login-user").count(): page.fill("#login-user", "admin"); page.fill("#login-pass", "admin1234") page.click("button[type=submit]"); page.wait_for_timeout(1500) pid = page.evaluate("""async () => { const r = await fetch('/api/projects').then(x=>x.json()).catch(()=>null); const l = Array.isArray(r) ? r : (r && (r.items||r.projects||r.data)) || []; return l.length ? l[0].id : null; }""") for route in ROUTES: if "{id}" in route: if not pid: continue route = route.replace("{id}", str(pid)) page.goto(BASE + route, wait_until="networkidle") page.wait_for_timeout(1800) tag = "%s/%s%s" % (WIDTH, theme, route) for rec in page.evaluate(CENSUS_JS): rec["where"] = tag; records.append(rec) for c in page.evaluate(NAMES_JS): c["where"] = tag; ctl_names.append(c) browser.close() gt = set(GLYPHS) exposed = [r for r in records if r["label"] in gt and not r["hidden"] and not r["hiddenAncestor"]] # AT 可读口径:排除计算后 visibility:hidden 的(包围盒非零但读屏念不到) readable = [r for r in exposed if r.get("vis") != "hidden"] sole = [r for r in readable if r["hostIconOnly"] and not r["hostLabel"] and not r["hostTitle"]] seensole = set(); sident = [] for r in sole: k = (r["label"], r["host"], r["hostText"], r["where"].split("/", 2)[-1]) if k in seensole: continue seensole.add(k); sident.append(r) name_leaks = [] for c in ctl_names: toks = set(re.findall(r"[a-z][a-z-]{2,}", c["axName"].lower())) if toks & gt: name_leaks.append((c["where"], c["tag"], c["axName"][:44], ",".join(sorted(toks & gt)))) json.dump(records, open(OUT + "/census-icons.json", "w"), ensure_ascii=False, indent=1) json.dump(ctl_names, open(OUT + "/census-controls.json", "w"), ensure_ascii=False, indent=1) print("图标读数 %d 条(%s × %s)" % (len(records), WIDTH, "/".join(THEMES))) print(" 字形名对 AT 可见:%d(包围盒口径)/ %d(AT 可读口径:排除 visibility:hidden 祖先)" % (len(exposed), len(readable))) print(" 其中「图标是宿主唯一语义」:%d 条 / %d 种" % (len(sole), len(sident))) print("\n── B 组:去掉图标就没名字(需要显式可读名称;按 AT 可读口径)") for r in sident: print(" %-15s host=%-34s text=%-18s %s" % (r["label"], r["host"][:34], (r["hostText"] or "-")[:18], r["where"][:52])) print("\n── A 组按字形聚合 top 22") for lab, n in Counter(r["label"] for r in exposed).most_common(22): print(" %-18s %d" % (lab, n)) print("\n── D 组:可读名称里混进字形 token 的控件(去重)") ded = {} for w, tag, nm, toks in name_leaks: ded.setdefault((tag, nm, toks), []).append(w) for (tag, nm, toks), ws in sorted(ded.items(), key=lambda kv: -len(kv[1])): print(" %-7s %-26s %-16s ×%-3d %s" % (tag, nm, toks, len(ws), ws[0][:46])) print(" 合计 %d 条读数 / %d 种" % (len(name_leaks), len(ded))) print("\nGLYPH 表 %d 项" % len(GLYPHS)) print("\n(只读普查:这条脚本恒返回 0。要当退出条件用的判据在 semanticcheck.GLYPH 与 classaudit 第 2 闸。)") if __name__ == "__main__": sys.exit(main() or 0)