579 lines
32 KiB
Python
579 lines
32 KiB
Python
#!/usr/bin/env python3
|
||
# ⚠ 已作废(2026-11-03 antd 重写):本脚本量的是**手写规范**那套自造尺子
|
||
# (--ctl-h / --fs-* / 词汇表用词),尺子本身已随 theme/{metrics,palette,css-vars}.ts 删除。
|
||
# 现行两道闸:`node scripts/ui/classaudit.mjs`(源码用词)+
|
||
# `.venv/bin/python scripts/ui/visualcheck.py`(渲染结果)。口径见 docs/UI规范.md §15。
|
||
"""前端体检跑批器:对齐 / 裸控件 / 高度档位 / 横向溢出 / 浮层,一条命令出结论。
|
||
|
||
技术栈:React 18 + Ant Design 5 + Vite + Zustand + React Router 6。
|
||
度量口径只有一份,住在同目录的 metrics.py(怎么算错位、什么算控件都改那里)。
|
||
|
||
.venv/bin/python -u scripts/ui/audit.py # 1440 · 明暗 · 全部页面
|
||
.venv/bin/python -u scripts/ui/audit.py --width 1280 900 # 多档宽度
|
||
.venv/bin/python -u scripts/ui/audit.py --only overlay # 只量抽屉/弹窗
|
||
.venv/bin/python -u scripts/ui/audit.py --theme dark --shots .local/ui-audit
|
||
NEX_UI_BASE=http://localhost:4173 .venv/bin/python -u scripts/ui/audit.py # 量构建产物
|
||
|
||
结论口径:
|
||
· naked(裸的原生 input/select/textarea)必须 0;
|
||
· misaligned(同一视觉盒子里字段列线错开 >1px、行内标签中心线与控件错开)必须 0;
|
||
· 控件高度只准 antd 的三档 24 / 32 / 40(theme/antd.ts 不改几何,尺子只有一把);
|
||
视口 ≤560px 仍然单独量一轮(窄屏堆叠与抽屉宽度只在那一档暴露),准的是同一把尺子;
|
||
内容自定的盒子(整卡热区、缩略图角标、图标位)不在档位里,
|
||
必须写进下面的 EXPECTED 白名单并给理由——白名单里出现「没命中」的条目同样报出来,
|
||
免得规范修好了、白名单还留着当遮羞布;
|
||
白名单认的是 kit 组件打的标记类(nex-tile / nex-stat / nex-media-remove …),
|
||
不再是「button.flex.items-center.gap-2.5」这种从页面上抄来的类名切片:
|
||
以前页面自己拼皮肤,白名单就得跟着抄类名,kit 改一个 utility 规则整条静默失效;
|
||
标记类由组件自己盖在 class 首位,组件在场规则就命中,组件删了规则就失效报错。
|
||
· 横向溢出同理:真溢出修掉,故意逃出裁剪的(absolute/fixed)由口径豁免,剩下的进白名单;
|
||
· 下拉浮层必须宽度 ≥ 触发器、完整落在视口内、选项文字不换行不裁切,
|
||
且中心点真的盖在最上面(elementFromPoint 命中自己)——被抽屉裁掉时几何照样正常;
|
||
· 被量的那块浮层表面必须在视口内且没被盖住:就地渲染(getContainer={false})的抽屉
|
||
是相对文档定位的,页面一滚整块就跑出视口,元素几何全绿而用户什么也看不见。
|
||
退出码:0 = 干净;1 = 有未解释项或白名单失效。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import asyncio
|
||
import collections
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||
|
||
from playwright.async_api import async_playwright # noqa: E402
|
||
import metrics as M # noqa: E402
|
||
|
||
BASE = os.environ.get("NEX_UI_BASE", "http://localhost:5173")
|
||
LOGIN = ("admin", "admin1234")
|
||
# 样例项目:有分镜、有素材、有流程数据,量出来的才是有内容的页面
|
||
PROJ = os.environ.get("NEX_UI_PROJECT", "10")
|
||
|
||
ROUTES = [
|
||
("dashboard", "/dashboard"),
|
||
("models", "/models"),
|
||
("assets", "/assets"),
|
||
("account", "/account"),
|
||
("users", "/users"),
|
||
("help", "/help"),
|
||
# login 不在这里:见下面 PUBLIC_ROUTES——已登录访问 /login 会被重定向,
|
||
# 留在这张表里 = 把 dashboard 量两遍,还多算一个「已覆盖视图」。
|
||
("proj_overview", f"/projects/{PROJ}/overview"),
|
||
("proj_storyboard", f"/projects/{PROJ}/storyboard"),
|
||
("proj_library", f"/projects/{PROJ}/library"),
|
||
("proj_dispatch", f"/projects/{PROJ}/dispatch"),
|
||
("proj_review", f"/projects/{PROJ}/review"),
|
||
("proj_timeline", f"/projects/{PROJ}/timeline"),
|
||
("proj_delivery", f"/projects/{PROJ}/delivery"),
|
||
]
|
||
|
||
# 盲区二:登录页必须用**未登录**的上下文单独量。M.login() 种好 token 之后再访问
|
||
# /login,App.tsx 的 chromeless 分支会直接 <Navigate to="/">,报出来的「login」
|
||
# 其实是 dashboard 的数字。所以它只住在这张表里,ROUTES 里那一条已经删掉——
|
||
# 两边都留 = 同一个 dashboard 量两遍,视图数还虚高一个。
|
||
PUBLIC_ROUTES = [
|
||
("login", "/login"),
|
||
]
|
||
|
||
# 浮层用例:(名字, 路由, 依次尝试的触发文案)。抽屉/弹窗里的尺子和页面不一样,单独量。
|
||
# 四元组最后一条 = 这一项**必须**落到的表面,量到别的直接判失败。
|
||
# 为什么要写死:探针找不到浮层时会一路兜底到 `main`,于是「把页面又量了一遍」
|
||
# 也照样显示成 misaligned=0——分镜检查器就是这么被假绿掩盖的(它 29 个字段
|
||
# 全在 `main` 外面那个 <aside> 里,一条没测)。声明之后,没开就是没开。
|
||
# drawer = antd 抽屉 · modal = antd 弹窗 · panel = kit 自拼的非模态面板
|
||
# lightbox = kit 自绘的满屏浮层(.nex-lightbox,全站只此一处)
|
||
# main = 页面内联面板(不是浮层;留在这里是为了顺手量它里面的下拉)
|
||
OVERLAYS = [
|
||
("assets_edit", "/assets", ["编辑"], "drawer"),
|
||
("assets_new", "/assets", ["新建人物"], "drawer"),
|
||
("assets_gen", "/assets", ["AI 生成"], "drawer"),
|
||
("models_config", "/models", ["配置"], "drawer"),
|
||
("models_add", "/models", ["添加大模型"], "drawer"),
|
||
# Dashboard 的「新建长视频项目」是页内展开的表单面板,不是浮层
|
||
("dash_new", "/dashboard", ["新建长视频项目"], "main"),
|
||
("lib_edit", f"/projects/{PROJ}/library", ["编辑"], "drawer"),
|
||
# 分镜「检查器」:入口是镜头卡整块热区,不是按钮(见 click_any 的 @ 前缀)。
|
||
# 以前的 "进入分镜"/"分镜与脚本" 命中的是侧边栏导航,浮层从未打开。
|
||
# 点的必须是标题行 [data-shot-select] 而不是整卡:探针点元素几何中心,
|
||
# 窄屏卡片中心落在缩略图上 → 打开的是灯箱,面板这一项又量不到(560 首跑就这么红的)。
|
||
("sb_shot", f"/projects/{PROJ}/storyboard",
|
||
["@article[data-shot-card] [data-shot-select]"], "panel"),
|
||
# 灯箱:kit 自绘的满屏浮层,靠 .nex-lightbox 认表面。它是全站唯一「盖满视口 +
|
||
# 自带翻页箭头」的一层,之前没有任何用例打开过它——箭头和产物切换因此从未被量到。
|
||
("sb_media", f"/projects/{PROJ}/storyboard",
|
||
["@article[data-shot-card] [data-shot-preview]"], "lightbox"),
|
||
# 用户管理的「新建账号」也是页内面板(UserAdmin.tsx 常驻那块)
|
||
("users_form", "/users", [], "main"),
|
||
]
|
||
|
||
# 控件高度 = antd 自己的三档 controlHeight(SM 24 / base 32 / LG 40)。
|
||
# 2026-11 起 theme/antd.ts 不再自定义几何:上一版自定的 31/38/44 与 antd 默认的
|
||
# 24/32/40 同时长在页面上,同一行里 antd 控件 32、kit 控件 38——用户报的
|
||
# 「字段标题与控件不对齐」有一半是这个。尺子只准有一把,那就用出厂那把。
|
||
TIERS_OK = {24, 32, 40}
|
||
# ≤560px 仍然单独量一轮:窄屏的堆叠、换行、抽屉宽度只在那一档才暴露。
|
||
# 「触摸档」(旧 css-vars.ts 的 touch() 把控件抬到 36/40)已随私有尺子一起删除,
|
||
# antd 没有触摸档,所以窄屏准的还是同一把尺子——留着这个名字是为了「窄屏必须真量」这件事。
|
||
NARROW = 560
|
||
TIERS_OK_TOUCH = TIERS_OK
|
||
|
||
# 白名单:不是控件的盒子 + 有意的例外。每条必须写理由,且必须被命中(未命中=失效)。
|
||
# route 用视图名做前缀匹配;h 是像素高;cls 是 "tag.class1.class2" 的正则。
|
||
EXPECTED = [
|
||
# ── 整块热区:点下去是「打开/选中一个东西」,不是一颗控件 ──────────────
|
||
dict(kind="tier", cls=r"^button\.nex-stat",
|
||
why="统计卡整块是筛选入口(ui/Panel.tsx 的 <Stat onClick>):数字 + 最多两行说明,"
|
||
"高度=内容;钉死档位会让两行说明的卡和一行说明的卡长得一样高、内容溢出"),
|
||
dict(kind="tier", cls=r"^button\.nex-tile",
|
||
why="整块热区族(ui/Tile.tsx):左导航 59~72px、执行流水整行 48px(窄屏换行更高)。"
|
||
"高度=内容是这只组件的定义,bar/pill 两档自己写 --ctl-h 与同排控件同高;"
|
||
"档位检查对它没有意义,但保留在报告里,方便看见「某处热区突然 200px」这种失控"),
|
||
# ── 贴在媒体上 / 文字行内的小按钮:自绘覆盖层,不参与表单档位 ──────────
|
||
dict(kind="tier", h=21, cls=r"^button\.nex-media-badge",
|
||
why="缩略图左下角版本/时长角标(media/MediaThumb.tsx):媒体覆盖层,钉在 34px 方块上,"
|
||
"高 = text-xs 行盒 18.9 + py-px 上下 2 = 21。抬到任何一档控件高度都会盖掉半张图。"
|
||
"读数随字号走,字号一动这条就会报失效——那是提醒,不是噪音"),
|
||
dict(kind="tier", h=20, cls=r"^button\.nex-media-remove",
|
||
why="缩略图右上删除叉(media/MediaThumb.tsx 的 MediaRemove):媒体覆盖层,"
|
||
"与时长角标同族;20 是圆点能看清的最小档"),
|
||
# ui/Button.tsx 的 IconSpot 自绘图标位:新尺子下 24px 正好是 SM 档,不再是例外,
|
||
# 所以这里没有它的条目了(旧条目挂在 h=31 那一代尺子上)。
|
||
dict(kind="tier", h=13, cls=r"^button\.ant-tabs-tab-remove",
|
||
why="页签上的关闭叉(antd Tabs 内部件):它不是可聚焦控件而是一枚贴在页签里的"
|
||
"图标按钮,高 = 12px 图标的行盒。页签整体高度由 Tabs 的 token 管,"
|
||
"把这颗叉抬到 24 会让页签被顶高"),
|
||
]
|
||
|
||
# 横向溢出白名单(真溢出该修的就修,这里只留设计上允许溢出/自带滚动的)
|
||
EXPECTED_OVR: list[dict] = []
|
||
|
||
# console 噪声白名单(正则 + 理由)。**目前一条都没有**:控制台报错是免费的探针,
|
||
# 页面里的东西坏了它先喊。加条目要写清楚为什么不是我们的问题(外网字体挂了、
|
||
# 后端 401 竞态这类),别拿它当遮羞布。
|
||
CONSOLE_IGNORE: list[tuple[str, str]] = []
|
||
|
||
# 命中记录跨视口/主题汇总:某个角标只在宽屏出现,不该在窄屏那轮被当成失效规则
|
||
HIT: set[int] = set()
|
||
COVERS_PAGES = True # run() 按 --only 改写
|
||
COVERS_OVERLAYS = True # 同上:只跑页面时浮层类白名单必然不命中
|
||
|
||
|
||
def explain(kind: str, item: dict, view: str):
|
||
"""命中白名单返回该条,否则 None。"""
|
||
for e in EXPECTED if kind == "tier" else EXPECTED_OVR:
|
||
if e["kind"] != kind:
|
||
continue
|
||
if e.get("route") and not view.startswith(e["route"]):
|
||
continue
|
||
if "h" in e and e["h"] != item.get("h"):
|
||
continue
|
||
if "w" in e and e["w"] != item.get("w"):
|
||
continue
|
||
if "cls" in e and not re.search(e["cls"], item.get("cls", "") or ""):
|
||
continue
|
||
if "txt" in e and e["txt"] not in (item.get("txt") or ""):
|
||
continue
|
||
return e
|
||
return None
|
||
|
||
|
||
async def settle(pg, tries: int = 25, gap: int = 120) -> bool:
|
||
"""等版面自己静止,再开始量。连续两次「全页盒子指纹」相同才算停。
|
||
|
||
症状:探针跑得比动画快。点完按钮立刻量,会量到 antd 水波纹(`.ant-wave`)
|
||
正在胀开的那一帧,报出「横向溢出 55px」;抽屉 0.3s 位移动画同理。
|
||
做法:以前是「轮询 `.ant-drawer-open` + 固定 sleep 700ms」——那个轮询只在
|
||
浮层用例上碰巧当了三秒静默,内联面板用例一缩短就露馅。改成量指纹:
|
||
谁在动都逃不掉,静止了也不必白等。页面自带常驻动画(脉冲、加载环)时
|
||
指纹永不收敛,靠 tries 封顶退化成固定等待,不会卡死。
|
||
"""
|
||
prev = None
|
||
for _ in range(tries):
|
||
cur = await pg.evaluate("""() => {
|
||
let n = 0, sum = 0;
|
||
document.querySelectorAll('*').forEach((el) => {
|
||
const b = el.getBoundingClientRect();
|
||
if (b.width || b.height) {
|
||
n++;
|
||
sum += Math.round(b.x) + Math.round(b.y) * 3 + Math.round(b.width) * 7
|
||
+ Math.round(b.height) * 11;
|
||
}
|
||
});
|
||
return n + ':' + sum;
|
||
}""")
|
||
if cur == prev:
|
||
return True
|
||
prev = cur
|
||
await pg.wait_for_timeout(gap)
|
||
return False
|
||
|
||
|
||
async def click_any(pg, names):
|
||
"""按文案点。名字以 `@` 开头 = 直接当 CSS 选择器用。
|
||
|
||
为什么要有这个口子:有些浮层的入口不是按钮,而是整块热区(分镜卡是
|
||
`<article onClick>`),按文案点只会命中侧边栏里同名的导航项——
|
||
点了个「已经在的页面」,浮层根本没开,探针就退到 `main` 把页面又量一遍,
|
||
「量过了」是假的(分镜检查器 29 个字段一条没测)。
|
||
"""
|
||
for n in names:
|
||
if n.startswith("@"):
|
||
try:
|
||
loc = pg.locator(n[1:]).first
|
||
if await loc.count() and await loc.is_visible():
|
||
await loc.click(timeout=4000)
|
||
return n
|
||
except Exception:
|
||
continue
|
||
continue
|
||
for sel in (f'button:has-text("{n}")', f'a:has-text("{n}")', f"text={n}"):
|
||
try:
|
||
loc = pg.locator(sel).first
|
||
if await loc.count() and await loc.is_visible():
|
||
await loc.click(timeout=4000)
|
||
return n
|
||
except Exception:
|
||
continue
|
||
return None
|
||
|
||
|
||
class Audit:
|
||
def __init__(self, shots: pathlib.Path):
|
||
self.shots = shots
|
||
self.views: list[str] = []
|
||
self.naked: list[tuple[str, dict]] = []
|
||
self.bad: list[tuple[str, dict]] = []
|
||
self.over: list[tuple[str, dict]] = []
|
||
self.tiers: dict[int, collections.Counter] = collections.defaultdict(collections.Counter)
|
||
self.tier_views: dict[int, set] = collections.defaultdict(set)
|
||
self.dd: list[tuple[str, dict]] = []
|
||
self.off: list[tuple[str, dict]] = []
|
||
self.console: list[tuple[str, str]] = []
|
||
self._buf: list[tuple[str, str]] = []
|
||
|
||
def attach(self, pg):
|
||
"""把 console / pageerror 接到这张页上。
|
||
|
||
为什么值得当判据:React 18 的 ref 静默失效(函数组件收不到 ref)、
|
||
antd 的废弃属性、`key` 漏了——全都不改像素,audit 那五项一条都不红,
|
||
但功能是真坏了(登录页不再自动聚焦、流程条不再滚到当前节点)。
|
||
报错按「刚量过的那个视图」归属:handler 只往缓冲里塞,measure/dropdown
|
||
结束时再取走,免得把上一次导航的尾巴算到新页面头上。
|
||
"""
|
||
pg.on("console", lambda m: self._buf.append((m.type, m.text))
|
||
if m.type in ("error", "warning") else None)
|
||
pg.on("pageerror", lambda e: self._buf.append(("pageerror", str(e))))
|
||
|
||
def drain(self, view: str) -> int:
|
||
"""取走缓冲,返回这一视图新增的 console error 条数(warning 只计数不算红)"""
|
||
buf, self._buf = self._buf, []
|
||
bad = 0
|
||
for typ, text in buf:
|
||
one = " ".join(text.split())[:200]
|
||
if any(re.search(pat, one) for pat, _ in CONSOLE_IGNORE):
|
||
continue
|
||
if typ in ("error", "pageerror"):
|
||
bad += 1
|
||
self.console.append((view, one))
|
||
return bad
|
||
|
||
SURFACE = """(scope) => {
|
||
const els = scope === '*' ? [document.body] : [...document.querySelectorAll(scope)];
|
||
let best = null, area = -1;
|
||
for (const el of els) { // 嵌套浮层取最上面(最大)那块
|
||
const r = el.getBoundingClientRect();
|
||
if (r.width * r.height > area) { area = r.width * r.height; best = el; }
|
||
}
|
||
if (!best) return null;
|
||
const r = best.getBoundingClientRect();
|
||
// 取样点夹到可见区:`main` 这种比视口高几倍的表面,几何中心在屏幕外,
|
||
// elementFromPoint 会返回 null——那是探针自己的错,不是页面的错。
|
||
const cx = (Math.max(r.left, 0) + Math.min(r.right, innerWidth)) / 2;
|
||
const cy = (Math.max(r.top, 0) + Math.min(r.bottom, innerHeight)) / 2;
|
||
const hit = document.elementFromPoint(cx, cy);
|
||
return {x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height),
|
||
vw: innerWidth, vh: innerHeight, scrollY: Math.round(scrollY),
|
||
pos: getComputedStyle(best).position,
|
||
// 只要「和视口有交集」的话,抽屉只剩底部 42px 也算过——那是给人看的一条缝,不是浮层
|
||
inView: r.width > 0 && r.height > 0 && r.top < innerHeight && r.bottom > 0
|
||
&& r.left < innerWidth && r.right > 0,
|
||
fullyInView: r.top >= -1 && r.bottom <= innerHeight + 1
|
||
&& r.left >= -1 && r.right <= innerWidth + 1,
|
||
// 中心点命中谁:不是自己也不是自己的子孙 = 这一层其实看不见
|
||
onTop: !!hit && (hit === best || best.contains(hit) || hit.contains(best)),
|
||
hit: hit ? hit.tagName.toLowerCase() : null};
|
||
}"""
|
||
|
||
async def surface(self, pg, name, scope, strict: bool = True) -> bool:
|
||
"""第七项判据:被量的那块表面**真的在屏幕上**。
|
||
|
||
为什么要有这一条:`getContainer={false}` 的抽屉是就地渲染的,antd 给它的是
|
||
相对文档的绝对定位——页面一滚,抽屉整块滚出视口,元素几何全都正常
|
||
(字段对齐、档位、溢出、下拉一律 0 项),用户却什么也没看见。
|
||
前六项量的是「元素长成什么样」,只有这一项量「元素在不在人眼里」。
|
||
strict=True(浮层)要求**完整**落在视口内;`main` 是页面本身,比视口高几倍是常态,
|
||
只要求有交集,否则总览页永远红。
|
||
"""
|
||
try:
|
||
x = await pg.evaluate(self.SURFACE, scope)
|
||
except Exception as e:
|
||
print(f"!! ov_{name:16s} 表面量不出来:{type(e).__name__}")
|
||
self.off.append((name, {"err": type(e).__name__}))
|
||
return False
|
||
if not x:
|
||
print(f"!! ov_{name:16s} 表面不存在:scope={scope}")
|
||
self.off.append((name, {"err": "no-such-scope"}))
|
||
return False
|
||
ok = x["onTop"] and (x["fullyInView"] if strict else x["inView"])
|
||
print((" " if ok else "!!") + f" ov_{name:16s} surface "
|
||
f"inView={int(x['inView'])} fully={int(x['fullyInView'])} onTop={int(x['onTop'])} "
|
||
f"rect=({x['x']},{x['y']},{x['w']}x{x['h']}) scrollY={x['scrollY']} "
|
||
f"pos={x['pos']} viewport={x['vw']}x{x['vh']}"
|
||
+ ("" if x["onTop"] else f" 中心点被 {x['hit']} 盖住"))
|
||
if not ok:
|
||
self.off.append((name, x))
|
||
return ok
|
||
|
||
async def measure(self, pg, name, scope="*", shot=True):
|
||
self.views.append(name)
|
||
naked = await pg.evaluate(M.js(M.NAKED), scope)
|
||
conts = await pg.evaluate(M.js(M.CONTAINER), scope)
|
||
over = await pg.evaluate(M.js(M.OVERFLOW), scope)
|
||
bad = [c for c in conts if M.flagged(c)]
|
||
for x in naked:
|
||
self.naked.append((name, x))
|
||
for c in bad:
|
||
self.bad.append((name, c))
|
||
for x in over:
|
||
if explain("overflow", x, name):
|
||
continue
|
||
self.over.append((name, x))
|
||
tiers_ok = TIERS_OK_TOUCH if M.W <= NARROW else TIERS_OK
|
||
for x in await pg.evaluate(M.js(M.TIERS), scope):
|
||
h = x["h"]
|
||
if h in tiers_ok:
|
||
continue
|
||
rule = explain("tier", x, name)
|
||
if rule:
|
||
HIT.add(id(rule))
|
||
continue
|
||
self.tiers[h][x["cls"][:72]] += 1
|
||
self.tier_views[h].add(name)
|
||
cons = self.drain(name)
|
||
flag = " " if not (naked or bad or over or cons) else "!!"
|
||
print(f"{flag} {name:18s} naked={len(naked)} boxes={len(conts)} misaligned={len(bad)} "
|
||
f"overflow={len(over)} console={cons}")
|
||
for c in bad:
|
||
print(" !!", json.dumps(c, ensure_ascii=False))
|
||
for x in naked[:8]:
|
||
print(" raw", json.dumps(x, ensure_ascii=False))
|
||
for x in over[:6]:
|
||
print(" ovr", json.dumps(x, ensure_ascii=False))
|
||
if shot:
|
||
await pg.screenshot(path=str(self.shots / f"{M.W}_{M.THEME}_{name}.png"))
|
||
|
||
async def dropdown(self, pg, name, scope):
|
||
"""下拉展开:宽度、视口落点、选项是否被裁。"""
|
||
sel = pg.locator(f"{scope} .ant-select:not(.ant-select-disabled)").first
|
||
try:
|
||
if not await sel.count():
|
||
return
|
||
await sel.click(timeout=3000)
|
||
await pg.wait_for_timeout(650)
|
||
dd = await pg.evaluate("""() => {
|
||
const pop = document.querySelector('.ant-select-dropdown:not(.ant-select-dropdown-hidden)');
|
||
if (!pop) return null;
|
||
const tr = document.querySelector('.ant-select-open .ant-select-selector');
|
||
const pb = pop.getBoundingClientRect(), tb = tr.getBoundingClientRect();
|
||
const opt = pop.querySelector('.ant-select-item-option');
|
||
const hit = document.elementFromPoint(pb.left + pb.width / 2,
|
||
Math.min(pb.top + 20, pb.bottom - 1));
|
||
return {popW: Math.round(pb.width), trigW: Math.round(tb.width),
|
||
inViewport: pb.top >= 0 && pb.bottom <= innerHeight && pb.right <= innerWidth + 1,
|
||
// 展开的面板被抽屉 body 裁掉 / 压在别的层下面时,几何照样正常但看不见
|
||
popOnTop: !!hit && pop.contains(hit),
|
||
bottom: Math.round(pb.bottom), vh: innerHeight,
|
||
optH: opt ? Math.round(opt.getBoundingClientRect().height) : null,
|
||
optClipped: opt ? (opt.scrollWidth > opt.clientWidth + 1) : null};
|
||
}""")
|
||
if dd:
|
||
ok = (dd["popW"] >= dd["trigW"] - 1 and dd["inViewport"]
|
||
and not dd["optClipped"] and dd["popOnTop"])
|
||
print((" dd " if ok else " !!dd"), json.dumps(dd, ensure_ascii=False))
|
||
if not ok:
|
||
self.dd.append((name, dd))
|
||
await pg.screenshot(path=str(self.shots / f"{M.W}_{M.THEME}_{name}_dd.png"))
|
||
await pg.keyboard.press("Escape")
|
||
except Exception as e:
|
||
print(" dd fail", type(e).__name__)
|
||
self.drain(name + "/dd")
|
||
await pg.wait_for_timeout(250)
|
||
|
||
def report(self, last: bool = False) -> int:
|
||
print("\n── 结论 ──────────────────────────────────────")
|
||
print(f"视图 {len(self.views)} 个:裸控件 {len(self.naked)} · 字段错位 {len(self.bad)} · "
|
||
f"未解释溢出 {len(self.over)} · 未解释档位 {sum(sum(c.values()) for c in self.tiers.values())} · "
|
||
f"下拉异常 {len(self.dd)} · 表面不在屏内 {len(self.off)} · console 报错 {len(self.console)}")
|
||
for name, t in self.console[:12]:
|
||
print(f" console {name} {t}")
|
||
for name, x in self.naked[:20]:
|
||
print(f" 裸控件 {name}", json.dumps(x, ensure_ascii=False))
|
||
for name, c in self.bad[:20]:
|
||
print(f" 错位 {name}", json.dumps(c, ensure_ascii=False))
|
||
for name, x in self.over[:20]:
|
||
print(f" 溢出 {name}", json.dumps(x, ensure_ascii=False))
|
||
for name, x in self.dd[:10]:
|
||
print(f" 下拉 {name}", json.dumps(x, ensure_ascii=False))
|
||
for name, x in self.off[:10]:
|
||
print(f" 出屏 {name}", json.dumps(x, ensure_ascii=False))
|
||
if self.tiers:
|
||
print("\n── 非三档控件高度(未解释)─────────────────────")
|
||
for h in sorted(self.tiers):
|
||
views = " ".join(sorted(self.tier_views[h]))[:70]
|
||
print(f"!! {h:3d}px " + " | ".join(f"{n}×{c}" for c, n in self.tiers[h].most_common(4)))
|
||
print(f" 出现在:{views}")
|
||
bad = self.naked or self.bad or self.over or self.tiers or self.dd or self.off or self.console
|
||
print("\n" + ("体检通过:全站一把尺子。" if not bad else "有未解释项,见上。"))
|
||
# 只跑一半时不判失效:--only page 碰不到只在浮层里出现的角标,
|
||
# --only overlay 碰不到页面档位,两种情况都会把活规则误报成僵尸规则。
|
||
if last and COVERS_PAGES and COVERS_OVERLAYS:
|
||
stale = [e for e in EXPECTED + EXPECTED_OVR if id(e) not in HIT]
|
||
if stale:
|
||
print("\n── 白名单失效(整轮没命中,删掉或放宽)──────────")
|
||
for e in stale:
|
||
print(" ?", json.dumps({k: v for k, v in e.items() if k != "why"},
|
||
ensure_ascii=False), "—", e["why"])
|
||
print("说明:规则白名单里留着不再命中的条目 = 规范和现实脱节,要么删要么放宽。")
|
||
return 1
|
||
return 1 if bad else 0
|
||
|
||
|
||
async def run(widths, themes, only, shots: pathlib.Path) -> int:
|
||
global COVERS_PAGES, COVERS_OVERLAYS
|
||
COVERS_PAGES = only in ("page", "all")
|
||
COVERS_OVERLAYS = only in ("overlay", "all")
|
||
shots.mkdir(parents=True, exist_ok=True)
|
||
code = 0
|
||
async with async_playwright() as p:
|
||
b = await p.chromium.launch()
|
||
for wi, w in enumerate(widths):
|
||
M.W = w
|
||
for ti, theme in enumerate(themes):
|
||
M.THEME = theme
|
||
ctx = await b.new_context(base_url=BASE, viewport={"width": w, "height": 900},
|
||
storage_state=M.storage(theme))
|
||
pg = await ctx.new_page()
|
||
a = Audit(shots)
|
||
a.attach(pg)
|
||
await M.login(pg)
|
||
print(f"\n======== {w}px · {theme} ========")
|
||
if only in ("page", "all"):
|
||
for name, route in ROUTES:
|
||
try:
|
||
await pg.goto(route, wait_until="networkidle", timeout=60000)
|
||
except Exception:
|
||
print(f"!! {name:18s} 导航失败")
|
||
code = 1
|
||
continue
|
||
await pg.wait_for_timeout(1400)
|
||
await a.measure(pg, name)
|
||
if only in ("overlay", "all"):
|
||
for name, route, clicks, want in OVERLAYS:
|
||
# 先等「这一项声明的那块表面」挂上,再等版面静止,然后才量。
|
||
want_sel = {"drawer": ".ant-drawer-open",
|
||
"modal": ".ant-modal-content",
|
||
"panel": "aside:has(.nex-drawer-body)",
|
||
"lightbox": ".nex-lightbox"}.get(want)
|
||
for attempt in (1, 2):
|
||
await pg.goto(route, wait_until="networkidle", timeout=60000)
|
||
# 点之前必须先等列表渲染完:900px 那轮 4 个浮层「入口没点开」,
|
||
# 量到的 boxes=0——卡片还没挂上,click_any 找不到可点元素,
|
||
# 探针于是退到 main 把空页面又量一遍(读数全 0,看着像通过)。
|
||
await settle(pg)
|
||
await pg.wait_for_timeout(400)
|
||
for c in clicks:
|
||
if await click_any(pg, [c]):
|
||
break
|
||
if not want_sel:
|
||
break
|
||
for _ in range(20):
|
||
if await pg.locator(want_sel).count():
|
||
break
|
||
await pg.wait_for_timeout(150)
|
||
if await pg.locator(want_sel).count():
|
||
break
|
||
# 没开:回顶部再来一次(窄屏入口可能在折叠线以下)
|
||
if attempt == 1:
|
||
await pg.evaluate("() => scrollTo(0, 0)")
|
||
await settle(pg)
|
||
kind = "modal"
|
||
if await pg.locator(".ant-drawer-open").count():
|
||
scope, kind = ".ant-drawer-content-wrapper", "drawer"
|
||
elif await pg.locator(".ant-modal-content").count():
|
||
scope, kind = ".ant-modal-content", "modal"
|
||
elif await pg.locator("aside:has(.nex-drawer-body)").count():
|
||
# 自拼的非模态面板(分镜检查器):不认这条就一直 fallback 到 main,
|
||
# 而面板挂在 main 外面,等于从未被量过
|
||
scope, kind = "aside:has(.nex-drawer-body)", "panel"
|
||
elif await pg.locator(".nex-lightbox").count():
|
||
# 自绘灯箱排在 antd 两类之后:antd 抽屉内容层也带 role=dialog,
|
||
# 认 role 会串味,所以认 kit 标记类
|
||
scope, kind = ".nex-lightbox", "lightbox"
|
||
else:
|
||
scope, kind = "main", "main"
|
||
if kind != want:
|
||
print(f"!! ov_{name:16s} 没量到该量的表面:期望 {want},实际 {kind}"
|
||
f"——入口没点开 / 点歪了,这一项的读数不算数")
|
||
code = 1
|
||
if not await a.surface(pg, name, scope, strict=(kind != "main")):
|
||
code = 1
|
||
await a.measure(pg, "ov_" + name, scope)
|
||
await a.dropdown(pg, "ov_" + name, scope)
|
||
await pg.keyboard.press("Escape")
|
||
await pg.wait_for_timeout(400)
|
||
if only in ("page", "all") and PUBLIC_ROUTES:
|
||
# 未登录:storage_state 只种 nex-the(主题),不带 token,
|
||
# 否则 /login 会被重定向,量到的还是总览页。
|
||
pctx = await b.new_context(base_url=BASE, viewport={"width": w, "height": 900},
|
||
storage_state=M.storage(theme))
|
||
ppg = await pctx.new_page()
|
||
pa = Audit(shots)
|
||
pa.attach(ppg)
|
||
for name, route in PUBLIC_ROUTES:
|
||
try:
|
||
await ppg.goto(route, wait_until="networkidle", timeout=60000)
|
||
except Exception:
|
||
print(f"!! {name:18s} 导航失败(未登录)")
|
||
code = 1
|
||
continue
|
||
await ppg.wait_for_timeout(1400)
|
||
await pa.measure(ppg, name)
|
||
code |= pa.report()
|
||
await pctx.close()
|
||
|
||
last = (wi == len(widths) - 1 and ti == len(themes) - 1)
|
||
code |= a.report(last=last)
|
||
await ctx.close()
|
||
await b.close()
|
||
return code
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description="前端 UI 体检(React 18 + Ant Design 5)")
|
||
ap.add_argument("--width", type=int, nargs="+", default=[1440], help="视口宽度,可多档:--width 1440 1280 900")
|
||
ap.add_argument("--theme", choices=["light", "dark", "both"], default="both")
|
||
ap.add_argument("--only", choices=["page", "overlay", "all"], default="page")
|
||
ap.add_argument("--shots", default=".local/ui-audit", help="截图目录(默认 .local/ui-audit,不进 git)")
|
||
a = ap.parse_args()
|
||
themes = ["light", "dark"] if a.theme == "both" else [a.theme]
|
||
sys.exit(asyncio.run(run(a.width, themes, a.only, pathlib.Path(a.shots))))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|