315 lines
16 KiB
Python
315 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
"""前端词汇表 lint:页面只许说业务,控件的「说法」由 kit 层统一。
|
||
|
||
为什么需要它:audit.py 量的是**渲染结果**(高度、对齐、溢出),
|
||
而「这一页又自己拼了一套皮肤」在渲染结果里往往看不出来——
|
||
它表现为「左导航内边距一页 11px 一页 12px」这种 1px 级别的分叉,
|
||
或者干脆被写死的类名糊过去。词汇表分叉一次,下一次改样式就要多改一处,
|
||
这正是这一轮重写之前的病根(30 多个页面各自长出一套会亮的方块)。
|
||
所以这条闸只看**源码用了哪些词**,与 audit.py 一上一下夹住。
|
||
|
||
.venv/bin/python scripts/ui/vocab.py # 检查
|
||
.venv/bin/python scripts/ui/vocab.py --verbose # 连通过项一起列
|
||
|
||
规则:
|
||
1. antd 只准出现在 kit 层:theme/、app/providers.tsx、components/{ui,forms,media}。
|
||
页面 import antd = 绕过统一皮肤直接调标准件,theme/antd.ts 的令牌就白配了。
|
||
2. pages/ 与 app/ 不许出现原生 <button>/<input>/<select>/<textarea>。
|
||
原生控件的悬停/焦点/禁用/键盘全靠页面自己补,补不全就是「看起来能点、点不动」。
|
||
3. <Chip> 必须带动作(onClick / onOpen / href)。没有动作的胶囊读起来像按钮、
|
||
又点不动,那种只读回显该用 <Tag>。
|
||
4. 页面私有皮肤常量棘轮:`const 大写 = 'bg-... border-...'` 每个都记在账上,
|
||
只降不升;没在账上的文件出现一个新的就失败。
|
||
5. ref 契约:谁被传了 ref,谁就必须是 forwardRef;kit 组件不许把 ref 当普通 prop 声明。
|
||
React 18 里函数组件收不到 ref——编译器不报错,只在运行时打一句 warning,
|
||
于是「点了不聚焦」「不滚到当前节点」这类功能静默死掉(详见报告第 26 章)。
|
||
6. JSX **子节点**位置上的注释(`/* … */` 或 `// …`)不是注释,是文本。
|
||
只有 `{/* … */}` 才是注释;直接写的会被渲染成一行字挂在页面上。
|
||
退出码:0 = 词汇表干净;1 = 有违规。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||
SRC = ROOT / "frontend" / "src"
|
||
|
||
# ── 规则 1:antd 的合法落点 ────────────────────────────────────────────
|
||
ANTD_OK = {
|
||
"theme", # 令牌本身
|
||
"app", # 只有 providers.tsx 允许(ConfigProvider 挂在那里)
|
||
"components/ui", # kit:控件 = antd + 统一皮肤
|
||
"components/forms", # kit:表单控件
|
||
"components/media", # kit:媒体族覆盖层
|
||
}
|
||
ANTD_OK_FILES = {"app/providers.tsx"}
|
||
ANTD_IMPORT = re.compile(r"""from\s+'(antd[^']*|@ant-design/[^']*)'""")
|
||
|
||
# ── 规则 4:页面私有皮肤常量棘轮 ───────────────────────────────────────
|
||
# 数字 = 该文件今天欠下的数量,只准调小。理由写在这里,别只写数字。
|
||
SKIN_CEILINGS: dict[str, tuple[int, str]] = {
|
||
"pages/Help.tsx": (36, "使用手册正文排版(字号/行距/目录/代码块)。这是文档自己的排版,"
|
||
"不是控件皮肤:手册要能独立复刻旧站文章版式,硬塞进 kit 反而把"
|
||
"「控件词汇表」和「文章排版」绑成一套,改字号要动 kit。"),
|
||
"pages/AssetLibrary.tsx": (12, "资产墙的文件砖 / 导入预览 / 弹窗列表还没收进 kit。"
|
||
"下一步:文件砖并入 MediaThumb 的 none 档,导入预览进 kit。"),
|
||
"pages/project/Storyboard.tsx": (12, "看板镜头卡与缩略图叠层(序号、时长、勾中角标)自成一套。"
|
||
"下一步:抽成 kit 的 ShotCard,看板与表格共用一个热区。"),
|
||
"pages/project/AgentConsole.tsx": (12, "控制台底纹 / 回复块 / 提示块(CALLOUT 族)。"
|
||
"下一步:CALLOUT 进 kit 成 Notice 的 tone 档。"),
|
||
"pages/Dashboard.tsx": (1, "封面占位(COVER_NONE):项目封面缺失时的占位块,"
|
||
"等 MediaThumb 的 none 档支持 16:9 占位后删除。"),
|
||
"pages/project/Delivery.tsx": (1, "表格空值占位 EMPTY_CELL。与 Dispatch/Review 三份相同,"
|
||
"等 kit 出 TableEmpty 后一次删掉三处。"),
|
||
"pages/project/Dispatch.tsx": (1, "同上(EMPTY_CELL)。"),
|
||
"pages/project/Review.tsx": (1, "同上(EMPTY_CELL)。"),
|
||
"pages/project/Library.tsx": (1, "勾中计数条 PICKED:等 Chip 选中态收敛后删除。"),
|
||
"pages/project/Timeline.tsx": (1, "副行文案 SUBLINE:等 kit 出 Subline 后删除。"),
|
||
"app/layout/SideNav.tsx": (1, "导航图标位 NAV_ICON:等 IconSpot 支持导航档后删除。"),
|
||
}
|
||
SKIN_CONST = re.compile(r"^const\s+([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$", re.M)
|
||
# 值里出现这些词 = 它在拼控件皮肤,不是在写业务文案
|
||
SKIN_TOKEN = re.compile(
|
||
r"\b(?:bg-|border-|rounded-|shadow-|ring-|gap-|p-[trblxy]?-|m-[trblxy]?-|"
|
||
r"leading-|tracking-|text-(?:ink|ink-2|ink-3|muted|faint|dim|on-accent|tiny|caption|ui|label|title|body)\b)")
|
||
|
||
NATIVE = re.compile(r"<(button|input|select|textarea)(?=[\s/>])")
|
||
|
||
# ── 规则 5:ref 契约 ───────────────────────────────────────────────────
|
||
# 5a) 组件被传了 ref,自身却没用 forwardRef:React 18 会把它无声丢掉。
|
||
# 只认我们自己源码里定义的组件;antd 的东西(AntInput / Input.Password)不经这条。
|
||
COMP_TAG = re.compile(r"<([A-Z][A-Za-z0-9_]*)")
|
||
REF_ATTR = re.compile(r"[\s{]ref[=:]")
|
||
DEF_CONST = re.compile(r"^(?:export\s+)?const\s+([A-Z][A-Za-z0-9_]*)\s*=", re.M)
|
||
DEF_FUNC = re.compile(r"^(?:export\s+)?function\s+([A-Z][A-Za-z0-9_]*)\b", re.M)
|
||
# 5b) React 19 风格的 `ref?: Ref<T>` 写在 props 里:18 下这条声明是假的,
|
||
# 类型检查照过,运行时照丢。kit 的 ref 只能来自 forwardRef 的第二个参数。
|
||
REF_PROP = re.compile(r"^\s*ref\?\s*:", re.M)
|
||
KIT_DIRS = ("components/", "app/", "theme/")
|
||
CHIP_OPEN = re.compile(r"<Chip\b")
|
||
|
||
# 规则 6:JSX 子节点上的注释。判定只看一件事——注释**左边最近的非空白字符是 `>`、
|
||
# 右边最近的是 `<`**,即它夹在两个标签之间 = JSX 的 children 位置。
|
||
# 属性位置上(`<X a={1} /* c */ b={2}>`)左右分别是 `}` 和标识符,不误伤;
|
||
# 写成 `{/* c */}` 的左右是 `{` 和 `}`,同样不误伤。
|
||
TAG_GAP = ("<", ">")
|
||
ACTIONProp = re.compile(r"\b(?:onClick|onOpen|href)\b")
|
||
|
||
|
||
def strip_code(src: str) -> str:
|
||
"""去掉注释但保住行号:JSX 注释里写「<input>」不该被当成用了原生控件。"""
|
||
out = []
|
||
i, n = 0, len(src)
|
||
state = "code" # code | line | block | sq | dq | tpl
|
||
while i < n:
|
||
c = src[i]
|
||
nxt = src[i + 1] if i + 1 < n else ""
|
||
if state == "code":
|
||
if c == "/" and nxt == "/":
|
||
state = "line"; out.append(" "); i += 2; continue
|
||
if c == "/" and nxt == "*":
|
||
state = "block"; out.append(" "); i += 2; continue
|
||
if c == "'":
|
||
state = "sq"
|
||
elif c == '"':
|
||
state = "dq"
|
||
elif c == "`":
|
||
state = "tpl"
|
||
out.append(c)
|
||
elif state == "line":
|
||
if c == "\n":
|
||
state = "code"; out.append(c)
|
||
else:
|
||
out.append(" ")
|
||
elif state == "block":
|
||
if c == "*" and nxt == "/":
|
||
state = "code"; out.append(" "); i += 2; continue
|
||
out.append(c if c == "\n" else " ")
|
||
else: # 字符串 / 模板串内部
|
||
if c == "\\":
|
||
out.append(c + nxt); i += 2; continue
|
||
if (state == "sq" and c == "'") or (state == "dq" and c == '"') or (state == "tpl" and c == "`"):
|
||
state = "code"
|
||
out.append(c) # 内容留着:棘轮要看值长什么样
|
||
i += 1
|
||
return "".join(out)
|
||
|
||
|
||
def opening_tag(src: str, start: int) -> str:
|
||
"""从 `<Chip` 的 `<` 起,取到本标签结束的 `>`(跳过 {} 表达式与字符串里的 >)。"""
|
||
depth = 0
|
||
i = start
|
||
while i < len(src):
|
||
c = src[i]
|
||
if c == "{":
|
||
depth += 1
|
||
elif c == "}":
|
||
depth -= 1
|
||
elif c == ">" and depth == 0:
|
||
return src[start:i + 1]
|
||
i += 1
|
||
return src[start:]
|
||
|
||
|
||
def comment_spans(src: str):
|
||
"""源码里真正的注释区间(跳过字符串与模板串):(起点, 终点, 是否单行)。"""
|
||
out = []
|
||
i, n = 0, len(src)
|
||
state = "code"
|
||
while i < n:
|
||
c = src[i]
|
||
nxt = src[i + 1] if i + 1 < n else ""
|
||
if state == "code":
|
||
if c == "/" and nxt == "/":
|
||
j = src.find("\n", i)
|
||
j = n if j < 0 else j
|
||
out.append((i, j, True)); i = j; continue
|
||
if c == "/" and nxt == "*":
|
||
j = src.find("*/", i + 2)
|
||
j = n if j < 0 else j + 2
|
||
out.append((i, j, False)); i = j; continue
|
||
state = {"'": "sq", '"': "dq", "`": "tpl"}.get(c, "code")
|
||
elif state in ("sq", "dq", "tpl"):
|
||
if c == "\\":
|
||
i += 2; continue
|
||
if (state == "sq" and c == "'") or (state == "dq" and c == '"') or (state == "tpl" and c == "`"):
|
||
state = "code"
|
||
i += 1
|
||
return out
|
||
|
||
|
||
def rel(p: pathlib.Path) -> str:
|
||
return str(p.relative_to(SRC))
|
||
|
||
def component_defs(src_files) -> dict[str, tuple[str, bool]]:
|
||
"""组件名 → (定义在哪个文件, 它是不是 forwardRef)。
|
||
|
||
只认 `const Name = ...` / `function Name(...)` 两种定义式;antd 的组件不在源码里,
|
||
自然落进不了这张表,页面写 `<AntButton ref=>` 不会被误伤。"""
|
||
defs: dict[str, tuple[str, bool]] = {}
|
||
for f in src_files:
|
||
body = strip_code(f.read_text(encoding="utf-8"))
|
||
r = rel(f)
|
||
for m in DEF_CONST.finditer(body):
|
||
tail = body[m.end():m.end() + 80].lstrip()
|
||
defs.setdefault(m.group(1), (r, tail.startswith(("forwardRef", "React.forwardRef"))))
|
||
for m in DEF_FUNC.finditer(body):
|
||
defs.setdefault(m.group(1), (r, False))
|
||
return defs
|
||
|
||
|
||
def scan() -> int:
|
||
ap = argparse.ArgumentParser(description="前端词汇表 lint")
|
||
ap.add_argument("--verbose", action="store_true", help="连通过项一起列")
|
||
args = ap.parse_args()
|
||
|
||
files = sorted(p for p in SRC.rglob("*.tsx") if "node_modules" not in str(p))
|
||
files += sorted(p for p in SRC.rglob("*.ts") if "node_modules" not in str(p))
|
||
defs = component_defs(files)
|
||
bad = 0
|
||
counts: dict[str, int] = {}
|
||
|
||
for f in files:
|
||
r = rel(f)
|
||
src = strip_code(f.read_text(encoding="utf-8"))
|
||
|
||
# 1) antd 的落点
|
||
for m in ANTD_IMPORT.finditer(src):
|
||
top = r.split("/")[0]
|
||
sub = "/".join(r.split("/")[:2]) if r.startswith("components/") else top
|
||
if sub not in ANTD_OK and r not in ANTD_OK_FILES:
|
||
print(f"✗ 规则1 antd 越界 {r}: import {m.group(1)} —— 页面请经由 components/{'ui' if not r.startswith('pages') else 'ui'} 取件")
|
||
bad += 1
|
||
|
||
# 5a) 被传了 ref 的组件必须 forwardRef
|
||
for m in COMP_TAG.finditer(src):
|
||
tag = opening_tag(src, m.start())
|
||
if not REF_ATTR.search(tag):
|
||
continue
|
||
name = m.group(1)
|
||
where = defs.get(name)
|
||
if where is None or where[1]:
|
||
continue
|
||
line = src[:m.start()].count("\n") + 1
|
||
print(f"✗ 规则5 ref 契约 {r}:{line}: <{name} ref=…> 的 ref 会被 React 18 丢掉——"
|
||
f" {where[0]} 里的 {name} 不是 forwardRef")
|
||
bad += 1
|
||
|
||
# 5b) kit 组件不许把 ref 当普通 prop 声明(那是 React 19 的写法)
|
||
if r.startswith(KIT_DIRS):
|
||
for m in REF_PROP.finditer(src):
|
||
line = src[:m.start()].count("\n") + 1
|
||
print(f"✗ 规则5 ref 契约 {r}:{line}: props 里声明了 ref —— React 18 收不到,"
|
||
f"请改成 forwardRef(见 lib/ref.ts)")
|
||
bad += 1
|
||
|
||
# 6) JSX 子节点位置上的注释会被当文本渲染(只有 .tsx 有 JSX)
|
||
if r.endswith(".tsx"):
|
||
raw = f.read_text(encoding="utf-8")
|
||
bare = strip_code(raw) # 注释被抹成空格、位置不变,拿它判左右邻居
|
||
for start, end, _single in comment_spans(raw):
|
||
left = bare[:start].rstrip()
|
||
right = bare[end:].lstrip()
|
||
if left.endswith(">") and right.startswith("<"):
|
||
line = raw[:start].count("\n") + 1
|
||
txt = " ".join(raw[start:end].split())[:48]
|
||
print(f"✗ 规则6 JSX 文本注释 {r}:{line}: 「{txt}」写在标签之间,"
|
||
f"React 会把它当文本渲染到页面上——要注释请用 {{/* … */}} 或移到 JSX 外面")
|
||
bad += 1
|
||
|
||
if not r.startswith(("pages/", "app/")):
|
||
continue
|
||
|
||
# 2) 原生控件
|
||
for m in NATIVE.finditer(src):
|
||
line = src[:m.start()].count("\n") + 1
|
||
print(f"✗ 规则2 原生控件 {r}:{line}: <{m.group(1)}> —— 请到 components/ui 取件(整块热区用 Tile,图标位用 IconSpot)")
|
||
bad += 1
|
||
|
||
# 3) 只读 Chip
|
||
for m in CHIP_OPEN.finditer(src):
|
||
tag = opening_tag(src, m.start())
|
||
if not ACTIONProp.search(tag):
|
||
line = src[:m.start()].count("\n") + 1
|
||
print(f"✗ 规则3 只读胶囊 {r}:{line}: <Chip> 没有 onClick/onOpen/href —— 点不动的回显请用 <Tag>")
|
||
bad += 1
|
||
|
||
# 4) 皮肤常量棘轮
|
||
hits = []
|
||
for m in SKIN_CONST.finditer(src):
|
||
val = m.group(2)
|
||
if not val.lstrip().startswith(("'", '"', "`")):
|
||
continue
|
||
if not SKIN_TOKEN.search(val):
|
||
continue
|
||
hits.append(m.group(1))
|
||
if hits:
|
||
counts[r] = len(hits)
|
||
ceiling = SKIN_CEILINGS.get(r)
|
||
if ceiling is None:
|
||
print(f"✗ 规则4 私有皮肤 {r}: {len(hits)} 个皮肤常量({'、'.join(hits[:5])})"
|
||
f"—— 新账不赊:收进 kit,或加进 SKIN_CEILINGS 并写理由")
|
||
bad += 1
|
||
elif len(hits) > ceiling[0]:
|
||
print(f"✗ 规则4 私有皮肤 {r}: {len(hits)} 个 > 记账上限 {ceiling[0]} —— 棘轮只降不升")
|
||
bad += 1
|
||
elif len(hits) < ceiling[0]:
|
||
print(f"↻ 规则4 可以还账 {r}: 已降到 {len(hits)},把 SKIN_CEILINGS 的上限从 "
|
||
f"{ceiling[0]} 改成 {len(hits)} 锁住成果")
|
||
|
||
total = sum(counts.values())
|
||
print(f"\n词汇表:{len(files)} 个文件 · 皮肤常量 {total} 个(棘轮记账 {sum(c for c, _ in SKIN_CEILINGS.values())} 个)"
|
||
f"· {'违规 ' + str(bad) if bad else '无违规'}")
|
||
if not bad and args.verbose:
|
||
for r in sorted(counts):
|
||
why = SKIN_CEILINGS.get(r, (0, ""))[1]
|
||
print(f" {counts[r]:3d} {r}" + (f" ← {why[:44]}…" if why else ""))
|
||
return 1 if bad else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(scan())
|