旧写法用固定 mt-0.5 给图标手拍偏移,而本项目 --line-height-relaxed 是 1.85(非 Tailwind 默认 1.625),根字号又有 16/17/18 三档 ⇒ 图标中心比文字行盒中心高 3.319/3.134/2.950px (地址行)与 3.313/3.133/2.945px(邮箱行)。 改为结构对齐:地址行图标包进高 = 行盒高(--line-height-relaxed × --font-size-sm)的 items-center 单元格,换行后仍对齐首行;邮箱行是单行链接,整行 items-center。 行高/字号/页高零变化,只移动两个图标。
252 lines
10 KiB
Python
252 lines
10 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
页脚图标对齐修复(2026-10-26)的视觉基线核验:证明每张被重采的 PNG 只有联系区两个图标在变。
|
||
|
||
判据(逐张,对比 HEAD blob 与工作树文件):
|
||
1. 宽高严格相等 —— 若页高/文字度量变了,全页图尺寸就会变;
|
||
2. 差异像素数 > 0 —— 该图确实被这条改动影响;
|
||
3. 差异包围盒(CSS px)= bbox / DPR,宽 ≤ 26、高 ≤ 74 ——
|
||
两个图标 18px 高、行距 47.14px、图标下移 3.32px ⇒ 真实包围盒约 18×68.5 CSS px;
|
||
文字一旦位移,宽度会立刻涨到上百 px;页脚整体位移,高度会越界。
|
||
|
||
差异阈值取「单通道 > 60」(可用 DIFF_THRESHOLD 覆盖):首页 hero 粒子场跨 run 有低幅漂移
|
||
(实测 thr>10 有近万 px、thr>30 数百 px,但 Playwright/pixelmatch 判绿),用 4 会把这类噪声
|
||
当成越界;而任何字形/布局位移在边缘处都是满对比差(远超 60),不会漏。
|
||
另外只看「≥4px 的连通团块」:粒子噪点会留下 1–2 个孤立像素,不按团块过滤就会把包围盒撑到整页
|
||
(webkit 首页实测:团块全部落在页脚,孤立像素 2 个、坐标在 hero 区)。
|
||
|
||
HEAD 里没有的基线(10-24 扩容后未入库的 20 路由 × 5 project = 100 张)无法做前后比对:
|
||
默认按「未授权的新增基线」判红(退出码 3),加 --allow-untracked 才降级为告警。
|
||
|
||
DPR 按 project 目录取(Playwright 设备表):desktop/firefox/webkit = 1,tablet = 2,mobile = 3。
|
||
|
||
退出码分档(lessons §5.40 口径):
|
||
0 = 全部通过;1 = 核验判红(含负对照未按预期失败);3 = 存在未入库基线且未授权;2 = 脚本/环境崩溃。
|
||
|
||
用法:
|
||
/usr/bin/python3 docs/acceptance/2026-10-26-footer-icon-align/verify-baseline-diff.py [--allow-untracked]
|
||
/usr/bin/python3 .../verify-baseline-diff.py --selftest # 先跑正/负对照自证
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import io
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
|
||
try:
|
||
import numpy as np
|
||
from PIL import Image
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f"SETUP-ERROR: 需要 /usr/bin/python3 的 Pillow/numpy({exc})", file=sys.stderr)
|
||
sys.exit(2)
|
||
|
||
REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
|
||
SNAPSHOT_DIR = "e2e/visual-snapshots"
|
||
DPR_BY_PROJECT = {
|
||
"visual-chromium-desktop": 1,
|
||
"visual-chromium-tablet": 2,
|
||
"visual-chromium-mobile": 3,
|
||
"visual-firefox-desktop": 1,
|
||
# Playwright 的 devices['Desktop Safari'] 带 deviceScaleFactor: 2 —— 实测基线宽 2548 = 1274×2。
|
||
# 按 1 算会把 16×65 的图标包围盒读成 34×130,误判成"文字被动过"。
|
||
"visual-webkit-desktop": 2,
|
||
}
|
||
PIXEL_THRESHOLD = int(os.environ.get("DIFF_THRESHOLD", "60"))
|
||
MAX_BBOX_WIDTH_CSS = 26.0
|
||
MAX_BBOX_HEIGHT_CSS = 74.0
|
||
MIN_COMPONENT_PIXELS = 4 # 小于 4px 的团块视为跨 run 的孤立噪点(见 check_pair 注释)
|
||
MAX_NOISE_PIXELS = 20
|
||
|
||
|
||
def run(cmd: list[str]) -> bytes:
|
||
out = subprocess.run(cmd, cwd=REPO, capture_output=True)
|
||
if out.returncode != 0:
|
||
raise RuntimeError(f"{' '.join(cmd)} 失败: {out.stderr.decode('utf-8', 'replace')[:400]}")
|
||
return out.stdout
|
||
|
||
|
||
def changed_pngs() -> list[str]:
|
||
raw = run(["git", "status", "--porcelain", "-z", "--", SNAPSHOT_DIR])
|
||
paths = []
|
||
for entry in raw.split(b"\0"):
|
||
if not entry:
|
||
continue
|
||
text = entry.decode("utf-8")
|
||
path = text[3:]
|
||
if path.endswith(".png"):
|
||
paths.append(path)
|
||
return sorted(paths)
|
||
|
||
|
||
def load_head(path: str) -> Image.Image | None:
|
||
"""HEAD 里没有这张基线时返回 None(10-24 扩容后未入库的那批)。"""
|
||
probe = subprocess.run(["git", "cat-file", "-e", f"HEAD:{path}"], cwd=REPO, capture_output=True)
|
||
if probe.returncode != 0:
|
||
return None
|
||
return Image.open(io.BytesIO(run(["git", "show", f"HEAD:{path}"]))).convert("RGB")
|
||
|
||
|
||
def diff_mask(old: Image.Image, new: Image.Image):
|
||
a = np.asarray(old, dtype=np.int16)
|
||
b = np.asarray(new, dtype=np.int16)
|
||
return (np.abs(a - b) > PIXEL_THRESHOLD).any(axis=2)
|
||
|
||
|
||
def components(mask):
|
||
"""8 连通的差异团块(mask 覆盖率很低,逐点 flood fill 足够快)。"""
|
||
seen = np.zeros(mask.shape, dtype=bool)
|
||
comps = []
|
||
ys, xs = np.where(mask)
|
||
for y0, x0 in zip(ys.tolist(), xs.tolist()):
|
||
if seen[y0, x0]:
|
||
continue
|
||
stack = [(y0, x0)]
|
||
seen[y0, x0] = True
|
||
pts = []
|
||
while stack:
|
||
y, x = stack.pop()
|
||
pts.append((y, x))
|
||
for dy in (-1, 0, 1):
|
||
for dx in (-1, 0, 1):
|
||
ny, nx = y + dy, x + dx
|
||
if 0 <= ny < mask.shape[0] and 0 <= nx < mask.shape[1] and mask[ny, nx] and not seen[ny, nx]:
|
||
seen[ny, nx] = True
|
||
stack.append((ny, nx))
|
||
comps.append(pts)
|
||
return comps
|
||
|
||
|
||
def check_pair(path: str, old: Image.Image, new: Image.Image) -> list[str]:
|
||
"""返回问题列表;空列表=通过。
|
||
|
||
只看「团块 ≥ MIN_COMPONENT_PIXELS」的差异:首页 hero 粒子场跨 run 会留 1–2 个孤立像素,
|
||
它们会把 bbox 撑到整页,但并不是布局/文字位移。孤立像素单独计数并打印,超过
|
||
MAX_NOISE_PIXELS 同样判红(噪声变多也可能是渲染真的变了)。
|
||
"""
|
||
problems: list[str] = []
|
||
if old.size != new.size:
|
||
problems.append(f"尺寸变了:HEAD {old.size} → 现在 {new.size}(页高/文字度量被改动)")
|
||
return problems
|
||
|
||
dpr = DPR_BY_PROJECT.get(path.split(os.sep)[2], 1)
|
||
mask = diff_mask(old, new)
|
||
if not mask.any():
|
||
problems.append("没有任何差异像素:这张图没被改动影响,不该出现在重采清单里")
|
||
return problems
|
||
|
||
comps = components(mask)
|
||
significant = [c for c in comps if len(c) >= MIN_COMPONENT_PIXELS]
|
||
noise_pixels = sum(len(c) for c in comps if len(c) < MIN_COMPONENT_PIXELS)
|
||
if noise_pixels > MAX_NOISE_PIXELS:
|
||
problems.append(f"孤立差异像素 {noise_pixels} > {MAX_NOISE_PIXELS}(噪声多到无法归因)")
|
||
if not significant:
|
||
problems.append(f"只有 {noise_pixels} 个孤立差异像素,没有形成团块")
|
||
return problems
|
||
|
||
ys = [p[0] for c in significant for p in c]
|
||
xs = [p[1] for c in significant for p in c]
|
||
x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys)
|
||
w_css = (x1 - x0 + 1) / dpr
|
||
h_css = (y1 - y0 + 1) / dpr
|
||
if w_css > MAX_BBOX_WIDTH_CSS:
|
||
problems.append(f"差异宽 {w_css:.1f} CSS px > {MAX_BBOX_WIDTH_CSS}(图标右侧/文字被动过)")
|
||
if h_css > MAX_BBOX_HEIGHT_CSS:
|
||
problems.append(f"差异高 {h_css:.1f} CSS px > {MAX_BBOX_HEIGHT_CSS}(页脚/整段被判位移)")
|
||
print(
|
||
f" {path.split(os.sep)[-1]:<62} dpr={dpr} diff={mask.sum():>6}px 团块={len(significant)} "
|
||
f"孤立={noise_pixels:>2}px bbox={w_css:.1f}x{h_css:.1f} CSS px @({x0/dpr:.0f},{y0/dpr:.0f})"
|
||
)
|
||
return problems
|
||
|
||
|
||
def shift_content(img: Image.Image, dy_css: float, dpr: int) -> Image.Image:
|
||
"""整张内容下移 dy_css(模拟页脚整体位移),画布尺寸不变。"""
|
||
dx = int(round(dy_css * dpr))
|
||
canvas = Image.new("RGB", img.size, img.getpixel((0, 0)))
|
||
canvas.paste(img, (0, dx))
|
||
return canvas
|
||
|
||
|
||
def nudge_patch(img: Image.Image, dpr: int) -> Image.Image:
|
||
"""把一处非图标区的小块横向挪 2 CSS px(模拟文字被动过)。"""
|
||
w, h = img.size
|
||
pw, ph = int(200 * dpr), int(24 * dpr)
|
||
x, y = int(w * 0.15), int(h * 0.5)
|
||
patch = img.crop((x, y, x + pw, y + ph))
|
||
out = img.copy()
|
||
out.paste(patch, (x + int(2 * dpr), y))
|
||
return out
|
||
|
||
|
||
def main() -> int:
|
||
paths = changed_pngs()
|
||
if not paths:
|
||
print("SETUP-ERROR: 工作树里没有改动的 PNG —— 先生成改动再核验", file=sys.stderr)
|
||
return 2
|
||
|
||
tracked = []
|
||
untracked = []
|
||
pairs = []
|
||
for path in paths:
|
||
old = load_head(path)
|
||
new = Image.open(os.path.join(REPO, path)).convert("RGB")
|
||
if old is None:
|
||
untracked.append(path)
|
||
else:
|
||
tracked.append(path)
|
||
pairs.append((path, old, new))
|
||
|
||
if "--selftest" in sys.argv:
|
||
if not pairs:
|
||
print("SETUP-ERROR: 没有可做前后比对的基线,负对照无法运行", file=sys.stderr)
|
||
return 2
|
||
path, old, new = pairs[0]
|
||
dpr = DPR_BY_PROJECT.get(path.split(os.sep)[2], 1)
|
||
print(f"负对照 A(内容下移 10 CSS px,应判红):{path}")
|
||
a_problems = check_pair(path, old, shift_content(new, 10, dpr))
|
||
print(f" 判红={'是' if a_problems else '否 —— 仪器对整体位移不敏感'}")
|
||
print(f"负对照 B(非图标区小块横移 2 CSS px,应判红):{path}")
|
||
b_problems = check_pair(path, old, nudge_patch(new, dpr))
|
||
print(f" 判红={'是' if b_problems else '否 —— 仪器对非图标改动不敏感'}")
|
||
print("正对照(真实新图,应通过):")
|
||
c_problems = check_pair(path, old, new)
|
||
print(f" 通过={'是' if not c_problems else '否'}")
|
||
ok = bool(a_problems) and bool(b_problems) and not c_problems
|
||
print(f"SELFTEST {'PASS' if ok else 'FAIL'}")
|
||
return 0 if ok else 1
|
||
|
||
failures: list[str] = []
|
||
print(f"核验 {len(pairs)} 张有 HEAD 参照的基线(阈值:单通道 > {PIXEL_THRESHOLD};包围盒 ≤ "
|
||
f"{MAX_BBOX_WIDTH_CSS}×{MAX_BBOX_HEIGHT_CSS} CSS px)")
|
||
for path, old, new in pairs:
|
||
problems = check_pair(path, old, new)
|
||
if problems:
|
||
failures.append(f"{path}: " + ";".join(problems))
|
||
|
||
if untracked:
|
||
print(f"\n未入库基线 {len(untracked)} 张(HEAD 无参照,无法做前后比对):")
|
||
for path in untracked:
|
||
print(f" NO-REFERENCE {path}")
|
||
|
||
print()
|
||
if failures:
|
||
print(f"判定红:{len(failures)}/{len(pairs)} 张越界")
|
||
for line in failures:
|
||
print(" - " + line)
|
||
return 1
|
||
print(f"可参照基线全部通过:{len(pairs)}/{len(pairs)} 张只差在联系区两个图标盒内,且尺寸零变化")
|
||
if untracked and "--allow-untracked" not in sys.argv:
|
||
print(f"存在 {len(untracked)} 张未入库基线:未经授权不得入库,退出码 3", file=sys.stderr)
|
||
return 3
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
sys.exit(main())
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f"SETUP-ERROR: {exc}", file=sys.stderr)
|
||
sys.exit(2)
|