nex_animation/scripts/ui/tableaudit.py

170 lines
9.0 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 第 28 轮起):登录 → 逐路由量每一张表的
「容器宽 / 可视宽 / 内容宽 / 各列宽 / 最高行 / 把行撑高的那个元素」。
为什么要它:行高是最容易「编译通过但页面是坏的」的一类。长文案列没给够宽就塞进
表格,单元格会折成四五行,整行被顶到 100~250px,一屏只能看见三条记录——tsc、
build、classaudit 全都测不出来,visualcheck 也只管溢出不管行高。所以这里把两条
红线钉死(见 docs/UI规范.md §13.2 R17):
1) 数据行最高 ≤ NEX_ROW_H_MAX(默认 84px ≈ 正文两行 + 一行次要元信息);
2) 横向溢出 ≤ NEX_SCROLL_SLACK(默认 40px,定宽列合计必须回到容器内)。
3) 一个格子里并排 ≥2 个子元素时:任何一个都不许越出该格内容盒 > 2px,
也不许互相压叠 > 2px(nowrap 的单元格会把整条线顶出盒子,2+3 一起看才抓得住)。
空态行(.ant-table-placeholder)是 antd 自己那条 60px 占位,不算数据行,跳过。
用法:
NEX_ROUTES="/,/assets,/projects/10/delivery" .venv/bin/python scripts/ui/tableaudit.py
# 路由里的 {id} 会用登录后的会话自动补成第一个项目的 id
退出码 = 违规表的张数(0 = 全绿)。
"""
import os
import sys
from playwright.sync_api import sync_playwright
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
WIDTH = int(os.environ.get("NEX_WIDTH", "1440"))
USER = os.environ.get("NEX_USER", "admin")
PWD = os.environ.get("NEX_PASS", "admin1234")
ROW_H_MAX = int(os.environ.get("NEX_ROW_H_MAX", "84"))
SCROLL_SLACK = int(os.environ.get("NEX_SCROLL_SLACK", "40"))
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").split(",") if r]
# 空项目每张表都是空态行,量不到任何东西 ⇒ {id} 取「镜头最多」的那个项目,
# 而不是列表第一个(开发库里第一个往往是刚建的空项目)。
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 || '';
}"""
# 一张表 → 一行报告。撑高元凶按「格子内高度最大的那个后代元素」给出,
# 直接指到 class 名,省得再人肉开 devtools。
PROBE = r"""() => [...document.querySelectorAll('.ant-table-wrapper')].map((w, i) => {
const body = w.querySelector('.ant-table-body') || w.querySelector('.ant-table-content');
const head = [...w.querySelectorAll('.ant-table-thead th')]
.filter(th => !th.className.includes('ant-table-cell-scrollbar'))
.map(th => ({ t: (th.textContent || '').trim().slice(0, 8), w: Math.round(th.getBoundingClientRect().width) }));
// measure 行是 rc-table 的量尺占位、placeholder 行是 antd 的空态,都不算数据行
const rows = [...w.querySelectorAll('.ant-table-tbody tr')]
.filter(r => !r.className.includes('measure') && !r.className.includes('placeholder'));
const tall = rows.map(r => {
const cells = [...r.children].map(td => {
let worst = null;
td.querySelectorAll('*').forEach(el => {
const h = Math.round(el.getBoundingClientRect().height);
if (!worst || h > worst.h) worst = { h, s: el.tagName + '.' + String(el.className).slice(0, 34) };
});
return { t: (td.textContent || '').trim().slice(0, 16), w: Math.round(td.getBoundingClientRect().width),
h: Math.round(td.getBoundingClientRect().height), worst };
});
return { h: Math.round(r.getBoundingClientRect().height), cells };
}).sort((a, b) => b.h - a.h)[0] || null;
/* 判据③:格子里的并排内容不许越出自己的盒子,也不许互相压叠。
症状(首页项目列表「进度」列):条是占满 100% 的行内盒,右边又跟了百分数,
单元格 nowrap 不折行,整条线被 text-align:right 往左推——百分数越出内容盒右缘
最多 32px,压到「时长」那一列的右边界上。行高和列宽都正常,只有像素看得见。 */
const spill=[];
w.querySelectorAll('.ant-table-tbody tr td').forEach(td=>{
if (td.closest('tr')?.className.includes('placeholder')) return;
const kids=[...td.children].filter(k=>{const kg=getComputedStyle(k),r=k.getBoundingClientRect();
return kg.display!=='none'&&kg.position!=='absolute'&&kg.position!=='fixed'&&r.height>2&&r.width>2;});
if (kids.length<2) return;
const r=td.getBoundingClientRect(), tg=getComputedStyle(td);
const L=r.left+parseFloat(tg.paddingLeft), R=r.right-parseFloat(tg.paddingRight);
kids.forEach(k=>{const kr=k.getBoundingClientRect();
const overR=Math.round(kr.right-R), overL=Math.round(L-kr.left);
if (overR>2||overL>2) spill.push({col:td.cellIndex,t:(td.textContent||'').trim().slice(0,14),
k:k.tagName+'.'+String(k.className).slice(0,26),overR,overL});});
for (let i=0;i<kids.length;i++) for (let j=i+1;j<kids.length;j++){
const a=kids[i].getBoundingClientRect(), bb=kids[j].getBoundingClientRect();
const ox=Math.round(Math.min(a.right,bb.right)-Math.max(a.left,bb.left));
const oy=Math.round(Math.min(a.bottom,bb.bottom)-Math.max(a.top,bb.top));
if (ox>2&&oy>2) spill.push({col:td.cellIndex,t:(td.textContent||'').trim().slice(0,14),
k:kids[i].tagName+'×'+kids[j].tagName,overR:ox,overlap:true});}
});
const title = (w.closest('.ant-card')?.querySelector('.ant-card-head-title')?.textContent || '').trim().slice(0, 18);
return { i, title, rows: rows.length,
boxW: Math.round(w.getBoundingClientRect().width),
spill,
clientW: body ? body.clientWidth : 0, scrollW: body ? body.scrollWidth : 0,
maxRowH: tall ? tall.h : 0, head, tall };
})"""
def login(page) -> None:
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)
def main() -> int:
bad = 0
with sync_playwright() as pw:
browser = pw.chromium.launch()
page = browser.new_page(viewport={"width": WIDTH, "height": 1100})
login(page)
for route in ROUTES:
if "{id}" in route:
pid = page.evaluate(PROJECT_JS)
if not pid:
print("!! 拿不到项目 id,跳过", route)
continue
route = route.replace("{id}", str(pid))
page.goto(BASE + route, wait_until="networkidle")
page.wait_for_timeout(2200)
tables = [t for t in page.evaluate(PROBE) if t["rows"]]
if not tables:
continue
print("=" * 24, route)
for t in tables:
over_w = t["scrollW"] - t["clientW"]
flags = []
if t["maxRowH"] > ROW_H_MAX:
flags.append(f"行高超 {ROW_H_MAX}")
if over_w > SCROLL_SLACK:
flags.append(f"横向溢出 {over_w}")
if t["spill"]:
flags.append("格子内容越界 " + str(len(t["spill"])) + " 处")
mark = " ⚠ " + "、".join(flags) if flags else ""
print(f'#{t["i"]} 「{t["title"]}」 容器{t["boxW"]} 可视{t["clientW"]}/内容{t["scrollW"]} '
f'行{t["rows"]} 最高行{t["maxRowH"]}{mark}')
print(" 列:", " ".join(f'{c["t"]}={c["w"]}' for c in t["head"]))
if flags and t["tall"]:
print(" 撑高行", t["tall"]["h"], "→", " | ".join(
f'{c["t"]}@{c["w"]}x{c["h"]}' for c in t["tall"]["cells"] if c["h"] > 48))
worst = max((c["worst"] for c in t["tall"]["cells"] if c["worst"]),
key=lambda x: x["h"], default=None)
if worst:
print(f' 元凶 h={worst["h"]} {worst["s"]}')
for sp in t["spill"][:4]:
print(' 越界 第', sp["col"], '格', repr(sp["t"]), sp["k"],
('压叠宽 ' if sp.get("overlap") else '右溢 ') + str(sp["overR"]) + 'px',
('左溢 ' + str(sp["overL"]) + 'px') if sp.get("overL") else '')
if flags:
bad += 1
browser.close()
print(f"\n=== 违规 {bad} 张表 ===")
return bad
if __name__ == "__main__":
sys.exit(main())