nex_animation/scripts/ui/gridcheck.py

244 lines
14 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 -*-
"""栅格体检:找「该用栅格却在自然排列」的容器(2026-11 第七轮起常驻)。
用户口径:**该用 grid 的地方不要用自然排列**。自然排列(`flex-wrap`)在同类子块
宽度参差时会产出两种坏画面:① 一行里右边缘参差不齐;② 折行点随内容漂移,
第二行的左边缘对不上第一行。同量子块只要 >2 个并排,就必须落在栅格里
(`Ctlbar cols={n}` / `Row+Col` / `OptionGrid` / CSS grid)。
判定(对着渲染结果量,不看代码):
容器 = display:flex + flex-direction:row + flex-wrap:wrap;
子块按「族」归类(form-item / select / input / number / card / check / seg …),
**同一族 ≥3 颗**才立案——混排的胶囊流本来就不要求等宽。
立案条件(任一):
rag 同族子块宽度极差 > 40px(一行放得下也没对齐)
misalign 折行后各行左边缘极差 > 8px(折行点随意)
折行错位按**容器全部子块**分行——行首的标签 / 前置按钮会把第一行推右,
只按同族子块分行会把这算成 100~270px 的假错位。
按族豁免:
btn 按钮组本就该按内容自然排列(同概念不跨行由 visualcheck 的 ActionGroup 断言管)
span .nex-chipbar / .nex-taggroup 里的胶囊与只读标签:筛已有内容 = 胶囊流,
宽度**必须**跟着文案走,等宽反而读不出区别
判据②(同一句话的另一半:横滚不是栅格):`[role="list"]` 是 kit `Steps`
流程条专用(全站唯一),它是一串**等宽重复卡片**,必须容器自适应铺开。
命中条件(任一):容器自身横向可滚 `scrollWidth-clientWidth > 2`;
或有子块右缘越出容器右缘 > 2px。
为什么单独立一条:横滚容器里 `flex-wrap` 根本不折行,判据①(看 rag/折行)
永远安静——第七轮实测流程条 12 格在 1440 宽度下 `scrollLeft=126`、
总控台那条 526px 容器装 1244px 内容,**9 格藏在视野外**而下面写着「已完成 10/12」,
正是判据① 看不见的那类「该用 grid 却在自然排列」。
判据③(同一行表单的「控件不对齐」):`.nex-form-row` 的一条视觉行里,
带标签字段的控件行(`.ant-form-item-control-input`)与**裸控件**(复选框 / 开关 /
按钮 / 下拉……直接坐在 Col 里、自己没标签)中心线相差 > 4px 立案。
为什么必须量像素:FormRow 的列是块级 Col,调用点在裸控件上写的
`self-center` / `self-end` 在块容器里根本不参与对齐——分镜检查器「环境声 / 启用字幕」
那颗复选框实测顶在标签行,和右边输入框的中心差 35px,写 class 的人以为对齐了。
现在由 app.css 表单 glue ⑥ 统一让位(让出标签块再在 controlHeight 里垂直居中),
这条判据盯的是「又有人在调用点自己写对齐」或「glue 被改坏」。
用法:
NEX_THEMES=light NEX_WIDTHS=1440,1280,1024 .venv/bin/python scripts/ui/gridcheck.py
退出码:0 = 干净,1 = 有立案。
"""
import os
import pathlib
import sys
from collections import Counter
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,1280,1024").split(",")]
THEMES = os.environ.get("NEX_THEMES", "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]
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_grid")); 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 || '';
}"""
JS = r"""() => {
const cls=(el)=>(typeof el.className==='string'?el.className:'').trim().split(/\s+/).slice(0,5).join('.');
// 子块「同类」判定:同一控件族才要求等宽
const kind=(el)=>{
if (el.matches('.ant-form-item')) return 'form-item';
if (el.matches('.ant-card')) return 'card';
if (el.matches('.ant-select')) return 'select';
if (el.matches('.ant-input-affix-wrapper,.ant-input')) return 'input';
if (el.matches('.ant-input-number')) return 'number';
if (el.matches('.ant-btn')) return 'btn';
if (el.matches('.ant-checkbox-wrapper')) return 'check';
if (el.matches('.ant-radio-button-wrapper,.ant-segmented-item')) return 'seg';
if (el.matches('.nex-chip,.ant-tag-checkable')) return 'tile'; // 可点胶囊 / 可选项
if (el.matches('.ant-tag')) return 'tag'; // 只读回显标签
if (el.matches('.nex-tile,.nex-opt-cell')) return 'tile';
return ''; // 裸 span/div/a 是内容不是控件族
};
const out=[];
for (const el of document.querySelectorAll('main *')) {
const cs=getComputedStyle(el);
if (cs.display!=='flex'||cs.flexDirection!=='row'||cs.flexWrap==='nowrap') 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>4&&r.width>20;});
if (kids.length<3) continue;
const byKind={};
kids.forEach(k=>{const g=kind(k);(byKind[g]=byKind[g]||[]).push(k);});
for (const [g,set] of Object.entries(byKind)) {
if (!g || set.length<3) continue;
if (g==='btn') continue; // 按钮组本就该自然排列
/* 只读标签(kit Tag / Status)整族豁免:宽度天生跟文案走。
「完成 6/6」「待补 2」这种并排回显挤在一起是设计意图,等宽反而读不出差别;
真正该上栅格的是**可选项**,它们走 Chip / OptionGrid(tile 族),仍然在检查里。
胶囊流(.nex-chipbar / .nex-taggroup)里的可点 Chip 同理豁免。 */
if (g==='tag') continue;
if (g==='tile' && set.every(k=>k.closest('.nex-chipbar,.nex-taggroup,.ant-pagination'))) continue;
const ws=set.map(k=>Math.round(k.getBoundingClientRect().width));
const rag=Math.max(...ws)-Math.min(...ws);
/* 折行错位要按**容器全部子块**分行:行首常有标签 / 选择按钮这类前置件,
只按同族子块分行会把「第一行被前置件推右」误判成折行错位(104~270px 的假案)。
分行容差 10px:居中排列时同排子块的 top 会差几像素。 */
const rows=[];
for (const k of kids.map(c=>({l:c.getBoundingClientRect().left,t:c.getBoundingClientRect().top}))
.sort((x,y)=>x.t-y.t)) {
const r=rows.find(g2=>Math.abs(g2.t-k.t)<=10); if (r) r.ls.push(k.l); else rows.push({t:k.t,ls:[k.l]});
}
const starts=rows.map(r=>Math.round(Math.min(...r.ls)));
const misalign=rows.length>1 ? Math.max(...starts)-Math.min(...starts) : 0;
if (misalign<=8 && rag<=40) continue;
if (rag>40 || misalign>8) out.push({kind:g,n:set.length,rag,misalign,rows:rows.length,
el:el.tagName.toLowerCase()+'.'+cls(el).slice(0,70),widths:ws.slice(0,8),
rows:rows.length,n:set.length,
texts:set.slice(0,6).map(k=>((k.innerText||'').trim().slice(0,10)))});
}
}
/* 判据②:重复卡片排成一条 = 容器自适应 grid,横向滚动 / 越界一律立案。
`role="list"` 全站只有 kit 的 Steps(流程条)在用;格子宽窄由 `.nex-steps`
的 auto-fill minmax 轨道决定,容器宽度变了就多排几列,而不是把尾巴滚掉。
rag 复用成「容器还能滚多少 px」,misalign 复用成「子块越出右缘多少 px」。 */
// 不加 main 前缀:流程条现在住在「项目概况」抽屉里(antd Drawer 挂到 body 的 portal,
// 实测 inMain=false),只查 main 会正好漏掉唯一那条长文流程条。
for (const el of document.querySelectorAll('[role="list"]')) {
const cs=getComputedStyle(el);
if (cs.display==='none'||cs.visibility==='hidden') continue;
const box=el.getBoundingClientRect();
if (box.width<40) 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>4&&r.width>20;});
if (kids.length<3) continue;
const over=Math.max(0, Math.round(el.scrollWidth-el.clientWidth));
const spill=Math.max(0, ...kids.map(k=>Math.round(k.getBoundingClientRect().right-box.right)));
if (over<=2 && spill<=2) continue;
out.push({kind:'rail',n:kids.length,rag:over,misalign:spill,rows:1,
el:el.tagName.toLowerCase()+'.'+cls(el).slice(0,70),
widths:kids.slice(0,8).map(k=>Math.round(k.getBoundingClientRect().width)),
texts:kids.slice(0,6).map(k=>((k.innerText||'').trim().replace(/\s+/g,'').slice(0,10)))});
}
/* 判据③:一行表单里的裸控件必须和同排字段的控件行对齐(kind=ctl)。
rag/misalign 都复用成「离控件中心线差多少 px」;按视觉行分组,窄屏折行之后
每行各量各的。比中心线而不是顶边:复选框 22 高、输入框 32 高,比顶边会误报。 */
for (const row of document.querySelectorAll('.nex-form-row')) {
const cs=getComputedStyle(row);
if (cs.display==='none'||cs.visibility==='hidden') continue;
const cols=[...row.children].filter(c=>c.matches('.ant-col')&&c.getBoundingClientRect().height>4);
if (cols.length<2) continue;
const lines=[];
for (const c of cols) {
const t=c.getBoundingClientRect().top;
const g=lines.find(l=>Math.abs(l.t-t)<=10); if (g) g.cs.push(c); else lines.push({t,cs:[c]});
}
for (const l of lines) {
if (l.cs.length<2) continue;
const labeled=[], bare=[];
for (const c of l.cs) {
const ctl=c.querySelector('.ant-form-item-control-input');
if (ctl) { labeled.push(ctl); continue; }
const k=[...c.children].find(x=>{const xg=getComputedStyle(x);
return xg.display!=='none'&&xg.position!=='absolute'&&xg.position!=='fixed'&&x.getBoundingClientRect().height>4;});
if (k&&k.matches('.ant-checkbox-wrapper,.ant-switch,.ant-btn,.ant-select,.ant-input,.ant-input-number,.ant-radio-group,.nex-chip')) bare.push(k);
}
if (!labeled.length||!bare.length) continue;
const mid=(e)=>{const r=e.getBoundingClientRect();return r.top+r.height/2};
const base=labeled.reduce((a,e)=>a+mid(e),0)/labeled.length;
const off=Math.round(Math.max(...bare.map(e=>Math.abs(mid(e)-base))));
if (off<=4) continue;
out.push({kind:'ctl',n:labeled.length+bare.length,rag:off,misalign:off,rows:1,
el:'div.'+cls(row).slice(0,70),
widths:l.cs.map(c=>Math.round(c.getBoundingClientRect().width)).slice(0,8),
texts:[...labeled,...bare].map(e=>(e.innerText||String(e.className)||'').trim().slice(0,12)).filter(Boolean).slice(0,6)});
}
}
return out;
}
"""
def main() -> int:
seen: Counter = Counter()
detail: dict = {}
with sync_playwright() as pw:
b = pw.chromium.launch()
ctx = b.new_context(viewport={"width": 1440, "height": 900})
pg = ctx.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)
for row in pg.evaluate(JS):
key = (route, theme, width, row["el"][:70], row["kind"])
seen[key] += 1
detail.setdefault(key, row)
b.close()
for k, v in seen.items():
d = detail[k]
print(f"{k[0]:<32} {k[1]}/{k[2]} x{v:<2} {k[4]:<10} "
f"rag={d['rag']:<4} mis={d['misalign']:<4} rows={d['rows']} n={d['n']} {k[3][:60]}")
print(f" widths={d['widths']} texts={d['texts']}")
total = sum(seen.values())
print("GRID_TOTAL", total, "unique", len(seen))
if total:
print("→ kind≠rail:同族子块 ≥3 却没走栅格,改 Ctlbar cols={n} / Row+Col / OptionGrid,"
"或确认它属于胶囊流(应在 .nex-chipbar / .nex-taggroup 里)")
print("→ kind=rail:流程条在横滚/越界(rag=还能滚 px,mis=越界 px),"
"格子别钉宽度,交给 .nex-steps 的 auto-fill minmax 轨道")
print("→ kind=ctl:同一行的裸控件没坐进控件行(rag=离控件中心线 px),"
"别在调用点写 self-center/self-end,交给 app.css 表单 glue ⑥")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())