UI 规范与两道常驻探针同步到 antd 版:classaudit.mjs + visualcheck.py,旧探针归档
docs/UI规范.md 按 antd 重写(16 章 / 十四条硬规矩 R1–R14): - §6 外壳(Header 56 + 两级 Sider + Content)、内容页不做多页签、页签只在页面内部, Tabs vs ViewSwitch 的判据;§9.3 值型控件的宽度归控件而非「标签+控件」+ nex-prose-value 豁免登记; §10 下拉面板「至少同宽」与折行、标记类全集 18 只;§5.1 按钮上的字必须整颗放得下; - §15 两道闸的判定口径写死,退出码都必须为 0。 scripts/ui/classaudit.mjs:四道判定(死类名 / 绕过登记表的图标 import / 裸 <button> / 浮层底部动作口径),基线 3912 个候选,必须在仓库根跑。 scripts/ui/visualcheck.py:登录 → 逐路由 × 逐档宽度 × 明暗截图,钉死八件事—— :root 尺子、行高、侧栏选中态(窄屏折叠时展开浮层复核二级项)、路由没被 path:'*' 静默吞掉、 display utility 被组件样式盖掉(R13 闸门)、横向溢出与切字、 控件标签**含下拉当前值**不许被省略号截断(散文型选项值按 nex-prose-value 放行)、 4xx/5xx 按 URL 分诊(素材缺文件单独计数,接口 404 点名发出它的路由)。 新增的 4xx/5xx 一条顺带治好了时间线 / 交付页「空状态对、代价是两条 404」的假绿。 旧的 audit.py / metrics.py / vocab.py 量的是已删的那套自造尺子,移进 scripts/ui/legacy/ 并标注作废。 README 与 docs/工程规范.md 同步:theme/ 只剩 antd.ts 一把尺子,导航与页签口径改为两级菜单 + 内部页签。 本轮验证:tsc 0 错 / classaudit 四道全 0 / vite build 通过 / visualcheck 两轮各 104 张(1440·992·768·430 × dark·light,空项目与数据齐全项目各一轮) console 0 条、HTTP 失败 0 条、断言 0 条。main
parent
d853560fa7
commit
62c356952c
29
README.md
29
README.md
|
|
@ -83,18 +83,27 @@ styles/ index.css(Tailwind @theme:语义名 → 变量,零像素)·
|
|||
再加一条 **ref 契约(R10)**:kit 组件一律 `forwardRef`,交给页面的 ref 只能是真实 DOM 节点,
|
||||
antd 的 `InputRef` / `TextAreaRef` 在 kit 内部折掉(`lib/ref.ts`)——React 18 的函数组件收不到 ref,
|
||||
`tsc` 不报错、像素不变,四处「点了不聚焦」就是这么静默死掉的(报告 26.6)。
|
||||
这些边界都不靠自觉:`scripts/ui/vocab.py` 逐文件比对源码用词(antd 落点 / 页面禁原生控件 /
|
||||
只读胶囊 / 私有皮肤棘轮 / ref 契约 / JSX 子节点上的注释,共六条),渲染结果由 `scripts/ui/audit.py` 量
|
||||
(七项判据:裸控件、字段错位、高度档位、横向溢出、下拉、**console 报错**、**浮层是否真的在视口内**)。选型理由(三条实测依据)、
|
||||
四层分工、四个咬过人的陷阱见 `docs/UI规范.md` §0.6,两道闸的口径见 §1.3 / §1.4。
|
||||
这些边界都不靠自觉,两道闸各管一头:
|
||||
|
||||
- `node scripts/ui/classaudit.mjs`——**源码用词**(静态):死类名 / 页面上的 `ant-*` 类名 /
|
||||
页面直接 `import 'antd'` / 自造像素档 / 页面禁原生控件 / ref 契约,逐文件比对;
|
||||
- `.venv/bin/python scripts/ui/visualcheck.py`——**渲染结果**(浏览器实测,逐路由 × 逐档宽度 × 明暗两色):
|
||||
`:root` 上的 `--ant-*` 是否真的铺到、文字行高有没有塌成 px、侧栏选中态是否跟路由走
|
||||
(窄屏折叠时展开浮层复核二级项)、横向溢出(祖先横向滚动/裁切盒接住的不算)、
|
||||
`overflow:hidden` 切掉的字、**控件标签被省略号截掉**(分段 / 页签 / 按钮 / **下拉当前值**)、
|
||||
display utility 有没有被组件样式静默盖掉(R13 那条层叠陷阱)、**console 报错**、
|
||||
**4xx/5xx**(按 URL 分诊:素材文件在开发库里缺失的 404 单独计数,接口 404 判失败并点名发出它的路由)。
|
||||
|
||||
选型理由、四层分工、咬过人的陷阱见 `docs/UI规范.md` §0(十四条硬规矩 R1–R14)与 §1。
|
||||
旧的手写规范探针(`scripts/ui/legacy/{audit,metrics,vocab}.py`)已作废归档。
|
||||
|
||||
改过控件、表单或主题,提交前跑一遍 UI 体检(前端 5173 与后端 8000 需在跑):
|
||||
|
||||
```bash
|
||||
cd frontend && npm run typecheck && npm run build
|
||||
.venv/bin/python scripts/ui/vocab.py # 词汇表 lint(不用起服务)
|
||||
.venv/bin/python -u scripts/ui/audit.py --width 1440 1280 900 --theme both --only page # 渲染结果体检
|
||||
.venv/bin/python -u scripts/ui/audit.py --width 1440 900 560 430 --theme both --only overlay
|
||||
cd frontend && npx tsc --noEmit && npm run build
|
||||
node scripts/ui/classaudit.mjs # 源码用词闸(不用起服务)
|
||||
NEX_WIDTHS=1440,992,768,430 NEX_THEMES=dark,light \
|
||||
.venv/bin/python -u scripts/ui/visualcheck.py # 渲染结果体检 + 截图
|
||||
```
|
||||
|
||||
体检默认量 dev server(5173):**`console` 那一项只能在 dev 上量**——React 与 antd 的告警是
|
||||
|
|
@ -575,8 +584,8 @@ blackdetect / freezedetect / font`。当 `subtitle_burn=false`(本机 ffmpeg
|
|||
cd backend && ../.venv/bin/python -m pytest -q # 全量回归,约 3 分钟,必须全绿
|
||||
bash -n scripts/*.sh # 脚本语法(shellcheck 没装也别跳过这条)
|
||||
cd frontend && npm run build # 类型与打包(tsc --noEmit && vite build)
|
||||
.venv/bin/python scripts/ui/vocab.py # 前端词汇表 lint(源码用词,秒级)
|
||||
.venv/bin/python -u scripts/ui/audit.py --width 1440 1280 900 --theme both --only page # UI 体检
|
||||
node scripts/ui/classaudit.mjs # 前端用词闸(源码,秒级)
|
||||
NEX_WIDTHS=1440,992,768,430 .venv/bin/python -u scripts/ui/visualcheck.py # UI 体检 + 截图
|
||||
```
|
||||
|
||||
碰到派发 / 合成 / 部署链路的改动,再补一次 §6.2 的端到端自检——pytest 用 TestClient
|
||||
|
|
|
|||
1582
docs/UI规范.md
1582
docs/UI规范.md
File diff suppressed because it is too large
Load Diff
14
docs/工程规范.md
14
docs/工程规范.md
|
|
@ -34,9 +34,11 @@ api/ → app/ → pages/ → components/{ui,forms,media}/ → theme/ · lib/ ·
|
|||
|
||||
**控件的行为与皮肤全部来自 antd 5**:浮层定位、翻边避让、焦点圈定与归还、键盘、Esc 分层、锁滚动、
|
||||
虚拟滚动、日期/下拉/抽屉/弹窗,都不再自己实现。`theme/` 是唯一给它定尺子的地方——
|
||||
`theme/antd.ts` 写 ComponentToken(402 行 / 33 个组件),`theme/metrics.ts` 写档位数值,
|
||||
`theme/css-vars.ts` 在 `createRoot` 之前把同一份数值注入成 `--ctl-h*` / `--tag-*` / `--radius-*` / `--fs-*`,
|
||||
`theme/palette.ts` 管明暗两套色板。于是 Tailwind 类和 antd token 用的是同一把尺子,漂不到两处去。
|
||||
`theme/antd.ts` 一处写完三件事:`buildAntdTheme(mode)` 的算法 + 全局 token(品牌色、表面色、
|
||||
少量结构性 token)+ ComponentToken;`applyRootVars(mode)` 在 `createRoot` 之前把 antd 算出来的
|
||||
`--ant-*` 铺到 `:root`,Tailwind 的 `@theme` 再把它转发成语义类名。**没有第二把尺子**:
|
||||
几何、字阶、圆角、间距、断点全部用 antd 默认档位(`metrics.ts` / `palette.ts` / `css-vars.ts`
|
||||
三个自造尺子文件已删,见 UI规范 §0 与 §1)。
|
||||
|
||||
`components/ui/` `forms/` 只认业务名字(`Button` `Input` `Select` `Menu` `Checkbox` `Overlay` `Pager`…),
|
||||
**全仓库只有 `theme/`、`app/providers.tsx`、`components/ui/`、`components/forms/` 四个目录可以
|
||||
|
|
@ -61,13 +63,13 @@ api/ → app/ → pages/ → components/{ui,forms,media}/ → theme/ · lib/ ·
|
|||
|
||||
| 想做的事 | 改哪儿 | 为什么不用改逻辑 |
|
||||
|---|---|---|
|
||||
| 加一类平台母版 | `pages/AssetLibrary.tsx:TYPE_META` 加一项 | 左栏、卡片、抽屉标题、生成台全部从这张表取标签/图标/提示 |
|
||||
| 加一个项目页签 | `app/layout/nav.ts` 加一行 + `app/router.tsx` 加子路由(带 `handle` 标题) | 侧栏与文档标题分别由这两处派生,无需注册第三处;新页签自动获得懒加载分包与 `ErrorBoundary` 兜底 |
|
||||
| 加一类平台母版 | `pages/AssetLibrary.tsx:TYPE_META` 加一项 | 内部页签(§6.4 的 `<Tabs>`)、卡片、抽屉标题、生成台全部从这张表取标签/图标/提示 |
|
||||
| 加一个项目环节 | `app/layout/nav.tsx:projectModules` 加一行 + `app/router.tsx` 加子路由(带 `handle` 标题) | 侧栏两级菜单与文档标题分别由这两处派生,无需注册第三处;新页自动获得懒加载分包与 `ErrorBoundary` 兜底 |
|
||||
| 改某页每页条数档位 | `Pager` 的 `sizes`(页面里传 `PAGE_SIZES`,`0` = 全部) | 默认档位和「全部」语义在 `Controls.tsx` 一处实现 |
|
||||
| 抽屉想要别的宽度 | `Drawer` 的 `width`(antd 的宽度值) | 默认值只在 `Overlay.tsx` 写一次,页面按屏宽传变体 |
|
||||
| 新增弹窗/表单 | `Modal` `Drawer` `Field` `FormRow` 组合 | 高度、间距、页脚按钮排布由原语和容器 `--ctl-h` 档位兜住 |
|
||||
| 加一类控件(tooltip / 日期选择 / 命令面板…) | `components/ui/` 新加一个文件包 antd 组件 → `ui/index.ts` 出口 → 需要定尺子就进 `theme/antd.ts` 的 ComponentToken → 登记进 UI规范 §0.5 | 页面那层永远只见到一个业务组件名;antd 没有合适的(比如整卡热区按钮)才自绘,自绘件登记进 §6 的「自绘区边界」 |
|
||||
| 控件档外的高度 | 容器上挂 `<Dense>`(31px)或写 `[--ctl-h:var(--ctl-h-md)]`;档位数值只有 `metrics.ts` 的 `controlHeight` 31/38/44 | 控件高度由 antd `componentSize` + token 下发,禁止单个控件写死像素 |
|
||||
| 控件档外的高度 | 容器上挂 `<Dense>`,或给控件传 antd 的 `size` | 控件高度由 antd `componentSize` + token 下发,禁止单个控件写死像素(R9) |
|
||||
|
||||
**根目录只允许**:`README.md`、`docker-compose.yml`、`.env`、`.env.example`、`.gitignore`
|
||||
和上面这些目录。历史上漂在根上的 `.schema shots`、`backend/nex_animation.db`(0 字节空库)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,342 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* 类名体检:抓「写了但生成不出规则」的死类名。
|
||||
*
|
||||
* 为什么要它:Tailwind v4 改过一批名字(break-anywhere → wrap-anywhere、
|
||||
* font-inherit 直接没了),写错不报错,只是静悄悄没有样式,肉眼很难发现。
|
||||
*
|
||||
* 做法:把项目真正的入口 CSS 喂给 Tailwind 编译器,逐个候选问它
|
||||
* 「这个词你能生成规则吗」。产物里有对应类选择器 = 有效,没有 = 死类名。
|
||||
* 判定用的是构建时同一套配置(@theme 语义色、自定义断点、@utility),不会误报。
|
||||
*
|
||||
* 第二道检查(2026-11 图标重设计加的):图标只许从 components/icons 取。
|
||||
* 全站唯一允许 `from '@ant-design/icons'` 的文件是那张登记表。
|
||||
* 为什么必须钉住:页面一旦直接 import 字形名(AppstoreOutlined),
|
||||
* 「这个位置到底是网格视图还是资产库」就又只有读代码的人才知道,
|
||||
* 换图标也又变成全站搜索替换——登记表当天就废掉。
|
||||
*
|
||||
* 第三道检查(2026-11 按钮重设计加的):裸 <button> 只许出现在「自定义表面族」里。
|
||||
* 判据不是「长得特殊」,而是几何:控件的宽高由所在的那块媒体/容器决定、
|
||||
* antd 三档(24/32/40)套不进去的,才是自定义表面(走带键、角标、遮罩、胶囊);
|
||||
* 只要是一颗独立矩形按钮,就必须是 antd <Button>,否则它不吃 theme token,
|
||||
* 换主题、改 controlHeight、加 disabled 语义时全都得手工再对一遍。
|
||||
* 白名单文件必须仍然写着 nex-* 标记类——标记类是给 CSS 和截图复核用的抓手,
|
||||
* 一个都不写了说明这一族已经被 antd 取代,条目就该从白名单里删掉。
|
||||
*
|
||||
* 第四道检查(2026-11 按钮重设计加的):浮层底部(Drawer 的 actions / Modal 的 footer)
|
||||
* 是一个「动作条」,不是一堆各写各的按钮。它只有一条口径,且必须能被机器验出来:
|
||||
* 从左到右 = 辅助动作 → 取消 → 主行动(和 antd Modal 自带页脚同序),整条右对齐。
|
||||
* 为什么把顺序也钉进脚本:这条是**语义**约定而不是样式约定,CSS 里没处可查;
|
||||
* 一旦某个抽屉把「保存」写在「取消」左边,全站抽屉就开始互相不一致,
|
||||
* 而这种漂移肉眼极难发现——只能靠脚本逐块读 DOM 顺序。
|
||||
*
|
||||
* 用法:node scripts/ui/classaudit.mjs [src 目录]
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const FRONTEND = path.resolve(HERE, '../../frontend')
|
||||
const { compile } = await import(path.join(FRONTEND, 'node_modules/tailwindcss/dist/lib.mjs'))
|
||||
|
||||
const SRC = path.resolve(process.argv[2] || path.join(FRONTEND, 'src'))
|
||||
const ENTRY = path.join(FRONTEND, 'src/styles/index.css')
|
||||
|
||||
/** antd 自己的类、我们的体检标记、自有组件类:都不是 Tailwind 的活 */
|
||||
const FOREIGN = /^(ant|nex|nf)-/
|
||||
|
||||
/**
|
||||
* 剥掉一行里的注释,并返回「这一行结束时是否仍在块注释里」。
|
||||
*
|
||||
* 症状(2026-11 第 4 道闸上线后冒出来的假阳性):块注释的**续行**不以 `*` 开头,
|
||||
* 于是「… .ant-segmented-item-label 的 overflow:hidden 裁掉半个字」收尾的那一行
|
||||
* 被当成源码用词,`overflow:hidden` 报成死类名——可它根本不是类名,是中文注释里的
|
||||
* 一个 CSS 属性。旧判据只看行首,天然处理不了跨行注释。
|
||||
* 做法:真的跟着块注释开合标记走状态;同一行内的整段抹掉,
|
||||
* 行首 // 与行尾 ` // `(代码里不会出现裸双斜杠)一并抹掉。
|
||||
*/
|
||||
function stripComments(line, wasInBlock) {
|
||||
let inBlock = wasInBlock()
|
||||
let q = null // 引号内的 /* 与 // 不是注释;字符串本身要留着(className 就在引号里)
|
||||
let out = ''
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]
|
||||
const two = line.slice(i, i + 2)
|
||||
if (inBlock) {
|
||||
if (two === '*/') { inBlock = false; i++ }
|
||||
continue
|
||||
}
|
||||
if (q) {
|
||||
out += ch
|
||||
if (ch === '\\') { if (i + 1 < line.length) { out += line[i + 1]; i++ } continue }
|
||||
if (ch === q) q = null
|
||||
continue
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === '`') { q = ch; out += ch; continue }
|
||||
if (two === '/*') { inBlock = true; i++; continue }
|
||||
if (two === '//') break
|
||||
out += ch
|
||||
}
|
||||
return [out, inBlock]
|
||||
}
|
||||
|
||||
function candidates() {
|
||||
const out = new Map()
|
||||
const walk = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walk(p); continue }
|
||||
if (!/\.(tsx|jsx)$/.test(ent.name)) continue
|
||||
let inBlock = false // 块注释状态要跨行:只看行首会漏掉续行(见 stripComments)
|
||||
inBlock = false
|
||||
fs.readFileSync(p, 'utf8').split('\n').forEach((raw, i) => {
|
||||
const [line, block] = stripComments(raw, () => inBlock)
|
||||
inBlock = block
|
||||
if (!line.trim()) return
|
||||
for (const tok of line.split(/[\s'"`]+/)) {
|
||||
if (tok.length < 3 || /-$/.test(tok) || FOREIGN.test(tok)) continue
|
||||
if (/[一-龥]/.test(tok)) continue
|
||||
if (!/^[a-z]/.test(tok)) continue
|
||||
if (!/^[\w:[\]().,%#*/=&>+~-]+$/.test(tok)) continue
|
||||
for (const ch of '[]()') {
|
||||
const open = ch === '[' || ch === '('
|
||||
const n = (tok.split(ch).length - 1)
|
||||
const mate = open ? (ch === '[' ? ']' : ')') : (ch === ']' ? '[' : '(')
|
||||
if (n !== tok.split(mate).length - 1) return
|
||||
}
|
||||
const at = `${path.relative(FRONTEND, p)}:${i + 1}`
|
||||
if (!out.has(tok)) out.set(tok, [])
|
||||
out.get(tok).push(at)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
walk(SRC)
|
||||
return out
|
||||
}
|
||||
|
||||
function generated(css) {
|
||||
const set = new Set()
|
||||
for (const m of css.matchAll(/\.((?:\\.|[-\w])+)/g)) set.add(m[1].replace(/\\(.)/g, '$1'))
|
||||
return set
|
||||
}
|
||||
|
||||
const compiler = await compile(fs.readFileSync(ENTRY, 'utf8'), {
|
||||
base: path.dirname(ENTRY),
|
||||
async loadStylesheet(id, base) {
|
||||
let p = id.startsWith('.') ? path.resolve(base, id) : path.resolve(FRONTEND, 'node_modules', id)
|
||||
if (fs.existsSync(p) && fs.statSync(p).isDirectory()) p = path.join(p, 'index.css')
|
||||
return { path: p, base: path.dirname(p), content: fs.readFileSync(p, 'utf8') }
|
||||
},
|
||||
async loadModule(p, base) { return { module: null, base } },
|
||||
})
|
||||
|
||||
const cands = candidates()
|
||||
const all = generated(compiler.build([...cands.keys()]))
|
||||
|
||||
/** 首段(grid / text / max-h …)在产物里出现过的,才认为「本该是工具类」 */
|
||||
const roots = new Set()
|
||||
for (const name of all) {
|
||||
const core = name.split(':').pop().replace(/\[[^\]]*\].*$/, '')
|
||||
roots.add(core.split('-')[0])
|
||||
}
|
||||
|
||||
/** 文案 / props 值 / antd Menu 的 group key —— 是英语单词,不是类名 */
|
||||
const PROSE = new Set([
|
||||
'align', 'break', 'duration', 'flex-end', 'gap', 'items', 'left', 'list', 'max',
|
||||
'max-height', 'min', 'min-width', 'not', 'object', 'order', 'pointer', 'right',
|
||||
'row', 'text', 'top', 'group-global', 'group-project',
|
||||
])
|
||||
|
||||
const dead = []
|
||||
for (const [tok, where] of cands) {
|
||||
if (all.has(tok)) continue
|
||||
const core = tok.split(':').pop()
|
||||
if (/^\d+$/.test(core) || /^[\w-]+\[[a-z0-9]\]$/.test(core)) continue // 模板字符串里的 key 片段
|
||||
const root = core.replace(/\[[^\]]*\]/g, '').split('-').filter(Boolean)[0]
|
||||
if (!root || !roots.has(root) || PROSE.has(core)) continue
|
||||
dead.push([tok, where])
|
||||
}
|
||||
|
||||
dead.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
for (const [tok, where] of dead) console.log(`DEAD ${tok.padEnd(26)} ${where.join(' ')}`)
|
||||
console.log(`\n${dead.length} 个死类名 / ${cands.size} 个候选`)
|
||||
|
||||
/* ── 第 2 条:图标出口唯一 ───────────────────────────────────────────────
|
||||
登记表自己是唯一可以 import 字形名的文件;其余文件一律写语义别名
|
||||
(IconGrid / IconWarn / IconTimeline),要新图形先在登记表登记一行。 */
|
||||
const REGISTRY = path.join(SRC, 'components/icons/index.ts')
|
||||
const stray = []
|
||||
const walkIcons = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walkIcons(p); continue }
|
||||
if (!/\.(tsx|ts)$/.test(ent.name) || p === REGISTRY) continue
|
||||
fs.readFileSync(p, 'utf8').split('\n').forEach((line, i) => {
|
||||
if (/from '@ant-design\/icons'/.test(line)) stray.push(`${path.relative(FRONTEND, p)}:${i + 1}: ${line.trim()}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
walkIcons(SRC)
|
||||
for (const hit of stray) console.log(`ICON ${hit}`)
|
||||
console.log(`${stray.length} 处绕过登记表的图标 import(只许 ${path.relative(FRONTEND, REGISTRY)})`)
|
||||
|
||||
/* ── 第 3 条:裸 <button> 收口到自定义表面族 ──────────────────────────────
|
||||
每条都要写清「为什么不是 antd Button」;新增文件先进这张表,别先写裸按钮。 */
|
||||
const CUSTOM_SURFACES = {
|
||||
'src/components/ui/Controls.tsx': 'Chip / TagChip 的叉:胶囊与标签,高度跟同排 antd 控件对齐(--ant-control-height*),antd 无此形态',
|
||||
'src/components/ui/Overlay.tsx': 'Scrim:整屏遮罩,点空白关闭;不是按钮,是命中区',
|
||||
'src/components/media/MediaThumb.tsx': '版本角标 + 删除叉:压在封面上的徽标,尺寸由封面决定',
|
||||
'src/components/media/AudioPlay.tsx': '走带键:三档直径 28/22/20 由音频行高决定,antd 圆钮最矮 24',
|
||||
'src/components/media/MediaLightbox.tsx': '灯箱左右翻页:压在媒体上的 40px 玻璃圆钮 + 悬停位移',
|
||||
'src/components/media/VersionPanel.tsx': '版本封面缩略:图块本身是热区,光标是 zoom-in',
|
||||
'src/pages/project/Storyboard.tsx': '注释里解释「卡片为什么不是 button」——命中数为 0 时删条目',
|
||||
}
|
||||
|
||||
/** 宿主元素不是字面量 <button> 的文件:Tile 用 <As>,As 可以是 button。
|
||||
它们同样要带 nex-* 标记,但不参与「字面量命中」对账。 */
|
||||
const HOST_ELEMENT = {
|
||||
'src/components/ui/Tile.tsx': 'Tile:整块热区(瓷贴/导航行/账号胶囊),宿主标签由 onClick 决定',
|
||||
}
|
||||
|
||||
const bare = []
|
||||
const hits = new Map()
|
||||
const walkButtons = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walkButtons(p); continue }
|
||||
if (!/\.tsx$/.test(ent.name)) continue
|
||||
const rel = path.relative(FRONTEND, p)
|
||||
const lines = fs.readFileSync(p, 'utf8').split('\n')
|
||||
lines.forEach((line, i) => {
|
||||
if (/^\s*(\*|\/\/|\/\*|#)/.test(line)) return // 注释里提到 button 不算
|
||||
if (!/<button(\s|>|$)/.test(line)) return
|
||||
if (/<\/button>|^\s*return <button/.test(line) || true) {
|
||||
if (!hits.has(rel)) hits.set(rel, [])
|
||||
hits.get(rel).push(i + 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
walkButtons(SRC)
|
||||
|
||||
const ALLOWED = { ...CUSTOM_SURFACES, ...HOST_ELEMENT }
|
||||
for (const [rel, rows] of [...hits].sort()) {
|
||||
if (!ALLOWED[rel]) {
|
||||
bare.push(`${rel}:${rows.join(',')} — 裸 <button> 不在自定义表面族白名单里,换 <Button>`)
|
||||
continue
|
||||
}
|
||||
const src = fs.readFileSync(path.join(FRONTEND, rel), 'utf8')
|
||||
if (!/\bnex-[a-z]/.test(src)) {
|
||||
bare.push(`${rel} — 白名单里的文件一个 nex-* 标记类都没有了,要么补标记要么从白名单删除`)
|
||||
}
|
||||
}
|
||||
/* 白名单要诚实:条目命中数为 0 就说明这一族已经被 antd 取代,打出来提醒删除,
|
||||
但不算失败——留一天的空条目比漏一颗裸按钮危害小。 */
|
||||
for (const rel of Object.keys(HOST_ELEMENT)) {
|
||||
if (CUSTOM_SURFACES[rel]) bare.push(`${rel} — 同一个文件既在白名单又在宿主元素表,删一个`)
|
||||
}
|
||||
for (const hit of bare) console.log(`BTN ${hit}`)
|
||||
const stale = Object.keys(CUSTOM_SURFACES).filter((k) => !hits.has(k))
|
||||
console.log(`${bare.length} 处未收口的裸 <button>(白名单 ${Object.keys(CUSTOM_SURFACES).length} 个文件 / 实际命中 ${hits.size} 个)`
|
||||
+ (stale.length ? `\n 可清理的白名单条目:${stale.join(' ')}` : ''))
|
||||
|
||||
/* ── 第 4 条:浮层底部动作条 ────────────────────────────────────────────
|
||||
口径的权威解释在 components/ui/Overlay.tsx 的 DRAWER_ACTIONS 上方;
|
||||
这里只负责让违反口径的代码无法合入。 */
|
||||
|
||||
/** 从 src[open](必须是 '{')找到配对的 '}',返回下标;找不到返回 -1。
|
||||
字符串/模板字面量整段跳过,JSX 表达式里的 } 用深度计数处理。 */
|
||||
function braceEnd(src, open) {
|
||||
let depth = 0
|
||||
for (let i = open; i < src.length; i++) {
|
||||
const c = src[i]
|
||||
if (c === '"' || c === "'" || c === '`') {
|
||||
const q = c
|
||||
i++
|
||||
while (i < src.length) {
|
||||
if (src[i] === '\\') { i += 2; continue }
|
||||
if (src[i] === q) break
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (c === '{') depth++
|
||||
else if (c === '}' && --depth === 0) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** 取 <Button …> 的开标签全文(含 '>')。深度 > 0 时不认 '>',
|
||||
所以 onClick={() => x} 里的箭头不会被误当成开标签结束。 */
|
||||
function openTag(src, start) {
|
||||
let depth = 0
|
||||
for (let i = start + 1; i < src.length; i++) {
|
||||
const c = src[i]
|
||||
if (c === '"' || c === "'" || c === '`') {
|
||||
const q = c
|
||||
i++
|
||||
while (i < src.length) {
|
||||
if (src[i] === '\\') { i += 2; continue }
|
||||
if (src[i] === q) break
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (c === '{') depth++
|
||||
else if (c === '}') depth--
|
||||
else if (c === '>' && depth === 0) return src.slice(start, i + 1)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 动作条的例外:整条只有一个动作、或根本不是动作条(只是把按钮当装饰塞进标题)。
|
||||
每条都要写理由,别用它绕过口径。 */
|
||||
const FOOTER_EXEMPT = new Set([])
|
||||
|
||||
const footerViolations = []
|
||||
const walkFooters = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walkFooters(p); continue }
|
||||
if (!/\.tsx$/.test(ent.name)) continue
|
||||
const rel = path.relative(FRONTEND, p)
|
||||
const src = fs.readFileSync(p, 'utf8')
|
||||
for (const m of src.matchAll(/\b(actions|footer)=\{/g)) {
|
||||
const open = m.index + m[0].length - 1
|
||||
const close = braceEnd(src, open)
|
||||
if (close < 0) continue
|
||||
const block = src.slice(open, close)
|
||||
const tags = []
|
||||
for (const b of block.matchAll(/<Button(?=[\s/>])/g)) {
|
||||
const at = open + b.index
|
||||
tags.push({ raw: openTag(src, at), line: src.slice(0, at).split('\n').length })
|
||||
}
|
||||
if (tags.length < 2) continue // 单动作不违反「取消在前」
|
||||
if (FOOTER_EXEMPT.has(`${rel}:${m[1]}`)) continue
|
||||
const at = (n) => `${rel}:${tags[0].line} (${m[1]}) ${n}`
|
||||
const sizeHit = tags.find((t) => /\bsize="/.test(t.raw))
|
||||
if (sizeHit) footerViolations.push(at('① 浮层底部一律 md 档,别写 size'))
|
||||
const primaries = tags.filter((t) => /type="primary"/.test(t.raw))
|
||||
if (primaries.length > 1) footerViolations.push(at(`② 一条底部最多一颗 type="primary",当前 ${primaries.length} 颗`))
|
||||
for (const t of tags.filter((x) => /\bdanger\b/.test(x.raw))) {
|
||||
if (!/type="primary"/.test(t.raw)) {
|
||||
footerViolations.push(`${rel}:${t.line} (${m[1]}) ③ 破坏性动作用 type="primary" danger`
|
||||
+ '——裸描边按钮比「取消」还轻,确认权重就反了')
|
||||
}
|
||||
}
|
||||
const last = tags[tags.length - 1]
|
||||
if (!/type="primary"/.test(last.raw)) {
|
||||
footerViolations.push(`${rel}:${last.line} (${m[1]}) ④ 最后一颗必须是主行动 type="primary"`
|
||||
+ '(DOM 顺序 = 视觉顺序:辅助 → 取消 → 主行动)')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
walkFooters(SRC)
|
||||
for (const hit of footerViolations) console.log(`FOOT ${hit}`)
|
||||
console.log(`${footerViolations.length} 处不符合浮层底部动作口径(Drawer actions / Modal footer)`)
|
||||
|
||||
process.exit(dead.length + stray.length + bare.length + footerViolations.length ? 1 : 0)
|
||||
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
#!/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。
|
||||
|
|
@ -13,8 +17,8 @@
|
|||
结论口径:
|
||||
· naked(裸的原生 input/select/textarea)必须 0;
|
||||
· misaligned(同一视觉盒子里字段列线错开 >1px、行内标签中心线与控件错开)必须 0;
|
||||
· 控件高度只准 31 / 38 / 44 三档(theme/metrics.ts 的 controlHeight);
|
||||
视口 ≤560px 改准 36 / 40 / 44(css-vars.ts 的 touch() 抬高两档令牌);
|
||||
· 控件高度只准 antd 的三档 24 / 32 / 40(theme/antd.ts 不改几何,尺子只有一把);
|
||||
视口 ≤560px 仍然单独量一轮(窄屏堆叠与抽屉宽度只在那一档暴露),准的是同一把尺子;
|
||||
内容自定的盒子(整卡热区、缩略图角标、图标位)不在档位里,
|
||||
必须写进下面的 EXPECTED 白名单并给理由——白名单里出现「没命中」的条目同样报出来,
|
||||
免得规范修好了、白名单还留着当遮羞布;
|
||||
|
|
@ -107,12 +111,16 @@ OVERLAYS = [
|
|||
("users_form", "/users", [], "main"),
|
||||
]
|
||||
|
||||
# 三档控件高度 = theme/metrics.ts 的 controlHeight(sm / main / lg)
|
||||
TIERS_OK = {31, 38, 44}
|
||||
# ≤560px(breakpoints.narrow)走触摸档:css-vars.ts 的 touch() 把 main/md 抬到 40 / 36,
|
||||
# lg 不跟着抬(页面不用 lg)。窄屏必须真量,否则「只在 ≤560 生效的规则」只是推理。
|
||||
# 控件高度 = 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 = {36, 40, 44}
|
||||
TIERS_OK_TOUCH = TIERS_OK
|
||||
|
||||
# 白名单:不是控件的盒子 + 有意的例外。每条必须写理由,且必须被命中(未命中=失效)。
|
||||
# route 用视图名做前缀匹配;h 是像素高;cls 是 "tag.class1.class2" 的正则。
|
||||
|
|
@ -126,15 +134,19 @@ EXPECTED = [
|
|||
"高度=内容是这只组件的定义,bar/pill 两档自己写 --ctl-h 与同排控件同高;"
|
||||
"档位检查对它没有意义,但保留在报告里,方便看见「某处热区突然 200px」这种失控"),
|
||||
# ── 贴在媒体上 / 文字行内的小按钮:自绘覆盖层,不参与表单档位 ──────────
|
||||
dict(kind="tier", h=17, cls=r"^button\.nex-media-badge",
|
||||
why="缩略图左下角时长角标(media/MediaThumb.tsx):媒体覆盖层,钉在 34px 方块上;"
|
||||
"抬到 31 会盖掉半张图"),
|
||||
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 是圆点能看清的最小档"),
|
||||
dict(kind="tier", h=24, cls=r"^button\.nex-icon-spot",
|
||||
why="24px 方形图标位(ui/Button.tsx 的 IconSpot):贴在说明文字行内,"
|
||||
"抬到 31 会把基线顶开"),
|
||||
# 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 会让页签被顶高"),
|
||||
]
|
||||
|
||||
# 横向溢出白名单(真溢出该修的就修,这里只留设计上允许溢出/自带滚动的)
|
||||
|
|
@ -147,7 +159,8 @@ CONSOLE_IGNORE: list[tuple[str, str]] = []
|
|||
|
||||
# 命中记录跨视口/主题汇总:某个角标只在宽屏出现,不该在窄屏那轮被当成失效规则
|
||||
HIT: set[int] = set()
|
||||
COVERS_PAGES = True # run() 按 --only 改写
|
||||
COVERS_PAGES = True # run() 按 --only 改写
|
||||
COVERS_OVERLAYS = True # 同上:只跑页面时浮层类白名单必然不命中
|
||||
|
||||
|
||||
def explain(kind: str, item: dict, view: str):
|
||||
|
|
@ -426,7 +439,9 @@ class Audit:
|
|||
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 "有未解释项,见上。"))
|
||||
if last and COVERS_PAGES: # 只跑浮层时页面档位规则不会命中,别误报失效
|
||||
# 只跑一半时不判失效:--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── 白名单失效(整轮没命中,删掉或放宽)──────────")
|
||||
|
|
@ -439,8 +454,9 @@ class Audit:
|
|||
|
||||
|
||||
async def run(widths, themes, only, shots: pathlib.Path) -> int:
|
||||
global COVERS_PAGES
|
||||
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:
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
# ⚠ 已作废(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)。
|
||||
|
||||
只有这一份实现:audit.py 把这里的 JS 片段拼进 page.evaluate,
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
#!/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。
|
||||
"""前端词汇表 lint:页面只许说业务,控件的「说法」由 kit 层统一。
|
||||
|
||||
为什么需要它:audit.py 量的是**渲染结果**(高度、对齐、溢出),
|
||||
|
|
@ -25,6 +29,16 @@
|
|||
于是「点了不聚焦」「不滚到当前节点」这类功能静默死掉(详见报告第 26 章)。
|
||||
6. JSX **子节点**位置上的注释(`/* … */` 或 `// …`)不是注释,是文本。
|
||||
只有 `{/* … */}` 才是注释;直接写的会被渲染成一行字挂在页面上。
|
||||
7. 图标只能用 @ant-design/icons,不许再拿 Unicode 字符当图标。
|
||||
规则 1 只挡 antd 的**控件**——图标是资产不是控件,走 icon 槽不绕过任何皮肤,
|
||||
所以页面直接 import @ant-design/icons 是合法的,这一条反过来逼它把字符换掉:
|
||||
7a) 几何图形 / 表情 / 箭头类字符出现在代码里就是图标位(✕ ▶ ▧ ⇪ ⚠ ★ …);
|
||||
散文方向、键帽、数学符号、带圈序号在 ICON_OK 里逐条写理由豁免。
|
||||
7b) 中文标签的**首尾**挂 ←↑→↓ = 把箭头当图标用,请走按钮的 icon 槽。
|
||||
正文里「创建项目 → 导入分镜」这类流程连接号不受影响(它不在标签首尾)。
|
||||
为什么值得单独一条闸:图标字符的粗细、大小、基线全部由字体决定,同一个「警告」
|
||||
在按钮里 12px、在小标题里 11px、在提示行里 13px,是「同一个意思三种长相」的根因;
|
||||
audit.py 量不出这种分叉,只能从源码侧夹住。
|
||||
退出码:0 = 词汇表干净;1 = 有违规。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
|
@ -45,13 +59,20 @@ ANTD_OK = {
|
|||
"components/forms", # kit:表单控件
|
||||
"components/media", # kit:媒体族覆盖层
|
||||
}
|
||||
ANTD_OK_FILES = {"app/providers.tsx"}
|
||||
ANTD_IMPORT = re.compile(r"""from\s+'(antd[^']*|@ant-design/[^']*)'""")
|
||||
# stores/notice.ts:全站唯一的「操作结果回执」入口,必须直接叫 antd 的 message /
|
||||
# notification,否则每页自己弹一次,位置与时长又是一把私尺。
|
||||
ANTD_OK_FILES = {"app/providers.tsx", "stores/notice.ts"}
|
||||
# 只挡 **控件包**。@ant-design/icons 是图标资产,不是控件:页面 import 它
|
||||
# 不会绕过 theme/antd.ts(图标没有皮肤,只继承容器字号与颜色),
|
||||
# 反过来页面**必须**能 import 它——见规则 7。
|
||||
ANTD_IMPORT = re.compile(r"""from\s+'(antd(?:/[^']*)?)'""")
|
||||
|
||||
# ── 规则 4:页面私有皮肤常量棘轮 ───────────────────────────────────────
|
||||
# 数字 = 该文件今天欠下的数量,只准调小。理由写在这里,别只写数字。
|
||||
SKIN_CEILINGS: dict[str, tuple[int, str]] = {
|
||||
"pages/Help.tsx": (36, "使用手册正文排版(字号/行距/目录/代码块)。这是文档自己的排版,"
|
||||
"pages/Help.tsx": (38, "使用手册正文排版(字号/行距/目录/代码块,含 38 条:SHELL 终端块、"
|
||||
"SIDE_LABEL 目录、TAG_A/TAG_H3 正文链接与三级标题、CHECKS 清单前缀、"
|
||||
"ICON 章节图标位)。这是文档自己的排版,"
|
||||
"不是控件皮肤:手册要能独立复刻旧站文章版式,硬塞进 kit 反而把"
|
||||
"「控件词汇表」和「文章排版」绑成一套,改字号要动 kit。"),
|
||||
"pages/AssetLibrary.tsx": (12, "资产墙的文件砖 / 导入预览 / 弹窗列表还没收进 kit。"
|
||||
|
|
@ -68,13 +89,16 @@ SKIN_CEILINGS: dict[str, tuple[int, str]] = {
|
|||
"pages/project/Review.tsx": (1, "同上(EMPTY_CELL)。"),
|
||||
"pages/project/Library.tsx": (1, "勾中计数条 PICKED:等 Chip 选中态收敛后删除。"),
|
||||
"pages/project/Timeline.tsx": (1, "副行文案 SUBLINE:等 kit 出 Subline 后删除。"),
|
||||
"app/layout/SideNav.tsx": (1, "导航图标位 NAV_ICON:等 IconSpot 支持导航档后删除。"),
|
||||
}
|
||||
SKIN_CONST = re.compile(r"^const\s+([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$", re.M)
|
||||
# 值里出现这些词 = 它在拼控件皮肤,不是在写业务文案
|
||||
# 颜色名跟着 styles/index.css 的 @theme 走:@theme 把 Tailwind 自带调色板清空、
|
||||
# 只登记转发 --ant-* 的那几十个,所以「在拼皮肤」= 用了这些名字之一。
|
||||
# 上一版这里还写着 text-ink / text-muted / text-tiny(重写前那套已删除的词),
|
||||
# 于是 text-text-secondary 这类真正在用的词一条都不计账,棘轮只降不升就成了假账。
|
||||
SKIN_TOKEN = re.compile(
|
||||
r"\b(?:bg-|border-|rounded-|shadow-|ring-|gap-|p-[trblxy]?-|m-[trblxy]?-|"
|
||||
r"leading-|tracking-|text-(?:ink|ink-2|ink-3|muted|faint|dim|on-accent|tiny|caption|ui|label|title|body)\b)")
|
||||
r"leading-|tracking-|text-(?:text|primary|on-primary|error|warning|success|info|white|black)\b)")
|
||||
|
||||
NATIVE = re.compile(r"<(button|input|select|textarea)(?=[\s/>])")
|
||||
|
||||
|
|
@ -98,6 +122,45 @@ CHIP_OPEN = re.compile(r"<Chip\b")
|
|||
TAG_GAP = ("<", ">")
|
||||
ACTIONProp = re.compile(r"\b(?:onClick|onOpen|href)\b")
|
||||
|
||||
# ── 规则 7:图标必须来自 @ant-design/icons ─────────────────────────────
|
||||
# 判定区间:单/双箭头与方块三角(2039–203A、2190–2BFF)、表情与象形文字
|
||||
# (1F000–1FAFF)、变体选择符 FE0F。这三段基本等于「会被当图标用的字符」。
|
||||
ICON_RANGES = ((0x2039, 0x203A), (0x2190, 0x2BFF), (0x1F000, 0x1FAFF), (0xFE0F, 0xFE0F))
|
||||
# 白名单:这些是**正文标点 / 键帽 / 序号**,不是图标位。加一条要写理由。
|
||||
ICON_OK = {
|
||||
"\u2190": "散文里的方向", "\u2192": "散文里的方向与流程连接",
|
||||
# ↑↓ 放行给键帽与快捷键提示(<code>↑</code>、「上一镜(K / ↑)」);
|
||||
# 按钮标签首尾的箭头由下面的 7b 单独拦,所以放行不会放走「↑ 上移」这种图标位。
|
||||
"\u2191": "方向键键帽 / 快捷键提示", "\u2193": "方向键键帽 / 快捷键提示",
|
||||
"\u2194": "双向", "\u2195": "双向",
|
||||
"\u21d2": "推出", "\u21d0": "推导", "\u21d4": "等价",
|
||||
"\u2318": "macOS 键帽", "\u21e7": "macOS 键帽", "\u2325": "macOS 键帽",
|
||||
"\u2303": "macOS 键帽", "\u21e5": "Tab 键帽", "\u23ce": "Enter 键帽",
|
||||
"\u2248": "约等", "\u2264": "小于等于", "\u2265": "大于等于", "\u2260": "不等",
|
||||
"\u221e": "无穷", "\u2212": "数学负号", "\u00b1": "正负",
|
||||
"\u00d7": "尺寸乘号(1024\u00d7576)", "\u00b7": "间隔号",
|
||||
"\u2026": "省略号", "\u2014": "破折号", "\u2013": "连接号",
|
||||
}
|
||||
# 7b 专门处理的箭头:它们在 ICON_OK 里(正文常用),只有贴在中文标签首尾才算图标位。
|
||||
ARROW_LABEL = "\u2190\u2191\u2192\u2193"
|
||||
|
||||
|
||||
def is_circled(ch: str) -> bool:
|
||||
"""\u2460\u2026\u24e9 / \u3251\u2026\u325f:带圈序号,帮助页拿来标流程步骤,不是图标。"""
|
||||
o = ord(ch)
|
||||
return 0x2460 <= o <= 0x24E9 or 0x3251 <= o <= 0x325F
|
||||
|
||||
|
||||
def icon_glyphs(text: str) -> list[str]:
|
||||
return [c for c in text
|
||||
if c not in ICON_OK and not is_circled(c)
|
||||
and any(a <= ord(c) <= b for a, b in ICON_RANGES)]
|
||||
|
||||
|
||||
ICON_CONTENT = re.compile(r"content-\[[^\]]*\]") # [&>li]:before:content-['\u2713'] 这类 CSS 内容
|
||||
TEXT_NODE = re.compile(r">([^<>]+)<")
|
||||
CJK = re.compile(r"[\u4e00-\u9fff]")
|
||||
|
||||
|
||||
def strip_code(src: str) -> str:
|
||||
"""去掉注释但保住行号:JSX 注释里写「<input>」不该被当成用了原生控件。"""
|
||||
|
|
@ -260,6 +323,22 @@ def scan() -> int:
|
|||
f"React 会把它当文本渲染到页面上——要注释请用 {{/* … */}} 或移到 JSX 外面")
|
||||
bad += 1
|
||||
|
||||
# 7) 图标必须走标准图标库(kit 层同样受管:它最容易顺手写一个 \u2715)
|
||||
src7 = ICON_CONTENT.sub("", src)
|
||||
for i, line in enumerate(src7.split("\n"), 1):
|
||||
glyphs = icon_glyphs(line)
|
||||
if glyphs:
|
||||
uniq = "".join(dict.fromkeys(glyphs))
|
||||
print(f"\u2717 规则7 字符图标 {r}:{i}: 「{uniq}」是 Unicode 字符当图标 —— "
|
||||
f"请用 @ant-design/icons(按钮走 icon 槽,行内文字用 <IconText>)")
|
||||
bad += 1
|
||||
for m in TEXT_NODE.finditer(line):
|
||||
txt = m.group(1).strip()
|
||||
if txt and CJK.search(txt) and (txt[0] in ARROW_LABEL or txt[-1] in ARROW_LABEL):
|
||||
print(f"\u2717 规则7 箭头图标 {r}:{i}: 「{txt[:28]}」把箭头当图标 —— "
|
||||
f"导航按钮不写尾随箭头,方向动作用 LeftOutlined / ArrowUpOutlined 进 icon 槽")
|
||||
bad += 1
|
||||
|
||||
if not r.startswith(("pages/", "app/")):
|
||||
continue
|
||||
|
||||
|
|
@ -0,0 +1,365 @@
|
|||
#!/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 切掉的字;
|
||||
分段控件 / 页签 / 按钮 / 下拉当前值的文字必须整颗放得下(省略号也算截断)。
|
||||
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").split(",") if r]
|
||||
# 侧栏导航覆盖到的路由:这些必须有选中项,否则 selectedKeys 断了
|
||||
NAV_ROUTES = [r for r in ROUTES if "/account" not in r and "/users" not in r and "/help" not in r]
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
# rc-resize-observer 在 React 18 下的已知告警,antd 内部依赖,与应用代码无关
|
||||
IGNORE = ("findDOMNode is deprecated", "Support for React will be removed")
|
||||
|
||||
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 sel = document.querySelector('.ant-menu-item-selected')
|
||||
|| 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'),
|
||||
},
|
||||
menu: sel ? {bg: sc.backgroundColor, color: sc.color, text: sel.textContent.trim().slice(0, 12)} : 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 高
|
||||
text: [...document.querySelectorAll('.text-xs, .text-sm, .text-base')].slice(0, 12)
|
||||
.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; // 整句型选项值:见上面的豁免说明
|
||||
if (overflows(el)) return;
|
||||
[...el.querySelectorAll('*')].some(overflows);
|
||||
});
|
||||
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)};
|
||||
}"""
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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 "{id}" in r:
|
||||
if not pid:
|
||||
pid = page.evaluate("""async () => {
|
||||
const t = localStorage.getItem('nex-auth');
|
||||
const tok = t ? (JSON.parse(t)?.state?.token || JSON.parse(t)?.token) : '';
|
||||
const r = await fetch('/api/projects', {headers:{Authorization:'Bearer '+tok}});
|
||||
const j = await r.json();
|
||||
const list = j.projects || j.items || j.data || (Array.isArray(j) ? j : []);
|
||||
return list[0]?.id || '';
|
||||
}""")
|
||||
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
|
||||
probe = page.evaluate(PROBE)
|
||||
lay = page.evaluate(LAYOUT)
|
||||
for o in lay["out"]:
|
||||
problems.append(f"{width}/{theme}{r}: 捅出视口 {o}")
|
||||
for o in lay["clip"]:
|
||||
problems.append(f"{width}/{theme}{r}: 文字被切 {o}")
|
||||
for o in lay["disp"]:
|
||||
problems.append(f"{width}/{theme}{r}: display utility 被组件样式盖掉 {o}")
|
||||
for o in lay["trunc"]:
|
||||
problems.append(f"{width}/{theme}{r}: 控件标签被省略号截断 {o}")
|
||||
if probe["theme"] != theme:
|
||||
problems.append(f"{width}/{theme}{r}: data-theme={probe['theme']}")
|
||||
for k, val in probe["root"].items():
|
||||
if not val:
|
||||
problems.append(f"{width}/{theme}{r}: :root 缺 --{k}")
|
||||
for bad in probe["text"]:
|
||||
problems.append(f"{width}/{theme}{r}: 行高塌了 {bad}")
|
||||
# 账号 / 用户管理 / 手册不在侧栏导航里,没有选中项是正常的
|
||||
if r in NAV_ROUTES and not probe["menu"]:
|
||||
problems.append(f"{width}/{theme}{r}: 菜单没有选中项")
|
||||
elif r in NAV_ROUTES and probe.get("collapsed") and probe.get("subSelected"):
|
||||
# 折叠态下只验到父级还不够: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}{r}: 折叠态浮层里没有选中的二级项")
|
||||
finally:
|
||||
page.mouse.move(5, 5)
|
||||
page.wait_for_timeout(150)
|
||||
slug = r.strip("/").replace("/", "-") or "home"
|
||||
name = f"{width}-{theme}-{slug}.png"
|
||||
page.screenshot(path=str(SHOTS / name))
|
||||
if width == WIDTHS[0]:
|
||||
print(f"shot {name:38} menu={probe['menu']} header={probe['header']}")
|
||||
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())
|
||||
Loading…
Reference in New Issue