feat(landing): 睿视 landing 由本仓统一管理——源码子目录化 + 四道门禁移植 + 契约路由
承接 ADR-0014 §4「第二等产品镜像起必须子目录化 + rewrites 前缀映射并回溯睿视」。
上一轮(2026-12-02)只搬了字节,源码落在 public/ 根命名空间;本轮把源码、门禁、
发布职责一并收进本仓,authority 侧退役对应产物。
源码与 URL 契约:
- public/novavis/{index.html,css,js,assets,images/logos} 一棵树自成一体
- index.html 引用保持站点级绝对路径(/css /js /assets /images/logos)不变。
因为同一份字节要服务两个落点:官网镜像 novalon.cn/novavis/,以及独立子域
novavis.p.novalon.cn/(页面在根路径)。改绝对路径会把子域首页变成 /novavis/
- 故用 4 条 prefix rewrite 把根命名空间映射进子目录,而非改写 HTML
四道门禁(从 authority 的四个 python 脚本移植为 Playwright,已并入 test:all):
- e2e/landing/{layout,motion,demo,a11y}.spec.ts + 独立 config(单引擎单 project 串行)
- layout:几何与焦点 / motion:js-grow 渐进生长与 reduced-motion 直达终态
- demo:首屏剧本四步 + 徽标一一对应 + 无 JS 降级四层真实可见性
- a11y:结构与全量对比度(同色无条件阻断)+ axe critical/serious=0
- 实测 13 passed / EXIT=0(1.4m)
补一个映射期暴露的真缺陷:landing 的 main.js 固定 POST /api/v1/contact 且只认
code===200,而本仓只有 /api/contact(formData + 必填 subject),镜像侧转化路径
一直 404。新增 src/app/api/v1/contact/route.ts 按 authority 契约响应(JSON +
{code:200}),而非改前端去适配本仓——改前端等于把适配成本转嫁给子域,且会让
两个落点的成功判据不一致。9 个单测覆盖校验、限流、上游失败不透传 5xx。
文档与配置同步:CLAUDE.md → AGENTS.md(单文档真源)、docs/landing.md、
docs/deployment.md §八、ADR-0014、qa-tracker §32、README 与 quality-gates 脚本表、
Jenkinsfile 落地「♿ 可访问性门禁」阶段的 landing 四道门禁、eslint 忽略
.next-dev-live 构建产物目录(未忽略时 eslint . 会扫出 21195 errors)。
门禁:tsc 0 / eslint 0 / jest app/api/v1 9/9 / test:landing 13 passed。
This commit was merged in pull request #70.
This commit is contained in:
1 parent
f20fc92dc3
commit
99eaa8c66a
38 files changed
+3904
-48
No files matched your search
@@ -0,0 +1,439 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Landing page 审计门禁:结构可访问性 + 全量可见文字对比度扫描。
|
||||
|
||||
用法(在仓库根目录,先起静态服务):
|
||||
cd landing && python3 -m http.server 8099 --bind 127.0.0.1
|
||||
/usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/
|
||||
/usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/ --shots /tmp/out --json
|
||||
|
||||
分级判据(第四道 landing 门禁):
|
||||
阻断级 P1(任一命中 → 退出码 1):
|
||||
- 同色前景/背景:`rgb(x, x, x) on rgb(x, x, x)`。**无条件阻断**,不受 --fail 影响——
|
||||
否则把 --fail 调到 ≤ 1.0 时同色(1.00:1)会静默放行,这正是 2026-11-04 Blocking① 的形态。
|
||||
- 对比度 < --fail(默认 3.0,WCAG 大号文本线)
|
||||
- 结构项:横向溢出 / 缺 alt / 可聚焦元素无名称 / h1 数量 ≠ 1
|
||||
警告级 P2(逐条打印,**退出码仍为 0**,须人工定夺,不得静默忽略):
|
||||
- 对比度落在 [--fail, --warn)(默认 4.5 = WCAG AA 正文线)
|
||||
- 焦点指示缺失
|
||||
退出码:有阻断级 P1 → 1;仅警告级 P2 → 0。
|
||||
结束行打印 `AUDIT_RESULT: PASS|FAIL` 及阻断/警告分项计数。
|
||||
|
||||
为什么扫「全量」而不是点选若干选择器:2026-11-04 的 Blocking①(屏 2 白底白字,
|
||||
对比度 1.05:1)之所以从三道门禁缝里漏掉,是因为点选式断言只覆盖被想到的选择器。
|
||||
本脚本改为遍历所有直接含文字的元素,并先解除动效的初始隐藏态
|
||||
(js-grow / js-reveal / showcase-panel hidden),把每一屏都点亮后再测——
|
||||
包括当前不在视口内、以及 aria-hidden 装饰子树内的文字。
|
||||
|
||||
SVG 文字按 paint 的 fill 判,并以同组内先绘制的形状为底:否则会把继承来的
|
||||
color(深色主题下是白)当成画出来的颜色,整片图谱标签误报 1.05:1。
|
||||
"""
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
import argparse, json, math, sys
|
||||
from pathlib import Path
|
||||
|
||||
FAIL_MIN_DEFAULT = 3.0 # WCAG 大号文本线;低于此视为不可读
|
||||
WARN_MIN_DEFAULT = 4.5 # WCAG 正文 AA 线
|
||||
|
||||
# 把所有动效门控的初始隐藏态解除,让每一屏、每一个生长元素都真实呈现后再测
|
||||
REVEAL_ALL_JS = """
|
||||
() => {
|
||||
const root = document.documentElement;
|
||||
root.classList.remove('js-grow', 'js-reveal');
|
||||
document.querySelectorAll('.rv').forEach((el) => el.classList.add('in'));
|
||||
// 生长元素:直接落到终态
|
||||
document.querySelectorAll('[data-grow]').forEach((host) => {
|
||||
host.classList.add('is-grown');
|
||||
host.querySelectorAll('*').forEach((c) => c.classList.add('is-grown'));
|
||||
if (!host.querySelector('[data-grow]')) host.classList.add('is-grown');
|
||||
});
|
||||
// 轮播面板全部展开(默认 hidden + 非 active 不渲染)
|
||||
document.querySelectorAll('.showcase-panel').forEach((p) => {
|
||||
p.hidden = false;
|
||||
p.classList.add('active');
|
||||
p.style.display = 'grid';
|
||||
});
|
||||
// 首屏演示:停在终态并暂停,避免计时器改 DOM
|
||||
const hero = document.querySelector('#heroDemo');
|
||||
if (hero) hero.className = hero.className.replace(/demo-step-\\d/g, 'demo-final');
|
||||
['#showcasePause', '#demoPause'].forEach((sel) => {
|
||||
const b = document.querySelector(sel);
|
||||
if (b && b.getAttribute('aria-pressed') === 'false') b.click();
|
||||
});
|
||||
return {
|
||||
panels: document.querySelectorAll('.showcase-panel').length,
|
||||
heroClass: hero ? hero.className : null,
|
||||
};
|
||||
}
|
||||
"""
|
||||
|
||||
CONTRAST_SCAN_JS = """
|
||||
(args) => {
|
||||
const {failMin, warnMin} = args;
|
||||
const parse = (s) => {
|
||||
if (!s) return null;
|
||||
const m = s.match(/rgba?\\(([^)]+)\\)/);
|
||||
if (!m) return null;
|
||||
const p = m[1].split(/[\\s,\\/]+/).filter(Boolean).map(parseFloat);
|
||||
if (p.length < 3 || p.some(isNaN)) return null;
|
||||
return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1};
|
||||
};
|
||||
const chan = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
|
||||
const lum = (c) => 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b);
|
||||
const ratio = (fg, bg) => {
|
||||
const l1 = lum(fg) + 0.05, l2 = lum(bg) + 0.05;
|
||||
return l1 >= l2 ? l1 / l2 : l2 / l1;
|
||||
};
|
||||
const over = (top, bottom) => ({
|
||||
r: top.r * top.a + bottom.r * (1 - top.a),
|
||||
g: top.g * top.a + bottom.g * (1 - top.a),
|
||||
b: top.b * top.a + bottom.b * (1 - top.a),
|
||||
a: 1,
|
||||
});
|
||||
const SVG_TEXT_TAGS = new Set(['text', 'tspan']);
|
||||
const isSvgText = (el) => SVG_TEXT_TAGS.has(el.tagName.toLowerCase()) && !!el.ownerSVGElement;
|
||||
// 前景:HTML 取 color;SVG 文字取 paint 的 fill(color 只是继承值,不是画出来的色)
|
||||
//
|
||||
// ⚠️ 返回的是**已解析但未合成**的色(可能带 alpha)。调用方必须在下结论前用
|
||||
// compositeFg() 把前景叠到真实背景上——**不要直接拿它算 ratio**,见下方长注释。
|
||||
const fgOf = (el, st) => {
|
||||
if (isSvgText(el)) {
|
||||
if (st.fill === 'none') return null;
|
||||
const f = parse(st.fill);
|
||||
return f && f.a > 0 ? f : null;
|
||||
}
|
||||
return parse(st.color);
|
||||
};
|
||||
// 前景按背景合成。
|
||||
//
|
||||
// 【为什么必须有这一步 —— 2026-11-07 §28.2 评审 BLOCK 落项】
|
||||
// ratio() 只吃 rgb 三元组、不看 alpha。若把带 alpha 的前景直接喂进去,得到的是
|
||||
// 「把这个半透明颜色当成不透明色」的对比度,即 alpha 越低算出的对比度越**高**:
|
||||
// color: rgba(0,0,0,.05) 在白底上 → 直接算 21.00:1(完美),真实 1.12:1(不可见)
|
||||
// color: transparent → 解析成 rgba(0,0,0,0) → 直接算 21.00:1,真实 1.00:1
|
||||
// 后者正是「标题消失」的常见写法之一,会让本门禁对同类回归零判别力
|
||||
// (本轮的立论点就是「它是唯一覆盖标题是否可见的门禁」)。
|
||||
// 实测佐证:`.process-step-number`(rgba(15,23,42,.04)) 真值 1.08:1,未合成时报 16.63:1。
|
||||
//
|
||||
// 背景侧 bgOfAncestors() 一直是逐层 over() 合成到不透明底的(那段是对的),
|
||||
// 缺的一直只有前景这一侧——补上后两侧口径才一致。
|
||||
// 返回 a=1 的实色;透明度为 0 的前景与背景同色,ratio 自然是 1.00,落入同色阻断。
|
||||
const compositeFg = (fg, bg) => (fg.a >= 0.999 ? {r: fg.r, g: fg.g, b: fg.b, a: 1} : over(fg, bg));
|
||||
const bgOfAncestors = (el) => {
|
||||
const layers = [];
|
||||
let n = el;
|
||||
while (n && n.nodeType === 1) {
|
||||
const c = parse(getComputedStyle(n).backgroundColor);
|
||||
if (c) {
|
||||
if (c.a >= 0.999) { layers.push(c); break; }
|
||||
layers.push(c);
|
||||
}
|
||||
n = n.parentElement;
|
||||
}
|
||||
let base = {r: 255, g: 255, b: 255, a: 1};
|
||||
for (let i = layers.length - 1; i >= 0; i--) base = over(layers[i], base);
|
||||
return base;
|
||||
};
|
||||
// SVG 文字的真实底:同一容器内、绘制顺序在它之前且有不透明 fill 的形状
|
||||
const shapeUnder = (el) => {
|
||||
const parent = el.parentElement;
|
||||
if (!parent) return null;
|
||||
let hit = null;
|
||||
for (const k of parent.children) {
|
||||
if (k === el) break;
|
||||
const t = k.tagName.toLowerCase();
|
||||
if (t === 'text' || t === 'tspan') continue;
|
||||
const f = parse(getComputedStyle(k).fill);
|
||||
if (f && f.a >= 0.9) hit = f;
|
||||
}
|
||||
return hit;
|
||||
};
|
||||
const effectiveBg = (el) => {
|
||||
const canvas = bgOfAncestors(el);
|
||||
if (isSvgText(el)) {
|
||||
const shape = shapeUnder(el);
|
||||
if (shape) return over({r: shape.r, g: shape.g, b: shape.b, a: shape.a}, canvas);
|
||||
}
|
||||
return canvas;
|
||||
};
|
||||
const pathOf = (el) => {
|
||||
const parts = [];
|
||||
let n = el;
|
||||
while (n && n.nodeType === 1 && parts.length < 4) {
|
||||
let s = n.id ? '#' + n.id : n.tagName.toLowerCase();
|
||||
if (!n.id && n.className && typeof n.className === 'string') {
|
||||
const c = n.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2);
|
||||
if (c.length) s += '.' + c.join('.');
|
||||
}
|
||||
parts.unshift(s);
|
||||
n = n.parentElement;
|
||||
}
|
||||
return parts.join(' > ');
|
||||
};
|
||||
const hasDirectText = (el) => [...el.childNodes].some(
|
||||
(n) => n.nodeType === 3 && n.textContent.trim().length > 0
|
||||
);
|
||||
const visible = (el) => {
|
||||
const st = getComputedStyle(el);
|
||||
if (st.visibility === 'hidden' || st.display === 'none' || parseFloat(st.opacity) < 0.05) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width >= 2 && r.height >= 2;
|
||||
};
|
||||
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const el of document.querySelectorAll('body *')) {
|
||||
if (!hasDirectText(el) || !visible(el)) continue;
|
||||
const st = getComputedStyle(el);
|
||||
const fg = fgOf(el, st);
|
||||
if (!fg) continue;
|
||||
const bg = effectiveBg(el);
|
||||
const fsz = parseFloat(st.fontSize);
|
||||
const weight = parseInt(st.fontWeight, 10) || 400;
|
||||
const need = (fsz >= 24 || (fsz >= 18.66 && weight >= 700)) ? 3.0 : 4.5;
|
||||
// 必须先按背景合成再算 ratio:否则半透明/透明前景会被算成「高对比」(见 compositeFg 注释)
|
||||
const fgSolid = compositeFg(fg, bg);
|
||||
const r = ratio(fgSolid, bg);
|
||||
if (r >= need) continue;
|
||||
const key = pathOf(el) + '|' + (el.textContent || '').trim().slice(0, 24);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({
|
||||
path: pathOf(el),
|
||||
ratio: +r.toFixed(2),
|
||||
need,
|
||||
fg: `rgb(${Math.round(fgSolid.r)}, ${Math.round(fgSolid.g)}, ${Math.round(fgSolid.b)})`,
|
||||
bg: `rgb(${Math.round(bg.r)}, ${Math.round(bg.g)}, ${Math.round(bg.b)})`,
|
||||
font: `${fsz}px/${weight}`,
|
||||
text: (el.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 40),
|
||||
hidden: !!el.closest('[aria-hidden="true"]'),
|
||||
// 显式装饰标记:**只有作者主动标注**才算,绝不从 aria-hidden 推断。
|
||||
// 为什么不做自动推断:装饰子图里同样可能藏真缺陷(本脚本刻意连 aria-hidden 子树一起扫),
|
||||
// 用 aria-hidden 推断豁免等于给「整块藏起来」开了后门,与本门禁的立论点冲突。
|
||||
decorative: !!el.closest('[data-audit-decorative]'),
|
||||
});
|
||||
}
|
||||
out.sort((a, b) => a.ratio - b.ratio);
|
||||
// 同色检测在全量 out 上做,不能被 worst 的 80 条截断吃掉
|
||||
const sameColor = out.filter((o) => o.fg === o.bg);
|
||||
// 装饰豁免的成立条件(**两条缺一不可**):
|
||||
// ① 作者以 data-audit-decorative **主动标注**(不从 aria-hidden 自动推断,那等于给"整块藏起来"开后门);
|
||||
// ② 该文字本身在 aria-hidden 子树里 —— 即它对辅助技术不存在、没有信息量。
|
||||
// 只标属性而不 aria-hidden 的正文**不成立豁免**:否则一段真的低对比度正文
|
||||
// 只要被打上装饰标记就能逃逸,豁免就变成绕过通道了(已用注入探针验证过这个边界)。
|
||||
// 另外同色**永远**阻断、不受豁免影响:透明标题是最典型的"标题消失"形态,
|
||||
// 让它可以靠标属性混过去,本门禁就等于没有(同样有注入探针钉住)。
|
||||
const isDeco = (o) => o.decorative && o.hidden && o.fg !== o.bg;
|
||||
const deco = out.filter(isDeco);
|
||||
const real = out.filter((o) => !isDeco(o));
|
||||
return {
|
||||
worst: real.slice(0, 80),
|
||||
total: real.length,
|
||||
belowFail: real.filter((o) => o.ratio < failMin).length,
|
||||
belowWarn: real.filter((o) => o.ratio < warnMin).length,
|
||||
minRatio: real.length ? real[0].ratio : null,
|
||||
sameColor: sameColor.length,
|
||||
sameColorKeys: sameColor.map((o) => o.path + '|' + o.text),
|
||||
blocked: real.filter((o) => o.ratio < failMin || o.fg === o.bg).length,
|
||||
warned: real.filter((o) => o.ratio >= failMin && o.ratio < warnMin && o.fg !== o.bg).length,
|
||||
// 装饰豁免项照常回报(逐条打印成 NOTE,不静默吞掉),但不计入阻断/警告
|
||||
decorative: deco.length,
|
||||
decorativeItems: deco.map((o) => ({path: o.path, ratio: o.ratio, text: o.text})),
|
||||
};
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def structural_checks(page, name):
|
||||
"""P1/P2 结构项:溢出、alt、可访问名、h1、焦点指示。"""
|
||||
issues = []
|
||||
scroll_w = page.evaluate("() => document.documentElement.scrollWidth")
|
||||
client_w = page.evaluate("() => window.innerWidth")
|
||||
if scroll_w > client_w:
|
||||
issues.append(f"P1 [{name}] horizontal overflow: {scroll_w} > {client_w}")
|
||||
|
||||
for img in page.locator("img").all():
|
||||
if img.get_attribute("alt") is None:
|
||||
issues.append(f"P1 [{name}] img missing alt: src={img.get_attribute('src')}")
|
||||
|
||||
bad = page.evaluate(
|
||||
"""() => {
|
||||
const els = Array.from(document.querySelectorAll(
|
||||
'a, button, input, textarea, select, [role="tab"], summary'));
|
||||
return els.filter(el => {
|
||||
const name = el.getAttribute('aria-label') || el.getAttribute('title') ||
|
||||
el.textContent.trim() || el.getAttribute('placeholder') || '';
|
||||
return !name;
|
||||
}).map(el => el.outerHTML.slice(0, 120));
|
||||
}"""
|
||||
)
|
||||
for b in bad[:5]:
|
||||
issues.append(f"P1 [{name}] interactive element without accessible name: {b}")
|
||||
|
||||
h1s = page.locator("h1").count()
|
||||
if h1s != 1:
|
||||
issues.append(f"P1 [{name}] heading hierarchy: {h1s} h1")
|
||||
|
||||
for sel in (".nav-links a", "#navToggle"):
|
||||
loc = page.locator(sel).first
|
||||
try:
|
||||
if not loc.is_visible():
|
||||
continue
|
||||
loc.focus()
|
||||
if loc.evaluate("el => getComputedStyle(el).outlineWidth") == "0px":
|
||||
issues.append(f"P2 [{name}] focus indicator missing on {sel}")
|
||||
except Exception:
|
||||
pass
|
||||
return issues, (scroll_w, client_w)
|
||||
|
||||
|
||||
def audit_page(browser, base_url, width, height, name, args, report):
|
||||
page = browser.new_page(viewport={"width": width, "height": height})
|
||||
page.goto(base_url, wait_until="networkidle")
|
||||
page.wait_for_timeout(600)
|
||||
issues, dims = structural_checks(page, name)
|
||||
|
||||
if args.shots:
|
||||
out_dir = Path(args.shots)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
shot = str(out_dir / f"audit-{name}-{width}.png")
|
||||
page.screenshot(path=shot, full_page=True)
|
||||
else:
|
||||
shot = None
|
||||
|
||||
reveal = page.evaluate(REVEAL_ALL_JS)
|
||||
page.wait_for_timeout(200)
|
||||
scan = page.evaluate(CONTRAST_SCAN_JS, {"failMin": args.fail, "warnMin": args.warn})
|
||||
|
||||
same_ids = set(scan["sameColorKeys"])
|
||||
# 阻断级 = 对比度 < --fail ∪ 同色(同色无条件阻断:--fail 调到 ≤ 1.0 时 1.00:1 不得放行)
|
||||
blocking = [
|
||||
o for o in scan["worst"]
|
||||
if o["ratio"] < args.fail or (o["path"] + "|" + o["text"]) in same_ids
|
||||
]
|
||||
band = [
|
||||
o for o in scan["worst"]
|
||||
if args.fail <= o["ratio"] < args.warn
|
||||
and (o["path"] + "|" + o["text"]) not in same_ids
|
||||
]
|
||||
for o in blocking:
|
||||
suffix = " [aria-hidden]" if o["hidden"] else ""
|
||||
if (o["path"] + "|" + o["text"]) in same_ids:
|
||||
issues.append(
|
||||
f"P1 [{name}] 同色前景/背景 {o['fg']} on {o['bg']}(对比度 {o['ratio']})"
|
||||
f"@{o['font']} — {o['path']} «{o['text']}»{suffix}"
|
||||
)
|
||||
else:
|
||||
issues.append(
|
||||
f"P1 [{name}] contrast {o['ratio']} < {args.fail} (需 {o['need']}) "
|
||||
f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»{suffix}"
|
||||
)
|
||||
for o in band[: args.list]:
|
||||
issues.append(
|
||||
f"P2 [{name}] contrast {o['ratio']} < {args.warn} (需 {o['need']}) "
|
||||
f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»"
|
||||
+ (" [aria-hidden]" if o["hidden"] else "")
|
||||
)
|
||||
if len(band) > args.list:
|
||||
issues.append(f"P2 [{name}] …另有 {len(band) - args.list} 条对比度落在 [{args.fail},{args.warn})")
|
||||
# 装饰豁免项:逐条打印为 NOTE(不静默),但不进阻断/警告计数。
|
||||
# 「不静默」是刻意的——豁免必须是可审计的,不能因为标了个属性就从报告里消失。
|
||||
for o in scan["decorativeItems"]:
|
||||
issues.append(
|
||||
f"NOTE [{name}] 装饰豁免 contrast {o['ratio']} — {o['path']} «{o['text']}»"
|
||||
"(作者以 data-audit-decorative 标注为刻意淡化,不计入阻断/警告)"
|
||||
)
|
||||
|
||||
page_errors = []
|
||||
report[name] = {
|
||||
"viewport": [width, height],
|
||||
"screenshot": shot,
|
||||
"scrollWidth": dims[0],
|
||||
"clientWidth": dims[1],
|
||||
"revealedPanels": reveal["panels"],
|
||||
"contrast": {
|
||||
"minRatio": scan["minRatio"],
|
||||
"offenders": scan["total"],
|
||||
"belowFail": scan["belowFail"],
|
||||
"belowWarn": scan["belowWarn"],
|
||||
"sameColor": scan["sameColor"],
|
||||
"decorative": scan["decorative"],
|
||||
},
|
||||
"blocked": scan["blocked"],
|
||||
"warned": scan["warned"],
|
||||
"issues": issues,
|
||||
}
|
||||
page.close()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Landing page 结构与对比度审计门禁")
|
||||
ap.add_argument("--url", default="http://127.0.0.1:8088/", help="已启动的 landing 静态服务地址")
|
||||
ap.add_argument("--shots", default="", help="传入目录则输出整页截图")
|
||||
ap.add_argument("--fail", type=float, default=FAIL_MIN_DEFAULT,
|
||||
help="阻断级对比度下限(默认 3.0);同色前景/背景不受此参数影响,始终阻断")
|
||||
ap.add_argument("--warn", type=float, default=WARN_MIN_DEFAULT,
|
||||
help="警告级对比度上限(默认 4.5);落在 [--fail, --warn) 只打印不阻断")
|
||||
ap.add_argument("--list", type=int, default=20, help="每个视口最多打印多少条 P2(默认 20)")
|
||||
ap.add_argument("--json", action="store_true", help="额外打印 JSON 报告")
|
||||
args = ap.parse_args()
|
||||
|
||||
report = {}
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
for width, height, name in (
|
||||
(1440, 900, "desktop"),
|
||||
(768, 1024, "tablet"),
|
||||
(390, 844, "mobile"),
|
||||
):
|
||||
audit_page(browser, args.url, width, height, name, args, report)
|
||||
browser.close()
|
||||
|
||||
p1 = [i for v in report.values() for i in v["issues"] if i.startswith("P1")]
|
||||
p2 = [i for v in report.values() for i in v["issues"] if i.startswith("P2")]
|
||||
notes = [i for v in report.values() for i in v["issues"] if i.startswith("NOTE")]
|
||||
same_total = sum(v["contrast"]["sameColor"] for v in report.values())
|
||||
|
||||
print("== Landing 全量可见文字对比度扫描(已解除动效隐藏态)==")
|
||||
for name, v in report.items():
|
||||
c = v["contrast"]
|
||||
print(
|
||||
f" {name:>8} 展开面板 {v['revealedPanels']} 最低 {c['minRatio']} "
|
||||
f"低于判据 {c['offenders']} 条 其中同色 {c['sameColor']} "
|
||||
f"阻断级(P1) {v['blocked']} 警告级(P2) {v['warned']}"
|
||||
)
|
||||
if p1 or p2:
|
||||
print("\n== 问题清单 ==")
|
||||
for i in p1:
|
||||
print(" " + i[:220])
|
||||
for i in p2:
|
||||
print(" " + i[:220])
|
||||
else:
|
||||
print("\n== 无问题 ==")
|
||||
# 装饰豁免始终单独列出(即使全绿):豁免必须可审计,不能因为"没红"就从报告里消失
|
||||
if notes:
|
||||
print("\n== 装饰豁免(作者以 data-audit-decorative 主动标注,不计入阻断/警告)==")
|
||||
for i in notes:
|
||||
print(" " + i[:220])
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
|
||||
print("\n" + "=" * 46)
|
||||
blocked_total = sum(v["blocked"] for v in report.values())
|
||||
warned_total = sum(v["warned"] for v in report.values())
|
||||
if p1:
|
||||
print(
|
||||
f"AUDIT_RESULT: FAIL (阻断 P1={len(p1)} [同色 {same_total}] "
|
||||
f"警告 P2={len(p2)} 全量: 阻断 {blocked_total} / 警告 {warned_total})"
|
||||
)
|
||||
sys.exit(1)
|
||||
print(
|
||||
f"AUDIT_RESULT: PASS (阻断 P1=0 警告 P2={len(p2)} "
|
||||
f"全量: 阻断 0 / 警告 {warned_total})"
|
||||
)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,247 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hero Live Demo 演示动画验证脚本(landing/index.html #heroDemo)。
|
||||
|
||||
用法:
|
||||
NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1 \
|
||||
python3 scripts/landing-demo-verify.py [--url http://127.0.0.1:8088/] [--out /tmp/demo-verify]
|
||||
|
||||
验证内容:
|
||||
1. 四步剧本各阶段截图(导入 → 图谱 → 检测 → AI 结论)
|
||||
2. 循环重播(第二轮 demo-step-1 回归)
|
||||
3. 无 JS 降级:演示层不可见、静态 mockup 完整、指标为终值
|
||||
4. prefers-reduced-motion:demo-final 终态一次呈现
|
||||
5. console error / pageerror 收集
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
# 剧本阶段与采样时刻(秒)。2026-11-07 hero 主图由图窗改为 /home 任务工作台后,
|
||||
# 四步语义随之重写(新建任务 → 打开任务 → 导入数据 → 就绪),阶段名同步改掉;
|
||||
# DUR = {s1:2.6, s2:3.4, s3:3.2, s4:3.8, hold:1.6},故 1.4 / 4.4 / 7.6 / 11.6 / 16.4 的
|
||||
# 采样点相对于新剧本仍然落在各自的步内——**时刻未改,只改了阶段名**,因为改动时刻会让
|
||||
# 「脚本采样点」与「动画真实时间轴」脱钩,那是判据自伤而不是适配。
|
||||
STEPS = [
|
||||
("step1-create", 1.4),
|
||||
("step2-open", 4.4),
|
||||
("step3-import", 7.6),
|
||||
("step4-ready", 11.6),
|
||||
("loop-restart", 16.4),
|
||||
]
|
||||
|
||||
|
||||
def cls_of(page):
|
||||
return page.evaluate("document.getElementById('heroDemo').className")
|
||||
|
||||
|
||||
# 步号 → 该步应当显示的徽标文案(与 index.html 的 data-badge 一一对应)
|
||||
BADGE_OF_STEP = {
|
||||
"demo-step-1": "新建任务",
|
||||
"demo-step-2": "打开任务",
|
||||
"demo-step-3": "导入数据",
|
||||
"demo-step-4": "就绪",
|
||||
}
|
||||
|
||||
|
||||
def badges_now(page):
|
||||
"""当前**真实可见**的徽标文案列表(三层可见性,与 nojs 判定同口径)。"""
|
||||
return page.evaluate("""
|
||||
() => [...document.querySelectorAll('.demo-chrome-badge-item')]
|
||||
.filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})) return false;
|
||||
if (r.width <= 0 || r.height <= 0) return false;
|
||||
let op = 1, n = el;
|
||||
while (n && n.nodeType === 1) {
|
||||
const o = parseFloat(getComputedStyle(n).opacity);
|
||||
if (!Number.isNaN(o)) op *= o;
|
||||
if (op <= 0.05) return false;
|
||||
n = n.parentElement;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((el) => el.textContent.trim())
|
||||
""")
|
||||
|
||||
|
||||
def check_badge_matches_step(cls_samples, badge_samples):
|
||||
"""【SHOULD-FIX-2 / 2026-11-07 复审】
|
||||
|
||||
徽标是 BLOCKING-1 修完后的核心资产(「徽标与步号同义」),但此前**只靠人眼守**:
|
||||
复审的 PROBE-E 把 style.css 里整块徽标显示规则删掉,四道门禁仍然全绿。
|
||||
这里补正向断言:四个采样点上,当前步必须**恰好显示 1 个**徽标,且文案与该步同义。
|
||||
|
||||
为什么是"恰好 1 个"而不是">= 1":同时显示两个徽标说明映射有重叠(正是首轮
|
||||
「错位一整步」的伴生症状),那会让观众同时看到两个互斥的进度。
|
||||
"""
|
||||
problems = []
|
||||
for name, cls in cls_samples.items():
|
||||
step = next((st for st in BADGE_OF_STEP if st in cls), None)
|
||||
if step is None:
|
||||
continue # loop-restart 采样点落在复位瞬间,不判
|
||||
want = BADGE_OF_STEP[step]
|
||||
got = badge_samples.get(name, [])
|
||||
if len(got) != 1:
|
||||
problems.append(f"{name}: {step} 应恰好显示 1 个徽标,实测 {len(got)} 个 {got}")
|
||||
elif got[0] != want:
|
||||
problems.append(f"{name}: {step} 应显示「{want}」,实测「{got[0]}」")
|
||||
return {"ok": not problems, "problems": problems}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--url", default="http://127.0.0.1:8088/")
|
||||
ap.add_argument("--out", default="/tmp/demo-verify")
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
report = {"console_errors": [], "page_errors": []}
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(channel="chrome", headless=True)
|
||||
|
||||
# ---- 场景 1:正常播放,分阶段截图 + 类名采样 ----
|
||||
pg = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
pg.on("console", lambda m: report["console_errors"].append(m.text) if m.type == "error" else None)
|
||||
pg.on("pageerror", lambda e: report["page_errors"].append(str(e)))
|
||||
pg.goto(args.url, wait_until="load", timeout=60000)
|
||||
samples = {}
|
||||
badges = {}
|
||||
start = time.time()
|
||||
for name, at in STEPS:
|
||||
delta = at - (time.time() - start)
|
||||
if delta > 0:
|
||||
pg.wait_for_timeout(delta * 1000)
|
||||
samples[name] = cls_of(pg)
|
||||
badges[name] = badges_now(pg)
|
||||
pg.screenshot(path=str(out / f"{name}.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
|
||||
report["class_samples"] = samples
|
||||
report["badge_samples"] = badges
|
||||
report["badge_step_check"] = check_badge_matches_step(samples, badges)
|
||||
|
||||
# ---- 场景 2:无 JS 降级 ----
|
||||
ctx2 = browser.new_context(java_script_enabled=False, viewport={"width": 1440, "height": 900})
|
||||
pg2 = ctx2.new_page()
|
||||
pg2.goto(args.url, wait_until="load", timeout=60000)
|
||||
pg2.wait_for_timeout(500)
|
||||
# 无 JS 降级(2026-11-07 口径迁移):原断言挂在图窗的 .demo-import / .demo-ai /
|
||||
# [data-count-to=2046](= 关系数)/ .app-mockup-alert 上,那四样随 hero 改画 /home 已不存在。
|
||||
# 新口径问的是同一个问题——"没有 JS 时,首屏该看见的数是不是已经看得见":
|
||||
# · 任务总数读数 = 6(而不是被脚本归零的 0)
|
||||
# · 当前打开行仍在(is-current 是静态类,不靠 JS 加)
|
||||
# · 列头可见(视口锁定后列头只渲染一次,它是纯静态结构)
|
||||
# 【2026-11-07 §28.2 评审 BLOCKING-2 修法:判据收紧,不是放宽】
|
||||
# 上一版只读 textContent + computed display,对「内容在、但看不见」零判别力:
|
||||
# 评审用 `html:not(.js-demo) .nv-home-rows{opacity:0!important;visibility:hidden!important}`
|
||||
# 注入后本门禁仍然 PASS,截图是空白台账。那与 2026-11-04 的 Blocking① 是同一失效模式
|
||||
# (那一轮也是"内容在、看不见、门禁全绿")。
|
||||
# 现改为**真实可见性**判定,四层缺一不可:
|
||||
# ① checkVisibility({checkOpacity, checkVisibilityCSS}) —— 浏览器自己的口径
|
||||
# ② 祖先链上 opacity 有效值 > 0.05(checkVisibility 对 opacity 的处理在旧内核不一致)
|
||||
# ③ 元素矩形有面积(width/height > 0,排除被 layout 折叠)
|
||||
# ④ 文字非空
|
||||
report["nojs"] = {
|
||||
# 台账读数是**静态数据**(6 个任务),不是动画指标——它旁边列着 4 行真实任务,
|
||||
# 若写成 0 就与内容自相矛盾。故这里断言它无 JS 时就等于 6。
|
||||
"task_total": pg2.evaluate(
|
||||
"document.querySelector('.nv-home-pager b').textContent"),
|
||||
"current_row": pg2.evaluate(
|
||||
"document.querySelectorAll('.nv-home-row.is-current').length"),
|
||||
# 列头 + 第一行任务:不仅看 display,还要真的**看得见**
|
||||
"cols_visible": pg2.evaluate(
|
||||
"document.querySelector('.nv-home-cols').checkVisibility("
|
||||
"{checkOpacity:true, checkVisibilityCSS:true})"),
|
||||
"rows_visible": pg2.evaluate("""
|
||||
() => {
|
||||
const rows = [...document.querySelectorAll('.nv-home-row')];
|
||||
if (rows.length === 0) return 0;
|
||||
return rows.filter((el) => {
|
||||
const st = getComputedStyle(el);
|
||||
const r = el.getBoundingClientRect();
|
||||
// ② 祖先链有效 opacity
|
||||
let op = 1, n = el;
|
||||
while (n && n.nodeType === 1) {
|
||||
const o = parseFloat(getComputedStyle(n).opacity);
|
||||
if (!Number.isNaN(o)) op *= o;
|
||||
if (op <= 0.05) return false;
|
||||
n = n.parentElement;
|
||||
}
|
||||
// ① + ③ + ④
|
||||
const visible = el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});
|
||||
return visible && r.width > 0 && r.height > 0
|
||||
&& (el.textContent || '').trim().length > 0;
|
||||
}).length;
|
||||
}
|
||||
"""),
|
||||
"demo_rows_seen": pg2.evaluate(
|
||||
"document.querySelectorAll('.nv-home-row').length"),
|
||||
# 反向断言:**仅动画层**的徽标在无 JS 时必须不可见。
|
||||
# 它只在演示推进时有意义("现在走到哪一步"),无 JS 时没有步骤可指,
|
||||
# 显示出来就是一条没有指涉的标签。评审用
|
||||
# `.demo-chrome-badge{display:flex!important}` 注入出一条,上一版断言放过了它。
|
||||
"badge_visible": pg2.evaluate("""
|
||||
() => [...document.querySelectorAll('.demo-chrome-badge-item')]
|
||||
.filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})
|
||||
&& r.width > 0 && r.height > 0;
|
||||
}).length
|
||||
"""),
|
||||
# 正向金丝雀:选择器必须真的命中元素。
|
||||
# 否则 `badge_visible == 0` 会因为"一个徽标都没选中"而恒真——恒真的断言等于没有断言
|
||||
# (本仓反复踩过这个形状:判据通过态是 0 或空集时,"0"本身不是证据)。
|
||||
"badge_count": pg2.evaluate(
|
||||
"document.querySelectorAll('.demo-chrome-badge-item').length"),
|
||||
}
|
||||
pg2.screenshot(path=str(out / "nojs-static.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
|
||||
ctx2.close()
|
||||
|
||||
# ---- 场景 3:prefers-reduced-motion ----
|
||||
ctx3 = browser.new_context(reduced_motion="reduce", viewport={"width": 1440, "height": 900})
|
||||
pg3 = ctx3.new_page()
|
||||
pg3.on("pageerror", lambda e: report["page_errors"].append("reduced: " + str(e)))
|
||||
pg3.goto(args.url, wait_until="load", timeout=60000)
|
||||
pg3.wait_for_timeout(1200)
|
||||
report["reduced"] = {
|
||||
"hero_class": pg3.evaluate("document.getElementById('heroDemo').className"),
|
||||
"task_total": pg3.evaluate(
|
||||
"document.querySelector('.nv-home-pager b').textContent"),
|
||||
"current_row": pg3.evaluate(
|
||||
"document.querySelectorAll('.nv-home-row.is-current').length"),
|
||||
}
|
||||
pg3.screenshot(path=str(out / "reduced-final.png"), clip={"x": 620, "y": 120, "width": 800, "height": 620})
|
||||
ctx3.close()
|
||||
|
||||
browser.close()
|
||||
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
# 判定:无 pageerror + 循环回归 demo-step-1 + 无 JS 降级成立
|
||||
ok = (
|
||||
not report["page_errors"]
|
||||
and "demo-step-1" in report["class_samples"].get("loop-restart", "")
|
||||
# 无 JS 时必须直接看到终值 6(脚本未接管就不该出现 0)
|
||||
and report["nojs"]["task_total"] == "6"
|
||||
and report["nojs"]["current_row"] == 1
|
||||
# 列头与**全部**任务行必须真的可见(不是"存在但被 opacity/visibility 藏起来")
|
||||
and report["nojs"]["cols_visible"] is True
|
||||
and report["nojs"]["demo_rows_seen"] > 0
|
||||
and report["nojs"]["rows_visible"] == report["nojs"]["demo_rows_seen"]
|
||||
# 仅动画层在无 JS 时不得可见;且选择器必须非空(否则上一条恒真)
|
||||
and report["nojs"]["badge_count"] > 0
|
||||
and report["nojs"]["badge_visible"] == 0
|
||||
and "demo-final" in report["reduced"]["hero_class"]
|
||||
# 徽标正向:每步恰好 1 个且与步号同义(SHOULD-FIX-2)
|
||||
and report["badge_step_check"]["ok"]
|
||||
)
|
||||
print("VERIFY_RESULT:", "PASS" if ok else "FAIL")
|
||||
return ok
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 判据必须同时体现在 stdout 和退出码上:只打印 FAIL 而恒 exit 0,
|
||||
# 会让 §19/§21 引用的「门禁 exit 0」失去证明力(自检见 scripts/selfcheck-gates.sh)
|
||||
sys.exit(0 if main() else 1)
|
||||
@@ -0,0 +1,31 @@
|
||||
<!doctype html>
|
||||
<!--
|
||||
门禁自检夹具(scripts/selfcheck-gates.sh 使用)
|
||||
|
||||
这是一个「必然让 landing-demo-verify.py 判 FAIL、但自己不抛异常」的页面:
|
||||
演示容器、无 JS 降级节点、reduced-motion 节点都存在(选择器齐全 ⇒ 不产生 pageerror),
|
||||
但类名与数值全部不符合剧本判据。用它证明被检门禁「有能力失败」。
|
||||
|
||||
Last updated: 2026-09-20
|
||||
-->
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>gate selfcheck fixture</title>
|
||||
<style>
|
||||
/* 截图裁剪区为 x620 y120 w800 h620,页面须铺满 1440x900 视口 */
|
||||
html, body { width: 1440px; height: 900px; min-width: 1440px; min-height: 900px; margin: 0; }
|
||||
.demo-import, .demo-ai, .demo-ai-msg, .app-mockup-alert { display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="heroDemo" class="hero-demo-static">
|
||||
<div class="demo-import">import</div>
|
||||
<div class="demo-ai">
|
||||
<div class="demo-ai-msg">ai</div>
|
||||
</div>
|
||||
<div class="app-mockup-alert">alert</div>
|
||||
<span data-count-to="2046">0</span>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,305 @@
|
||||
#!/usr/bin/env python3
|
||||
"""landing 布局几何与焦点管理验证(复评 P2-7 / P2-8 / P2-9 的判别性门禁)。
|
||||
|
||||
前置:先起本地静态服务
|
||||
python3 -m http.server 8088 --bind 127.0.0.1 --directory landing
|
||||
|
||||
用法:
|
||||
NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1 \
|
||||
python3 scripts/verify-landing-layout.py [--url http://127.0.0.1:8088/] [--only tabs,focus,cta] [--shots /tmp/landing-shots]
|
||||
|
||||
检查项:
|
||||
1. tabs:各视口下 .showcase-tabs 的每个 tab 中心不被 #showcasePause 覆盖
|
||||
(窄视口下绝对定位的暂停按钮压在 tab 行之上),且无横向溢出
|
||||
2. focus:showcase 轮播的焦点管理(WCAG 2.2.2 精神)
|
||||
a. 焦点进入卡片后自动轮播让位(持焦期间 active tab 不变)
|
||||
b. 持焦 tab 不被摘掉 tabindex(摘掉即被移出 tab 序列,键盘焦点无处可回)
|
||||
c. 失焦后轮播恢复(证明 a 不是「轮播整体坏了」的假通过)
|
||||
3. roving:方向键切换后整组只留一只 tab 可被 Tab 键到达,且该只即 active 那只
|
||||
(roving tabindex 单点不变量;焦点须跟随 active)
|
||||
4. cta:nav 转化入口与信息链接有可视分层(描边/底色至少一项不同)
|
||||
5. --shots:把上述几处截成图片,供人工看几何与视觉权重(像素层面的重叠、
|
||||
留白、按钮挤行无法靠数值断言穷尽)
|
||||
|
||||
注意:悬停会冻结轮播(既有设计),故 focus 项全程把鼠标移到 (0,0) 并显式核对
|
||||
卡片已滚入视口——否则测的是 hover 冻结而非 focusin 暂停(本仓踩过)。
|
||||
2b 与 3 分工:2b 只在「持焦期间不切」的暂停语义下观察,真正判别 tabindex 时序
|
||||
缺陷的是 3(方向键切换 → syncRovingTabindex 与 focus() 的先后决定旧 tab 是否残留
|
||||
tabindex="0")。二者都不覆盖 2b 所防的那个竞态窗口(轮播回调已在 focusin 之前入队),
|
||||
该分支须驱动闭包内部函数才能命中,不为其暴露生产 API,仅由代码注释交代。
|
||||
|
||||
Last updated: 2026-09-20
|
||||
maintainer: novavis-authority
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
VIEWPORTS = [
|
||||
("桌面 1440", 1440, 900),
|
||||
("笔记本 1024", 1024, 768),
|
||||
("平板竖屏 768", 768, 1024),
|
||||
("手机 480", 480, 900),
|
||||
("手机 375", 375, 812),
|
||||
]
|
||||
|
||||
CYCLE_MS = 5500
|
||||
# 轮播间隔 + 余量:等待窗口内若未暂停,active tab 必定已切换
|
||||
WAIT_S = (CYCLE_MS / 1000) + 2.0
|
||||
|
||||
TAB_INFO = """() => {
|
||||
const pause = document.querySelector('#showcasePause');
|
||||
const pr = pause && getComputedStyle(pause).display !== 'none'
|
||||
? pause.getBoundingClientRect() : null;
|
||||
const covers = (r) => {
|
||||
if (!pr) return false;
|
||||
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
|
||||
return pr.left <= cx && cx <= pr.right && pr.top <= cy && cy <= pr.bottom;
|
||||
};
|
||||
return [...document.querySelectorAll('.showcase-tab')].map((t) => {
|
||||
const r = t.getBoundingClientRect();
|
||||
return {
|
||||
id: t.id,
|
||||
covered: covers(r),
|
||||
centerInViewport: (() => {
|
||||
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
|
||||
return cx >= 0 && cy >= 0 && cx <= innerWidth && cy <= innerHeight;
|
||||
})(),
|
||||
};
|
||||
});
|
||||
}"""
|
||||
|
||||
|
||||
def check_tabs(page, failures):
|
||||
"""1. tab 行与暂停按钮不重叠、无横向溢出"""
|
||||
for name, w, h in VIEWPORTS:
|
||||
page.set_viewport_size({"width": w, "height": h})
|
||||
page.evaluate("() => window.scrollTo(0, 0)")
|
||||
page.mouse.move(0, 0)
|
||||
page.locator(".showcase-tabs").scroll_into_view_if_needed()
|
||||
time.sleep(0.3)
|
||||
tabs = page.evaluate(TAB_INFO)
|
||||
covered = [t["id"] for t in tabs if t["covered"]]
|
||||
offscreen = [t["id"] for t in tabs if not t["centerInViewport"]]
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth - document.documentElement.clientWidth"
|
||||
)
|
||||
print(f" {name:>12} 被暂停按钮覆盖={covered or '无'} 出视口={offscreen or '无'} 横向溢出={overflow}px")
|
||||
if covered:
|
||||
failures.append(f"{name}: tab 被 #showcasePause 覆盖 {covered}")
|
||||
if offscreen:
|
||||
failures.append(f"{name}: tab 中心不在视口内 {offscreen}")
|
||||
if overflow > 1:
|
||||
failures.append(f"{name}: 页面横向溢出 {overflow}px")
|
||||
|
||||
|
||||
def active_tab(page):
|
||||
return page.evaluate("() => document.querySelector('.showcase-tab.active')?.id ?? null")
|
||||
|
||||
|
||||
def focused_tab_state(page):
|
||||
return page.evaluate(
|
||||
"""() => {
|
||||
const el = document.activeElement;
|
||||
if (!el || !el.classList || !el.classList.contains('showcase-tab')) return null;
|
||||
return { id: el.id, tabindex: el.getAttribute('tabindex') };
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
def check_focus(page, failures):
|
||||
"""2. 焦点进入卡片期间轮播让位;持焦 tab 不被摘 tabindex;失焦后轮播恢复"""
|
||||
page.set_viewport_size({"width": 1440, "height": 900})
|
||||
page.reload(wait_until="load")
|
||||
page.mouse.move(0, 0)
|
||||
page.locator(".showcase-tabs").scroll_into_view_if_needed()
|
||||
time.sleep(0.6)
|
||||
page.mouse.move(0, 0)
|
||||
|
||||
before = active_tab(page)
|
||||
page.evaluate(
|
||||
"""() => { const t = document.querySelector('.showcase-tab.active'); t && t.focus(); }"""
|
||||
)
|
||||
state = focused_tab_state(page)
|
||||
print(f" 持焦 tab = {state}")
|
||||
if not state:
|
||||
failures.append("未能把焦点放进 tablist(用例前提不成立)")
|
||||
return
|
||||
time.sleep(WAIT_S)
|
||||
after = active_tab(page)
|
||||
print(f" 持焦 {WAIT_S:.1f}s 后 active = {after}(持焦前 {before},期望不变)")
|
||||
if after != before:
|
||||
failures.append(f"焦点在卡片内时轮播未让位:active {before} → {after}")
|
||||
held = focused_tab_state(page)
|
||||
print(f" 持焦元素 tabindex = {held}")
|
||||
if held and held.get("tabindex") == "-1":
|
||||
failures.append(f"持焦 tab {held['id']} 的 tabindex 被摘成 -1(键盘焦点会被移出序列)")
|
||||
|
||||
# 失焦后须恢复轮播:否则上一条「不变」可能只是轮播整体失效
|
||||
page.evaluate("() => document.activeElement && document.activeElement.blur()")
|
||||
page.evaluate("() => window.scrollTo(0, 0)")
|
||||
page.mouse.move(0, 0)
|
||||
page.locator("#nav").scroll_into_view_if_needed()
|
||||
page.locator(".showcase-tabs").scroll_into_view_if_needed()
|
||||
deadline = time.time() + WAIT_S + 1.0
|
||||
resumed = None
|
||||
while time.time() < deadline:
|
||||
current = active_tab(page)
|
||||
if current != before:
|
||||
resumed = current
|
||||
break
|
||||
time.sleep(0.5)
|
||||
print(f" 失焦后轮播恢复 = {resumed}(期望 ≠ {before})")
|
||||
if not resumed:
|
||||
failures.append("失焦后轮播未恢复:前一条「持焦不变」可能是轮播整体失效的假通过")
|
||||
|
||||
|
||||
def check_roving(page, failures):
|
||||
"""3. 方向键切换后 roving tabindex 单点不变量"""
|
||||
page.set_viewport_size({"width": 1440, "height": 900})
|
||||
page.reload(wait_until="load")
|
||||
page.mouse.move(0, 0)
|
||||
page.locator(".showcase-tabs").scroll_into_view_if_needed()
|
||||
time.sleep(0.4)
|
||||
page.evaluate(
|
||||
"""() => { const t = document.querySelector('.showcase-tab.active'); t && t.focus(); }"""
|
||||
)
|
||||
if focused_tab_state(page) is None:
|
||||
failures.append("未能把焦点放进 tablist(roving 不变量前提不成立)")
|
||||
return
|
||||
page.keyboard.press("ArrowRight")
|
||||
time.sleep(0.3)
|
||||
state = page.evaluate(
|
||||
"""() => {
|
||||
const tabs = [...document.querySelectorAll('.showcase-tab')];
|
||||
const isTab = (el) => !!el && el.classList && el.classList.contains('showcase-tab');
|
||||
return {
|
||||
zero: tabs.filter((t) => t.getAttribute('tabindex') === '0').map((t) => t.id),
|
||||
active: tabs.filter((t) => t.classList.contains('active')).map((t) => t.id),
|
||||
focused: isTab(document.activeElement) ? document.activeElement.id : null,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
print(f" 方向键后 tabindex=0 = {state['zero']},active = {state['active']},持焦 = {state['focused']}")
|
||||
if len(state["zero"]) != 1:
|
||||
failures.append(
|
||||
f"方向键切换后整组有 {len(state['zero'])} 只 tab 可被 Tab 键到达({state['zero']}),"
|
||||
"违反 roving tabindex 单点(旧 tab 仍留在序列里)"
|
||||
)
|
||||
elif not state["active"] or state["zero"][0] != state["active"][0]:
|
||||
failures.append(
|
||||
f"可被 Tab 键到达的 tab({state['zero']})不是 active tab({state['active']})"
|
||||
)
|
||||
if not state["active"]:
|
||||
failures.append("方向键切换后无 active tab")
|
||||
elif state["focused"] != state["active"][0]:
|
||||
failures.append(f"方向键切换后焦点未跟随 active tab(持焦 {state['focused']})")
|
||||
|
||||
|
||||
def check_cta(page, failures):
|
||||
"""3. nav 转化入口与信息链接分层"""
|
||||
page.set_viewport_size({"width": 1440, "height": 900})
|
||||
page.evaluate("() => window.scrollTo(0, 0)")
|
||||
styles = page.evaluate(
|
||||
"""() => {
|
||||
const links = [...document.querySelectorAll('.nav-links a')];
|
||||
const info = links.find((a) => a.getAttribute('href') === '#features');
|
||||
const cta = links.find((a) => a.getAttribute('href') === '#contact');
|
||||
const pick = (el) => {
|
||||
if (!el) return null;
|
||||
const s = getComputedStyle(el);
|
||||
return {
|
||||
cls: el.className,
|
||||
border: `${s.borderTopWidth} ${s.borderTopStyle} ${s.borderTopColor}`,
|
||||
bg: s.backgroundColor,
|
||||
color: s.color,
|
||||
};
|
||||
};
|
||||
return { info: pick(info), cta: pick(cta) };
|
||||
}"""
|
||||
)
|
||||
print(f" 信息链接 = {styles['info']}")
|
||||
print(f" 转化入口 = {styles['cta']}")
|
||||
if not styles["info"] or not styles["cta"]:
|
||||
failures.append("nav 信息链接或 #contact 转化入口不存在")
|
||||
return
|
||||
if styles["info"] == styles["cta"]:
|
||||
failures.append("nav 转化入口与信息链接样式完全相同(无分层)")
|
||||
# 转化入口须比信息链接更醒目:文字更亮(白色)
|
||||
print(" 判据:转化入口须与信息链接在描边/底色/文字色上至少一项不同")
|
||||
|
||||
|
||||
def take_shots(page, out):
|
||||
"""4. 人工评审截图:nav 分层(宽/窄)、窄视口 showcase tab 行"""
|
||||
page.set_viewport_size({"width": 1440, "height": 900})
|
||||
page.reload(wait_until="load")
|
||||
page.mouse.move(0, 0)
|
||||
time.sleep(1.0)
|
||||
page.locator("#nav").screenshot(path=str(out / "nav-1440.png"))
|
||||
|
||||
page.set_viewport_size({"width": 375, "height": 812})
|
||||
page.evaluate("() => window.scrollTo(0, 0)")
|
||||
page.click("#navToggle")
|
||||
time.sleep(0.5)
|
||||
# 展开面板是 #nav 的绝对定位子元素,元素截图会裁到导航条自身高度,故截整个视口
|
||||
page.screenshot(path=str(out / "nav-375-open.png"))
|
||||
page.click("#navToggle")
|
||||
|
||||
for w in (480, 375):
|
||||
page.set_viewport_size({"width": w, "height": 900})
|
||||
page.locator(".showcase-tabs").scroll_into_view_if_needed()
|
||||
page.mouse.move(0, 0)
|
||||
time.sleep(0.5)
|
||||
page.locator(".showcase-card").screenshot(path=str(out / f"showcase-{w}.png"))
|
||||
print(f" 截图已写入 {out}:nav-1440 / nav-375-open / showcase-480 / showcase-375")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--url", default="http://127.0.0.1:8088/")
|
||||
ap.add_argument("--only", default="tabs,focus,roving,cta")
|
||||
ap.add_argument("--shots", default="", help="传入目录则产出人工评审用截图")
|
||||
args = ap.parse_args()
|
||||
only = {s.strip() for s in args.only.split(",") if s.strip()}
|
||||
|
||||
failures = []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(channel="chrome", headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
page.goto(args.url, wait_until="load")
|
||||
time.sleep(1.2)
|
||||
|
||||
if "tabs" in only:
|
||||
print("== 1. showcase tab 行与暂停按钮几何 ==")
|
||||
check_tabs(page, failures)
|
||||
if "focus" in only:
|
||||
print("\n== 2. showcase 轮播焦点管理 ==")
|
||||
check_focus(page, failures)
|
||||
if "roving" in only:
|
||||
print("\n== 3. 键盘 roving tabindex 单点 ==")
|
||||
check_roving(page, failures)
|
||||
if "cta" in only:
|
||||
print("\n== 4. nav 转化入口分层 ==")
|
||||
check_cta(page, failures)
|
||||
if args.shots:
|
||||
print("\n== 5. 人工评审截图 ==")
|
||||
out = Path(args.shots)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
take_shots(page, out)
|
||||
|
||||
browser.close()
|
||||
|
||||
print("\n" + "=" * 46)
|
||||
if failures:
|
||||
print("RESULT: FAIL")
|
||||
for f in failures:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("RESULT: PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""验证 landing 页面的渐进生长动效(GROW 模块)。
|
||||
|
||||
前置:先起本地静态服务
|
||||
cd landing && python3 -m http.server 8088 --bind 127.0.0.1
|
||||
|
||||
用法:
|
||||
python3 scripts/verify-landing-motion.py [base_url]
|
||||
|
||||
检查项:
|
||||
1. html.js-grow 已挂载(CSS 初始隐藏态生效的前提)
|
||||
2. Hero mockup 在进入视口后元素依次点亮(密集采样至终态,剧本会循环复位)
|
||||
3. Showcase 四个 panel 切 tab 后各自重播到全部点亮
|
||||
4. 离开视口后复位(is-grown 清零)
|
||||
5. prefers-reduced-motion 下直接呈现终态
|
||||
6. 装饰性图形对 AT 隐藏,且 aria-hidden 子树内无可聚焦元素(axe aria-hidden-focus)
|
||||
7. 无 JS 运行时错误
|
||||
|
||||
注意:生长动效由剧本时间轴驱动(Hero 约 7s 到终态后循环复位),固定短窗口采样会假失败,
|
||||
故 2/3 用「密集采样取峰值」判定,峰值须等于目标总数。
|
||||
|
||||
Last updated: 2026-09-19
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8088/"
|
||||
|
||||
PANELS = [
|
||||
("#showcase-tab-graph", "#showcase-panel-graph", "关系图谱"),
|
||||
("#showcase-tab-flow", "#showcase-panel-flow", "资金流向"),
|
||||
("#showcase-tab-ai", "#showcase-panel-ai", "AI 分析"),
|
||||
("#showcase-tab-process", "#showcase-panel-process", "分析过程"),
|
||||
]
|
||||
|
||||
|
||||
def total_targets(page, sel):
|
||||
"""统计该容器内的待点亮目标总数(与 JS targetsOf 的规则一致)。"""
|
||||
return page.evaluate(
|
||||
"""(s) => {
|
||||
const root = document.querySelector(s);
|
||||
if (!root) return 0;
|
||||
let n = 0;
|
||||
root.querySelectorAll('[data-grow]').forEach(el => {
|
||||
n += (el.tagName.toLowerCase() === 'g') ? el.children.length : 1;
|
||||
});
|
||||
return n;
|
||||
}""",
|
||||
sel,
|
||||
)
|
||||
|
||||
|
||||
def grown(page, sel):
|
||||
return page.locator(f"{sel} .is-grown").count()
|
||||
|
||||
|
||||
def watch_growth(page, sel, total, window=12.0, interval=0.4):
|
||||
"""密集采样到峰值:剧本会循环复位,故以「是否曾到达终态」而非末次快照判定。"""
|
||||
peak, samples, waited = 0, [], 0.0
|
||||
while waited < window:
|
||||
cur = grown(page, sel)
|
||||
peak = max(peak, cur)
|
||||
samples.append(cur)
|
||||
if peak == total:
|
||||
break
|
||||
time.sleep(interval)
|
||||
waited += interval
|
||||
return peak, samples
|
||||
|
||||
|
||||
def watch_demo_steps(page, selector, window=14.0):
|
||||
"""采样 demo-step-* 类的推进序列(去重、保序)。
|
||||
|
||||
用于 /home 剧本:hero 改画任务工作台后不再有 data-grow 元素,
|
||||
「动画在跑」这件事改由步骤类推进来证明。
|
||||
"""
|
||||
seen = []
|
||||
samples = []
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < window:
|
||||
cls = page.evaluate(
|
||||
"sel => document.querySelector(sel)?.className ?? ''", selector)
|
||||
cur = None
|
||||
for step in ("demo-step-1", "demo-step-2", "demo-step-3", "demo-step-4"):
|
||||
if step in cls:
|
||||
cur = step
|
||||
samples.append(cur)
|
||||
if cur is not None and cur not in seen:
|
||||
seen.append(cur)
|
||||
time.sleep(0.25)
|
||||
return seen, samples
|
||||
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(channel="chrome", headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
page.goto(BASE, wait_until="load")
|
||||
time.sleep(1.5)
|
||||
|
||||
print("== 1. html.js-grow 挂载 ==")
|
||||
ok = page.evaluate("document.documentElement.classList.contains('js-grow')")
|
||||
print(f" js-grow = {ok}")
|
||||
if not ok:
|
||||
failures.append("html.js-grow 未挂载")
|
||||
|
||||
# == 2. Hero 首屏演示推进 ==
|
||||
# 2026-11-07:hero 主图由图窗改为 /home 任务工作台,图窗那批 data-grow 元素随之移出 hero,
|
||||
# 故"生长"这一判据在 hero 上已无作用对象(目标总数恒 0)。判据换成**同一意图的等价物**:
|
||||
# 首屏演示是否真的在推进 —— 采样 demo-step-* 类为单一线性推进(1→2→3→4),
|
||||
# 且不回头。这与"元素逐批生长"检验的是同一件事:剧本在跑、不是冻在第一帧。
|
||||
# 四屏 showcase 的 data-grow 判据(第 3 节)保持原样不动,那里仍有 37/6/7/7 个生长目标。
|
||||
print("\n== 2. Hero 首屏演示推进(/home 剧本)==")
|
||||
h_total = total_targets(page, ".hero-visual")
|
||||
steps_seen, step_samples = watch_demo_steps(page, "#heroDemo", window=14.0)
|
||||
print(f" data-grow 目标={h_total}(/home 上预期 0) 观察到的步骤={steps_seen}")
|
||||
if h_total != 0:
|
||||
print(f" 注:hero 上出现 {h_total} 个 data-grow 目标,将同时按生长判据检查")
|
||||
if len(steps_seen) < 3:
|
||||
failures.append(f"Hero 剧本未推进:只观察到 {steps_seen}(样本 {step_samples})")
|
||||
if "demo-step-1" not in steps_seen or not any(
|
||||
x in steps_seen for x in ("demo-step-3", "demo-step-4")):
|
||||
failures.append(f"Hero 剧本未走完前半程:{steps_seen}")
|
||||
|
||||
print("\n== 3. Showcase 四个 panel 重播 ==")
|
||||
page.locator("#showcase").scroll_into_view_if_needed()
|
||||
time.sleep(0.5)
|
||||
for tab_sel, panel_sel, name in PANELS:
|
||||
page.click(tab_sel)
|
||||
time.sleep(0.2)
|
||||
total = total_targets(page, panel_sel)
|
||||
before = grown(page, panel_sel)
|
||||
peak, samples = watch_growth(page, panel_sel, total, window=10.0)
|
||||
grew = before < peak or peak == total
|
||||
print(f" {name}: 总数={total:>3} 切换后={before:>3} 峰值={peak:>3} "
|
||||
f"采样步数={len(samples)}")
|
||||
if not grew:
|
||||
failures.append(f"{name} 切换后未重播: 峰值 {peak}(切换后 {before})")
|
||||
if peak != total:
|
||||
failures.append(f"{name} 未跑完: 峰值 {peak}/{total}")
|
||||
|
||||
print("\n== 4. 离开视口复位 ==")
|
||||
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
|
||||
time.sleep(1.0)
|
||||
after_leave = grown(page, "#showcase-panel-process")
|
||||
print(f" 滚到页面底部后 is-grown = {after_leave} (期望 0)")
|
||||
if after_leave != 0:
|
||||
failures.append(f"离开视口未复位: {after_leave}")
|
||||
|
||||
print("\n== 5. prefers-reduced-motion 直接终态 ==")
|
||||
page.emulate_media(reduced_motion="reduce")
|
||||
page.reload(wait_until="load")
|
||||
time.sleep(1.2)
|
||||
page.locator("#showcase").scroll_into_view_if_needed()
|
||||
time.sleep(0.4)
|
||||
r_total = total_targets(page, "#showcase-panel-graph")
|
||||
r_grown = grown(page, "#showcase-panel-graph")
|
||||
print(f" reduced-motion 下 is-grown = {r_grown}/{r_total} (期望相等)")
|
||||
if r_grown != r_total:
|
||||
failures.append(f"reduced-motion 未直达终态: {r_grown}/{r_total}")
|
||||
page.emulate_media(reduced_motion="no-preference")
|
||||
|
||||
print("\n== 6. 装饰性图形无障碍属性 ==")
|
||||
a11y = page.evaluate(
|
||||
"""() => {
|
||||
const FOCUSABLE = 'a[href], button, input, select, textarea, [tabindex]';
|
||||
const focusable = (sel) => [...document.querySelectorAll(sel)]
|
||||
.filter(e => e.matches(FOCUSABLE) || e.querySelector(FOCUSABLE))
|
||||
.map(e => e.id || e.className);
|
||||
return {
|
||||
heroDemo: document.querySelector('#heroDemo')?.getAttribute('aria-hidden') ?? null,
|
||||
showcaseVisuals: [...document.querySelectorAll('.showcase-visual')]
|
||||
.map(e => e.getAttribute('aria-hidden')),
|
||||
heroVisual: document.querySelector('.hero-visual')?.getAttribute('aria-hidden') ?? null,
|
||||
focusableInHidden: [...document.querySelectorAll('[aria-hidden="true"]')]
|
||||
.flatMap(root => [...root.querySelectorAll(FOCUSABLE)])
|
||||
.filter(e => !e.hasAttribute('disabled') && e.tabIndex >= 0)
|
||||
.map(e => `${e.tagName.toLowerCase()}#${e.id}`),
|
||||
demoPause: (() => {
|
||||
const btn = document.querySelector('#demoPause');
|
||||
return btn ? { exists: true, label: btn.getAttribute('aria-label'),
|
||||
pressed: btn.getAttribute('aria-pressed') } : { exists: false };
|
||||
})(),
|
||||
};
|
||||
}"""
|
||||
)
|
||||
print(f" #heroDemo aria-hidden = {a11y['heroDemo']} (期望 true)")
|
||||
print(f" .showcase-visual aria-hidden = {set(a11y['showcaseVisuals'])} (期望 {{'true'}})")
|
||||
print(f" .hero-visual aria-hidden = {a11y['heroVisual']!r} "
|
||||
f"(期望 None——容器承载暂停按钮,隐藏会连带隐藏控件)")
|
||||
print(f" aria-hidden 子树内可聚焦元素 = {a11y['focusableInHidden'] or '无'} (期望 无)")
|
||||
print(f" 暂停控件 = {a11y['demoPause']}")
|
||||
if a11y["heroDemo"] != "true":
|
||||
failures.append(f"演示层未对 AT 隐藏: {a11y['heroDemo']}")
|
||||
if set(a11y["showcaseVisuals"]) != {"true"} or not a11y["showcaseVisuals"]:
|
||||
failures.append(f"showcase 装饰图形 aria-hidden 异常: {a11y['showcaseVisuals']}")
|
||||
if a11y["heroVisual"] == "true":
|
||||
failures.append(".hero-visual 不应整体 aria-hidden(内含暂停按钮)")
|
||||
if a11y["focusableInHidden"]:
|
||||
failures.append(f"aria-hidden 子树内含可聚焦元素: {a11y['focusableInHidden']}")
|
||||
if not a11y["demoPause"].get("exists") or not a11y["demoPause"].get("label"):
|
||||
failures.append(f"暂停按钮缺失或无无障碍名: {a11y['demoPause']}")
|
||||
|
||||
print("\n== 7. JS 运行时错误 ==")
|
||||
print(f" {errors or '无'}")
|
||||
if errors:
|
||||
failures.append(f"JS 错误: {errors}")
|
||||
|
||||
browser.close()
|
||||
|
||||
print("\n" + "=" * 46)
|
||||
if failures:
|
||||
print("RESULT: FAIL")
|
||||
for f in failures:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("RESULT: PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user