nex_animation/scripts/ui/rhythmcheck.py

189 lines
10 KiB
Python
Raw Normal View History

规范补到十七条并把探针升到「六道 + 一道反向验证」:行高、栅格、纵向节奏、标签底色全部有闸 症状:这一轮改的每一类毛病里,有四类靠人眼复查根本守不住——表格行被内容撑高(实测最高 255px)、该用栅格的地方用自然排列(窄屏两种坏画面:一行右边缘参差不齐、折行点随内容 漂移)、纵向节奏断(底边不齐 / 收缩错位)、标签自带彩色底纹(§2.1 要求中性底);而卡头 `right` 长起来把标题压成竖排(430 档标题 291×145)也没有任何闸门会报。更麻烦的是 rhythmcheck 的判据原先读像素,豁免写宽一格就永远安静地返回 0——14 条命中里混着探针 自己的假警报,没人敢信它的红。 做法:①`docs/UI规范.md` 新增 R17 表格行高纪律(§13.2)与 R16 信息块三件套的落地口径 (§13.1),§9.3 补卡头折行那条(含「折行样式要挂在 `.ant-card-head-wrapper` 而不是 `.ant-card-head`」这个陷阱与 430/1440 的实测数据),§15 扩成 15.1–15.7 六道常驻探针 加一道反向验证,§16 提交清单插入第 9 步「动过布局跑三张像素闸、改过判据跑 gateprobe」; ②新增 `tableaudit.py`(逐表报容器宽/可视宽/行数/最高行/列宽,超行高点名)、 `gridcheck.py`、`rhythmcheck.py`(GAP + RAG,四条写法级豁免逐条写明为什么豁免)、 `tagcheck.py`(扫标签 tinted 底);③`gateprobe.py` 用「坏 fixture 必须被点名、合法形态 必须被放行」两组用例反向验证三张像素闸,共 4/4 全对,不碰源码不触发 HMR; ④`rhythmcheck.py` 的判据改成只读写法不读像素(`isPin` 认 mt-auto / inline margin-top / justify-content;RAG 侧放行子块自带 max-width、align-self 与整行居中的胶囊组), `classaudit.mjs` 把 `<Flex align="flex-start">` 的取值加进 PROSE 白名单(它天天作为 props 值出现,逐行切词分不清引号内外);⑤`visualcheck.py` 的项目子页改成量「镜头最多」 的项目并支持 NEX_PROJECT_ID 覆盖——列表第一个常是空项目,空态下溢出与截断两类断言等于 没测;⑥README 的规范条目数同步到十七条(只提这一行,其余内容归并行的后端改动)。 为什么:这类毛病全是「看起来挺整齐、量一下才知道差 200px」,只有把它们变成退出码才能 防止下一轮又漏回去;而像素闸一旦可能悄悄失灵,就必须配一道反向验证——先证明闸门坏了 会响,它的绿才有意义。
2026-11-03 12:21:39 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""节奏体检:组件之间的上下、左右边距是否由**版面尺子**给(2026-11 第七轮起常驻)。
用户口径:**组件之间的上下、左右边距要合理**。本站唯一的纵向间距来源是
`PageStack`(页内区块)与栅格 `gutter`(格与格),页面里再补 `mt-*/mb-*`
就会同一屏出现 12/16/20/24 混着来。这里对着渲染结果量两件事:
1) 纵向节奏(gap):容器(flex-column / grid / .nex-stack)里相邻可见子块的
实际间距必须**只有一档**,且 ≤ 24px(= --ant-margin 那一档)。
豁免三种合法形态:
· 末块**钉**在容器内容底——只认既定写法(卡底动作 `mt-auto`、`justify-content`
钉两端),跨卡把按钮排到同一水平线上用的,这一档间距本来就不该固定;
钉底不能读像素(margin-top:auto 的计算值恰好等于它吃掉的余量,永远算不出
「有余量」;而内容撑开的列容器里末块天然贴着内容底,只比位置等于把全站末档全放过);
· 同一行的两块(top 齐平 / 纵向重叠 / 横向不相接——grid 多列 + items-center
时两块的 top 会差几十 px,只比 top 会把并排量成 -30px 的假间距);
· 单行胶囊按钮(高 ≤48,宽度跟文案走是设计意图)。
2) 收缩错位(ragged):flex-column 容器把子块排成「一块宽一块窄」的
shrink-wrap 效果。同样豁免两种刻意行为:子块自己写了 max-width / align-self
(正文 `max-w-[72ch]` 这种栏宽)、整块内容居中(容器 items-center 且每个子块
align-self:center,是排版不是排列)。
用法:
NEX_THEMES=light,dark NEX_WIDTHS=1440,1280 .venv/bin/python scripts/ui/rhythmcheck.py
退出码:0 = 干净,1 = 有立案。
"""
import json
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")
WIDTHS = [int(x) for x in os.environ.get("NEX_WIDTHS", "1440").split(",")]
THEMES = os.environ.get("NEX_THEMES", "light,dark").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]
USER = os.environ.get("NEX_USER", "admin")
PWD = os.environ.get("NEX_PASS", "admin1234")
OUT = pathlib.Path(os.environ.get("NEX_SHOTS", "/tmp/nex_ui_rhythm")); OUT.mkdir(parents=True, exist_ok=True)
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 || '';
}"""
# 纵向节奏:同一容器内相邻子块的间距只准一档
GAP = r"""() => {
const cls=(el)=>(typeof el.className==='string'?el.className:'').trim().split(/\s+/).slice(0,4).join('.');
const out=[];
const all=[document.querySelector('main')||document.body,...document.querySelectorAll('main *')];
for (const el of all) {
const cs=getComputedStyle(el);
if (!(el.classList.contains('nex-stack')||(cs.display==='flex'&&cs.flexDirection==='column')||cs.display==='grid')) continue;
const kids=[...el.children].filter(c=>{const k=getComputedStyle(c),r=c.getBoundingClientRect();
return k.display!=='none'&&k.position!=='absolute'&&k.position!=='fixed'&&r.height>6&&r.width>120;});
if (kids.length<2) continue;
const gaps=[];
const box=el.getBoundingClientRect();
const pb=parseFloat(cs.paddingBottom)||0;
/* 「末块是钉到底上的」只能读写法,不能读像素:margin-top:auto 的计算值就是
它吃掉的全部余量,于是「有余量」永远算不出来;而内容撑开的容器里最后一块
**天然**贴着内容底,只看位置等于把每条容器的最后一档间距全放过。
本站钉底只有两种写法:卡底动作的 `mt-auto`,和 justify-content 的钉两端。 */
const jc=['flex-end','space-between','space-around','space-evenly'].includes(cs.justifyContent);
const isPin=(k)=>/(^|\s)mt-auto(\s|$)/.test(typeof k.className==='string'?k.className:'')
|| (k.style && k.style.marginTop==='auto') || jc;
for (let i=1;i<kids.length;i++){
const a=kids[i-1].getBoundingClientRect(),b=kids[i].getBoundingClientRect();
/* 「同一行」的三种形态都要跳过:top 齐平;纵向有重叠;横向根本不相接
(grid 多列 + items-center 时两个子块的 top 会差几十 px,只比 top 会把
并排的两块当成上下两块,量出 -30px 的假间距)。 */
const vOverlap = a.top < b.bottom - 1 && b.top < a.bottom - 1;
const sideBySide = a.right <= b.left + 1 || b.right <= a.left + 1;
if (Math.abs(a.top-b.top)<2 || vOverlap || sideBySide) continue;
// 末块确实钉在容器「内容底」(减掉下内边距,直接比 border box 会永远差一个 padding)
// 注意 isPin 要读**元素**——b 已经是 DOMRect 了,传进去永远判不出钉底
if (i===kids.length-1 && isPin(kids[i])) {
if (Math.abs(box.bottom-pb-b.bottom)<=2) continue;
}
gaps.push(Math.round(b.top-(a.top+a.height)));
}
if (!gaps.length) continue;
const uniq=[...new Set(gaps.map(g=>Math.abs(g)))];
if (uniq.length>1||uniq[0]>24) out.push({el:el.tagName.toLowerCase()+'.'+cls(el),kids:kids.length,gaps,
detail:kids.slice(0,8).map(k=>k.tagName.toLowerCase()+'.'+cls(k)+':'+Math.round(k.getBoundingClientRect().height))});
}
return out;
}"""
# shrink-wrap:列容器里子块宽度参差
RAG = r"""() => {
const cls=(el)=>(typeof el.className==='string'?el.className:'').trim().split(/\s+/).slice(0,4).join('.');
const out=[];
for (const el of document.querySelectorAll('main *')) {
const cs=getComputedStyle(el);
const col=el.classList.contains('nex-tile')||(cs.display==='flex'&&cs.flexDirection==='column');
if (!col) continue;
const kids=[...el.children].filter(c=>{const k=getComputedStyle(c),r=c.getBoundingClientRect();
return k.display!=='none'&&k.display!=='contents'&&k.position!=='absolute'&&k.position!=='fixed'&&r.height>10&&r.width>40;});
if (kids.length<2) continue;
const cw=el.getBoundingClientRect().width; if (cw<260) continue;
const hh=el.getBoundingClientRect().height;
// 单行胶囊 / 标签按钮:align-items:center + 子块宽度跟文案走,本来就该收缩
if (hh<=48) continue;
/* 「比容器窄」有两种,只有一种是病:
· 子块自己写了 max-width(正文 72ch 那种刻意的栏宽)或 align-self——是设计选择,放行;
· 整块内容居中(容器 items-center 且每个子块 align-self:center)——排版不是排列,放行;
· 剩下的才是 shrink-wrap:容器在要求撑满,子块却各自贴着内容宽度,左右边缘七零八落。 */
const optOut=(k)=>{const s=getComputedStyle(k);
return s.maxWidth!=='none'||s.alignSelf!=='auto'||/max-w-|w-\[/.test(typeof k.className==='string'?k.className:'');};
const widths=kids.map(k=>Math.round(k.getBoundingClientRect().width));
const ragged=kids.some((k,i)=>cw-widths[i]>48&&!optOut(k));
const al=cs.alignItems;
const centered=al==='center'&&kids.every(k=>getComputedStyle(k).alignSelf==='center');
if (al==='flex-start'||al==='start'||al==='end'||al==='baseline'||
(ragged&&!centered&&al!=='center'&&!el.classList.contains('nex-stack')))
out.push({el:el.tagName.toLowerCase()+'.'+cls(el),align:al,cw:Math.round(cw),widths,
first:kids[0].tagName.toLowerCase()+'.'+cls(kids[0]).slice(0,40)});
}
return out;
}"""
def main() -> int:
res = {"gap": {}, "rag": {}}
with sync_playwright() as pw:
b = pw.chromium.launch()
pg = b.new_context(viewport={"width": 1440, "height": 900}).new_page()
pg.set_default_timeout(20000)
pg.goto(BASE + "/login")
pg.wait_for_selector("#login-user")
pg.fill("#login-user", USER)
pg.fill("#login-pass", PWD)
pg.click("button[type=submit]")
pg.wait_for_url(lambda u: "/login" not in u, timeout=20000)
pid = pg.evaluate(PROJECT_JS)
for width in WIDTHS:
pg.set_viewport_size({"width": width, "height": 900})
for theme in THEMES:
pg.evaluate("(t) => localStorage.setItem('nex-the', t)", theme)
for r in ROUTES:
if "{id}" in r and not pid:
continue
route = r.replace("{id}", str(pid))
pg.goto(BASE + route)
pg.wait_for_timeout(1300)
key = f"{route}@{width}/{theme}"
res["gap"][key] = pg.evaluate(GAP)
res["rag"][key] = pg.evaluate(RAG)
bg = pg.evaluate("getComputedStyle(document.body).backgroundColor")
b.close()
for k in res["gap"]:
for x in res["gap"][k]:
print(f"GAP {k:<34} {x['el'][:60]} kids={x['kids']} gaps={x['gaps']}")
print(f" {x['detail']}")
for k in res["rag"]:
for x in res["rag"][k]:
print(f"RAG {k:<34} {x['el'][:60]} align={x['align']} cw={x['cw']} widths={x['widths']}")
g = sum(len(v) for v in res["gap"].values())
rg = sum(len(v) for v in res["rag"].values())
print("body-bg", bg, "GAP_TOTAL", g, "RAGGED_TOTAL", rg)
(OUT / "rhythm.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
if g or rg:
print("→ 纵向间距只准由 PageStack / 栅格 gutter 给:删掉页面里补的 mt-*/mb-*,"
"或给列容器 items-stretch 让子块撑满")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())