nex_animation/scripts/ui/visualcheck.py

521 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""视觉体检:登录 → 逐路由 × 逐档宽度 × 明暗两色截图,同时校验尺子是否真的接上了 antd。
为什么需要它:改完 CSS 只跑 tsc 和 build 是不够的——变量名写错、token 没铺到
:root、选中态被 antd 默认样式盖掉,这些都是「编译通过但页面是坏的」。
所以除了截图,这里还会读一遍浏览器里的计算样式,把五件事钉死:
1) applyRootVars 有没有把 --ant-* 铺到 :root(app.css 全靠它);
2) 文字行高没塌成 px(无单位倍数被误写 px 时肉眼很容易漏);
3) 侧栏选中态跟着路由走(selectedKeys 没断);
4) 这一档宽度下没有元素横向捅出视口、没有被 overflow:hidden 切掉的字;
分段控件 / 页签 / 按钮 / 下拉当前值的文字必须整颗放得下(省略号也算截断);
桌面档(>=1024)里每颗 <ActionGroup> 必须待在同一行——同一概念的几颗按钮
被劈成两排就是没分组(`stack` 的竖排等宽除外)。
5) 请求没有 4xx/5xx——按 URL 分诊:素材文件在开发库里本来就没落盘是数据问题,
其余(接口 404、chunk 加载失败)一律算故障。
用法:
NEX_ROUTES="/,/assets" NEX_WIDTHS=1440,768 NEX_THEMES=dark,light \\
.venv/bin/python scripts/ui/visualcheck.py
产出:<NEX_SHOTS>/shots/*.png + 控制台报告。
"""
import os
import pathlib
import sys
from playwright.sync_api import sync_playwright
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
OUT = pathlib.Path(os.environ.get("NEX_SHOTS", "/tmp/nex_ui"))
SHOTS = OUT / "shots"
SHOTS.mkdir(parents=True, exist_ok=True)
WIDTHS = [int(x) for x in os.environ.get("NEX_WIDTHS", "1440").split(",")]
THEMES = os.environ.get("NEX_THEMES", "dark,light").split(",")
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,"
"/account,/users,/help,/login").split(",") if r]
# 侧栏导航覆盖到的路由:这些必须有选中项,否则 selectedKeys 断了。
# 登录页不在导航里(chromeless),主循环也不跑它——见下面登录前的专用一趟。
NAV_ROUTES = [r for r in ROUTES
if not any(x in r for x in ("/account", "/users", "/help", "/login"))]
USER = os.environ.get("NEX_USER", "admin")
FORCED_PID = os.environ.get("NEX_PROJECT_ID", "")
PWD = os.environ.get("NEX_PASS", "admin1234")
# 项目子页一律量「镜头最多」的那个项目:列表第一个往往是刚建的空项目,
# 空项目的分镜墙 / 调度清单 / 审核表全是空态,溢出与截断这两类断言等于没测。
# 需要指定项目时用 NEX_PROJECT_ID。
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 || '';
}"""
# rc-resize-observer 在 React 18 下的已知告警,antd 内部依赖,与应用代码无关
IGNORE = ("findDOMNode is deprecated", "Support for React will be removed")
# ── 颜色闸(2026-11 撤掉自造的柠檬绿品牌之后常驻)────────────────────────────
# 1) 主色必须等于 antd 各自 algorithm 的出厂蓝。这个数非量不可:
# darkAlgorithm 会把喂进来的 seed 再走一遍色板生成器取第 5 档,
# 「把出厂值 #1668dc 填回 SEED.colorPrimary」量到的是 #165bbe(差一档),
# 截图上肉眼看不出来,只有读 --ant-color-primary 才发现覆盖回来了。
# 2) 侧栏选中态必须是 antd 自己那一组:浅色 = controlItemBgActive + colorPrimary
# (#e6f4ff / #1677ff,4.4:1,antd 官网同款);深色由 theme/antd.ts 补 antd
# dark 菜单的默认对(实心主色 + 白字,6.4:1)。深色要是删掉这两条,
# light 菜单的 #15325b 底 + #1668dc 字只有 2.2:1,选中项比未选中还淡。
# 3) 全站不许再出现旧品牌那一族(antd lime-1..10:#a0d911 / #5b8c00 是它的 6/8 档)。
ANTD_PRIMARY = {"light": "#1677ff", "dark": "#1668dc"}
MENU_SELECTED = {
"light": ("rgb(230, 244, 255)", "rgb(22, 119, 255)"),
"dark": ("rgb(22, 104, 220)", "rgb(255, 255, 255)"),
}
# lime 族的色相窗口:实测 antd lime-1..10 落在 71°~83°,而 green 族(语义 success
# 用的那一族,含 darkAlgorithm 重映射出来的 #82c058 / #3b512c)落在 88°~102°。
# 取 62~88 当窗口:黄橙(warning 一族 45°~55°)和状态绿都进不来。
COLORSCAN = r"""() => {
const props = ['color', 'backgroundColor', 'borderTopColor', 'borderLeftColor', 'outlineColor', 'fill', 'stroke'];
const hit = {};
const parse = (s) => {
if (!s || s === 'transparent' || s === 'none') return null;
let m = s.match(/^rgba?\(([^)]]+)\)$/i);
if (m) { const p = m[1].split(/[,\s/]+/).filter(Boolean).map(Number);
return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1}; }
m = s.match(/^#([0-9a-f]{6})$/i);
if (m) { const v = parseInt(m[1], 16); return {r: v >> 16 & 255, g: v >> 8 & 255, b: v & 255, a: 1}; }
return null;
};
for (const el of document.querySelectorAll('body *')) {
const cs = getComputedStyle(el);
if (cs.display === 'none') continue;
for (const p of props) {
const c = parse(cs[p]);
if (!c || c.a < 0.05) continue;
const mx = Math.max(c.r, c.g, c.b), mn = Math.min(c.r, c.g, c.b);
if (mx === mn) continue;
const h = mx === c.r ? 60 * (((c.g - c.b) / (mx - mn)) % 6)
: mx === c.g ? 60 * ((c.b - c.r) / (mx - mn) + 2)
: 60 * ((c.r - c.g) / (mx - mn) + 4);
const hue = h < 0 ? h + 360 : h;
if (!(hue >= 62 && hue <= 88 && (mx - mn) / mx > 0.12)) continue;
const key = '#' + [c.r, c.g, c.b].map((n) => n.toString(16).padStart(2, '0')).join('');
const rec = hit[key] || (hit[key] = {n: 0, e: ''});
rec.n++;
if (!rec.e) rec.e = el.tagName.toLowerCase() + '.' +
((typeof el.className === 'string' ? el.className : '').trim().slice(0, 48) || '-') + ' {' + p + '}';
}
}
return hit;
}"""
PROBE = """() => {
const cs = getComputedStyle(document.documentElement);
const v = (n) => (cs.getPropertyValue(n) || '').trim();
// 窄屏侧栏是折叠的(Sider breakpoint=md),二级项不在 DOM 里而在 hover 浮层里,
// 此时 antd 把选中态打在父级 .ant-menu-submenu-selected 上 —— 这不是选中态断了。
// collapsed 一并报出去,让 Python 那边决定要不要再展开浮层复核。
const item = document.querySelector('.ant-menu-item-selected');
const sel = item
|| document.querySelector('.ant-menu-submenu-selected > .ant-menu-submenu-title');
const sc = sel ? getComputedStyle(sel) : null;
const bar = document.querySelector('.ant-layout-header') || document.querySelector('[class*=nex-header]');
return {
root: {
primary: v('--ant-color-primary'),
bg: v('--ant-color-bg-layout'),
bar: v('--nex-bar'),
marginXs: v('--ant-margin-xs'),
fontWeightStrong: v('--ant-font-weight-strong'),
fontSize: v('--ant-font-size'),
controlHeight: v('--ant-control-height'),
borderRadius: v('--ant-border-radius'),
},
// kind=item 才是真正被选中的菜单项,能吃 antd 的 controlItemBgActive;
// kind=submenu 只是折叠态下高亮的父级标题,antd 给它的是透明底 + colorPrimary 文字,
// 这是折叠态的正确长相,拿选中项的色板去比必然误报。
menu: sel ? {bg: sc.backgroundColor, color: sc.color, text: sel.textContent.trim().slice(0, 12),
kind: item ? 'item' : 'submenu'} : null,
header: bar ? {h: Math.round(bar.getBoundingClientRect().height),
bg: getComputedStyle(bar).backgroundColor} : null,
theme: document.documentElement.dataset.theme,
collapsed: !!document.querySelector('.ant-layout-sider-collapsed'),
subSelected: !!document.querySelector('.ant-menu-submenu-selected'),
// 行高是无单位倍数:一旦 --ant-line-height-* 被写成 px,每一行文字都会塌成 1px 高
// .anticon 除外:antd 的图标复位把所有图标写成 line-height:0(实测菜单/头部/正文图标全是 0px),
// 图标的盒子由 font-size 撑开(12px 字图标实高 12px,没塌),这条断言管的是「文字行」。
// 图标一旦同时带 Tailwind 的 text-*,按 class 选元素就会把它误报成「行高塌了」。
text: [...document.querySelectorAll('.text-xs, .text-sm, .text-base')].slice(0, 12)
.filter((el) => !el.classList.contains('anticon'))
.map((el) => { const c = getComputedStyle(el);
const fs = parseFloat(c.fontSize), lh = parseFloat(c.lineHeight);
return Number.isFinite(lh) && lh < fs ? `${el.className.slice(0, 40)} fs=${fs} lh=${lh}` : null; })
.filter(Boolean),
};
}"""
# 布局体检:找出「捅出视口」和「被 hidden 切掉」的东西。
# 只写 JS,不用正则,避免 Python 字符串转义把 evaluate 打挂。
LAYOUT = r"""() => {
const vw = document.documentElement.clientWidth;
const desc = (el) => {
const r = el.getBoundingClientRect();
let cls = (typeof el.className === 'string' ? el.className : '').trim().replace(/\\s+/g, ' ');
cls = cls.length > 46 ? cls.slice(0, 46) + '..' : cls;
return el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (cls ? '.' + cls.split(' ').join('.') : '')
+ ' [' + Math.round(r.width) + 'x' + Math.round(r.height) + ' @' + Math.round(r.left) + ',' + Math.round(r.top) + ']';
};
// 「捅出视口」只有在溢出真的漏到页面上时才是 bug。祖先里只要有一个横向
// 滚动/裁切盒把它接住了,就不是溢出:auto|scroll 是能滚,hidden|clip 且
// scrollWidth > clientWidth 是「正在被程序滚动的裁切盒」——antd 的页签条
// (.ant-tabs-nav-wrap) 就是这一类,rc-tabs 用 transform 滚它,overflowX 却是 hidden。
// 被裁掉的**文字**另有 clip 那条检查兜着,不会漏。
const contained = (el) => {
for (let p = el.parentElement; p && p !== document.documentElement; p = p.parentElement) {
const c = getComputedStyle(p);
if (c.overflowX === 'auto' || c.overflowX === 'scroll') return true;
if ((c.overflowX === 'hidden' || c.overflowX === 'clip')
&& p.scrollWidth > p.clientWidth + 2) return true;
}
return false;
};
// 断点 utility 与 antd 组件样式的层叠陷阱:Tailwind 的 utility 在 @layer utilities,
// antd 若没进层就会盖掉 display —— <Flex className="max-md:hidden"> 算出来还是 flex。
const DISP = { hidden: 'none', block: 'block', flex: 'flex', 'inline-flex': 'inline-flex',
grid: 'grid', 'inline-block': 'inline-block', inline: 'inline' };
const BPORDER = ['2xl', 'xl', 'lg', 'md', 'sm']; // 大 → 小,用于算变体优先级
const BP = { sm: 576, md: 768, lg: 992, xl: 1200, '2xl': 1600 };
const dispBad = [];
// flex / grid 容器的子项会被 CSS Display 规范「块级化」:inline-flex→flex、
// inline-block|inline→block。这是规范行为,不是 utility 被组件样式盖掉。
const BLOCKIFY = { 'inline-flex': 'flex', 'inline-block': 'block', inline: 'block' };
const flowParentDisplay = (el) => {
for (let p = el.parentElement; p; p = p.parentElement) {
const d = getComputedStyle(p).display;
if (d === 'contents') continue; // display:contents 不生成盒子,容器往上找
return d;
}
return '';
};
// 返回 {want, score}:一个元素上可能同时挂 flex 与 max-xl:grid + max-lg:flex,
// 命中哪个由 Tailwind 生成顺序决定(实测 dist 产物):同一条 utility,无变体在最前,
// 然后 max-* 按断点从大到小排(2xl→sm),最后 min-* 按断点从小到大排(sm→2xl)。
// 后写的赢 ⇒ max-* 里「断点最小的」赢,min-* 里「断点最大的」赢。取 score 最大的候选。
// BPORDER 是大→小,所以 max-* 用 +idx、min-* 用 (len-1-idx) 换算。
// max-* 与 min-* 同时命中、或带 hover/dark 之类判不准的变体 → 返回 null 跳过,宁漏不误。
const wantDisplay = (tok) => {
const parts = tok.split(':');
const base = parts[parts.length - 1];
if (!DISP[base] || tok.indexOf('[') >= 0 || tok.indexOf('/') >= 0) return null;
let maxSeen = false, minSeen = false, maxIdx = 0, minIdx = 0;
for (const v of parts.slice(0, -1)) {
if (v.startsWith('max-')) {
const key = v.slice(4);
if (BP[key] === undefined || vw >= BP[key]) return null;
const idx = BPORDER.indexOf(key);
maxIdx = maxSeen ? Math.max(maxIdx, idx) : idx; // 断点最小的 max-* 写在最后,赢
maxSeen = true;
} else if (BP[v] !== undefined) {
if (vw < BP[v]) return null;
const idx = BPORDER.indexOf(v);
minIdx = minSeen ? Math.min(minIdx, idx) : idx; // 断点最大的 min-* 写在最后,赢
minSeen = true;
} else return null; // hover / focus / dark / light 之类的变体这里判不准,跳过
}
if (maxSeen && minSeen) return null;
const score = maxSeen ? 100 + maxIdx : minSeen ? 200 + (BPORDER.length - 1 - minIdx) : 0;
return { want: DISP[base], score };
};
const out = [], clip = [];
const all = document.querySelectorAll('body *');
for (const el of all) {
const c = getComputedStyle(el);
if (c.display === 'none' || c.visibility === 'hidden' || c.opacity === '0') continue;
const r = el.getBoundingClientRect();
const cands = ((typeof el.className === 'string' ? el.className : '').trim().split(/\s+/)
.map(wantDisplay).filter((x) => x !== null));
// 多个候选取优先级最高的那一个(而不是写在最前面的那一个)
let want = null;
for (const x of cands) if (want === null || x.score > want.score) want = x;
if (want) {
const pd = flowParentDisplay(el);
if (pd === 'flex' || pd === 'inline-flex' || pd === 'grid' || pd === 'inline-grid') {
want.want = BLOCKIFY[want.want] || want.want;
}
want = want.want;
}
if (want && el.parentElement && c.display !== want) {
// display:none 的祖先里量不到,期望 flex 却读到 none 也算通过(父级自己会报)
if (!(want === 'none')) dispBad.push(desc(el) + ' want display=' + want + ' got=' + c.display);
else if (r.width > 2) dispBad.push(desc(el) + ' want display=none got=' + c.display);
}
if (r.width < 2 || r.height < 2) continue;
if (r.right > vw + 2 && !contained(el)) {
// 只要最外层那一个:父级已经报过就跳过子级
let dup = false;
for (let p = el.parentElement; p; p = p.parentElement) {
if (p.__flag) { dup = true; break; }
}
if (!dup) { el.__flag = 1; out.push(desc(el)); }
}
// line-clamp / ellipsis 是「故意截断」,不算切字
const clamp = c.webkitLineClamp && c.webkitLineClamp !== 'none';
const ox = c.overflowX;
if ((ox === 'hidden' || ox === 'clip') && !clamp && c.textOverflow !== 'ellipsis' && el.scrollWidth > el.clientWidth + 2) {
const own = [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim().length);
if (own && el.textContent.trim().length) clip.push(desc(el) + ' text=' + el.textContent.trim().slice(0, 24));
}
}
// 控件标签不许省略号截断。上面那条 clip 故意放过 text-overflow:ellipsis,
// 因为散文里截断是有意的;但分段控件/页签/按钮/下拉当前值的文字就是这一个选项
// **唯一**的说明,截一半等于把「全部素材」显示成「全部素」、把「按更新时间」显示成「按更…」。
// 病灶一(2026-11 实测):PanelHead 的 right 槽给 ViewSwitch 传了 block,
// antd 把三段等分成 71.3px,而「全部素材」连图标要 76px —— .ant-segmented-item-label
// 的 overflow:hidden 把最后一个字裁掉半格,tsc / build / 旧 clip 全都是绿的。
// 病灶二(同月实测,23 处):档位写的是「标签+控件」的总宽,标签列一长
// 下拉当前值就-first-被咬——「全部状态」77>70、「按更新时间」91>70、「有限思考」77>46。
// 选中值是筛选条件本身,看不见等于没筛,所以它必须在盒子里整颗放得下。
// 唯一豁免:选项名本身就是一整句话的下拉(时间线「内嵌软字幕轨(播放器可开关,画质无损 · 推荐)」、
// 交付「跟随时间线设置(默认内嵌软字幕轨)」),盒子中放不下整句是几何事实,
// antd 的 ellipsis + title + 面板折行(.nex-select-popup)才是正解,页面用
// nex-prose-value 显式标出来,不许再靠 ellipsis 静默。
// 菜单不在名单里:侧栏项目名截断是设计(省略号 + title 全文)。
const trunc = [];
const overflows = (n) => {
// 只认「自己带文字」的节点:按钮里那个隐藏的 file input 永远 scrollWidth > clientWidth,
// 但它没有文字,截不截都读得出来。
const own = [...n.childNodes].some((x) => x.nodeType === 3 && x.textContent.trim().length);
if (!own && !(n.textContent || '').trim()) return false;
const c = getComputedStyle(n);
if ((c.overflowX === 'hidden' || c.overflowX === 'clip') && n.scrollWidth > n.clientWidth + 1) {
trunc.push(desc(n) + ' ' + n.scrollWidth + '>' + n.clientWidth
+ ' text=' + (n.textContent || '').trim().slice(0, 24));
return true;
}
return false;
};
document.querySelectorAll(
'.ant-segmented-item-label, .ant-tabs-tab-btn, .ant-btn, .ant-select-selection-item'
).forEach((el) => {
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return;
if (el.closest('.nex-prose-value')) return; // 整句型选项值:见上面的豁免说明
// 顶栏那颗项目胶囊(.nex-console)属于**外壳**,不是页面里的控件:56px 高的 Header
// 要同时装项目名 + 状态 + 12 段轨道 + 百分比 + 「当前 · …」整句(自然宽 651px),
// 而它自己只分到 327~640px。全文三条路都在:按钮 title(《名字》流程进度 83% ·
// 已完成 10/12 · 当前节点:X)、两段文字各自的 ellipsis tooltip、点开就是「项目概况」抽屉。
// 与「菜单不在名单里:侧栏项目名截断是设计」同一条口径(见本函数末行注释)。
// 它管住的是「不许塌成 30px 的残字」——那由组件里 flex-none 的项目名保证(实测 ≥149)。
if (el.closest('.nex-console')) return;
if (overflows(el)) return;
[...el.querySelectorAll('*')].some(overflows);
});
// 「同一概念的按钮组不许乱跨行」(docs/UI规范.md §7):ActionGroup 是一组按钮的**原子单位**,
// 要挪整组一起挪。这里量的是渲染结果而不是 class:同一容器里子项的垂直中心落在两条
// 水平线上 = 这组被折成两排。stack(antd 给 ant-flex-vertical)是刻意的竖排等宽,跳过;
// 只在主宽度及以上做(窄屏工具条折行是设计,桌面档折行是没分组)。
const wrap = [];
if (vw >= 1024) {
for (const el of document.querySelectorAll('.nex-action-group')) {
if ((typeof el.className === 'string' ? el.className : '').indexOf('ant-flex-vertical') >= 0) continue;
const kids = [...el.children].filter((k) => k.getBoundingClientRect().width > 0);
if (kids.length < 2) continue;
const rows = [];
for (const k of kids) {
const r = k.getBoundingClientRect();
const y = r.top + r.height / 2;
if (!rows.some((v) => Math.abs(v - y) < 8)) rows.push(y);
}
if (rows.length > 1) {
wrap.push(desc(el) + ' rows=' + rows.length + ' '
+ kids.map((k) => (k.innerText || k.tagName).trim().slice(0, 8)).join('|'));
}
}
}
return {vw, page: document.documentElement.scrollWidth, out: out.slice(0, 8),
clip: clip.slice(0, 8), disp: dispBad.slice(0, 8), trunc: trunc.slice(0, 8),
wrap: wrap.slice(0, 6)};
}"""
def audit(page, route: str, width: int, theme: str, problems: list[str], *,
menu_required: bool = False, shot_prefix: bool = True) -> None:
"""量一把渲染结果并截图:登录页与业务页共用同一份尺子,不允许两套口径。
`menu_required` 只由调用方按「这一条在不在侧栏导航里」给:账号 / 用户管理 /
手册 / 登录页没有选中项是正常的,业务路由没有就是 selectedKeys 断了。
"""
probe = page.evaluate(PROBE)
lay = page.evaluate(LAYOUT)
for o in lay["out"]:
problems.append(f"{width}/{theme}{route}: 捅出视口 {o}")
for o in lay["clip"]:
problems.append(f"{width}/{theme}{route}: 文字被切 {o}")
for o in lay["disp"]:
problems.append(f"{width}/{theme}{route}: display utility 被组件样式盖掉 {o}")
for o in lay["trunc"]:
problems.append(f"{width}/{theme}{route}: 控件标签被省略号截断 {o}")
for o in lay["wrap"]:
problems.append(f"{width}/{theme}{route}: 同一概念的按钮组被拆成两排 {o}")
if probe["theme"] != theme:
problems.append(f"{width}/{theme}{route}: data-theme={probe['theme']}")
for k, val in probe["root"].items():
if not val:
problems.append(f"{width}/{theme}{route}: :root 缺 --{k}")
want = ANTD_PRIMARY[theme]
got = probe["root"]["primary"].lower()
if got != want:
problems.append(f"{width}/{theme}{route}: 主色 {got} ≠ antd 出厂蓝 {want}"
f"(站内不覆盖 colorPrimary,见 theme/antd.ts)")
# 逐元素扫颜色只在主宽度做:换色不看宽度,四个宽度重复扫只是多花一倍时间
if width == WIDTHS[0]:
for hexv, rec in page.evaluate(COLORSCAN).items():
problems.append(f"{width}/{theme}{route}: 残留旧品牌lime族 {hexv} ×{rec['n']} e.g. {rec['e']}")
for bad in probe["text"]:
problems.append(f"{width}/{theme}{route}: 行高塌了 {bad}")
if menu_required:
if not probe["menu"]:
problems.append(f"{width}/{theme}{route}: 菜单没有选中项")
elif probe["menu"].get("kind") != "item":
pass # 折叠态:父级标题只证明 selectedKeys 指对了分支,色板比不了,交给下面浮层复核
else:
want_bg, want_fg = MENU_SELECTED[theme]
if probe["menu"]["bg"] != want_bg or probe["menu"]["color"] != want_fg:
problems.append(f"{width}/{theme}{route}: 侧栏选中态 {probe['menu']['bg']}"
f"/{probe['menu']['color']},应为 {want_bg}/{want_fg}")
if probe["menu"] and probe["menu"].get("kind") == "submenu":
# 折叠态下只验到父级还不够:selectedKeys 传错时父级照样会亮。
# 展开浮层,确认这一条路由对应的二级项真的在里面被选中。
try:
page.hover(".ant-menu-submenu-selected > .ant-menu-submenu-title")
page.wait_for_timeout(450)
hit = page.evaluate(
"() => { const p = document.querySelector('.ant-menu-submenu-popup');"
" const s = p && p.querySelector('.ant-menu-item-selected');"
" return s ? s.textContent.trim().slice(0, 12) : null; }")
if not hit:
problems.append(f"{width}/{theme}{route}: 折叠态浮层里没有选中的二级项")
finally:
page.mouse.move(5, 5)
page.wait_for_timeout(150)
slug = route.strip("/").replace("/", "-") or "home"
name = f"{width}-{theme}-{slug}.png"
page.screenshot(path=str(SHOTS / name))
if shot_prefix and width == WIDTHS[0]:
print(f"shot {name:38} menu={probe['menu']} header={probe['header']}")
def main() -> int:
problems: list[str] = []
errors: list[str] = []
http_bad: list[str] = [] # 非素材接口的 4xx/5xx:真故障
media_missing: set[str] = set() # /media/file/ 404:库里有记录、磁盘上没文件
with sync_playwright() as pw:
browser = pw.chromium.launch()
ctx = browser.new_context(viewport={"width": 1440, "height": 900}, device_scale_factor=1)
page = ctx.new_page()
page.on("console", lambda m: errors.append(f"[{m.type}] {m.text}")
if m.type in ("error", "warning") else None)
page.on("pageerror", lambda e: errors.append(f"[pageerror] {e}"))
def on_response(res) -> None:
# 浏览器对失败请求只打一句不带 URL 的 "Failed to load resource",
# 120 次素材 404 和 1 次接口 404 在 console 里长得一模一样,必须自己按 URL 分诊。
url, status = res.url, res.status
if status < 400 or url.startswith(("ws:", "wss:")) or "/@vite" in url or "/@fs/" in url:
return
url = url.split("?")[0]
if "/media/file/" in url:
media_missing.add(url)
else:
# 带上是哪一页发出的:同一句 404 可能只在某一档宽度 / 某个页面出现
http_bad.append(f"{page.url.replace(BASE, '') or '/'} → {status} {url}")
page.on("response", on_response)
# 登录页专用的一趟(必须在登录之前跑):它没有 Header/Sider,
# 而且登录之后再访问 /login 会被守卫回落首页——URL 比对就成了假故障。
# 先落地一个同源页面:about:blank 上没有 localStorage 可写。
page.goto(BASE + "/login", wait_until="domcontentloaded")
for width in WIDTHS:
page.set_viewport_size({"width": width, "height": 900})
for theme in THEMES:
page.evaluate("(t) => localStorage.setItem('nex-the', t)", theme)
page.goto(BASE + "/login", wait_until="networkidle")
page.wait_for_timeout(500)
if not page.locator("#login-user").count():
problems.append(f"{width}/{theme}/login: 登录表单没渲染(#login-user 不在)")
continue
audit(page, "/login", width, theme, problems)
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)
if page.locator("#login-pass").count():
print("LOGIN FAILED:", page.locator("body").inner_text()[:400])
return 2
pid = ""
for width in WIDTHS:
page.set_viewport_size({"width": width, "height": 900})
for theme in THEMES:
page.evaluate("(t) => localStorage.setItem('nex-the', t)", theme)
for route in ROUTES:
r = route
if r == "/login":
continue # 登录前那一趟量过了,这里再访问只会撞守卫
if "{id}" in r:
pid = pid or FORCED_PID
if not pid:
pid = page.evaluate(PROJECT_JS)
if not pid:
print("!! 拿不到项目 id,跳过", r)
continue
r = r.replace("{id}", str(pid))
page.goto(BASE + r, wait_until="networkidle")
page.wait_for_timeout(600)
# path:'*' 会把不存在的路线静默重定向回首页:不比对 URL 就会白测一页
if not page.url.rstrip("/").endswith(r.rstrip("/")):
problems.append(f"{width}/{theme}{r}: 路由不存在,实际落在 {page.url}")
continue
audit(page, r, width, theme, problems, menu_required=r in NAV_ROUTES)
browser.close()
print("\n=== :root 尺子 ===")
print("(见上方逐行 menu/header)")
# 「Failed to load resource」不带 URL,是素材还是接口上面已经分诊过了,这里不再重复计数
real = [e for e in dict.fromkeys(errors)
if not any(g in e for g in IGNORE) and "Failed to load resource" not in e]
print(f"\n=== console({len(real)} 条,已豁免 {len(errors) - len(set(errors))} 条重复)===")
for e in real:
print(e[:300])
print(f"\n=== HTTP 失败({len(set(http_bad))} 条)===")
for e in list(dict.fromkeys(http_bad))[:10]:
print(e[:200])
if media_missing:
print(f"(另有 {len(media_missing)} 个素材 404:开发库里有记录、磁盘上没这个文件。"
f"UI 侧 MediaThumb 的 onError 会兜成「文件缺失」占位,不计入故障)")
print(f"\n=== 断言({len(problems)} 条)===")
for p in list(dict.fromkeys(problems))[:40]:
print(p)
return 0 if not real and not problems and not http_bad else 1
if __name__ == "__main__":
sys.exit(main())