nex_animation/scripts/ui/gridcheck.py

166 lines
8.4 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 里的胶囊与只读标签:筛已有内容 = 胶囊流,
宽度**必须**跟着文案走,等宽反而读不出区别
用法:
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)))});
}
}
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("→ 这些容器同族子块 ≥3 却没走栅格:改 Ctlbar cols={n} / Row+Col / OptionGrid,"
"或确认它属于胶囊流(应在 .nex-chipbar / .nex-taggroup 里)")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())