1188 lines
72 KiB
Python
1188 lines
72 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""语义与行为体检(2026-11-08 · NEX 阶段 8.5 第 4 项批准:第 9 闸语义检查)。
|
||
|
||
为什么要它:第 9 闸(`classaudit` 的 BP)以及此前所有源码级检查,量的都是
|
||
**字符串**——`aria-label` 写没写、`tabIndex` 写没写。字符串能骗人:
|
||
· `aria-label=""`、`aria-label=" "`、指向一个不存在的 `aria-labelledby` id,源码看着都在;
|
||
· `aria-expanded="true"` 常年写在 JSX 上,运行时对应的抽屉根本没开;
|
||
· `role="button"` 给了 `div`,但没给 `tabIndex`,源码两条都齐,Tab 就是到不了;
|
||
· 焦点环被 `outline:none` 吃掉——源码里那行根本不在 TSX 里,在 CSS 里。
|
||
这里全部换成**浏览器里的真东西**:CDP 的 `Accessibility.getFullAXTree` 给辅助技术
|
||
实际读到的角色与名称,`getComputedStyle` 给算出来的焦点环,真按 Tab / Space / Escape
|
||
给键盘实际走到哪儿。
|
||
|
||
八条判据(退出码 = offender 条数,0 = 全绿):
|
||
|
||
NAME 交互元素必须有辅助技术读得到的名字。AX 树里 name 为空的节点**分两档**:
|
||
硬档(进退出码)= 整片上下文都拿不到名字。做法:把无名节点用 CDP
|
||
`DOM.resolveNode` + `Runtime.callFunctionOn` 打上 `data-nex-unnamed` 句柄,
|
||
再一次性回读它的 aria-label / title / placeholder / aria-labelledby(解析成真文字)/
|
||
所在 `<label>` 的文字(这三条算 own:AT 一定读得到),以及三类「写在页面上但
|
||
AT 读不到」的相邻标签:① 所在 `.ant-form-item` / `.nex-field` 的标签列文字;
|
||
② 所在表的列头与行首单元格;③ 往上四层内形状像标签的前兄弟(≤24 字、不是句子)。
|
||
三类全空才立案。软档(只打印清单与计数,默认不红)= 控件本身没名字,
|
||
但紧邻处有可见标签文字——读屏念得出那行字,用户靠相邻播报猜得出来,
|
||
属于「补一句 aria-label 就干净」的历史欠账。
|
||
两种例外直接算硬档,不吃相邻文字:勾选类(checkbox / radio / switch)——
|
||
旁边那句话根本不进它的辅助技术名称,读屏只念「复选框,未选中」,
|
||
一屏十颗时用户不知道勾的是哪一颗;以及连相邻文字都找不到的裸控件。
|
||
为什么不把软档也写进退出码:本项目当前有 20 颗/主题属于软档(时间线
|
||
轨道行的 NumberInput、概览与交付页的 Select),它们坐在成熟的业务代码里,
|
||
补 aria-label 属于 P2 批量整改。第一天就把这批欠账写进退出码,
|
||
这道闸第二天就会被以「全是噪音」为由关掉——闸要活下去,必须只咬真缺陷。
|
||
`NEX_NAMESTRICT=1` 把软档升成硬档(P2 整改收尾时翻默认用)。
|
||
HOTSPOT 鼠标能点(cursor:pointer)的东西必须键盘也能到:原生可交互标签、
|
||
或 role + tabindex≥0。豁免边界见 COLLECT 里的 SHELL——**容器与外壳不算 antd 内部结构**
|
||
(整棵树都在 .ant-app 里,按「祖上有 ant- 就豁免」量出来恒为 0)。
|
||
两类噪声就地滤掉:自己或内部已有可聚焦控件的(键盘走得到那颗控件)、
|
||
以及热区里再套 pointer 的(只报最外层)。
|
||
剩下的分两档:写了 role 没给 tabindex、或带 data-clickable 没键盘路径 = 硬档(我们的承诺);
|
||
antd 组件根 + 我们的皮肤类(筛选胶囊 span.ant-tag-checkable.nex-chip 那一族)= 软档,
|
||
打印计数与退出码分开,`NEX_HOTSPOTSTRICT=1` 升硬——理由同 NAME 软档那段
|
||
TAB 真按 Tab 走一遍:页面上每个可见的 role=button/link/switch/checkbox 必须被访问到。
|
||
认元素靠**走位前重打的句柄**,sig 多重集兜底:dataset 不是 React 托管的属性,
|
||
标记会被一次局部重渲染整族抹掉(详见 RETARGET 上面那段);走位覆盖不完整时
|
||
差额记进「覆盖说明」,不把「没轮到」说成「到不了」。
|
||
FOCUS Tab 落到的每个焦点必须**看得见**。不比字符串:走位前先给全站可聚焦元素拍一张
|
||
「没聚焦时长什么样」的快照,走到位再读一次,描边 / 外发光 / 边框 / 底色四项
|
||
在**自身、上面五层包裹层、旁边两个兄弟节点**上全都纹丝不动才算缺陷。
|
||
为什么要看到包裹层与兄弟:本项目的输入类控件按 theme/antd.ts 的既定决策
|
||
「只变边框、不发蓝光」,实测变化落在第 3~4 层(.ant-select-selector 的
|
||
#C3CCD6→#1677FF、.ant-input-affix-wrapper 同理);复选框更绝,焦点皮肤
|
||
outline:3px 画在 input 的兄弟 .ant-checkbox-inner 上,input 自己一点不动。
|
||
只看 activeElement 会把这三类成熟的键盘可达实现全部误判成缺陷,
|
||
反过来 CSS 里一句 outline:none 吃环,这条照样咬得住。
|
||
按完 Tab 必须停 260ms 再读:antd 控件带 0.2s 过渡,立刻读数读到的是过渡起点。
|
||
ARIA 声明与行为一致:aria-expanded 随抽屉开合真翻转、aria-current 唯一且对得上路径、
|
||
role=tab 只有一颗 aria-selected=true;aria-describedby / aria-labelledby /
|
||
aria-controls 指向的 id 不在时,**先悬停、再键盘展开、再点**复查目标是否真的会出现
|
||
(antd 的 Tooltip 描述与下拉面板都是懒挂载的,源码里查 id 一律查不到:
|
||
首页 9 条悬空引用里 5 条是悬停就出来的 Tooltip 描述,1 条要 Space 展开下拉
|
||
才挂出 rc_select_0_list——鼠标点它会被「已选项」那层壳挡住,只有键盘进得去),
|
||
唤出来还看不到才立案。两种情况只计数不立案:宿主是 antd 自己的内部结构
|
||
(收起态菜单项、Typography 省略号)且它本身有 title 或自己的文字可读——说明
|
||
没丢;以及被 aria-hidden / display:none 藏起来的宿主(Tabs 溢出用的「更多」
|
||
按钮),辅助技术根本读不到它。这些计数每页打印,免得变成第二个黑洞
|
||
LIVE 播报通道唯一:可见的 aria-live / role=status / role=alert 容器 ≤ 2,
|
||
且必须带 polite/assertive(不许 live="off" 假装有)
|
||
STATES 空 / 载入 / 错误三种表面必须说得出口:空表有文案、骨架屏有名字与 aria-busy、
|
||
错误块有可读文本
|
||
GLYPH 图标自带的英文字形码不许混进控件的可读名称(2026-11-08 · 阶段 8.5.1 · S-2):
|
||
antd 的图形是 `<span role=img aria-label=字形码>`,名字进了控件就是
|
||
VoiceOver 实测到的「upload 导入脚本」「down 导出」(取证
|
||
reports/ui_evidence/nex-p8f/07-screen-reader/voiceover-announcements-2026-11-08.txt
|
||
V7/V8/V11)。NAME 那条查不出这种缺陷——它的名称**非空**,只是空话。
|
||
判据在 DOM 上认「aria-label 等于自己的类名后缀 `anticon-<码>`」:人写的名字
|
||
不会长成这样,所以登记表将来换写法(现在是 decorative() 统一 aria-hidden)
|
||
也照样咬得住,不需要维护一份字形名单。三档:
|
||
· 宿主控件自己有 aria-label / 有效的 aria-labelledby → 名称被宿主接管,
|
||
字形码进不去 = **遮蔽**,只计数(不立案:AT 实际念的是那句人话);
|
||
· 宿主存在但名字要靠 contents 算(只有文字 / 只有 title / 什么都没有)→
|
||
字形码会拼进可读名称 = **立案**;
|
||
· 宿主之外(标签上的图标、提示条图标、状态点)→ 那是「这个图形是什么」的
|
||
独立语义位,本轮承诺只管操作名称,**只打印位置**,逐条列进覆盖说明。
|
||
另有一条独立的**交叉核对**(只打印,不立案):拿 CDP AX 树里辅助技术真读到的
|
||
名称去撞登记表解析出来的字形码集合。DOM 侧安静而 AX 侧有命中,说明名字来自
|
||
正文文本(实测:按钮文字里写着 `/api/meta`,撞中的是 `api`)或闸门看不见的
|
||
第三处——两种都要人看一眼,所以进覆盖说明。
|
||
|
||
用法:
|
||
NEX_BASE=http://127.0.0.1:5199 .venv/bin/python scripts/ui/semanticcheck.py
|
||
NEX_WIDTH=430 NEX_ROUTES="/,/projects/{id}/storyboard" … # 只跑改过的页
|
||
环境变量:NEX_WIDTH(默认 1440)、NEX_THEME(dark|light|both,默认 both)、
|
||
NEX_NAMESTRICT=1(NAME 软档升成硬档,默认只打印)、
|
||
NEX_TABS(Tab 最多按几下,默认 200,见 COLLECT 走位注释)、NEX_FOCUS_DWELL(每站停留毫秒,默认 260)、
|
||
NEX_ROUTES(逗号分隔,`{id}` 换成镜头最多的项目)。
|
||
"""
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
from collections import Counter
|
||
|
||
from playwright.sync_api import sync_playwright
|
||
|
||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
|
||
WIDTH = int(os.environ.get("NEX_WIDTH", "1440"))
|
||
HEIGHT = int(os.environ.get("NEX_HEIGHT", "1000"))
|
||
USER = os.environ.get("NEX_USER", "admin")
|
||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||
THEMES = {"both": ["dark", "light"], "dark": ["dark"], "light": ["light"]}[
|
||
os.environ.get("NEX_THEME", "both")]
|
||
TAB_MAX = int(os.environ.get("NEX_TABS", "200"))
|
||
# 每站停留:antd 控件的焦点样式带 0.2s 过渡,按完 Tab 立刻读数会读到过渡起点(看着没变)
|
||
FOCUS_DWELL = int(os.environ.get("NEX_FOCUS_DWELL", "260"))
|
||
ROUTES = [r for r in os.environ.get(
|
||
"NEX_ROUTES",
|
||
"/,/assets,/models,/projects/{id}/overview,/projects/{id}/library,"
|
||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||
"/projects/{id}/timeline,/projects/{id}/delivery,/403,/9e0f-not-a-page").split(",") if r]
|
||
|
||
# ── GLYPH 用:全站唯一图标登记表里解析出来的字形英文码(upload / down / appstore…)
|
||
# 两种导出形状都要认——阶段 8.5.1 之后一律走 decorative(),但这条闸的职责是
|
||
# 「写法换了也认得出字形码」,所以旧的 `export { A as IconB }` 照样解析。
|
||
# 注意它**只服务交叉核对**:立案判据看的是「aria-label == 类名后缀」,不依赖这张表。
|
||
REGISTRY = pathlib.Path(__file__).resolve().parents[2] / "frontend/src/components/icons/index.ts"
|
||
|
||
|
||
def glyph_tokens():
|
||
try:
|
||
src = REGISTRY.read_text(encoding="utf8")
|
||
except OSError:
|
||
return set()
|
||
glyphs = [g for g, _ in re.findall(r"export\s*\{\s*(\w+)\s+as\s+(Icon\w+)\s*\}", src)]
|
||
glyphs += [g for _, g in re.findall(r"export\s+const\s+(Icon\w+)\s*=\s*decorative\(\s*(\w+)\s*,", src)]
|
||
out = set()
|
||
for name in glyphs:
|
||
token = re.sub(r"(Outlined|Filled|TwoTone)$", "", name)
|
||
out.add(re.sub(r"(?<!^)(?=[A-Z])", "-", token).lower())
|
||
return out
|
||
|
||
|
||
GLYPH_TOKENS = glyph_tokens()
|
||
# DOM 侧的字形码豁免(键 = 宿主 sig):写不进退出码的真例外,空表也要打印命中数,
|
||
# 免得哪天变成没人敢删的僵尸条目。
|
||
GLYPH_ALLOW = {}
|
||
|
||
# 豁免:antd 自己的内部结构由组件库负责(它的 combobox 在里层 input 上、
|
||
# 焦点环由 token 给),我们只审自己写的标记。
|
||
ANT = "ant-"
|
||
|
||
# NAME 两档开关:软档默认只打印(详见文档字符串 NAME 那条的理由)。
|
||
NAME_STRICT = os.environ.get("NEX_NAMESTRICT") == "1"
|
||
# HOTSPOT 两档开关:同上,软档默认只打印(详见文档字符串 HOTSPOT 那条)。
|
||
HOTSPOT_STRICT = os.environ.get("NEX_HOTSPOTSTRICT") == "1"
|
||
# 这几类控件的相邻文字不算名字:见 §15.13。
|
||
LABEL_LESS = {"checkbox", "radio", "switch"}
|
||
|
||
# 无名节点的命名上下文回读。判据分「AT 一定读得到」(own) 与「人眼看得见但 AT 读不到」
|
||
# (near) 两组,绝不能混:混了就会把素材墙那种「旁边有素材名、名称却是空的」勾选框放过。
|
||
# 注意不采集「控件自己的当前值」当成标签——Select 里那句「自动」是值不是名字。
|
||
UNNAMED_CTX = r"""() => [...document.querySelectorAll('[data-nex-unnamed]')].map(el => {
|
||
const T = (n) => ((n && (n.innerText || n.textContent)) || '').replace(/\s+/g, ' ').trim();
|
||
const A = (k) => (el.getAttribute(k) || '').trim();
|
||
const role = (el.getAttribute('role') || el.tagName || '').toLowerCase();
|
||
const own = [];
|
||
['aria-label', 'title', 'placeholder'].forEach(k => { if (A(k)) own.push(k + '「' + A(k).slice(0, 44) + '」') });
|
||
const lb = A('aria-labelledby');
|
||
if (lb) {
|
||
const p = lb.split(/\s+/).map(i => T(document.getElementById(i))).filter(Boolean);
|
||
if (p.length) own.push('aria-labelledby「' + p.join(' ').slice(0, 44) + '」');
|
||
else own.push('aria-labelledby 指向不存在的 id');
|
||
}
|
||
const host = el.closest('label');
|
||
if (host && T(host)) own.push('label 内文字「' + T(host).slice(0, 44) + '」');
|
||
const near = [];
|
||
const push = (k, v) => {
|
||
v = (v || '').trim();
|
||
if (v && v !== A('value') && !near.some(x => x.v === v)) near.push({ k, v: v.slice(0, 44) });
|
||
};
|
||
/* (a) 真正的标签元素:antd Form.Item 把标签渲染成 .ant-form-item-label,
|
||
但 **外层没有 <Form> 时 antd 不给控件生成 id、label 的 for 是空的**
|
||
(实测:时间线轨道行 14 颗 NumberInput、概览 2 颗、交付 3 颗、审核 1 颗,
|
||
AX 名称全空,而屏幕上标签就贴在控件左边)。这类是「名字写了、关联没接上」,
|
||
补一句 aria-label 或给字段一个 id 就干净 → 软档。 */
|
||
const fi = el.closest('.ant-form-item,.nex-field');
|
||
if (fi) {
|
||
const lab = fi.querySelector('.ant-form-item-label label,label,legend,caption');
|
||
if (lab && T(lab) && lab !== host) push('表单标签(未关联)', T(lab));
|
||
}
|
||
/* (b) 表格里:列头与行首单元格是这一格的天然名字 */
|
||
const cell = el.closest('td,th');
|
||
if (cell) {
|
||
const row = cell.closest('tr'), tb = cell.closest('table');
|
||
if (row && tb && tb.rows.length) {
|
||
const head = tb.rows[0] && [...tb.rows[0].cells][[...row.cells].indexOf(cell)];
|
||
push('所在列表头', T(head));
|
||
}
|
||
}
|
||
const row = el.closest('tr');
|
||
if (row && row.cells && row.cells.length) push('行首单元格', T(row.cells[0]));
|
||
const fs = el.closest('fieldset');
|
||
if (fs && T(fs.querySelector('legend'))) push('fieldset legend', T(fs.querySelector('legend')));
|
||
/* (c) 往上四层里「形状像标签」的前兄弟:短(≤24 字)、不是段落。
|
||
为什么要往上走:antd 的控件被 .ant-input-number / .ant-select-selector 包了三四层,
|
||
标签在同级的外面那层(实测 .ant-form-item-control 的前一个兄弟),
|
||
只看 closest 匹配到的第一个容器(那是 .ant-input-number 自己)会什么都找不到。 */
|
||
for (let n = el, lvl = 0; n && n !== document.body && lvl < 5; n = n.parentElement, lvl++) {
|
||
let p = n.previousElementSibling;
|
||
for (let i = 0; p && i < 2; i++, p = p.previousElementSibling) {
|
||
const t = T(p);
|
||
if (t && t.length <= 24 && !/。|[,,]$/.test(t))
|
||
push(lvl + ' 层外前一个短标签', t);
|
||
}
|
||
}
|
||
return { n: +el.getAttribute('data-nex-unnamed'), role,
|
||
sig: el.tagName.toLowerCase()
|
||
+ (typeof el.className === 'string' && el.className.trim()
|
||
? '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.') : ''),
|
||
own, near };
|
||
})"""
|
||
|
||
# ── 页内一次采齐:候选交互元素、热区、aria 引用、live 区、状态表面 ──────────────
|
||
# 采集用的几把尺子(COLLECT 与 RETARGET 共用,别再抄第二份):走位前重打标记必须用
|
||
# **同一把尺子**,否则两次采集口径不同,「走不到」到底是页面缺陷还是口径漂移就分不清了。
|
||
PRIMITIVES = r"""
|
||
const VIS = (el) => {
|
||
const r = el.getBoundingClientRect();
|
||
if (r.width < 2 || r.height < 2) return false;
|
||
const cs = getComputedStyle(el);
|
||
return cs.visibility !== 'hidden' && cs.display !== 'none' && +cs.opacity > 0.02;
|
||
};
|
||
const cls = (el) => (typeof el.className === 'string' ? el.className : '');
|
||
/* 「antd 自己的内部结构」的边界,第 8.5 轮第二次实测重定(前一版是空转的,别改回去):
|
||
整棵树被 .ant-app 包住、页面内容坐在 .ant-card-body / .ant-tabs-tabpane / .ant-row 里,
|
||
「祖先链上出现 ant- 就豁免」等于**整页豁免**——12 条路由 × 3 视口实测 HOTSPOT/TAB 恒为 0,
|
||
是 gateprobe 的夹具(div[role=button] 无 tabindex)抓出来的:夹具种在 body 下都能被看见,
|
||
真页面上 46 颗点得着的筛选胶囊却一个都不报。
|
||
现在的口径:① 元素自己带 ant- 且不带 nex- → antd 的标记,豁免;
|
||
② 祖先是 antd 的**控件**(.ant-btn / .ant-select / .ant-tag 这种有行为的组件)→ 它家的内部结构,豁免;
|
||
③ 祖先是**容器与外壳**(下面的 SHELL)→ 那只是我们内容住的房间,继续往上找,不豁免。
|
||
带 nex- 的一律算我们的(kit 用 antd 组件渲染的表面,行为归我们)。 */
|
||
const SHELL = /^(ant-(layout|app|css-var|card|tabs|tab|list|row|col|space|flex|form|table|spin|empty|result|segmented|drawer|modal|popover|popconfirm|tooltip|dropdown|menu|grid|badge|divider|anchor|breadcrumb|steps|descriptions|collapse|collapse-panel|float-btn))/;
|
||
/* 元素自己就是 antd 的标记 -> 它家的东西,行为归它(SHELL 只用来判断**祖先**是房间还是控件)。
|
||
为什么单独拆出来:合成一个循环时,自己的类名一旦落进 SHELL 名单
|
||
(ant-tabs-tab-btn 既是 antd 的控件又匹配 tabs 外壳),就被「那是房间,继续往上找」抢先,
|
||
rc-tabs 的页签反而被判成我们写的标记 —— 实测每主题 3 条 TAB 假阳性。
|
||
antd v5 的图标根节点是 class="anticon anticon-appstore",**不含 ant- 子串**,
|
||
只认 ant- 会把图标判成我们的自绘标记 —— 实测每主题 5 条 HOTSPOT 假阳性。 */
|
||
const selfAnt = (el) => {
|
||
const toks = cls(el).split(/\s+/).filter(Boolean);
|
||
return !toks.some((x) => x.startsWith('nex-'))
|
||
&& toks.some((x) => /^(ant-|anticon)/.test(x));
|
||
};
|
||
const inAnt = (el) => {
|
||
if (selfAnt(el)) return true;
|
||
for (let n = el.parentElement; n && n !== document.body; n = n.parentElement) {
|
||
const c = cls(n);
|
||
if (!c.includes('ant-') || c.includes('nex-')) continue;
|
||
if (c.split(/\s+/).some((x) => SHELL.test(x))) continue;
|
||
return true;
|
||
}
|
||
return false;
|
||
};
|
||
const sig = (el) => {
|
||
const c = cls(el).split(/\s+/).filter(x => x && !/^(css-|ant-)/.test(x)).slice(0, 2).join('.');
|
||
const key = el.getAttribute('aria-label') || el.getAttribute('title') ||
|
||
(el.id ? '#' + el.id : '');
|
||
return el.tagName.toLowerCase() + (c ? '.' + c : '') + (key ? `[${key.slice(0, 24)}]` : '');
|
||
};
|
||
const NATIVE = 'a[href],button,input,select,textarea,summary,iframe,audio,video';
|
||
/* 交互 role:HOTSPOT 的承诺是「鼠标点得着的东西键盘也到得了」,这句话只对**交互角色**成立。
|
||
role=img / group / status / presentation 只是语义标注,通常坐在别人的按钮里
|
||
(antd 图标就是这个形状),要求它们自己有 Tab 序列是判据越界。 */
|
||
const INT = new Set(['button','link','tab','switch','checkbox','radio','menuitem','menuitemcheckbox',
|
||
'menuitemradio','option','listbox','combobox','searchbox','slider','spinbutton',
|
||
'textbox','treeitem','row','cell','gridcell','columnheader','separator']);
|
||
const ROLE = '[role="button"],[role="link"],[role="tab"],[role="switch"],[role="checkbox"],'
|
||
+ '[role="radio"],[role="menuitem"],[role="option"],[role="combobox"],'
|
||
+ '[role="searchbox"],[role="slider"],[role="spinbutton"],[role="textbox"]';
|
||
/* Tab 目标:可见的自定义角色元素,必须在 Tab 序列里出现。
|
||
认元素靠句柄不靠 sig:sig 会撞名(两个没留类名的按钮都叫 "button"),
|
||
撞了就等于「别的按钮被走到了」→ 该报的走不到没报。
|
||
**COLLECT 与 RETARGET 共用这一个打靶函数**:两处 filter 手抄一遍,
|
||
漂一次就是一族假阳性(本轮 46 条的教训),所以宁可放进公共尺子里。 */
|
||
const pickTargets = () => {
|
||
let tid = 0;
|
||
return [...document.querySelectorAll(ROLE)]
|
||
.filter(el => VIS(el) && !inAnt(el) && el.getAttribute('aria-hidden') !== 'true')
|
||
.map(el => { el.dataset.nexTarget = 't' + (++tid);
|
||
return { sig: sig(el), h: el.dataset.nexTarget }; });
|
||
};
|
||
"""
|
||
|
||
# 走位前重新打靶 + 重新量现场(第 8.5 轮第三类「标记生命周期假设不成立」事故)。
|
||
# dataset **不是 React 托管的属性**:COLLECT 打上的 data-nex-target 会被任何一次局部重渲染
|
||
# 整族抹掉。实测 /assets@430 —— COLLECT 采到 19 颗,照闸的顺序走完 resolve_ref 的悬停/点击,
|
||
# 再 querySelectorAll('[data-nex-target]') 已经是 **0 颗**,19 个句柄全部 gone;
|
||
# 走位端 pop 不到 → 素材墙整族误报「Tab 序列里找不到」,两档视口 46 条假阳性。
|
||
# 正解不是在页面里塞属性,而是:① 净场之后、走位之前按同一把尺子重打一次;
|
||
# ② 可聚焦元素数也在走位前现量——前面那几步点过页签,面板早换了
|
||
# (实测 /library@430:进页面 50 颗,点过页签后现场只剩 26 颗,
|
||
# 闸拿旧账 50 算出「32/50 覆盖不足」;干净加载同一页实测走满 62/63 站);
|
||
# ③ 走位之后再用 sig 多重集复核(认不出句柄 ≠ 走不到)。
|
||
RETARGET = r"""(FOC) => {
|
||
/*__PRIMITIVES__*/
|
||
return { targets: pickTargets(),
|
||
visFocusables: [...document.querySelectorAll(FOC)].filter(VIS).length };
|
||
}""".replace("/*__PRIMITIVES__*/", PRIMITIVES)
|
||
|
||
COLLECT = r"""() => {
|
||
/*__PRIMITIVES__*/
|
||
|
||
/* 1 热区:鼠标可点、键盘到不了,而且是**我们自己**写的标记 */
|
||
const hotspots = [];
|
||
/* 采集必须可重入:下面的「只报最外层」靠 data-nex-hotspot 做记号,
|
||
而 `gateprobe` 会把这一段**按判据逐条 evaluate 三遍**(HOTSPOT / HOTSPOT-hard / TABTARGET)。
|
||
不清章的话第二遍每个热区都被「上一层已经报过」吃掉,硬档清单恒为空 ——
|
||
实测反向验证 pb-sema / pb-semb 两条「必须点名」的夹具第二轮就查无此人。 */
|
||
document.querySelectorAll('[data-nex-hotspot]').forEach(n => n.removeAttribute('data-nex-hotspot'));
|
||
for (const el of document.querySelectorAll('body *')) {
|
||
if (!VIS(el) || inAnt(el)) continue;
|
||
if (getComputedStyle(el).cursor !== 'pointer') continue;
|
||
if (el.closest(NATIVE)) continue; // 原生控件本体或它的内部
|
||
if (el.matches(NATIVE)) continue;
|
||
const role = el.getAttribute('role');
|
||
const ti = el.hasAttribute('tabindex') ? +el.getAttribute('tabindex') : null;
|
||
if (role && ti !== null && ti >= 0) continue; // 补过 tabindex 的自定义控件
|
||
if (!role && ti !== null && ti >= 0) continue;
|
||
if (!el.onclick && !el.getAttribute('onclick') && !el.closest('[data-clickable]')) {
|
||
// 没有直接监听器的 pointer(纯样式)只在它自己带 role 时才要求语义
|
||
if (!role) continue;
|
||
}
|
||
// 噪声①:自己或内部就有可聚焦控件(button / a[href] / input / tabindex)——
|
||
// 键盘走得到那颗控件就走得到这件事,卡片底行「三颗按钮 + 一块空白也能点」不该立案。
|
||
if (el.matches(NATIVE + ', [tabindex]') ||
|
||
el.querySelector(NATIVE + ', [tabindex]:not([tabindex="-1"])')) {
|
||
// 盖一章再放行:这一族「整行可点 + 行里有按钮」的东西(交付页的成本行、
|
||
// 分镜表的可点行)本身被内部那颗按钮救回来了,它**里面**那颗 caret 图标
|
||
// 不该再单独立案——否则一条行报两次,硬档立刻被噪声灌满。
|
||
el.dataset.nexHotspot = 'covered';
|
||
continue;
|
||
}
|
||
// 噪声②:只报最外层。热区里再套 pointer(可点行里的那颗 caret 图标)算一处,不算两处。
|
||
if (el.closest('[data-nex-hotspot]')) continue;
|
||
el.dataset.nexHotspot = '1';
|
||
// 分档(与 NAME 两档同一套理由):
|
||
// hard = 我们**自己承诺过**键盘可达的东西——写了 role 却没给 tabindex(ARIA 契约当场违反),
|
||
// 或带 data-clickable(阶段 2 定的热区约定)却没键盘路径。这类必须红。
|
||
// soft = antd 组件根 + 我们的皮肤类(`span.ant-tag-checkable.nex-chip` 那种筛选胶囊),
|
||
// 是真欠账但属于 P2 批量整改,写进退出码会让闸当天就被以「全是噪音」为由关掉。
|
||
// `NEX_HOTSPOTSTRICT=1` 升硬(P2 收尾时翻默认)。
|
||
hotspots.push({ sig: sig(el), role: role || '', ti: ti === null ? '—' : String(ti),
|
||
dc: el.closest('[data-clickable]') ? '1' : '',
|
||
hard: (INT.has((role || '').toLowerCase()) || el.closest('[data-clickable]')) ? '1' : '',
|
||
path: (el.closest('[class]') ? cls(el.closest('[class]')).split(/\s+/)[0] : '') });
|
||
}
|
||
|
||
/* 2 Tab 目标(尺子在 PRIMITIVES 里,两处共用) */
|
||
const tabTargets = pickTargets();
|
||
|
||
/* 3 aria 引用完整性 + live 区 + 状态表面 */
|
||
const ids = new Set([...document.querySelectorAll('[id]')].map(n => n.id));
|
||
/* 悬空引用不直接立案:antd 的描述/面板节点是**懒挂载**的(Tooltip 没悬停、
|
||
Select 没展开时那棵树根本不在 DOM 里)。这里只登记句柄,交给外面用真鼠标、
|
||
真键盘把它唤出来再复查——唤得出来 = 引用有效,唤不出来才算缺陷。 */
|
||
const broken = [];
|
||
let handle = 0;
|
||
const hidden = (el) => el.closest('[aria-hidden="true"]') !== null;
|
||
for (const el of [...document.querySelectorAll('[aria-labelledby],[aria-describedby],[aria-controls]')]) {
|
||
// 藏起来的宿主读不到,引用再悬空也不影响辅助技术(Tabs 的溢出「更多」按钮就是这种)
|
||
if (!VIS(el) || hidden(el)) continue;
|
||
for (const attr of ['aria-labelledby', 'aria-describedby', 'aria-controls']) {
|
||
const v = el.getAttribute(attr);
|
||
if (!v) continue;
|
||
for (const id of v.split(/\s+/).filter(Boolean)) {
|
||
if (ids.has(id)) continue;
|
||
if (!el.dataset.nexSem) el.dataset.nexSem = String(++handle);
|
||
broken.push({ sig: sig(el), attr, id, h: el.dataset.nexSem,
|
||
ant: cls(el).includes('ant-') && !cls(el).includes('nex-'),
|
||
t: el.hasAttribute('title') ||
|
||
((el.innerText || el.textContent || '').trim() !== '') });
|
||
}
|
||
}
|
||
}
|
||
const live = [];
|
||
for (const el of document.querySelectorAll('[aria-live],[role="status"],[role="alert"],[role="log"]')) {
|
||
if (!VIS(el) && el.children.length === 0) continue;
|
||
const pol = el.getAttribute('aria-live')
|
||
|| (el.getAttribute('role') === 'alert' ? 'assertive' : 'polite');
|
||
live.push({ sig: sig(el), pol: pol || '(缺省=off)', vis: VIS(el) });
|
||
}
|
||
const empties = [...document.querySelectorAll('.ant-table-placeholder')]
|
||
.filter(VIS).map(el => (el.innerText || '').trim().slice(0, 40));
|
||
const skeletons = [...document.querySelectorAll('[class*="skeleton" i],[aria-busy]')]
|
||
.filter(VIS).map(el => ({ sig: sig(el),
|
||
name: el.getAttribute('aria-label') || el.getAttribute('title') || '',
|
||
busy: el.getAttribute('aria-busy') || '', role: el.getAttribute('role') || '' }));
|
||
const errors = [...document.querySelectorAll('[class*="nex-notice"],[class*="error" i]')]
|
||
.filter(el => VIS(el) && (el.innerText || '').trim()).length;
|
||
|
||
/* 5 图标字形码是否混进可读名称(S-2):认「aria-label == 自己的类名后缀」
|
||
—— 人写的名字不会长成 `anticon-upload` 的尾巴,所以不需要维护字形名单。 */
|
||
const ownName = (el) => {
|
||
if ((el.getAttribute('aria-label') || '').trim()) return 'aria-label';
|
||
const lb = el.getAttribute('aria-labelledby') || '';
|
||
if (lb.split(/\s+/).some((id) => {
|
||
const n = document.getElementById(id);
|
||
return n && (n.innerText || n.textContent || '').trim();
|
||
})) return 'aria-labelledby';
|
||
return '';
|
||
};
|
||
const glyphs = [];
|
||
for (const el of document.querySelectorAll('.anticon[aria-label]')) {
|
||
if (!VIS(el) || el.getAttribute('aria-hidden') === 'true') continue;
|
||
let hid = false;
|
||
for (let a = el.parentElement; a; a = a.parentElement) {
|
||
if (a.getAttribute && a.getAttribute('aria-hidden') === 'true') { hid = true; break; }
|
||
}
|
||
if (hid) continue; // 整块被藏起来,AT 读不到,不占名额
|
||
const lab = (el.getAttribute('aria-label') || '').trim();
|
||
const tok = (cls(el).split(/\s+/).find((x) => x.startsWith('anticon-')) || '')
|
||
.slice('anticon-'.length);
|
||
if (!tok || tok !== lab) continue; // 显式给过语义名(「清空搜索」)→ 不是字形码外泄
|
||
const host = el.parentElement
|
||
? el.parentElement.closest(ROLE + ',' + NATIVE + ',[tabindex]') : null;
|
||
glyphs.push({ tok, sig: sig(el), own: host ? ownName(host) : '',
|
||
host: host ? sig(host) : '', ant: host ? selfAnt(host) : false,
|
||
txt: host ? (host.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 28) : '' });
|
||
}
|
||
|
||
/* 4 页签与选中态 */
|
||
let xid = 0;
|
||
const tabs = [...document.querySelectorAll('[role="tab"]')].filter(VIS).map(el => {
|
||
el.dataset.nexTab = 'p' + (++xid);
|
||
return { sel: el.getAttribute('aria-selected') || '', ctrl: el.getAttribute('aria-controls') || '',
|
||
dis: el.getAttribute('aria-disabled') === 'true',
|
||
txt: (el.innerText || '').trim().slice(0, 40),
|
||
h: el.dataset.nexTab, sig: sig(el) };
|
||
});
|
||
const current = [...document.querySelectorAll('[aria-current="true"]')].filter(VIS)
|
||
.map(el => ({ href: el.getAttribute('href') || el.closest('a')?.getAttribute('href') || '', sig: sig(el) }));
|
||
|
||
return {
|
||
path: location.pathname,
|
||
hasLandmark: !!document.querySelector('main,[role="main"]'),
|
||
hotspots, tabTargets, broken, live, empties, skeletons, errors, tabs, current, glyphs,
|
||
docScrollW: document.documentElement.scrollWidth,
|
||
focusables: document.querySelectorAll(
|
||
'a[href],button:not([disabled]),input:not([type=hidden]),select,textarea,[tabindex]:not([tabindex="-1"])').length,
|
||
visFocusables: [...document.querySelectorAll(
|
||
'a[href],button:not([disabled]),input:not([type=hidden]),select,textarea,[tabindex]:not([tabindex="-1"])')].filter(VIS).length,
|
||
openLayers: document.querySelectorAll(
|
||
'.ant-drawer-open,.ant-modal-wrap:not([style*="display: none"]),'
|
||
+ '.ant-select-dropdown:not(.ant-select-dropdown-hidden),'
|
||
+ '.ant-popover:not(.ant-popover-hidden),.ant-dropdown:not(.ant-dropdown-hidden)').length
|
||
};
|
||
}""".replace("/*__PRIMITIVES__*/", PRIMITIVES)
|
||
|
||
# 一个元素的「长相」:描边 + 外发光 + 边框 + 底色,连它上面三层一起取。
|
||
# 为什么连祖先:antd 输入框的焦点变化落在 .ant-input-affix-wrapper 上(里层 <input>
|
||
# 自己的 border-width 是 0),本项目又明确关掉了输入类控件的外发光
|
||
# (theme/antd.ts:焦点 = 边框变主色,不发蓝光)。只盯 activeElement
|
||
# 会把这套既定设计误判成「焦点不可见」。
|
||
# 走位前先给每个可聚焦元素拍一张「没被聚焦时长什么样」的快照:
|
||
# 焦点可见性的正解是「聚焦前后有没有肉眼看得出的变化」,而要量前后就得把焦点挪开——
|
||
# 挪焦点会打断 Tab 走位(实测站数从 8 掉到 3)。先拍快照,走位时只比对,焦点一路向前。
|
||
FOCUSABLES = ('a[href],button:not([disabled]),input:not([type=hidden]),select,'
|
||
'textarea,[tabindex]:not([tabindex="-1"])')
|
||
BASELINE = r"""(SEL) => {
|
||
// 一把尺子:走位前后的两次读数必须同源,否则「变没变」比的是两把尺子的差
|
||
window.__nexLook = (el) => {
|
||
const row = (n, rel) => {
|
||
const cs = getComputedStyle(n);
|
||
return rel + '|' + [cs.outlineStyle, cs.outlineWidth, cs.outlineColor, cs.boxShadow,
|
||
cs.borderTopColor, cs.borderTopWidth, cs.borderBottomColor,
|
||
cs.backgroundColor].join('|');
|
||
};
|
||
const rows = [];
|
||
for (let n = el, d = 0; n && d < 5; n = n.parentElement, d++) rows.push(row(n, 'd' + d));
|
||
// 还要看**兄弟**:antd 把复选框 / 开关的焦点皮肤画在 input 旁边的壳上,
|
||
// 实测 input[选择镜头 1] 聚焦时 .ant-checkbox-inner 是 outline: 3px solid,
|
||
// 而 input 自己四条样式纹丝不动——只往上看会把键盘可达的东西判成看不见。
|
||
for (let n = el.nextElementSibling, i = 0; n && i < 2; n = n.nextElementSibling, i++) {
|
||
rows.push(row(n, 's' + i));
|
||
if (n.firstElementChild) rows.push(row(n.firstElementChild, 's' + i + 'c'));
|
||
}
|
||
return rows;
|
||
};
|
||
const look = window.__nexLook;
|
||
const map = {};
|
||
let i = 0;
|
||
for (const el of document.querySelectorAll(SEL)) {
|
||
el.dataset.nexLook = String(++i);
|
||
map[el.dataset.nexLook] = look(el);
|
||
}
|
||
return map;
|
||
}"""
|
||
|
||
# 焦点可见性:Tab 走位时逐个读计算样式
|
||
FOCUS_PROBE = r"""() => {
|
||
const el = document.activeElement;
|
||
if (!el || el === document.body) return null;
|
||
const cs = getComputedStyle(el);
|
||
const ow = parseFloat(cs.outlineWidth) || 0;
|
||
const ring = cs.outlineStyle !== 'none' && ow > 0;
|
||
const shadow = cs.boxShadow && cs.boxShadow !== 'none';
|
||
if (!el.dataset.nexLook)
|
||
el.dataset.nexLook = 'f' + (window.__nexFocSeq = (window.__nexFocSeq || 0) + 1);
|
||
const rows = window.__nexLook ? window.__nexLook(el) : [];
|
||
const cls = (typeof el.className === 'string' ? el.className : '');
|
||
const c = cls.split(/\s+/).filter(x => x && !/^(css-|ant-)/.test(x)).slice(0, 2).join('.');
|
||
return { lk: el.dataset.nexLook, th: el.dataset.nexTarget || '',
|
||
sig: el.tagName.toLowerCase() + (c ? '.' + c : '')
|
||
+ (el.getAttribute('aria-label') || el.getAttribute('title') ? '[' + (el.getAttribute('aria-label') || el.getAttribute('title')).slice(0, 24) + ']' : ''),
|
||
ring, shadow, ow, os: cs.outlineStyle, look: rows,
|
||
antd: cls.includes('ant-'), fv: el.matches(':focus-visible') };
|
||
}"""
|
||
|
||
# 走位净场用:当前有几层浮层可能带着焦点陷阱(抽屉 / 模态 / 下拉 / 浮层 / 菜单)。
|
||
LAYERS_JS = """() => document.querySelectorAll(
|
||
'.ant-drawer-open,.ant-modal-wrap:not([style*="display: none"]),'
|
||
+ '.ant-select-dropdown:not(.ant-select-dropdown-hidden),'
|
||
+ '.ant-popover:not(.ant-popover-hidden),.ant-dropdown:not(.ant-dropdown-hidden)').length"""
|
||
|
||
PROJECT_JS = r"""async () => {
|
||
const t = localStorage.getItem('nex-auth');
|
||
const tok = t ? (JSON.parse(t)?.state?.token || JSON.parse(t)?.token) : '';
|
||
const h = {headers: {Authorization: 'Bearer ' + tok}};
|
||
const j = await (await fetch('/api/projects', h)).json();
|
||
const list = j.projects || j.items || j.data || (Array.isArray(j) ? j : []);
|
||
let best = ''; let n = -1;
|
||
for (const p of list) {
|
||
const s = await (await fetch(`/api/projects/${p.id}/shots`, h)).json();
|
||
const c = s.count ?? (s.shots || []).length;
|
||
if (c > n) { n = c; best = p.id; }
|
||
}
|
||
return best || list[0]?.id || '';
|
||
}"""
|
||
|
||
|
||
def login(page) -> None:
|
||
page.goto(BASE + "/login", wait_until="networkidle")
|
||
if page.locator("#login-user").count():
|
||
page.fill("#login-user", USER)
|
||
page.fill("#login-pass", PWD)
|
||
page.click("button[type=submit]")
|
||
page.wait_for_timeout(1500)
|
||
|
||
|
||
def ax_names(cdp):
|
||
"""CDP → 辅助技术实际读到的 (role, name, ignored, backendDOMNodeId)。"""
|
||
try:
|
||
tree = cdp.send("Accessibility.getFullAXTree")["nodes"]
|
||
except Exception:
|
||
return None
|
||
INTERACTIVE = {"button", "link", "textbox", "combobox", "searchbox", "listbox", "menuitem",
|
||
"menuitemcheckbox", "menuitemradio", "option", "radio", "checkbox", "switch",
|
||
"tab", "slider", "spinbutton", " DisclosureTriangle".strip()}
|
||
out = []
|
||
for n in tree:
|
||
if n.get("ignored"):
|
||
continue
|
||
role = (n.get("role") or {}).get("value") or ""
|
||
if role not in INTERACTIVE:
|
||
continue
|
||
name = ((n.get("name") or {}).get("value") or "").strip()
|
||
out.append({"role": role, "name": name,
|
||
"bid": n.get("backendDOMNodeId"),
|
||
"focusable": bool((n.get("properties") or []))})
|
||
return out
|
||
|
||
|
||
def describe(cdp, bid):
|
||
try:
|
||
n = cdp.send("DOM.describeNode", {"backendNodeId": bid}).get("node", {})
|
||
attrs = n.get("attributes") or []
|
||
kv = dict(zip(attrs[0::2], attrs[1::2]))
|
||
cls = (kv.get("class") or "").split()
|
||
nc = [c for c in cls if not c.startswith(("css-", "ant-"))][:2]
|
||
keep = ("." + ".".join(nc)) if nc else ""
|
||
return (n.get("nodeName", "?").lower() + keep
|
||
+ ("[%s]" % kv.get("title", kv.get("aria-label", ""))[:26]
|
||
if (kv.get("title") or kv.get("aria-label")) else ""))
|
||
except Exception:
|
||
return "backendNodeId=%s" % bid
|
||
|
||
|
||
def unnamed_context(cdp, page, bids):
|
||
"""把 AX 树里没名字的节点(backendDOMNodeId)标上句柄,再一次性读回命名上下文。
|
||
|
||
为什么要绕这一圈:`Accessibility.getFullAXTree` 给的是 backendNodeId,
|
||
`page.evaluate` 只认 DOM;而逐个 `evaluate` 又要为每个节点付一次往返。
|
||
"""
|
||
for i, bid in enumerate(bids, 1):
|
||
try:
|
||
obj = cdp.send("DOM.resolveNode", {"backendNodeId": bid})["object"]
|
||
cdp.send("Runtime.callFunctionOn", {
|
||
"objectId": obj["objectId"],
|
||
"functionDeclaration": "function(h){ this.setAttribute('data-nex-unnamed', h) }",
|
||
"arguments": [{"value": str(i)}]})
|
||
except Exception:
|
||
pass # 节点已卸载 / 不在文档里:交给下面的兜底
|
||
try:
|
||
rows = {r["n"]: r for r in page.evaluate(UNNAMED_CTX)}
|
||
except Exception:
|
||
rows = {}
|
||
page.evaluate("() => document.querySelectorAll('[data-nex-unnamed]')"
|
||
".forEach(n => n.removeAttribute('data-nex-unnamed'))")
|
||
return {bid: rows[i] for i, bid in enumerate(bids, 1) if i in rows}
|
||
|
||
|
||
def name_tier(role, ctx):
|
||
"""返回 (档位, 证据)。ok = AT 其实读得到名字,不算缺陷。"""
|
||
if ctx is None:
|
||
return "soft", "命名上下文读不到(节点已卸载或刚重渲染)"
|
||
if ctx["own"]:
|
||
return "ok", ";".join(ctx["own"])
|
||
if role in LABEL_LESS:
|
||
return "hard", "勾选类控件:旁边的文字不进辅助技术名称,读屏只念「复选框,未选中」"
|
||
if ctx["near"]:
|
||
return "soft", "相邻可见标签 " + " / ".join(
|
||
"%s「%s」" % (s["k"], s["v"]) for s in ctx["near"][:2])
|
||
return "hard", "整片上下文里找不到任何可读文字(无 aria-label/title/placeholder/" \
|
||
"label 文字/同行标签/列表头/行首单元格)"
|
||
|
||
|
||
def ref_kind(page, handle):
|
||
"""这个悬空引用的宿主是什么控件:能唤出浮层的才值得动它,链接一律不点。"""
|
||
return page.evaluate("""(h) => {
|
||
const el = document.querySelector(`[data-nex-sem="${h}"]`);
|
||
if (!el) return 'gone';
|
||
const role = (el.getAttribute('role') || el.tagName.toLowerCase()).toLowerCase();
|
||
if (el.tagName.toLowerCase() === 'a' || role === 'link') return 'link';
|
||
if (role === 'combobox' || role === 'listbox' || role === 'searchbox'
|
||
|| role === 'textbox') return 'combo';
|
||
if (role === 'button' || role === 'tab' || el.hasAttribute('aria-expanded')
|
||
|| el.tagName.toLowerCase() === 'button') return 'expandable';
|
||
return 'plain';
|
||
}""", handle)
|
||
|
||
|
||
def ref_present(page, ref_id, attr):
|
||
"""目标节点现在在不在;描述类还要求它真的说得出话。"""
|
||
return page.evaluate("""(a) => {
|
||
const t = document.getElementById(a.id);
|
||
if (!t) return false;
|
||
if (a.attr === 'aria-controls') return t.getBoundingClientRect().height > 1;
|
||
return ((t.innerText || t.textContent) || '').trim() !== '';
|
||
}""", {"id": ref_id, "attr": attr})
|
||
|
||
|
||
def resolve_ref(page, item):
|
||
"""用真鼠标 / 真键盘把引用唤出来复查(antd 的描述与面板是懒挂载的)。
|
||
|
||
返回 'ok'(唤出来了,引用有效)/'dead'(唤不出来)/'gone'(元素已卸载)。
|
||
"""
|
||
sel = '[data-nex-sem="%s"]' % item["h"]
|
||
if not page.locator(sel).count():
|
||
return "gone"
|
||
loc = page.locator(sel).first
|
||
kind = ref_kind(page, item["h"])
|
||
if kind == "gone":
|
||
return "gone"
|
||
try:
|
||
loc.scroll_into_view_if_needed(timeout=2000)
|
||
loc.hover(timeout=2000)
|
||
except Exception:
|
||
pass # 悬不动的(被遮挡、触屏档隐藏)交给下一步
|
||
page.wait_for_timeout(450)
|
||
if ref_present(page, item["id"], item["attr"]):
|
||
page.mouse.move(2, 2)
|
||
page.wait_for_timeout(150)
|
||
return "ok"
|
||
if kind == "combo":
|
||
# 下拉的输入框常被「已选项」那层壳挡住鼠标(实测 pointer events 被
|
||
# .ant-select-selection-item 截走),走键盘:聚焦 → Space 展开 → Esc 收起。
|
||
try:
|
||
loc.evaluate("e => e.focus()")
|
||
page.keyboard.press("Space")
|
||
except Exception:
|
||
pass
|
||
page.wait_for_timeout(700)
|
||
hit = ref_present(page, item["id"], item["attr"])
|
||
page.keyboard.press("Escape")
|
||
page.wait_for_timeout(250)
|
||
if hit:
|
||
return "ok"
|
||
elif kind == "expandable":
|
||
try:
|
||
loc.click(timeout=2000)
|
||
page.wait_for_timeout(650)
|
||
hit = ref_present(page, item["id"], item["attr"])
|
||
page.keyboard.press("Escape")
|
||
page.wait_for_timeout(250)
|
||
if hit:
|
||
return "ok"
|
||
except Exception:
|
||
pass
|
||
page.mouse.move(2, 2)
|
||
return "dead"
|
||
|
||
|
||
TAB_STATE_JS = """(a) => {
|
||
const el = document.querySelector(`[data-nex-tab="${a.h}"]`);
|
||
if (!el) return null;
|
||
const r = el.getBoundingClientRect();
|
||
const wrap = el.closest('.ant-tabs-nav-wrap') || el.closest('.ant-tabs-nav');
|
||
const w = wrap ? wrap.getBoundingClientRect() : null;
|
||
const tol = 2; // 亚像素布局不该算「被裁」
|
||
const clipped = !!w && (r.width < 1 || r.right > w.right + tol || r.left < w.left - tol);
|
||
return { sel: el.getAttribute('aria-selected') || '', clipped: clipped,
|
||
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
|
||
wrap: w ? [Math.round(w.x), Math.round(w.right), Math.round(w.width)] : null };
|
||
}"""
|
||
|
||
|
||
def tab_state(page, h, ctrl=""):
|
||
"""读一颗页签的真实现场:aria-selected + 本体有没有被 nav-wrap 裁在可视条带外。"""
|
||
try:
|
||
return page.evaluate(TAB_STATE_JS, {"h": h, "ctrl": ctrl})
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def click_tab(page, t):
|
||
"""真鼠标点一颗页签:返回 'direct' / 'overflow' / None(两条路都走不到才算点不动)。
|
||
|
||
窄屏(430 这一档)rc-tabs 把放不下的页签收进「更多」按钮:被裁掉的那颗本体坐在
|
||
`overflow: hidden` 的 .ant-tabs-nav-wrap 里,条带靠 rc-tabs 自己的 transform 滚动,
|
||
Playwright 的 scrollIntoView 滚不动它 → 直点必然 2500 ms 超时。
|
||
实测 /models@430:resolve_ref 为了唤懒挂载面板点过右边几颗,条带滚到最右,
|
||
左边 llm / video 两颗被裁住 → 2 条「鼠标点不动」假 offender。
|
||
|
||
第二类假阳性更阴(同一条路由,实测 8 条):**直点不抛异常 ≠ 点到了**。
|
||
Playwright 的可见性判定不看祖先的 overflow 裁剪,被裁那颗 rect 完整、vis=visible、
|
||
pointer-events:auto,`click()` 顺利返回;可事件其实落在盖在同一块像素上的
|
||
.ant-tabs-nav-operations(那颗「更多」按钮)上,rc-tabs 只把条带滚了一段
|
||
(translate(0)→translate(-110px)),aria-selected 一动不动,面板也没挂出来。
|
||
本函数因此:① 被裁住的压根不直点;② 直点后轮询 1.2 s 真验 aria-selected;
|
||
③ 没选上再走用户在这个宽度真正做得出的动作——「更多」溢出菜单。
|
||
这不是放宽:调用方那两条断言(选中态 + 面板存在)一条没减,只是换成真人在 430
|
||
做得到的动作来验同一份契约。
|
||
"""
|
||
sel = '[data-nex-tab="%s"]' % t["h"]
|
||
if not page.locator(sel).count():
|
||
return None
|
||
st = tab_state(page, t["h"], t.get("ctrl", ""))
|
||
if st is None:
|
||
return None
|
||
if st["sel"] == "true":
|
||
return "direct" # 已经是选中态:复位用的这一跳不需要动作
|
||
txt = (t.get("txt") or "").strip()
|
||
more = page.locator('.ant-tabs-nav-more, .ant-tabs-nav-operations button')
|
||
has_menu = bool(txt) and bool(more.count())
|
||
# ① 本体完整落在可视条带里才直点
|
||
if not st["clipped"]:
|
||
try:
|
||
page.locator(sel).first.click(timeout=2500)
|
||
for _ in range(6):
|
||
page.wait_for_timeout(200)
|
||
after = tab_state(page, t["h"], t.get("ctrl", ""))
|
||
if after and after["sel"] == "true":
|
||
return "direct"
|
||
except Exception:
|
||
pass
|
||
if not has_menu:
|
||
# 没溢出菜单可走:直点没抛异常却选不上 → 交回调用方按「选中态没跟上」立案
|
||
return "direct" if not st["clipped"] else None
|
||
# ② 溢出菜单:rc-tabs 给窄屏准备的、真人用得上的那条路
|
||
try:
|
||
more.first.click(timeout=2000)
|
||
page.wait_for_timeout(450)
|
||
item = page.locator('.ant-tabs-dropdown-menu-item', has_text=txt)
|
||
if not item.count():
|
||
# 菜单里没有它 = 它压根没被收进溢出(只差几个像素的边缘情况):
|
||
# 刚才那一下直点是落在本体上的,落空的原因归行为,不归「点不动」。
|
||
page.keyboard.press("Escape")
|
||
page.wait_for_timeout(250)
|
||
return None if st["clipped"] else "direct"
|
||
item.first.click(timeout=2000)
|
||
for _ in range(6):
|
||
page.wait_for_timeout(200)
|
||
after = tab_state(page, t["h"], t.get("ctrl", ""))
|
||
if after and after["sel"] == "true":
|
||
return "overflow"
|
||
return "overflow" # 菜单项确实点着了:选中态有没有跟上交给调用方断言
|
||
except Exception:
|
||
try:
|
||
page.keyboard.press("Escape")
|
||
except Exception:
|
||
pass
|
||
return None
|
||
|
||
|
||
def main() -> int:
|
||
offenders = []
|
||
coverage = []
|
||
soft = {}
|
||
seen = {}
|
||
nav_names = {}
|
||
lone = {}
|
||
ax_glyph = {}
|
||
with sync_playwright() as pw:
|
||
browser = pw.chromium.launch()
|
||
page = browser.new_page(viewport={"width": WIDTH, "height": HEIGHT})
|
||
cdp = page.context.new_cdp_session(page)
|
||
cdp.send("DOM.enable")
|
||
cdp.send("Accessibility.enable")
|
||
for theme in THEMES:
|
||
page.add_init_script("try{localStorage.setItem('nex-the','%s')}catch(e){}" % theme)
|
||
login(page)
|
||
pid = page.evaluate(PROJECT_JS)
|
||
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(2000)
|
||
d = page.evaluate(COLLECT)
|
||
tag = "%s/%s%s" % (WIDTH, theme, route)
|
||
names = ax_names(cdp)
|
||
|
||
# NAME:AX 树里没名字的交互节点 → 现场回读命名上下文,分硬/软两档
|
||
hard = soft_ = 0
|
||
if names is None:
|
||
offenders.append("NAME %s AX 树读不到(CDP 失败)" % tag)
|
||
else:
|
||
empt = [n for n in names if not n["name"] and n.get("bid")]
|
||
ctxs = unnamed_context(cdp, page, [n["bid"] for n in empt])
|
||
for n in empt:
|
||
c = ctxs.get(n["bid"])
|
||
tier, why = name_tier(n["role"], c)
|
||
if tier == "ok":
|
||
continue
|
||
sig = (c["sig"] if c else describe(cdp, n["bid"])) or "?"
|
||
line = "%s role=%s %s" % (sig, n["role"], why)
|
||
if tier == "hard" or NAME_STRICT:
|
||
hard += 1
|
||
offenders.append("NAME %s %s 无可读名称:%s" % (tag, sig, why))
|
||
else:
|
||
soft_ += 1
|
||
soft.setdefault(line, 0)
|
||
soft[line] += 1
|
||
|
||
hs_hard = hs_soft = 0
|
||
for h in d["hotspots"]:
|
||
line = "%s role=%s tabindex=%s%s:pointer 可点但键盘到不了" % (
|
||
h["sig"], h["role"], h["ti"], "(data-clickable 热区)" if h.get("dc") else "")
|
||
if h.get("hard") or HOTSPOT_STRICT:
|
||
hs_hard += 1
|
||
offenders.append("HOTSPOT %s %s" % (tag, line))
|
||
else:
|
||
hs_soft += 1
|
||
soft.setdefault(line, 0)
|
||
soft[line] += 1
|
||
if d["hotspots"]:
|
||
print(" ARIA %-22s 热区 hard %d / soft %d(候选共 %d,已滤内部可聚焦与嵌套热区)"
|
||
% (tag, hs_hard, hs_soft, len(d["hotspots"])))
|
||
# ARIA 引用完整性:先用真鼠标/真键盘把懒挂载的目标唤出来复查
|
||
resolved = deferred = 0
|
||
for b in d["broken"]:
|
||
st = resolve_ref(page, b)
|
||
if st == "ok":
|
||
resolved += 1
|
||
elif st == "dead":
|
||
# 唤不出来,但这是 antd 自己写在宿主上的标记(收起态菜单项、
|
||
# Typography 省略号那类),且这个宿主本身有原生 title 或自己的文字
|
||
# 可读——说明文字没丢,我们也不去深层覆盖 antd 的 DOM(AGENTS.md 第 9 条)。
|
||
# 记一笔、不立案;自绘元素(带 nex- 或原生标签)照样算 offender。
|
||
if b["ant"] and b["t"]:
|
||
deferred += 1
|
||
else:
|
||
offenders.append("ARIA %s %s %s=\"%s\" → 悬停、展开之后目标仍不存在"
|
||
% (tag, b["sig"], b["attr"], b["id"]))
|
||
page.evaluate("() => document.querySelectorAll('[data-nex-sem]')"
|
||
".forEach(n => n.removeAttribute('data-nex-sem'))")
|
||
# 页签:aria-controls 指向的面板是懒挂载的,源码里查 id 一律查不到,
|
||
# 必须真点一下——面板挂出来、aria-selected 跟着搬过来,才算声明与行为一致。
|
||
if d["tabs"]:
|
||
on = [t for t in d["tabs"] if t["sel"] == "true"]
|
||
if len(on) != 1:
|
||
offenders.append("ARIA %s 页签里 aria-selected=true 有 %d 颗(应为 1)"
|
||
% (tag, len(on)))
|
||
back = on[0]["h"] if on else ""
|
||
skipped_dis = via_more = 0
|
||
# resolve_ref 为了唤面板可能已经把条带点到别的页签上:先复位到
|
||
# 进页面时那颗,再逐颗点,否则第一颗开始就在跟滚过的条带较劲。
|
||
if back and len(d["tabs"]) > 1:
|
||
click_tab(page, on[0])
|
||
page.wait_for_timeout(350)
|
||
for t in d["tabs"][:6]:
|
||
# aria-disabled=true 的页签点不动是**声明的行为**,不是契约违反:
|
||
# /models 在数据加载完成前把未就绪的页签标成禁用(实测稳定态 4 颗全无禁用),
|
||
# 闸恰好采在这个中间态。禁用态照样算进 aria-selected 唯一性,只是不去点它。
|
||
if t.get("dis"):
|
||
skipped_dis += 1
|
||
continue
|
||
sel = '[data-nex-tab="%s"]' % t["h"]
|
||
if not page.locator(sel).count():
|
||
continue
|
||
how = click_tab(page, t)
|
||
if how is None:
|
||
offenders.append("ARIA %s role=tab %s 鼠标点不动"
|
||
"(直点与「更多」溢出菜单都点不着:页签不可用?)"
|
||
% (tag, t["sig"]))
|
||
continue
|
||
if how == "overflow":
|
||
via_more += 1
|
||
page.wait_for_timeout(500)
|
||
r = page.evaluate("""(a) => {
|
||
const el = document.querySelector(`[data-nex-tab="${a.h}"]`);
|
||
const p = a.ctrl ? document.getElementById(a.ctrl) : null;
|
||
return { sel: el ? el.getAttribute('aria-selected') : null,
|
||
exists: !!p };
|
||
}""", t)
|
||
if r["sel"] != "true":
|
||
offenders.append("ARIA %s role=tab %s 点下去 aria-selected=%s:选中态没跟上进行为"
|
||
% (tag, t["sig"], r["sel"]))
|
||
if t["ctrl"] and not r["exists"]:
|
||
offenders.append("ARIA %s role=tab %s 点下去之后 aria-controls=%s 的面板仍不存在"
|
||
% (tag, t["sig"], t["ctrl"]))
|
||
if skipped_dis:
|
||
print(" ARIA %s 页签 aria-disabled=true 有 %d 颗(中间态,未点)"
|
||
% (tag, skipped_dis))
|
||
if via_more:
|
||
print(" ARIA %s 页签 %d 颗被 rc-tabs 收进溢出「更多」菜单"
|
||
"(窄屏条带放不下):走菜单点着了才算走到" % (tag, via_more))
|
||
if back and len(d["tabs"]) > 1:
|
||
for row in d["tabs"]:
|
||
if row["h"] == back:
|
||
click_tab(page, row) # 复位,别把选中态留在最后一颗上
|
||
page.wait_for_timeout(400)
|
||
break
|
||
page.evaluate("() => document.querySelectorAll('[data-nex-tab]')"
|
||
".forEach(n => n.removeAttribute('data-nex-tab'))")
|
||
if len(d["current"]) > 1:
|
||
offenders.append("ARIA %s aria-current=true 有 %d 处(同一时刻只能有一个「在这里」)"
|
||
% (tag, len(d["current"])))
|
||
for cur in d["current"]:
|
||
if cur["href"] and cur["href"].split("?")[0] != d["path"]:
|
||
offenders.append("ARIA %s 选中项指向 %s,当前路由 %s" % (tag, cur["href"], d["path"]))
|
||
vis_live = [l for l in d["live"] if l["vis"]]
|
||
if len(vis_live) > 2:
|
||
offenders.append("LIVE %s 可见播报区 %d 个:%s" % (tag, len(vis_live), " / ".join(l["sig"] for l in vis_live)))
|
||
for l in d["live"]:
|
||
if l["pol"].lower() in ("off", ""):
|
||
offenders.append("LIVE %s %s 的 aria-live=%s 不会播报" % (tag, l["sig"], l["pol"]))
|
||
for e in d["empties"]:
|
||
if not e:
|
||
offenders.append("STATES %s 空表没有任何文案" % tag)
|
||
for s in d["skeletons"]:
|
||
if not s["name"]:
|
||
offenders.append("STATES %s 载入骨架 %s 没有可访问名称" % (tag, s["sig"]))
|
||
if not d["hasLandmark"]:
|
||
offenders.append("NAME %s 页面没有 main 地标,读屏无法跳过导航" % tag)
|
||
|
||
# GLYPH:图标字形码进进了控件的可读名称(阶段 8.5.1 · S-2)
|
||
g_leak = g_shadow = g_allow = 0
|
||
for g in d["glyphs"]:
|
||
if g["own"]:
|
||
g_shadow += 1 # 宿主自己的名字接管,AT 念的是人话
|
||
elif not g["host"]:
|
||
lone.setdefault("%s @ %s" % (g["tok"], g["sig"]), 0)
|
||
lone["%s @ %s" % (g["tok"], g["sig"])] += 1
|
||
elif g["host"] in GLYPH_ALLOW:
|
||
g_allow += 1
|
||
else:
|
||
g_leak += 1
|
||
offenders.append(
|
||
"GLYPH %s 图标字形码「%s」进入控件可读名称:%s%s"
|
||
% (tag, g["tok"], g["host"],
|
||
"(宿主文字「%s」)" % g["txt"] if g["txt"] else "(宿主只有这颗图标)"))
|
||
if d["glyphs"]:
|
||
print(" GLYPH %-21s 可见图标 %2d · 外泄 %d / 遮蔽 %d / 无宿主 %d / 豁免 %d"
|
||
% (tag, len(d["glyphs"]), g_leak, g_shadow,
|
||
sum(1 for g in d["glyphs"] if not g["host"]), g_allow))
|
||
# 交叉核对:AX 树里辅助技术真读到的名称 vs 登记表字形码(只打印,不立案)
|
||
if names and GLYPH_TOKENS:
|
||
for n in names:
|
||
low = n["name"].lower()
|
||
hit = [t for t in sorted(GLYPH_TOKENS)
|
||
if re.search(r"(?<![a-z0-9-])" + re.escape(t) + r"(?![a-z0-9-])", low)]
|
||
if hit:
|
||
ax_glyph.setdefault((n["role"], n["name"][:40], ",".join(hit)), 0)
|
||
ax_glyph[(n["role"], n["name"][:40], ",".join(hit))] += 1
|
||
|
||
# TAB + FOCUS:真按键盘走一遍
|
||
# 拍基线前先确认「没有任何东西带着焦点」:前面那几步(悬停、Space、点页签)
|
||
# 会把焦点留在控件上,带着焦点拍出来的基线 == 聚焦态,比出来永远是「没变」
|
||
# —— 状态筛选那条就是这么被冤枉的(实测差值在 .ant-select-selector 的
|
||
# border #C3CCD6→#1677FF 与 2px 外发光上)。blur 之后还要等过渡走完再拍。
|
||
page.evaluate("""() => {
|
||
const a = document.activeElement;
|
||
if (a && a.blur) a.blur();
|
||
// 只 blur 不够:blur 把「顺序焦点导航起点」留在刚刚那个元素上,
|
||
// 下一次 Tab 从**那儿**继续,文档开头到那儿之间的控件全部跳过。
|
||
// 实测 delivery 页:先前那几步把焦点留在第 16 个控件上,blur 之后
|
||
// 只走 10 站(起点手柄 16),干净加载从手柄 1 起走满 25 站。
|
||
// 正解:给 body 临时 tabindex=-1 并聚焦它 = 起点回到文档最前,走完再摘掉。
|
||
document.body.setAttribute('tabindex', '-1');
|
||
document.body.focus();
|
||
window.scrollTo(0, 0);
|
||
}""")
|
||
page.wait_for_timeout(FOCUS_DWELL)
|
||
# 净场:前面那几步(悬停唤描述、Space 展开下拉、点页签)可能留下打开的浮层。
|
||
# 浮层自带焦点陷阱,Tab 会在里面绕圈,而闸把「绕回已走过的元素」当成
|
||
# 「绕完一整页」当场收工 —— 整页剩下的元素全被误报成「Tab 序列里找不到」。
|
||
# 实测 library 走 23 站就收,独立探针净场后走到 62/63。
|
||
layers0 = d["openLayers"]
|
||
for _ in range(3):
|
||
if not page.evaluate(LAYERS_JS):
|
||
break
|
||
page.keyboard.press("Escape")
|
||
page.wait_for_timeout(350)
|
||
page.evaluate("""() => {
|
||
const a = document.activeElement;
|
||
if (a && a.blur) a.blur();
|
||
window.scrollTo(0, 0);
|
||
}""")
|
||
page.wait_for_timeout(FOCUS_DWELL)
|
||
layers = page.evaluate(LAYERS_JS)
|
||
# 重打标记 + 现量现场:拿 COLLECT 那一刻的旧账走位 = 整族假阳性
|
||
rt = page.evaluate(RETARGET, FOCUSABLES)
|
||
visf = rt["visFocusables"]
|
||
c0 = Counter(t["sig"] for t in d["tabTargets"])
|
||
c1 = Counter(t["sig"] for t in rt["targets"])
|
||
churn = sum((c0 - c1).values()) + sum((c1 - c0).values())
|
||
baseline = page.evaluate(BASELINE, FOCUSABLES)
|
||
visited, invisible, undetermined = [], [], []
|
||
term = "?"
|
||
unreachable = {t["h"]: t["sig"] for t in rt["targets"]}
|
||
seenlk, checked = set(), 0
|
||
for _ in range(TAB_MAX):
|
||
page.keyboard.press("Tab")
|
||
page.wait_for_timeout(FOCUS_DWELL) # 等 antd 那 0.2s 过渡走完再读样式
|
||
f = page.evaluate(FOCUS_PROBE)
|
||
if not f:
|
||
term = "焦点掉出文档"
|
||
break
|
||
if f["lk"] in seenlk:
|
||
term = "绕回起点" # 回到已走过的元素 = 绕完一圈
|
||
break
|
||
seenlk.add(f["lk"])
|
||
visited.append(f)
|
||
unreachable.pop(f["th"], None)
|
||
# 焦点可见性:描边与外发光都没有时,不比字符串——拿走位前那张基线比,
|
||
# 看它自己或上面五层包裹层的描边 / 外发光 / 边框 / 底色有没有真的变。
|
||
# 本项目的输入类控件按 theme/antd.ts 的既定决策只变边框不发蓝光,
|
||
# 而变化实测落在第 3~4 层(.ant-select-selector、.ant-input-affix-wrapper),
|
||
# 「outline 为空」不等于「看不见」;反过来 outline:none 吃环照样咬得住。
|
||
if not (f["ring"] or f["shadow"]):
|
||
base = baseline.get(f["lk"])
|
||
if base is None:
|
||
undetermined.append(f["sig"]) # 快照之后新长出来的(浮层里的)
|
||
elif base != f["look"]:
|
||
checked += 1
|
||
elif f["sig"] not in invisible:
|
||
invisible.append(f["sig"])
|
||
if len(visited) >= TAB_MAX:
|
||
term = "触顶 NEX_TABS"
|
||
break
|
||
# TAB 判定:句柄优先、sig 多重集兜底。
|
||
# 句柄认不出来只证明「标记被重建抹掉了」,不证明「键盘走不到」;
|
||
# 真缺陷的口径是「走位覆盖完整页之后,这类自定义角色元素还是没走到」。
|
||
if unreachable:
|
||
live = Counter(x["sig"] for x in page.evaluate(RETARGET, FOCUSABLES)["targets"])
|
||
got = Counter(f["sig"] for f in visited)
|
||
deficit = {sg: n - got.get(sg, 0) for sg, n in live.items() if n > got.get(sg, 0)}
|
||
short = sum(deficit.values())
|
||
covered = layers == 0 and (len(visited) + 1 >= visf or term == "绕回起点")
|
||
if short and covered:
|
||
for sg, n in sorted(deficit.items()):
|
||
offenders.append("TAB %s %s ×%d 在 Tab 序列里走不到"
|
||
"(%d 次 Tab 走完 %d 个可见可聚焦元素)"
|
||
% (tag, sg, n, len(visited), visf))
|
||
elif short:
|
||
coverage.append("TAB %s 走位 %d/%d 站提前收工(%s):还有 %d 颗没轮到,"
|
||
"按覆盖限制记账,不立 offender"
|
||
% (tag, len(visited), visf, term, short))
|
||
else:
|
||
coverage.append("TAB %s 句柄未对上 %d 个(走位期间标记被 React 重建抹掉),"
|
||
"sig 多重集复核全部走到" % (tag, len(unreachable)))
|
||
if churn:
|
||
coverage.append("采集 %s COLLECT 与走位前打靶差 %d 颗自定义角色元素"
|
||
"(轮询 / 局部重渲染),以走位前那次为准" % (tag, churn))
|
||
page.evaluate("() => document.body.removeAttribute('tabindex')")
|
||
page.evaluate("() => document.querySelectorAll('[data-nex-look]')"
|
||
".forEach(n => n.removeAttribute('data-nex-look'))")
|
||
for r_ in sorted(set(invisible)):
|
||
offenders.append("FOCUS %s %s 焦点不可见:描边、外发光、边框、底色在聚焦前后一模一样"
|
||
% (tag, r_))
|
||
seen[tag] = (len(visited), len(d["hotspots"]), len(names or []),
|
||
len(d["broken"]), resolved, deferred, len(set(undetermined)),
|
||
hard, soft_, visf, term, layers0, layers)
|
||
|
||
# ARIA 行为:汉堡按钮的 aria-expanded 必须随抽屉真的翻,Esc 必须关得掉,
|
||
# 而且辅助技术实际读到的名字要跟面板状态同向。
|
||
# 定位不写死完整 label:AppHeader 按既定决策在窄屏说「打开/关闭导航菜单」,
|
||
# 名称本身随状态翻转,写死「打开导航菜单」的话点一下就查不到这颗按钮
|
||
# (上一轮 430 就是这么崩在 get_attribute 超时上的)。名称翻转是要求的行为,
|
||
# 所以用 CDP 读 AX 名字一起断言,而不是绕过它。
|
||
btn = page.get_by_role("button", name="导航菜单")
|
||
if WIDTH < 768 and btn.count():
|
||
def ax_name():
|
||
hits = [n["name"] for n in (ax_names(cdp) or [])
|
||
if n["role"] == "button" and "导航菜单" in n["name"]]
|
||
return hits[0] if hits else ""
|
||
name_before = ax_name()
|
||
before = btn.first.get_attribute("aria-expanded")
|
||
btn.first.click(); page.wait_for_timeout(900)
|
||
drawer = page.locator('.ant-drawer-open').count()
|
||
mid = btn.first.get_attribute("aria-expanded")
|
||
name_mid = ax_name()
|
||
page.keyboard.press("Escape"); page.wait_for_timeout(900)
|
||
after = btn.first.get_attribute("aria-expanded")
|
||
name_after = ax_name()
|
||
closed = page.locator('.ant-drawer-open').count()
|
||
if drawer and "关闭" not in name_mid:
|
||
offenders.append("NAME %s 抽屉已展开,按钮的辅助技术名称却是「%s」(应含「关闭」)"
|
||
% (tag, name_mid))
|
||
if (not closed) and "关闭" in name_after:
|
||
offenders.append("NAME %s 抽屉已收起,按钮的辅助技术名称仍是「%s」(应含「打开」)"
|
||
% (tag, name_after))
|
||
nav_names[tag] = (name_before, name_mid, name_after)
|
||
if mid != "true" or drawer == 0:
|
||
offenders.append("ARIA %s 点汉堡后 aria-expanded=%s、抽屉 %d 个:声明与行为不一致"
|
||
% (tag, mid, drawer))
|
||
if after != "false" or closed:
|
||
offenders.append("ARIA %s Esc 关不掉抽屉:aria-expanded=%s、仍开 %d"
|
||
% (tag, after, closed))
|
||
if before != "false":
|
||
offenders.append("ARIA %s 汉堡初始 aria-expanded=%s(应为 false)" % (tag, before))
|
||
browser.close()
|
||
|
||
print("语义与行为体检 · 视口 %d · 主题 %s · Tab 上限 %d" % (WIDTH, "/".join(THEMES), TAB_MAX))
|
||
for tag, (tabs, hot, axn, refs, resolved, deferred, inflight, nh, ns,
|
||
visf, term, l0, l1) in seen.items():
|
||
# 覆盖率必须打印:走位「绕回起点」却只走了可见可聚焦元素的一小截 = 判据自己瞎了,
|
||
# 不是页面干净。没有这一行,第二次空转还是没人看得出来。
|
||
flag = "" if (tabs + 1 >= visf or term == "触顶 NEX_TABS") else " \u26a0 覆盖不足"
|
||
print(" %-40s Tab 走 %d/%d 站(%s)· AX 节点 %3d(无名 硬 %d/软 %d)· 热区 %d"
|
||
" · 引用 唤出 %d/antd 内部 %d/共 %d · 浮层焦点 %d · 走位前浮层 %d->%d%s"
|
||
% (tag, tabs, visf, term, axn, nh, ns, hot, resolved, deferred, refs,
|
||
inflight, l0, l1, flag))
|
||
if soft:
|
||
print("\n--- NAME 软档(历史欠账,补一句 aria-label 即可;"
|
||
"NEX_NAMESTRICT / NEX_HOTSPOTSTRICT=1 转硬档)%d 类 ---" % len(soft))
|
||
for line, cnt in sorted(soft.items(), key=lambda x: -x[1]):
|
||
print(" ×%-3d %s" % (cnt, line))
|
||
for tg, nm in nav_names.items():
|
||
print(" ARIA %-28s 汉堡名称 初始「%s」→ 展开「%s」→ 收起「%s」" % (tg, nm[0], nm[1], nm[2]))
|
||
if lone:
|
||
print("\n--- GLYPH 无宿主图标 %d 类(图形自己承担语义的位置:标签内图标、提示条图标、"
|
||
"状态点。S-2 只管操作名称,这里逐条列出来给人看,不立案)---" % len(lone))
|
||
for k, cnt in sorted(lone.items(), key=lambda x: (-x[1], x[0])):
|
||
print(" ×%-3d %s" % (cnt, k))
|
||
for (role, nm, toks), cnt in sorted(ax_glyph.items(), key=lambda x: (-x[1], x[0])):
|
||
coverage.append("GLYPH AX 名称撞中字形码 %-13s role=%-9s 「%s」 ×%d"
|
||
" —— DOM 侧没立案:名字来自正文文本或闸门看不见的第三处,要人眼确认"
|
||
% (toks, role, nm, cnt))
|
||
if not GLYPH_TOKENS:
|
||
coverage.append("GLYPH %s 解析出 0 个字形码 —— 交叉核对空转,登记表结构变了要同步改这里"
|
||
% REGISTRY)
|
||
else:
|
||
coverage.append("GLYPH 交叉核对用 %d 个字形码(解析自 %s);DOM 侧立案判据不依赖这张表"
|
||
% (len(GLYPH_TOKENS), REGISTRY.name))
|
||
coverage.append("GLYPH 在册豁免 %d 条%s"
|
||
% (len(GLYPH_ALLOW), (":" + " / ".join(GLYPH_ALLOW)) if GLYPH_ALLOW else "(空表)"))
|
||
if coverage:
|
||
# 覆盖说明 ≠ 放行:这些是闸自己看不见的部分,打印出来供人核对;
|
||
# 不立 offender 是因为它们不是页面缺陷,而是判据的现场限制。
|
||
print("\n--- 覆盖说明(闸的现场限制,不立 offender)%d 条 ---" % len(coverage))
|
||
for c in coverage:
|
||
print(" " + c)
|
||
if offenders:
|
||
print("\n--- offenders %d 条 ---" % len(offenders))
|
||
for o in offenders:
|
||
print(" " + o)
|
||
else:
|
||
print("\n=== 语义与行为 0 条违规 ===")
|
||
return len(offenders)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|