2087 lines
130 KiB
Python
2087 lines
130 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 树里辅助技术**真读到的**名称撞登记表字形码集合,按「整条名称
|
||
是不是就是那个字形码」分两支(判据函数 `whole_glyph_name`,DOM 侧与 AX 侧共用,
|
||
gateprobe ⑲ 钉它):
|
||
· 整条 = 字形码(实测坏形状 `ellipsis`:rc-tabs 的溢出「…」在补名称之前,
|
||
AT 念出来的是一个英文单词)→ **立案**。NAME 查不出这种缺陷:名称非空,
|
||
只是空话;DOM 侧那条也可能因为名字不挂在 `.anticon[aria-label]` 上而看不见。
|
||
· 字形码只是名称里的一段(正文文本里写着 `/api/meta`,撞中的是 `api`)
|
||
→ 仍然**只打印**:那是内容不是图标名,立案就是假阳性,而假阳性的下场
|
||
是这条闸被人以噪音为由关掉。
|
||
第四支(阶段 23 · S-2 收口)补的是**图形自己出声**这一族,与上面两支正交:
|
||
· 上面两支都要求「字形码挂在交互元素的名称里」或「字形码写在 .anticon 自己的
|
||
aria-label 上且等于类名后缀」。antd 内部图形是第三种形状:宿主**已经**具名
|
||
(数字框「增加数值」、分页键「上一页」),可图形那颗
|
||
`<span role=img aria-label="up|down|left|right">` 在 AX 树里仍是独立对象,
|
||
读屏念完宿主再补一句英文 —— `ax_names()` 只收 INTERACTIVE 角色,一条都看不见;
|
||
登记表名单是语义别名(chevron-left),撞不中字形本名(left)。
|
||
· 判据:AX 树里**没被忽略**、名称非空、DOM 带 `anticon` 的图形,整条名称必须含汉字;
|
||
否则立案(函数 `ax_graphic_zh_defect`,gateprobe ㉔ 钉它)。
|
||
为什么不是「撞名单」:名单只有我们的别名,antd 内部图形用的就是字形本名,
|
||
维护第二份「所有可能出现的英文字形码」等于给这条闸埋一次新的空转。
|
||
为什么只管 `anticon`:真 `<img>` 的 alt 是内容(模型代号、文件名),不是控件属性。
|
||
名称为空的图形不在这一支 —— 那是 NAME / C 支的口径(没报名 ≠ 报错了名)。
|
||
第五支(阶段 34 · 2026-11-10 · S-2 宿主级收口)补的是**撤名撤出洞**这一族:
|
||
· `decorative()` 把字形名从辅助技术里撤掉(默认 aria-hidden)之后,缺陷不再是
|
||
「名字里混了英文」,而是「这颗操作控件**整条名称为空**」。前四支全绿——
|
||
它们都以「某处有名字」为前提——读屏念出来的却是角色名,或干脆什么都不念。
|
||
阶段 32 曾用 DOM 量这一族(`s2surface.py` C 支),但句柄打在图标那颗 span 上,
|
||
量的是 span 自己的 AX 名 ⇒ 宿主已具名的 `ant-btn-icon` 也被算成缺名,672 条过计。
|
||
· 判据(函数 `ax_nameless_actors` + `nameless_icon_host`,gateprobe ㉙ 钉它):
|
||
AX 树里**未被忽略**、角色可操作、整条名称为空的控件,回查 DOM,
|
||
里面有 `anticon` / `svg[data-icon]` / `role=img` 图标的立案;
|
||
无名又没图标的(空文本框、分组标题)交还 NAME 闸,不在这儿重复立案。
|
||
· 采集方向与 NAME 闸相反:**先问 AX,再回查 DOM**,量的天然是宿主那一颗,
|
||
一颗控件一条,图标是几个 span 都只算一次。全站点活体复量见
|
||
`reports/ui_evidence/nex-p34/s2host.py`(含本闸够不着的浮层打开态)。
|
||
FILE 浏览器**原生控件**文案混进辅助技术名称(2026-11-10 · 阶段 35 · S-3)。
|
||
为什么单独立一条而不是并入 LOCALE:LOCALE 量的是 antd 语言包回落,采的是
|
||
DOM 上的属性与文字;`<input type=file>` 的 `Choose File` / `No file chosen`
|
||
是浏览器影子 DOM 里的东西,DOM 侧一条都读不到(阶段 34 的取证只能靠 CDP
|
||
问 AX 树,见 `reports/ui_evidence/nex-p34/s2host-430-interact-overlays.json`
|
||
里那一排 `axname:"Choose File"`),两条闸的取材通道根本不同。
|
||
症状(`reports/ui_evidence/nex-p35/filepick-ax-before.json`):kit `FilePick`
|
||
把隐藏的 file input 用 `inset:0` 铺满整颗按钮,于是
|
||
· 那颗 input 自己是一个 AT 停靠点,名字 = 浏览器原生英文 `Choose File`;
|
||
· 外层按钮按 name-from-contents 算名,影子文字整条渗进去
|
||
——`定妆图 Choose File: No file chosen`。
|
||
这与 S-2「图标字形名混入名称」是同一族缺陷,只是来源从图形换成了 UA 原生控件。
|
||
判据两条,一头一尾:
|
||
① DOM 侧(函数 `file_name_defect`,gateprobe ㉚ 钉它):AT 读得到的
|
||
`input[type=file]` 必须自带**含汉字**的 `aria-label`。空 / 纯英文都立案。
|
||
为什么必须给它名字而不是 `aria-hidden`:它**就是**真正的激活目标
|
||
(整块热区靠它开文件框、Enter 也归它),撤名 = 焦点落进 AT 里的哑节点。
|
||
② AX 侧(`UA_NATIVE_FILE`):任何未被忽略节点的名称里出现
|
||
`Choose File` / `No file chosen` 即立案 —— ① 只钉 input 本体,
|
||
这一条钉「渗进了别的控件的名字」这个症状,谁把 label 挪回按钮、
|
||
忘了 input,①会红,而②保证即使判据被写窄症状也跑不掉。
|
||
取证:`reports/ui_evidence/nex-p35/filepick_ax.py` → `logs/filepick-ax-{before,after}.json`
|
||
(改前改后两份 AX 读数:5 个状态 / 25 颗热区 / 0 失败)。
|
||
TABKBD 窄屏溢出页签的纯键盘通道(2026-11-08 · 阶段 9 · S-3)。为什么单独一条:页签放不下时
|
||
rc-tabs 把它们收进右端那颗「…」,**被裁那颗本体还留在 DOM 里**(rect 完整、AX 树读得到),
|
||
所以源码闸、NAME、TAB 三条都看不出问题,真鼠标也点得着——风险全在键盘这一侧:
|
||
① 触发器可聚焦:原生 button/a **且没被 tabindex=-1 踢出序列**,或 role=button + tabindex>=0。
|
||
(反向验证抓到过判据写宽:原先只认标签名,tabindex=-1 直接放行,
|
||
缺陷要等第④步「按 Tab 没落到」才响,报的是症状不是病灶。)
|
||
② 辅助技术里的名称:非空、且不混字形码。这颗的名称**不在它自己的属性上**——
|
||
antd 的 MoreProps 只开 `icon` 一条口子,本项目的 aria-label 挂在内层图标上,
|
||
按钮的名字靠 name-from-contents 算出来 → 只能问 CDP(DOM.getDocument →
|
||
querySelector → describeNode → Accessibility.queryAXTree 取 role=button 的 name),
|
||
读 DOM 属性必漏(S-2 那族缺陷在这颗上单独钉一遍)。
|
||
③ 声明一致:aria-haspopup=listbox、未展开时 aria-expanded=false。
|
||
④ 真按键:从选中那颗页签按 Tab(最多 4 下)必须落到触发器 = 它真的在 Tab 序列里。
|
||
⑤ 焦点可见:停在那颗上必须有描边或外发光(实测 antd 给的是 outline 2px,
|
||
light #1677FF / dark #1668DC)。这里只看它自己:FOCUS 那条「查五层包裹 +
|
||
两个兄弟」是给「变化藏在第 3~4 层」的输入类控件准备的,对这颗按钮用不上。
|
||
⑥ 走通整条路:↓ 展开 → 逐颗方向键找到被裁页签 → Enter 选中 →
|
||
aria-selected 搬过去且恒 1 颗、aria-controls 的面板真挂载 → Esc 关闭(expanded 翻回 false)。
|
||
菜单里的下标不写死:Enter 之后 rc-tabs 不一定关菜单,而刚选上那颗已经从溢出名单里
|
||
搬走、菜单会缩短,按死下标必然对不上。
|
||
只在**真的溢出**时说话:这一档放得下就跳过(1440 恒跳过,但触发器仍在 DOM 里,不算缺陷)。
|
||
覆盖读数每次必报「溢出条带 / 被裁颗数 / 纯键盘选中成功颗数」,全 0 也打印出来——
|
||
这一族闸门的失败方式从来不是响错,而是安静地什么都没看见(反向验证见 gateprobe 判据 ⑱)。
|
||
|
||
LOCALE antd 组件**自己画出来的**文案不许是英文(阶段 12 · S-3 根因防线)。
|
||
为什么单独一条:语言包这条链坏掉是**静默**的。`antd/locale/zh_CN` 是个 CJS 壳,
|
||
构建器把整个 module.exports 当默认导出交出来 ⇒ `providers.tsx` 拿到的是
|
||
`{default: 真 locale}`,antd 的 useLocale 认不出这层形状就直接回落 enUS——
|
||
不报错、不警告、typecheck 过、build 过,只有分页的 hover 提示变成 `Previous Page`、
|
||
跳转框的可访问名称变成 `Go to`、空表变成 `No data`。这一族缺陷 NAME 与 GLYPH
|
||
都看不见(名称非空、也不是图标字形码),只有人工读屏才会撞上——它红了半年没人发现。
|
||
所以这条盯**结果**不盯写法:语言包通道无论怎么坏(interop / import 路径 /
|
||
换 ConfigProvider),只要 antd 内置件又吐出英文就响。三条口径:
|
||
· 作用域只圈 antd 的内置件(分页 / 选择器与其下拉 / 空态 / 日期 / 表格筛选 /
|
||
模态页脚 / 步进器 / 穿梭框 / 图片预览),且只取 `selfAnt` 的节点
|
||
(自己带 ant- 且不带 nex-)⇒ 业务节点、/help 正文、我们自己的按钮永远进不来;
|
||
· 只读它家写死的三样属性(`title` / `aria-label` / `placeholder`)加两处它家
|
||
自己画的文字(空态描述、模态页脚按钮)。Select 的选项、Table 的单元格
|
||
那些**我们的数据**一个都不读,否则一条英文素材名就成了语言包缺陷;
|
||
· 可见性用 **AT 可达**(排除 display:none / visibility:hidden / aria-hidden),
|
||
不用像素可见:这条量的是读屏念到的文案。antd 的步进器静止态藏在
|
||
`opacity:0` 的 handler-wrap 里,按像素量整族采不到——量不到就没有判决,
|
||
它哪天回落成英文(kit 的收口被绕过 / 换 antd 改了写法)这条闸永远安静;
|
||
· Python 侧**精确匹配 + 大小写敏感**(`OK` 算、`ok` 不算)。子串匹配会把业务
|
||
数据判成缺陷,而假阳性的下场永远是这条闸被以「全是噪音」为由关掉。
|
||
在册豁免**空表**(2026-11-09 阶段 18 起)。表里原来只有一条真事实:
|
||
`Increase Value` / `Decrease Value` 写死在 rc-input-number 的 StepHandler.js:87/97,
|
||
antd 的 zh_CN 语言包**没有 InputNumber 这一段**、只把 upHandler/downHandler 当图标
|
||
透传 ⇒ 语言包通道与组件属性通道两条都不存在。修法不是画新步进器(那要动已验证的
|
||
视觉),而是 `components/ui/Input.tsx` 在 kit 的两个数字框出口上就地改掉那两条
|
||
`aria-label`(结构 / 类名 / 像素 / 鼠标与键盘行为一字未动,MutationObserver 兜重挂载)。
|
||
再撞见这两条英文 = kit 的收口失效,是真回归 ⇒ 往豁免表加业务串依然禁止。
|
||
真页面 0 条命中(2026-11-08 修完 providers.tsx、2026-11-09 修完步进器名之后实测),
|
||
没有历史欠账 ⇒ 这一条直接进退出码;扫描面与豁免命中数每次必报,
|
||
反向验证见 gateprobe 判据「semanticcheck.LOCALE / -seen」。
|
||
|
||
用法:
|
||
.venv/bin/python scripts/ui/semanticcheck.py # 默认打 :5173(dev),换端口才需要 NEX_BASE
|
||
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 走位注释——
|
||
和判据 TABKBD 无关,别混名)、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", "admin@123")
|
||
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"))
|
||
# /help 是阶段 10(S-2 收尾)加进来的,为的是给「整条名称 = 字形码」那一支留一个
|
||
# **真页面上的好样本**:手册正文里那条链接的名字就叫 `/api/meta`,撞中了登记表里的
|
||
# `api`,但整条名称不是字形码 → 必须只打印不立案。没有它,这一半只活在 gateprobe 的
|
||
# 名称表里(喂出来的名字终究是我们自己写的)。实测 1440 与 430 × 明暗:0 条违规。
|
||
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,/help").split(",") if r]
|
||
|
||
# ── GLYPH 用:全站唯一图标登记表里解析出来的字形英文码(upload / down / appstore…)
|
||
# 两种导出形状都要认——阶段 8.5.1 之后一律走 decorative(),但这条闸的职责是
|
||
# 「写法换了也认得出字形码」,所以旧的 `export { A as IconB }` 照样解析。
|
||
# 注意它**只服务交叉核对**:立案判据看的是「aria-label == 类名后缀」,不依赖这张表。
|
||
# 2026-11-09 阶段 25:登记表从一个文件变成一个**目录**(core.ts 首屏表 + extra.ts 懒页面表
|
||
# + _kit.ts 公共件 + index.ts 桶),词汇表跟着读整个目录,一条字形码都不漏。
|
||
REGISTRY = pathlib.Path(__file__).resolve().parents[2] / "frontend/src/components/icons"
|
||
|
||
|
||
def glyph_tokens():
|
||
try:
|
||
src = "\n".join(sorted(f.read_text(encoding="utf8")
|
||
for f in REGISTRY.glob("*.ts")))
|
||
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()
|
||
|
||
|
||
def whole_glyph_name(name):
|
||
"""整条可读名称恰好是一个登记表字形码时返回那个码,否则返回空串。
|
||
|
||
为什么只要「整条」:这是能不能写进退出码的分界线。
|
||
· `upload 导入脚本` 这种混拼,宿主还有半句人话,AT 念得出「导入脚本」,
|
||
归 DOM 侧那条(aria-label == anticon-<后缀>)管,本函数不管;
|
||
· `ellipsis` 这种整条就是字形码,用户听到的是一个英文单词,**等于没有名称**,
|
||
而 NAME 查不出它(名称非空,只是空话)——只有这一种够格进退出码。
|
||
为什么还要撞登记表:`/api/meta`、`Esc`、`OK` 都是合法名称,不是字形码。
|
||
"""
|
||
key = (name or "").strip().casefold()
|
||
return key if key in GLYPH_TOKENS else ""
|
||
CJK_NAME = re.compile(r"[\u4e00-\u9fff]")
|
||
|
||
|
||
def ax_graphic_zh_defect(name, html):
|
||
"""AT 树里没被忽略的图标图形:整条名称一个汉字都没有 ⇒ 缺陷描述,否则空串。
|
||
|
||
为什么判「没有汉字」而不是「撞中登记表字形码」:`whole_glyph_name` 的名单解析自
|
||
**我们自己的语义别名**(`IconChevronLeft` → `chevron-left`),antd 内部图形报的是
|
||
**字形本名**(`left` / `up` / `down`)——名单撞不中,阶段 23 全站 AT 侧 72 条英文字形码
|
||
就是这么漏的。本项目界面语言是中文(`LOCALE` 已经按这条口径钉 antd 内置件),
|
||
所以「AT 看得见的那颗图形必须用中文报名」比名单更稳,也不需要维护第二份名单。
|
||
为什么只认 `anticon`:素材封面、灯箱大图这些真 `<img>` 的 alt 是**内容**,
|
||
里面出现英文(模型代号、文件名)不算缺陷;只有图标字形这一族的名字是控件属性。
|
||
名称为空不在这一支(那是 `NAME` 与 C 支的口径:图形没报名 ≠ 报错了名)。
|
||
"""
|
||
if "anticon" not in (html or ""):
|
||
return ""
|
||
name = (name or "").strip()
|
||
if not name or CJK_NAME.search(name):
|
||
return ""
|
||
return name[:40]
|
||
|
||
|
||
def ax_graphic_nodes(cdp):
|
||
"""CDP → AX 树里**没被忽略**、名称非空的图形节点,带自己的 outerHTML。
|
||
|
||
为什么不复用 `ax_names()`:那把尺子只收 INTERACTIVE 角色。装饰图形不是交互元素,
|
||
可它自己那颗 `<span role=img aria-label="up">` 在 AX 树里是一条能单独念出来的东西——
|
||
宿主有名字(「增加数值」)不影响它作为子对象被暴露,读屏在宿主之后还会补一句英文。
|
||
outerHTML 只用来确认「这颗图形是 anticon」,不做别的推断;取不到节点就计入
|
||
`unresolved` 并打出来,**不猜**(「没量到」≠「通过」)。
|
||
"""
|
||
try:
|
||
tree = cdp.send("Accessibility.getFullAXTree")["nodes"]
|
||
except Exception:
|
||
return None
|
||
out = {"rows": [], "unresolved": 0}
|
||
for n in tree:
|
||
if n.get("ignored"):
|
||
continue
|
||
role = (n.get("role") or {}).get("value") or ""
|
||
if role not in ("img", "image", "graphic"):
|
||
continue
|
||
name = ((n.get("name") or {}).get("value") or "").strip()
|
||
if not name:
|
||
continue
|
||
bid = n.get("backendDOMNodeId")
|
||
try:
|
||
html = cdp.send("DOM.getOuterHTML", {"backendNodeId": bid}).get("outerHTML", "")
|
||
except Exception:
|
||
out["unresolved"] += 1
|
||
continue
|
||
out["rows"].append({"name": name, "role": role, "html": html})
|
||
return out
|
||
|
||
|
||
# ── GLYPH 5d(阶段 34 · 2026-11-10 · S-2 宿主级收口)────────────────────────────
|
||
# 前三支(5a DOM 外泄 / 5b AT 整名=字形码 / 5c AT 可见图形报英文名)全部以
|
||
# 「某处有名字」为前提。`decorative()`(`components/icons/_kit.ts`)把字形名从辅助
|
||
# 技术里撤掉之后,缺陷换成了新形状:**图标没了名字,宿主也没补**,于是这颗操作控件
|
||
# 在 AX 树里是一条「未被忽略 + 名称为空」的节点,三支柱子都撞不到它。
|
||
# 阶段 32 的 `s2surface.py` C 支想用 DOM 量这一族,但句柄打在图标那颗 span 上,
|
||
# 量的是 span 自己的 AX 名 ⇒ 宿主已具名的 `ant-btn-icon` 也被算成缺名(672 条过计)。
|
||
# 这一支的口径与 `reports/ui_evidence/nex-p34/s2host.py` 一致:**先拿 AX 树里辅助技术
|
||
# 真看得见的交互控件,名称为空的那些再回查 DOM 看里面有没有图标** —— 量的是宿主那颗。
|
||
AX_ACTOR_ROLES = {"button", "link", "textbox", "combobox", "searchbox", "listbox",
|
||
"menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio",
|
||
"checkbox", "switch", "tab", "slider", "spinbutton"}
|
||
ICONISH_HOST = re.compile(r'class="[^"]*\banticon\b|<svg[^>]{0,160}\bdata-icon=|role="img"', re.I)
|
||
|
||
|
||
def nameless_icon_host(html):
|
||
"""名称为空的宿主里**有图标** ⇒ 返回图标的字形名(或「图标」),否则空串。
|
||
|
||
只认 `anticon` / `data-icon` / `role=img` 三种图标形状,和 5c 同一把尺子。
|
||
名称为空但里面没图标(空文本框、无标签的 `<tr>`、分组标题)不在这里立案 ——
|
||
那是常驻 `NAME` 闸的口径,与图标无关,混进来只会把这条闸的读数搅浑。
|
||
"""
|
||
if not ICONISH_HOST.search(html or ""):
|
||
return ""
|
||
m = re.search(r"anticon-([\w-]+)", html or "")
|
||
return m.group(1) if m else "图标"
|
||
|
||
|
||
# ── FILE(阶段 35 · 2026-11-10 · S-3)──────────────────────────────────────────
|
||
# 浏览器给 `<input type=file>` 的原生文案(影子 DOM,DOM 侧读不到,只在 AX 名称里现身)。
|
||
UA_NATIVE_FILE = ("Choose File", "No file chosen")
|
||
CJK_RE = re.compile(r"[\u4e00-\u9fff]")
|
||
|
||
|
||
def file_name_defect(aria_label):
|
||
"""文件选择控件的 `aria-label` 不合格 ⇒ 返回缺陷描述;合格返回空串。
|
||
|
||
口径只有两条:**有**名字,且名字里**有汉字**。
|
||
为什么判「含汉字」而不是撞英文名单:原生文案随浏览器界面语言变(英文宿主 `Choose File`、
|
||
中文宿主「选择文件」),按名单认英文会在换语言的机器上当场空转;
|
||
本项目界面语言是中文,「名字里有汉字」就是这条控件被我们自己具过名的唯一硬证据。
|
||
"""
|
||
v = (aria_label or "").strip()
|
||
if not v:
|
||
return "没有 aria-label —— 读屏念的是浏览器原生文案(英文宿主上就是 Choose File)"
|
||
if not CJK_RE.search(v):
|
||
return "aria-label 里没有汉字:「%s」" % v
|
||
return ""
|
||
|
||
|
||
def ax_nameless_actors(cdp):
|
||
"""CDP → AX 树里**未被忽略**、名称为空的可操作控件(带 outerHTML)。
|
||
|
||
与 `ax_graphic_nodes` 同一套采集方向(AX 为准、DOM 只用来补身份),区别只在角色:
|
||
那一条收图形,这一条收交互控件。取不到 outerHTML 的计入 `unresolved` 并打出来,
|
||
**不猜**(「没量到」≠「通过」)。
|
||
"""
|
||
try:
|
||
tree = cdp.send("Accessibility.getFullAXTree")["nodes"]
|
||
except Exception:
|
||
return None
|
||
out = {"rows": [], "unresolved": 0}
|
||
for n in tree:
|
||
if n.get("ignored"):
|
||
continue
|
||
role = (n.get("role") or {}).get("value") or ""
|
||
if role not in AX_ACTOR_ROLES:
|
||
continue
|
||
if (((n.get("name") or {}).get("value") or "").strip()):
|
||
continue
|
||
try:
|
||
html = cdp.send("DOM.getOuterHTML",
|
||
{"backendNodeId": n.get("backendDOMNodeId")}).get("outerHTML", "")
|
||
except Exception:
|
||
out["unresolved"] += 1
|
||
continue
|
||
out["rows"].append({"role": role, "html": html})
|
||
return out
|
||
|
||
|
||
# DOM 侧的字形码豁免(键 = 宿主 sig):写不进退出码的真例外,空表也要打印命中数,
|
||
# 免得哪天变成没人敢删的僵尸条目。
|
||
GLYPH_ALLOW = {}
|
||
|
||
# ── LOCALE 用:antd 内置件自己写的文案回落成英文时的那些原话(S-3 根因防线)。
|
||
# 名单来源:2026-11-08 用 node 打印 antd/lib/locale/{en_US,zh_CN} 对拼(`node -e` 见阶段 12 报告),
|
||
# 只留**上面 BUILTIN_SCOPE 作用域里真渲染得出来**的键。取值一律**精确匹配、大小写敏感**:
|
||
# 子串匹配会把业务数据(正文里的 `/api/meta`、模型代号)判成语言包缺陷,代价是这条闸被关掉。
|
||
# 右侧是它在 en_US 里的键路径——命中时打出来,人一眼能判断是哪一类组件在漏。
|
||
# 末尾**两条不是语言包键**:rc-input-number 把这两个 aria-label 写死在步进 `<span>` 上
|
||
# (`es/StepHandler.js:87`/`:97`,`zh_CN` 没有 `InputNumber` 段),阶段 12 立项时它们是
|
||
# 唯一的在册豁免,阶段 18 在 kit 层改名后豁免清空 ⇒ 必须搬进这张表,否则英文名不再命中。
|
||
LOCALE_EN = {
|
||
# Pagination:修好之前真页面上漏的就是这几条(/assets 分页器实测 title=Previous Page)
|
||
"Go to": "Pagination.jump_to",
|
||
"confirm": "Pagination.jump_to_confirm",
|
||
"Page": "Pagination.page",
|
||
"Page Size": "Pagination.page_size",
|
||
"Previous Page": "Pagination.prev_page",
|
||
"Next Page": "Pagination.next_page",
|
||
"Previous 5 Pages": "Pagination.prev_5",
|
||
"Next 5 Pages": "Pagination.next_5",
|
||
"Previous 3 Pages": "Pagination.prev_3",
|
||
"Next 3 Pages": "Pagination.next_3",
|
||
# Empty / Table(本项目 22 处 <Table> 有 14 处沿用 antd 默认空态,这条是真会渲染的)
|
||
"No data": "Empty.description · Table.emptyText",
|
||
"No filters": "Table.filterEmptyText",
|
||
"Filter menu": "Table.filterTitle",
|
||
"Select all items": "Table.filterCheckAll",
|
||
"Search in filters": "Table.filterSearchPlaceholder",
|
||
"Select current page": "Table.selectAll · Transfer.selectCurrent",
|
||
"Invert current page": "Table.selectInvert · Transfer.selectInvert",
|
||
"Clear all data": "Table.selectNone",
|
||
"Select all data": "Table.selectionAll · Transfer.selectAll",
|
||
"Expand row": "Table.expand",
|
||
"Collapse row": "Table.collapse",
|
||
"Click to sort descending": "Table.triggerDesc",
|
||
"Click to sort ascending": "Table.triggerAsc",
|
||
"Click to cancel sorting": "Table.cancelSort",
|
||
# Modal / Popconfirm / 表格筛选面板的按钮(本项目 kit Modal 恒传 footer,当前渲染不到;留作防线)
|
||
"OK": "Modal.okText · Popconfirm.okText · Table.filterConfirm",
|
||
"Cancel": "Modal.cancelText · Popconfirm.cancelText · Table.filterReset 同族",
|
||
"Reset": "Table.filterReset",
|
||
# 下面这几类组件本项目当前没用到,留着是为了哪天用上时不用重画名单
|
||
"Select date": "DatePicker.lang.placeholder",
|
||
"Select time": "TimePicker.placeholder",
|
||
"Start date": "DatePicker.lang.rangePlaceholder[0]",
|
||
"End date": "DatePicker.lang.rangePlaceholder[1]",
|
||
"Start time": "TimePicker.rangePlaceholder[0]",
|
||
"End time": "TimePicker.rangePlaceholder[1]",
|
||
"Today": "DatePicker.lang.today",
|
||
"Now": "DatePicker.lang.now",
|
||
"Clear": "DatePicker.lang.clear",
|
||
"Back to today": "DatePicker.lang.backToToday",
|
||
"Search here": "Transfer.searchPlaceholder",
|
||
"Remove": "Transfer.remove",
|
||
"Preview": "Image.preview",
|
||
"Next": "Tour.Next",
|
||
"Previous": "Tour.Previous",
|
||
"Finish": "Tour.Finish",
|
||
# 步进器那对(阶段 18 · S-3-2 收口):kit `components/ui/Input.tsx` 已把它们改成
|
||
# 「增加数值 / 减少数值」,真页面 0 命中;哪天改名失效或 antd 换写法,这里当场点名。
|
||
"Increase Value": "InputNumber.up handler(rc-input-number 写死,非 en_US 键)",
|
||
"Decrease Value": "InputNumber.down handler(rc-input-number 写死,非 en_US 键)",
|
||
}
|
||
# 取值带数字前缀的那一类:enUS `items_per_page = "/ page"`、zh_CN `"条/页"`,
|
||
# 渲染出来是「12 / page」/「12 条/页」,整串永远不相等 ⇒ 只能按后缀认。
|
||
LOCALE_EN_SUFFIX = [(" / page", "Pagination.items_per_page")]
|
||
# 在册豁免:**空表**(2026-11-09 阶段 18 清空 · 原因与修法见文档串 LOCALE 那一段)。
|
||
# 原来那两条(数字框的 Increase / Decrease Value)已经在 `components/ui/Input.tsx`
|
||
# 就地换成中文,真页面 0 命中 ⇒ 这里保持空表。真撞在业务值上时该改窄取值或收小
|
||
# 作用域,**不许**往这里加业务串——加了这条判据就只剩形式了。
|
||
LOCALE_EXEMPT: dict = {}
|
||
|
||
|
||
def locale_source(v):
|
||
"""这条文案是不是 antd 英文语言包里的原话;是的话返回它的键路径,否则空串。"""
|
||
v = (v or "").strip()
|
||
if v in LOCALE_EXEMPT:
|
||
return LOCALE_EXEMPT[v]
|
||
if v in LOCALE_EN:
|
||
return LOCALE_EN[v]
|
||
for suf, key in LOCALE_EN_SUFFIX:
|
||
if v.endswith(suf):
|
||
return key
|
||
return ""
|
||
|
||
|
||
def locale_exempt(v):
|
||
return (v or "").strip() in LOCALE_EXEMPT
|
||
|
||
|
||
def locale_offenders(builtins):
|
||
"""LOCALE 判据本体:antd 内置件吐出的英文文案 → 违规描述串(空表 = 这一页干净)。
|
||
|
||
抽成函数是给 gateprobe 直接 import 的——判据写在哪一层,反例就得造在哪一层
|
||
(§15.12)。名单、后缀、豁免三样都只在这里生效,别再在采集 JS 里判一遍。
|
||
"""
|
||
out = []
|
||
for b in builtins or []:
|
||
v = (b.get("v") or "").strip()
|
||
src = locale_source(v)
|
||
if not src or locale_exempt(v):
|
||
continue
|
||
out.append("%s=%s「%s」(%s · %s)" % (b.get("kind", "?"), b.get("part", ""), v, src, b.get("sig", "")))
|
||
return out
|
||
|
||
|
||
# 豁免: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) : '' });
|
||
}
|
||
/* 5b 整条名称只剩一个拉丁词。上面那条认的是「图标自己的 aria-label == 类名后缀」,
|
||
够不着这一形状:名字是按 contents 算出来的,字形码落在别个元素上
|
||
(antd 的溢出「…」修法之前就是这样,AT 念出来的就是 `ellipsis`)。
|
||
这里只交候选:名称必须**整条**是一个小写拉丁词,`/api/meta`、`Esc`、「导入脚本」
|
||
天然落榜;是不是真字形码由 Python 按登记表判,不在表里的词不立案。 */
|
||
const nameOnly = [];
|
||
for (const el of document.querySelectorAll(ROLE + ',' + NATIVE + ',[tabindex]')) {
|
||
if (!VIS(el) || hidden(el)) continue;
|
||
const nm = String(el.getAttribute('aria-label') || el.getAttribute('title')
|
||
|| el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();
|
||
if (!/^[a-z][a-z0-9-]{1,24}$/.test(nm)) continue;
|
||
nameOnly.push({ tok: nm, sig: sig(el), al: String(el.getAttribute('aria-label') || '').trim() });
|
||
}
|
||
|
||
/* 6b antd 内置件自己写的文案(LOCALE · S-3 根因防线)。三条口径写在文档串 LOCALE 那一段,
|
||
这里只落实「采什么」:作用域 → selfAnt → 三样写死的属性 + 两处它家自己画的文字。
|
||
**判定不在这里**(名单与精确匹配在 Python 侧的 locale_offenders),这里只交原料。 */
|
||
const BUILTIN_SCOPE = '.ant-pagination,.ant-select,.ant-select-dropdown,.ant-empty,'
|
||
+ '.ant-picker,.ant-table-filter,.ant-modal-footer,.ant-modal-confirm-btns,'
|
||
+ '.ant-input-number,.ant-transfer,.ant-image';
|
||
/* 可见性用的是 atReadable,不是 VIS:这条判据量的是**辅助技术读到的文案**,
|
||
不是像素上看得见的文案。antd 的步进器包在 opacity:0 的 handler-wrap 里(静止态藏起来,
|
||
悬停才显形),按 VIS 量整族采不到 ⇒ 步进器那颗名字无论中文英文都进不了扫描面,
|
||
这条闸对它就只剩形式(阶段 18 的中文改名正是靠 AT 口径才被量到的)。
|
||
display:none / visibility:hidden / aria-hidden 才是 AT 真读不到的形状。 */
|
||
const atReadable = (el) => {
|
||
const cs = getComputedStyle(el);
|
||
return cs.display !== 'none' && cs.visibility !== 'hidden' && !el.closest('[aria-hidden="true"],[hidden]');
|
||
};
|
||
const builtins = [];
|
||
const seenB = new Set();
|
||
const pushB = (kind, el, raw) => {
|
||
const v = String(raw === null || raw === undefined ? '' : raw).replace(/\s+/g, ' ').trim().slice(0, 40);
|
||
if (!v) return;
|
||
const part = cls(el).split(/\s+/).find((t) => /^(ant-|anticon)/.test(t)) || el.tagName.toLowerCase();
|
||
const dedup = kind + '|' + v + '|' + part; // 同一页几十颗同款控件只交一份
|
||
// 自家夹具不参与去重:真页面上同款控件排在前面会把夹具的 sig 抢先,
|
||
// 于是 seen 那条反向验证(「好形状必须仍然被采到」)成了假 FAIL。
|
||
if (seenB.has(dedup) && !/(^|[\s"])p[bg]-/.test(cls(el))) return;
|
||
seenB.add(dedup);
|
||
builtins.push({ kind, v, part, sig: sig(el) });
|
||
};
|
||
for (const scope of document.querySelectorAll(BUILTIN_SCOPE)) {
|
||
if (!atReadable(scope)) continue;
|
||
for (const el of [scope, ...scope.querySelectorAll('*')]) {
|
||
if (!selfAnt(el) || !atReadable(el)) continue; // 我们的标记与我们的数据一律不进
|
||
pushB('title', el, el.getAttribute('title'));
|
||
pushB('aria-label', el, el.getAttribute('aria-label'));
|
||
pushB('placeholder', el, el.getAttribute('placeholder'));
|
||
if (el.matches('.ant-empty-description')) pushB('text', el, el.innerText);
|
||
if (el.matches('.ant-modal-footer button, .ant-modal-confirm-btns button')) pushB('text', el, el.innerText);
|
||
}
|
||
}
|
||
|
||
/* 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) }));
|
||
|
||
/* FILE(阶段 35 · S-3):AT 读得到的 file input 有没有被我们自己具过名。
|
||
可见性沿用 atReadable(opacity:0 的 nex-file-input 也算 AT 读得到 —— 它恰恰是激活目标)。 */
|
||
const filepicks = [];
|
||
for (const el of document.querySelectorAll('input[type=file]')) {
|
||
if (!atReadable(el)) continue;
|
||
filepicks.push({ sig: sig(el), al: String(el.getAttribute('aria-label') || '').trim() });
|
||
}
|
||
return {
|
||
path: location.pathname,
|
||
filepicks,
|
||
hasLandmark: !!document.querySelector('main,[role="main"]'),
|
||
hotspots, tabTargets, broken, live, empties, skeletons, errors, tabs, current, glyphs, nameOnly, builtins,
|
||
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'),
|
||
/* offender 的可读位置:offender 报「div 焦点不可见」而不说哪一层,
|
||
等于把定位工作丢给下一个读日志的人(2026-11-08 阶段 11 实测就是这样)。
|
||
取「tag.第一个非 css-/ant- 类」往上三层,再加 24 字内容 —— 足够在页面上认出它。 */
|
||
path: (() => {
|
||
const seg = [];
|
||
for (let n = el, i = 0; n && n.nodeType === 1 && i < 3; n = n.parentElement, i++) {
|
||
const k = (typeof n.className === 'string' ? n.className : '')
|
||
.split(/\s+/).filter(x => x && !/^css-/.test(x))[0] || '';
|
||
seg.unshift(n.tagName.toLowerCase() + (k ? '.' + k : ''));
|
||
}
|
||
const txt = (el.innerText || el.textContent || '').trim().slice(0, 24);
|
||
return seg.join(' > ') + (txt ? ' 「' + txt + '」' : '');
|
||
})() };
|
||
}"""
|
||
|
||
# 走位净场用:当前有几层浮层可能带着焦点陷阱(抽屉 / 模态 / 下拉 / 浮层 / 菜单)。
|
||
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 settle_layers(page, limit=3):
|
||
"""撤掉**探针自己**掀开的浮层,别让它污染后面几步的测量(2026-11-08 · 阶段 11)。
|
||
|
||
为什么现在必须有这一步:顶栏那颗项目概况胶囊(`button.nex-console`)从阶段 11 起
|
||
悬停 300 ms 就展开「项目概况」抽屉,而这只抽屉是**带遮罩的模态**——遮罩盖住整页,
|
||
`.ant-drawer` 子树把 header 上所有控件的 pointer events 都截走。
|
||
于是本闸自己的动作顺序变成了自我妨碍:resolve_ref 为了唤出胶囊那句 aria-describedby
|
||
悬停它 → 450 ms 等待里抽屉开了 → 鼠标移开也不会自动收(既定设计:移出不关)→
|
||
后面每一次 hover / click 全落在遮罩上:
|
||
· 主题按钮的 Tooltip 唤不出来 → 误报「aria-describedby 悬空」14 条;
|
||
· library 页签点不动 → 误报「role=tab 鼠标点不动(页签不可用?)」;
|
||
· Tab 走位掉进抽屉的焦点陷阱 → 覆盖率与「绕回起点」一起失真;
|
||
· 430 档最惨:汉堡那一步直接 30s TimeoutError 把整闸打断
|
||
(`/tmp/p11-sema430.log`:`<div class="ant-drawer-mask"></div> … subtree intercepts
|
||
pointer events`,退出码 1 是 traceback 不是「1 条 offender」)。
|
||
这不是页面坏了,是**量具把被测物推进了一个模态态里**,然后照着模态态打分。
|
||
收法只有一条:谁掀的开谁收——Esc 撤到没有浮层为止,再把鼠标停回左上角。
|
||
这里不负责「进页面时就有浮层」:那是页面自己的状态,走位前那一步净场
|
||
(LAYERS_JS + Escape 循环)已经在管,两处判据不重复、也不互相顶包。
|
||
"""
|
||
n = 0
|
||
for _ in range(limit):
|
||
try:
|
||
if not page.evaluate(LAYERS_JS):
|
||
break
|
||
page.keyboard.press("Escape")
|
||
except Exception:
|
||
break
|
||
page.wait_for_timeout(320)
|
||
n += 1
|
||
try:
|
||
page.mouse.move(2, 2)
|
||
except Exception:
|
||
pass
|
||
return n
|
||
|
||
|
||
def resolve_ref(page, item):
|
||
"""唤出引用 + 收尾净场:任何一条返回路径都不能把浮层留给下一步。"""
|
||
try:
|
||
return _summon_ref(page, item)
|
||
finally:
|
||
settle_layers(page)
|
||
|
||
|
||
def _summon_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
|
||
|
||
|
||
# ══════════════════ TABKBD(阶段 9 · S-3:窄屏溢出页签的纯键盘通道)══════════════════
|
||
#
|
||
# 为什么单独一条:430 这一档 rc-tabs 会把放不下的页签收进「更多」按钮,被裁那颗
|
||
# 本体还留在 DOM 里(rect 完整、vis=visible),所以**源码字符串和 AX 树都看不出问题**,
|
||
# 上一轮的 click_tab 也只证明「鼠标点得着」。真正的风险是键盘:
|
||
# · 那颗触发器是不是在 Tab 序列里(放不上 = 整条溢出路径对键盘用户不存在);
|
||
# · 它有没有可读名称(antd 的 MoreProps 只给 `icon` 一个口子,本项目的 aria-label 挂在
|
||
# 内层图标上,名称靠 name-from-contents 算出来 → 只能问 CDP 的 AX 树,读 DOM 属性必漏);
|
||
# · aria-expanded 有没有跟着开合(写了不动 = AT 用户永远以为菜单是关的);
|
||
# · 方向键 + Enter 能不能真的把被裁那颗选中(面板挂出来、aria-selected 搬过来);
|
||
# · 菜单里是不是**每一颗**被裁页签都在(少一颗就是窄屏把业务数据弄丢了)。
|
||
# 实测口径(rc-tabs 15.7.0 / antd 5.29.3):触发器是原生 <button aria-haspopup="listbox">,
|
||
# 打开后再按一下方向键才落到第一项(首按只负责展开,selectedKey 还是 null,
|
||
# 此时按 Enter 是空操作)——判据照这个真实形状走位,不按「理想 ARIA」凭空断言。
|
||
TABKBD_MARK = """() => {
|
||
const lists = [...document.querySelectorAll('[role=tablist]')];
|
||
lists.forEach((list, i) => {
|
||
const nav = list.closest('.ant-tabs') || list;
|
||
const more = nav.querySelector('.ant-tabs-nav-more');
|
||
if (more) more.setAttribute('data-nex-more', String(i));
|
||
const act = nav.querySelector('.ant-tabs-tab-active .ant-tabs-tab-btn')
|
||
|| list.querySelector('[role=tab][aria-selected=true]');
|
||
if (act) act.setAttribute('data-nex-kb', String(i));
|
||
});
|
||
return lists.length;
|
||
}"""
|
||
|
||
TABKBD_STATE = """() => {
|
||
const out = [];
|
||
[...document.querySelectorAll('[role=tablist]')].forEach((list, i) => {
|
||
const nav = list.closest('.ant-tabs') || list;
|
||
const wrap = nav.querySelector('.ant-tabs-nav-wrap') || nav;
|
||
const wr = wrap.getBoundingClientRect();
|
||
const tabs = [...list.querySelectorAll('[role=tab]')].map((el) => {
|
||
const r = el.getBoundingClientRect();
|
||
return { text: (el.textContent || '').trim().slice(0, 20),
|
||
sel: el.getAttribute('aria-selected'),
|
||
dis: el.getAttribute('aria-disabled'),
|
||
ctrl: el.getAttribute('aria-controls'),
|
||
clipped: (r.width < 1 || r.right > wr.right + 2 || r.left < wr.left - 2) };
|
||
});
|
||
const more = nav.querySelector('.ant-tabs-nav-more');
|
||
out.push({ i: i, n: tabs.length, tabs: tabs,
|
||
more: more ? { tag: more.tagName, ti: more.getAttribute('tabindex'),
|
||
role: more.getAttribute('role'),
|
||
expanded: more.getAttribute('aria-expanded'),
|
||
popup: more.getAttribute('aria-haspopup'),
|
||
w: Math.round(more.getBoundingClientRect().width) } : null });
|
||
});
|
||
return out;
|
||
}"""
|
||
|
||
TABKBD_MENU = """() => {
|
||
const dd = document.querySelector('.ant-tabs-dropdown:not(.ant-tabs-dropdown-hidden)');
|
||
const items = dd ? [...dd.querySelectorAll('.ant-tabs-dropdown-menu-item')] : [];
|
||
const on = items.find((x) => x.getAttribute('aria-selected') === 'true');
|
||
return { open: !!dd,
|
||
texts: items.map((x) => (x.textContent || '').trim().slice(0, 20)),
|
||
selText: on ? (on.textContent || '').trim().slice(0, 20) : null,
|
||
role: dd ? (dd.querySelector('[role=listbox]') ? 'listbox' : null) : null };
|
||
}"""
|
||
|
||
TABKBD_AFTER = """(a) => {
|
||
const list = document.querySelectorAll('[role=tablist]')[a.i];
|
||
const nav = list.closest('.ant-tabs') || list;
|
||
const on = [...list.querySelectorAll('[role=tab][aria-selected=true]')];
|
||
const t = on[0];
|
||
return { selText: t ? (t.textContent || '').trim().slice(0, 20) : null,
|
||
onCount: on.length,
|
||
panel: (t && t.getAttribute('aria-controls'))
|
||
? !!document.getElementById(t.getAttribute('aria-controls')) : null,
|
||
expanded: nav.querySelector('.ant-tabs-nav-more')
|
||
? nav.querySelector('.ant-tabs-nav-more').getAttribute('aria-expanded') : null };
|
||
}"""
|
||
|
||
# 焦点看不看得见:只比这颗按钮自己(antd 给 tabs 溢出按钮的焦点皮肤是 outline,
|
||
# 实测 light #1677FF / dark #1668DC;上一轮 FOCUS 判据那套「查五层包裹 + 两个兄弟」
|
||
# 是给「变化藏在第 3~4 层」的输入类控件准备的,这里用不上,也不该顺手动它)。
|
||
TABKBD_RING = """(a) => {
|
||
const m = document.querySelector(`[data-nex-more="${a.i}"]`);
|
||
if (!m) return null;
|
||
const c = getComputedStyle(m);
|
||
return { ow: c.outlineWidth, os: c.outlineStyle, oc: c.outlineColor,
|
||
sh: c.boxShadow.slice(0, 60), bg: c.backgroundColor,
|
||
fv: m.matches(':focus-visible') };
|
||
}"""
|
||
|
||
|
||
def ax_button_name(cdp, selector):
|
||
"""问辅助技术:这颗元素到底叫什么。返回字符串(可能为空),CDP 失败返回 None。"""
|
||
try:
|
||
doc = cdp.send("DOM.getDocument", {"depth": 1})
|
||
nid = cdp.send("DOM.querySelector",
|
||
{"nodeId": doc["root"]["nodeId"], "selector": selector}).get("nodeId")
|
||
if not nid:
|
||
return None
|
||
bid = cdp.send("DOM.describeNode", {"nodeId": nid})["node"]["backendNodeId"]
|
||
for n in cdp.send("Accessibility.queryAXTree",
|
||
{"backendNodeId": bid}).get("nodes", []):
|
||
if n.get("ignored"):
|
||
continue
|
||
if ((n.get("role") or {}).get("value") or "") == "button":
|
||
return ((n.get("name") or {}).get("value") or "").strip()
|
||
return ""
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def tab_kbd_check(page, cdp, tag, offenders, coverage):
|
||
"""溢出页签的键盘通道。返回 {'lists': 有溢出的条带数, 'picked': 键盘选中成功数}。"""
|
||
stat = {"lists": 0, "picked": 0, "clipped": 0}
|
||
try:
|
||
page.evaluate(TABKBD_MARK)
|
||
lists = page.evaluate(TABKBD_STATE)
|
||
except Exception:
|
||
return stat
|
||
for lst in lists:
|
||
clipped = [t for t in lst["tabs"] if t["clipped"] and t["sel"] != "true"]
|
||
if not clipped:
|
||
continue # 这一档放得下:没有溢出就没有这条判据要说的话
|
||
stat["lists"] += 1
|
||
stat["clipped"] += len(clipped)
|
||
i = lst["i"]
|
||
more = lst["more"]
|
||
if not more:
|
||
offenders.append("TABKBD %s 页签 %d 颗被裁进可视条带外(%s),却找不到「更多」触发器"
|
||
% (tag, len(clipped), " / ".join(t["text"] for t in clipped)))
|
||
continue
|
||
# ① 触发器必须是可聚焦控件:原生 button/a **且没被 tabindex=-1 踢出 Tab 序列**,
|
||
# 或 role=button 且显式给了 tabindex>=0。
|
||
# 为什么要连 tabindex 一起看(2026-11-08 · 反向验证补的洞):这一条原先只认标签名,
|
||
# gateprobe 的负向夹具把 rc-tabs 那颗真 button 改成 tabindex=-1 时它放行了,
|
||
# 缺陷是靠第④步「按 Tab 四下没落到它」才响的——报出来的话是「键盘到不了」,
|
||
# 真正的病灶(有人给它铺了 tabindex=-1)得人去翻。早一步点名,话说得准,
|
||
# 也不必先按四轮 Tab。
|
||
ti = more["ti"]
|
||
focusable = ((more["tag"] in ("BUTTON", "A") and ti != "-1")
|
||
or (more["role"] == "button" and ti is not None and ti != "-1"))
|
||
if not focusable:
|
||
offenders.append("TABKBD %s 溢出触发器 %s 不可聚焦(tabindex=%s role=%s):键盘走不到溢出页签"
|
||
% (tag, more["tag"], more["ti"], more["role"]))
|
||
continue
|
||
# ② 辅助技术里的名称:非空、且不是字形码(S-2 的口径在这颗上单独钉一遍,
|
||
# 因为它的名称来自内层图标,删掉那句 aria-label 后按钮会变成「未命名按钮」)
|
||
name = ax_button_name(cdp, '[data-nex-more="%s"]' % i)
|
||
if name is None:
|
||
offenders.append("TABKBD %s 溢出触发器读不到 AX 名称(CDP 失败)" % tag)
|
||
elif not name:
|
||
offenders.append("TABKBD %s 溢出触发器在辅助技术里没有名字(读作「未命名按钮」)" % tag)
|
||
elif any(tok in name.lower() for tok in GLYPH_TOKENS):
|
||
offenders.append("TABKBD %s 溢出触发器名称混进字形码:%s" % (tag, name))
|
||
# ③ 声明:haspopup + 初始 expanded=false
|
||
if more["popup"] != "listbox":
|
||
offenders.append("TABKBD %s 溢出触发器 aria-haspopup=%s(菜单是 listbox,声明要一致)"
|
||
% (tag, more["popup"]))
|
||
if more["expanded"] != "false":
|
||
offenders.append("TABKBD %s 溢出触发器未展开时 aria-expanded=%s(应为 false)"
|
||
% (tag, more["expanded"]))
|
||
# ④ 真按键:从选中那颗页签按 Tab 必须落到触发器(= 它真的在 Tab 序列里)
|
||
try:
|
||
page.evaluate("() => { const e = document.querySelector('[data-nex-kb=\"%d\"]');"
|
||
" if (e) e.focus(); }" % i)
|
||
except Exception:
|
||
continue
|
||
reached = 0
|
||
for _ in range(4):
|
||
page.keyboard.press("Tab")
|
||
page.wait_for_timeout(180)
|
||
reached = page.evaluate(
|
||
"() => !!(document.activeElement && document.activeElement.closest('[data-nex-more]'))")
|
||
if reached:
|
||
break
|
||
if not reached:
|
||
offenders.append("TABKBD %s 从选中页签按 Tab 4 下没落到「更多」触发器:溢出页签键盘到不了" % tag)
|
||
continue
|
||
# ⑤ 焦点可见
|
||
ring = page.evaluate(TABKBD_RING, {"i": i}) or {}
|
||
if ring.get("os") in (None, "none") and ring.get("sh") in (None, "none"):
|
||
offenders.append("TABKBD %s Tab 停在「更多」触发器上没有任何焦点描边/外发光:看不见焦点" % tag)
|
||
# ⑥ 开菜单 → 逐颗键盘选中被裁页签 → Esc 关闭
|
||
page.keyboard.press("Escape") # 清掉可能残留的上一轮菜单
|
||
page.wait_for_timeout(200)
|
||
page.keyboard.press("ArrowDown")
|
||
page.wait_for_timeout(450)
|
||
m = page.evaluate(TABKBD_MENU)
|
||
if not m.get("open"):
|
||
offenders.append("TABKBD %s 焦点在触发器上按 ↓ 没有展开溢出菜单" % tag)
|
||
continue
|
||
if m.get("role") != "listbox":
|
||
offenders.append("TABKBD %s 溢出菜单 role=%s,与触发器声明的 aria-haspopup=listbox 不一致"
|
||
% (tag, m.get("role")))
|
||
missing = [t["text"] for t in clipped if t["text"] not in m["texts"]]
|
||
if missing:
|
||
offenders.append("TABKBD %s 被裁页签 %s 不在溢出菜单里:窄屏把页签弄丢了"
|
||
% (tag, " / ".join(missing)))
|
||
# 逐颗真选中。不写死「第 k 项按 k 下」:Enter 之后 rc-tabs 不一定关菜单,
|
||
# 而刚选上那颗已经从溢出名单里搬走、菜单会缩短——按死下标必然对不上。
|
||
# 改成「按 ↓ 一路找,找到那颗为止」,走的仍是纯键盘通道,但不依赖实现细节。
|
||
for target in [t for t in clipped if t["text"] in m["texts"]]:
|
||
cur = page.evaluate(TABKBD_MENU)
|
||
if not cur.get("open"):
|
||
page.keyboard.press("ArrowDown") # 关掉的话重新展开(首按只负责展开)
|
||
page.wait_for_timeout(400)
|
||
cur = page.evaluate(TABKBD_MENU)
|
||
hit = False
|
||
for _ in range(len(cur.get("texts") or [""]) + 1):
|
||
if cur.get("selText") == target["text"]:
|
||
hit = True
|
||
break
|
||
page.keyboard.press("ArrowDown")
|
||
page.wait_for_timeout(180)
|
||
cur = page.evaluate(TABKBD_MENU)
|
||
if not cur.get("open"):
|
||
break
|
||
if not hit:
|
||
offenders.append("TABKBD %s 溢出菜单里用方向键找不到「%s」(菜单现有 %s)"
|
||
% (tag, target["text"], " / ".join(cur.get("texts") or []) or "空"))
|
||
continue
|
||
page.keyboard.press("Enter")
|
||
page.wait_for_timeout(700)
|
||
af = page.evaluate(TABKBD_AFTER, {"i": i})
|
||
if af.get("selText") != target["text"]:
|
||
offenders.append("TABKBD %s 键盘选中「%s」后 aria-selected 停在「%s」:选中态没跟上"
|
||
% (tag, target["text"], af.get("selText")))
|
||
elif af.get("panel") is not True:
|
||
offenders.append("TABKBD %s 键盘选中「%s」后 aria-controls 指向的面板不存在"
|
||
% (tag, target["text"]))
|
||
elif af.get("onCount") != 1:
|
||
offenders.append("TABKBD %s 键盘选中后 aria-selected=true 有 %d 颗(应为 1)"
|
||
% (tag, af.get("onCount")))
|
||
else:
|
||
stat["picked"] += 1
|
||
page.keyboard.press("Escape")
|
||
page.wait_for_timeout(300)
|
||
af = page.evaluate(TABKBD_AFTER, {"i": i})
|
||
if af.get("expanded") != "false":
|
||
offenders.append("TABKBD %s Esc 关不掉溢出菜单:aria-expanded=%s" % (tag, af.get("expanded")))
|
||
print(" TABKBD %s 页签 %d 颗 · 被裁 %d 颗 · 名称「%s」· 键盘选中成功 %d 颗"
|
||
% (tag, lst["n"], len(clipped), name or "?", stat["picked"]))
|
||
try:
|
||
page.evaluate("() => document.querySelectorAll('[data-nex-more],[data-nex-kb]')"
|
||
".forEach(n => { n.removeAttribute('data-nex-more');"
|
||
" n.removeAttribute('data-nex-kb') })")
|
||
except Exception:
|
||
pass
|
||
return stat
|
||
|
||
|
||
def main() -> int:
|
||
offenders = []
|
||
coverage = []
|
||
soft = {}
|
||
seen = {}
|
||
nav_names = {}
|
||
lone = {}
|
||
ax_glyph = {}
|
||
ax_name_cand = ax_name_hit = 0 # GLYPH 5b:整条名称 = 字形码(AT 层)的候选 / 命中
|
||
# GLYPH 5c(阶段 23 · S-2 收口):AT 树里没被忽略的图形必须中文报名
|
||
axg_seen = axg_bad = axg_unresolved = 0
|
||
# GLYPH 5d(阶段 34 · S-2 宿主级):AT 看得见的操作控件整条名称为空、里面只剩图标
|
||
axd_seen = axd_bad = axd_plain = axd_unresolved = 0
|
||
# FILE 累计(阶段 35 · S-3):扫到几颗 AT 读得到的文件选择控件 / 几颗名字不合格
|
||
# / AX 名称里渗进原生英文文案的节点数。0 也要报,否则这条闸会安静地空转。
|
||
fp_seen = fp_bad = fp_ua = 0
|
||
# TABKBD 累计:跑完这一趟有没有真的遇见过溢出页签。0 也要说出来(见末尾覆盖说明)。
|
||
tabkbd = {"lists": 0, "picked": 0, "clipped": 0}
|
||
# LOCALE 累计:扫描面(采到几处内置文案 / 几种取值)、英文命中数、在册豁免命中数。
|
||
locale_seen = locale_hit = locale_exempt_n = 0
|
||
locale_values = set()
|
||
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
|
||
# TABKBD(阶段 9 · S-3):上面那条鼠标通道只证明「点得着」。被 rc-tabs
|
||
# 裁进「更多」的那几颗,键盘走不走得到、菜单里少不少一颗、焦点看不看得见,
|
||
# 全部由这一条用真按键验。必须排在鼠标通道之后:它要用进页时那颗选中态做起点。
|
||
kb = tab_kbd_check(page, cdp, tag, offenders, coverage)
|
||
for k in ("lists", "picked", "clipped"):
|
||
tabkbd[k] += kb[k]
|
||
if back and kb["picked"] 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
|
||
ax_c = ax_h = 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 "(宿主只有这颗图标)"))
|
||
# 5b:控件整条可读名称就是一个字形码(AT 层,上面那条 DOM 判据够不着)
|
||
for c in d.get("nameOnly", []):
|
||
if not whole_glyph_name(c["tok"]):
|
||
continue
|
||
ax_h += 1
|
||
offenders.append(
|
||
"GLYPH %s 控件整条可读名称就是图标字形码「%s」:%s"
|
||
" —— 读屏念的是字形英文名,不是这条操作叫什么"
|
||
% (tag, c["tok"], c["sig"]))
|
||
ax_c = len(d.get("nameOnly", []))
|
||
ax_name_cand += ax_c
|
||
ax_name_hit += ax_h
|
||
if d["glyphs"] or d.get("nameOnly"):
|
||
print(" GLYPH %-21s 可见图标 %2d · 外泄 %d / 遮蔽 %d / 无宿主 %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,
|
||
len(d.get("nameOnly", [])),
|
||
sum(1 for c in d.get("nameOnly", []) if whole_glyph_name(c["tok"]))))
|
||
# 交叉核对:AX 树里辅助技术真读到的名称 vs 登记表字形码(只打印,不立案)
|
||
if names and GLYPH_TOKENS:
|
||
for n in names:
|
||
low = n["name"].lower()
|
||
if whole_glyph_name(low):
|
||
# AT 读到的整条名称就是一个字形码 —— DOM 侧那条可能因为
|
||
# 名字不在 `.anticon` 上而看不见(antd 自己的部件就是这种形状),
|
||
# 所以这一支必须自己立案,不能再只打印。
|
||
offenders.append(
|
||
"GLYPH %s AX 树里辅助技术读到的整条名称就是字形码「%s」"
|
||
"(role=%s)—— 该操作对读屏没有中文名" % (tag, low, n["role"]))
|
||
continue
|
||
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
|
||
|
||
# GLYPH 5c(阶段 23 · S-2 收口):**AT 树里看得见的图标图形必须中文报名**。
|
||
# 前三支量的是「名字挂在 .anticon 上写错了」与「交互元素的整条名称是字形码」,
|
||
# 漏了这一族:宿主已经具名(「增加数值」/「上一页」),可图形自己那颗
|
||
# `role=img aria-label="up|down|left|right"` 仍是 AX 树里一个独立对象
|
||
# ——读屏念完宿主再补一句英文字形码。阶段 23 全站 AT 侧实测 72 条
|
||
# (`reports/ui_evidence/nex-p23/predis/`),`ax_names()` 只收 INTERACTIVE 角色,
|
||
# 一条都看不见;登记表名单又是语义别名(chevron-left),撞不中字形本名(left)。
|
||
graphics = ax_graphic_nodes(cdp)
|
||
if graphics is None:
|
||
offenders.append("GLYPH %s AX 树读不到(CDP 失败)—— 图形一支这一页没量到" % tag)
|
||
else:
|
||
axg_unresolved += graphics["unresolved"]
|
||
for g in graphics["rows"]:
|
||
axg_seen += 1
|
||
bad = ax_graphic_zh_defect(g["name"], g["html"])
|
||
if not bad:
|
||
continue
|
||
axg_bad += 1
|
||
offenders.append(
|
||
"GLYPH %s AT 看得见的图标图形没有中文名称:整条名称=「%s」 :: %s"
|
||
" —— 宿主具名就让图形 aria-hidden,要报名就得说中文"
|
||
% (tag, bad, g["html"].replace("\n", " ")[:120]))
|
||
|
||
# GLYPH 5d(阶段 34 · S-2 宿主级收口):**撤了图标名,宿主必须自己报名**。
|
||
# 这一族只在 AX 层存在:图标 `aria-hidden` 之后 DOM 上看不到任何「名字写错」
|
||
# 的痕迹,5a/5b/5c 三支全绿,读屏念出来却是「按钮」两个字(或干脆什么都不念)。
|
||
hosts = ax_nameless_actors(cdp)
|
||
if hosts is None:
|
||
offenders.append("GLYPH %s AX 树读不到(CDP 失败)—— 无名宿主一支这一页没量到" % tag)
|
||
else:
|
||
axd_unresolved += hosts["unresolved"]
|
||
for h in hosts["rows"]:
|
||
axd_seen += 1
|
||
glyph = nameless_icon_host(h["html"])
|
||
if not glyph:
|
||
axd_plain += 1 # 无名但没图标:归常驻 NAME 闸,不在这里重复立案
|
||
continue
|
||
axd_bad += 1
|
||
offenders.append(
|
||
"GLYPH %s 辅助技术看得见这颗 %s,但整条可读名称为空、里面只有图标"
|
||
"「%s」 :: %s —— decorative() 撤掉字形名之后,这条操作对读屏就没有名字了"
|
||
% (tag, h["role"], glyph, h["html"].replace("\n", " ")[:120]))
|
||
|
||
# FILE(阶段 35 · S-3):文件选择控件的中文名称 + 原生英文文案外泄。
|
||
for f in d.get("filepicks", []):
|
||
fp_seen += 1
|
||
bad = file_name_defect(f["al"])
|
||
if bad:
|
||
fp_bad += 1
|
||
offenders.append("FILE %s %s:%s" % (tag, f["sig"], bad))
|
||
for nm in (names or []):
|
||
raw = nm.get("name") or ""
|
||
leak = [u for u in UA_NATIVE_FILE if u in raw]
|
||
if leak:
|
||
fp_ua += 1
|
||
offenders.append(
|
||
"FILE %s 浏览器原生文件控件文案%s出现在辅助技术名称里(role=%s · 名称=%s)"
|
||
" —— 读屏在中文界面上会念出一段英文" % (tag, "/".join(leak), nm.get("role"), raw[:60]))
|
||
|
||
# LOCALE:antd 内置件自己写的文案有没有回落成英文(S-3 根因防线)。
|
||
# 语言包坏掉是静默回落,别的判据看不出来,这里必须自己数、自己报扫描面。
|
||
builtins = d.get("builtins", [])
|
||
l_hits = locale_offenders(builtins)
|
||
locale_seen += len(builtins)
|
||
locale_hit += len(l_hits)
|
||
locale_exempt_n += sum(1 for b in builtins
|
||
if locale_source(b["v"]) and locale_exempt(b["v"]))
|
||
for b in builtins:
|
||
locale_values.add("%s=%s" % (b["kind"], b["v"]))
|
||
for h in l_hits:
|
||
offenders.append(
|
||
"LOCALE %s antd 内置文案是英文:%s"
|
||
" —— 中文语言包没生效,读屏与 hover 提示都会念英文" % (tag, h))
|
||
if l_hits:
|
||
print(" LOCALE %-21s 内置文案 %2d 处 · 英文 %d 条:%s"
|
||
% (tag, len(builtins), len(l_hits), "; ".join(l_hits)))
|
||
|
||
# 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 all(x[0] != f["sig"] for x in invisible):
|
||
invisible.append((f["sig"], f.get("path", "")))
|
||
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_, pth in sorted(set(invisible)):
|
||
offenders.append("FOCUS %s %s%s 焦点不可见:描边、外发光、边框、底色在聚焦前后一模一样"
|
||
% (tag, r_, ("(位置 %s)" % pth) if pth else ""))
|
||
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 名字一起断言,而不是绕过它。
|
||
# 汉堡这一步单独再净一次场:点的是 header 左端那颗按钮,现场只要还剩一只带遮罩的抽屉
|
||
# (阶段 11 起悬停胶囊就会展开概况抽屉),click 会被 .ant-drawer-mask 拦住并 30s 超时
|
||
# ——上一轮 430 档就是这么崩的(`/tmp/p11-sema430.log`:subtree intercepts pointer events)。
|
||
settle_layers(page)
|
||
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 目录里的 %d 个 .ts);DOM 侧立案判据不依赖这张表"
|
||
% (len(GLYPH_TOKENS), REGISTRY.name, len(list(REGISTRY.glob("*.ts")))))
|
||
if tabkbd["lists"]:
|
||
coverage.append("TABKBD 溢出条带 %d 处 / 被裁页签 %d 颗 / 纯键盘选中成功 %d 颗"
|
||
"(视口 %d;Tab→↓→↓→↵→Esc 全程真按键)"
|
||
% (tabkbd["lists"], tabkbd["clipped"], tabkbd["picked"], WIDTH))
|
||
else:
|
||
coverage.append("TABKBD 本次视口 %d 没有任何页签被裁进「更多」溢出菜单 —— 这条判据空转,"
|
||
"要咬得住必须 NEX_WIDTH=430 再跑一遍(/models、/projects/{id}/library 实测溢出)"
|
||
% WIDTH)
|
||
coverage.append("GLYPH AT 可见图形(未忽略 · 名称非空 · DOM 带 anticon)%d 颗,其中整条名称无汉字 %d 颗"
|
||
"(CDP 对不上号的图形 %d 颗已计入「没量到」,不当通过)%s"
|
||
% (axg_seen, axg_bad, axg_unresolved,
|
||
"命中即立案" if axg_bad else "本遍无命中 —— 0 也要报,这条不许悄悄空转"))
|
||
coverage.append("GLYPH AT 可见但名称为空的操作控件 %d 颗:里面有图标(S-2 宿主级缺名)%d 颗、"
|
||
"无图标交还 NAME 闸 %d 颗(CDP 对不上号 %d 颗计入「没量到」,不当通过)%s"
|
||
% (axd_seen, axd_bad, axd_plain, axd_unresolved,
|
||
"命中即立案" if axd_bad else "本遍无命中 —— 0 也要报,这条不许悄悄空转"))
|
||
coverage.append("GLYPH 在册豁免 %d 条%s"
|
||
% (len(GLYPH_ALLOW), (":" + " / ".join(GLYPH_ALLOW)) if GLYPH_ALLOW else "(空表)"))
|
||
coverage.append("GLYPH 名称整体=单个拉丁词的交互元素 %d 个,其中整条名称就是登记表字形码 %d 个"
|
||
"(%s;0 也要报,这条不许悄悄空转)"
|
||
% (ax_name_cand, ax_name_hit,
|
||
"命中即立案" if ax_name_hit else "本遍无命中"))
|
||
coverage.append("FILE AT 读得到的文件选择控件 %d 颗,其中名称不合格 %d 颗;"
|
||
"辅助技术名称里渗进浏览器原生英文文案 %d 处%s"
|
||
% (fp_seen, fp_bad, fp_ua,
|
||
"命中即立案" if (fp_bad or fp_ua)
|
||
else "本遍无命中 —— 0 也要报,这条不许悄悄空转"))
|
||
coverage.append("LOCALE 扫描 antd 内置件文案 %d 处、%d 种取值;英文命中 %d · 在册豁免 %d%s"
|
||
"(0 也要报,这条不许悄悄空转)"
|
||
% (locale_seen, len(locale_values), locale_hit, locale_exempt_n,
|
||
":" + " / ".join(sorted(LOCALE_EXEMPT)) if LOCALE_EXEMPT else "(空表)"))
|
||
coverage.append("LOCALE 实际读到的取值:%s"
|
||
% (" / ".join(sorted(locale_values)[:24]) or "(一个都没采到 —— 作用域或 selfAnt 口径变了)"))
|
||
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())
|