nex_animation/scripts/ui/classaudit.mjs

368 lines
18 KiB
JavaScript
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 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)`)
/* ── 第 5 条:`import 'antd'` 只许出现在尺子、外壳与 kit 里(R8)────────────
页面一旦直接 import 组件库,主题与档位就再也收不口:换 antd 大版本、调 token、
甚至只是想让「按钮三档高度」跟着系统走,都得把 20 多个页面重扫一遍。
白名单只有四处:theme/(尺子本体)· app/(外壳没有第二份实现,直接铺 Layout/Menu)·
components/{ui,forms}(kit 唯一封装层)· stores/notice.ts(antd message 的唯一出口)。
以前这条只写在文档里,没人拦——补成闸。 */
const ANTD_OK = (rel) => /^(theme|app)\//.test(rel)
|| /^components\/(ui|forms)\//.test(rel) || rel === 'stores/notice.ts'
const antdStray = []
const walkAntd = (dir) => {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name)
if (ent.isDirectory()) { walkAntd(p); continue }
if (!/\.(tsx|ts)$/.test(ent.name)) continue
const rel = path.relative(FRONTEND, p).replace(/^src\//, '')
if (ANTD_OK(rel)) continue
fs.readFileSync(p, 'utf8').split('\n').forEach((line, i) => {
if (/from 'antd'/.test(line)) antdStray.push(`${rel}:${i + 1}: ${line.trim()}`)
})
}
}
walkAntd(SRC)
for (const hit of antdStray) console.log(`ANTD ${hit}`)
console.log(`${antdStray.length} 处越界的 import 'antd'(R8:只许 theme/ · app/ · components/{ui,forms} · stores/notice.ts)`)
process.exit(dead.length + stray.length + bare.length + footerViolations.length + antdStray.length ? 1 : 0)