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,433 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
|
||||
/**
|
||||
* Landing 门禁 ④:结构与全量可见文字对比度(移植自 `novavis-authority/scripts/landing-audit.py`)
|
||||
*
|
||||
* ## 这道门禁为什么必须存在
|
||||
*
|
||||
* 2026-11-04 的 Blocking①(屏 2 整屏白底白字)能连过前三道门禁,因为那三道**根本不读颜色**。
|
||||
* 本门禁是唯一覆盖「标题是否可见」的一道:它遍历所有直接含文字的元素,读 computed
|
||||
* foreground / background 实算对比度。
|
||||
*
|
||||
* ## 判据分级(与迁移前逐条一致)
|
||||
*
|
||||
* | 级别 | 判据 | 结果 |
|
||||
* |---|---|---|
|
||||
* | P1 阻断 | 同色前景/背景(`rgb(x,x,x)` on `rgb(x,x,x)`) | 无条件失败,**不受阈值影响** |
|
||||
* | P1 阻断 | 对比度 < 3.0(WCAG 大号文本线) | 失败 |
|
||||
* | P1 阻断 | 结构项:横向溢出 / `img` 缺 `alt` / 可聚焦元素无无障碍名 / `h1` 数量 ≠ 1 | 失败 |
|
||||
* | P2 警告 | 对比度落在 [3.0, 4.5) | **不失败**,但逐条打印(须人工定夺) |
|
||||
* | P2 警告 | 焦点指示缺失 | **不失败**,逐条打印 |
|
||||
* | NOTE | 装饰豁免(作者以 `data-audit-decorative` 主动标注 **且** 在 `aria-hidden` 子树内) | 逐条打印,不计入 |
|
||||
*
|
||||
* ## 三条必须知道的口径(原脚本用注入探针钉过,不许简化)
|
||||
*
|
||||
* 1. **前景必须先按背景合成 alpha 再算对比度**。`ratio()` 只吃 rgb 三元组、不看 alpha;
|
||||
* 把带 alpha 的前景直接喂进去,alpha 越低算出的对比度越**高**:
|
||||
* `color: rgba(0,0,0,.05)` 未合成报 21.00:1,真值 1.12:1;`color: transparent` 未合成报
|
||||
* 21.00:1,真值 1.00:1 —— 后者正是「标题消失」的常见写法。本文件 `compositeFg()` 补齐。
|
||||
* 2. **同色无条件阻断、与阈值解耦**。若只按 `ratio < 3.0` 判,把阈值调到 ≤1.0 时同色
|
||||
* (恒 1.00)会被静默放行 —— 正好复现 Blocking① 的形态。
|
||||
* 3. **装饰豁免必须两条同时满足**:作者主动标注 `data-audit-decorative` **且** 该文字在
|
||||
* `aria-hidden` 子树内。只标属性而不 `aria-hidden` 的正文不成立豁免(否则一段真的低对比度
|
||||
* 正文只要打上标记就能逃逸)。同色永远阻断、不受豁免影响。
|
||||
*
|
||||
* ## 与 axe 的分工
|
||||
*
|
||||
* 本门禁的对比度扫描覆盖「所有直接含文字的元素」(含 SVG `<text>`,且按真实背景合成),
|
||||
* axe 的 `color-contrast` 规则覆盖的是它自己的可达元素集。两者**都跑**:axe 提供标准的
|
||||
* 无障碍树口径,自写扫描提供「标题是否消失」这个 axe 判不出的角度(axe 跳过 `aria-hidden`
|
||||
* 子树,而本门禁刻意连它一起扫)。
|
||||
*/
|
||||
|
||||
const LANDING_URL = '/novavis';
|
||||
|
||||
/** 阻断级对比度下限(WCAG 大号文本线)。同色不受此参数影响。 */
|
||||
const FAIL_MIN = 3.0;
|
||||
/** 警告级对比度上限(WCAG 正文 AA 线)。 */
|
||||
const WARN_MIN = 4.5;
|
||||
|
||||
const VIEWPORTS = [
|
||||
{ name: 'desktop', width: 1440, height: 900 },
|
||||
{ name: 'tablet', width: 768, height: 1024 },
|
||||
{ name: 'mobile', width: 390, height: 844 },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 把所有动效门控的初始隐藏态解除,让每一屏、每一个生长元素都真实呈现后再测。
|
||||
* (未解除时 `js-grow` 下的元素 opacity 为 0,会被 `visible()` 过滤掉 ⇒ 扫描面大幅缩水,
|
||||
* 而门禁仍然「绿」——那是分母静默变小。)
|
||||
*/
|
||||
function revealAll() {
|
||||
const root = document.documentElement;
|
||||
root.classList.remove('js-grow', 'js-reveal');
|
||||
document.querySelectorAll<HTMLElement>('.rv').forEach((el) => el.classList.add('in'));
|
||||
document.querySelectorAll<HTMLElement>('[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');
|
||||
});
|
||||
document.querySelectorAll<HTMLElement>('.showcase-panel').forEach((p) => {
|
||||
p.hidden = false;
|
||||
p.classList.add('active');
|
||||
p.style.display = 'grid';
|
||||
});
|
||||
const hero = document.querySelector<HTMLElement>('#heroDemo');
|
||||
if (hero) hero.className = hero.className.replace(/demo-step-\d/g, 'demo-final');
|
||||
['#showcasePause', '#demoPause'].forEach((sel) => {
|
||||
const b = document.querySelector<HTMLElement>(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` 逐条同义)。
|
||||
*
|
||||
* 参数是普通对象:Playwright 的 JS 版 `evaluate` 支持「函数 + 一个可序列化入参」。
|
||||
*/
|
||||
function contrastScan(args: { failMin: number; warnMin: number }) {
|
||||
const { failMin, warnMin } = args;
|
||||
|
||||
interface Rgba {
|
||||
r: number;
|
||||
g: number;
|
||||
b: number;
|
||||
a: number;
|
||||
}
|
||||
|
||||
const parse = (s: string | null): Rgba | null => {
|
||||
if (!s) return null;
|
||||
const m = s.match(/rgba?\(([^)]+)\)/);
|
||||
if (!m || m[1] === undefined) return null;
|
||||
const p = m[1]
|
||||
.split(/[\s,/]+/)
|
||||
.filter(Boolean)
|
||||
.map(parseFloat);
|
||||
if (p.length < 3 || p.some(Number.isNaN)) return null;
|
||||
return { r: p[0]!, g: p[1]!, b: p[2]!, a: p.length > 3 ? p[3]! : 1 };
|
||||
};
|
||||
const chan = (c: number): number => {
|
||||
const v = c / 255;
|
||||
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
|
||||
};
|
||||
const lum = (c: Rgba): number => 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b);
|
||||
const ratio = (fg: Rgba, bg: Rgba): number => {
|
||||
const l1 = lum(fg) + 0.05;
|
||||
const l2 = lum(bg) + 0.05;
|
||||
return l1 >= l2 ? l1 / l2 : l2 / l1;
|
||||
};
|
||||
const over = (top: Rgba, bottom: Rgba): Rgba => ({
|
||||
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: Element): boolean =>
|
||||
SVG_TEXT_TAGS.has(el.tagName.toLowerCase()) && !!(el as SVGElement).ownerSVGElement;
|
||||
|
||||
// 前景:HTML 取 color;SVG 文字取 paint 的 fill(color 只是继承值,不是画出来的色)
|
||||
// 返回的是**已解析但未合成**的色(可能带 alpha),调用方必须先 compositeFg。
|
||||
const fgOf = (el: Element, st: CSSStyleDeclaration): Rgba | null => {
|
||||
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);
|
||||
};
|
||||
// 前景按背景合成:见文件头口径 ①,不合成会把半透明前景算成「高对比」。
|
||||
const compositeFg = (fg: Rgba, bg: Rgba): Rgba => (fg.a >= 0.999 ? { ...fg, a: 1 } : over(fg, bg));
|
||||
|
||||
const bgOfAncestors = (el: Element): Rgba => {
|
||||
const layers: Rgba[] = [];
|
||||
let n: Element | null = 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: Rgba = { 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: Element): Rgba | null => {
|
||||
const parent = el.parentElement;
|
||||
if (!parent) return null;
|
||||
let hit: Rgba | null = null;
|
||||
for (const k of Array.from(parent.children)) {
|
||||
if (k === el) break;
|
||||
const t = k.tagName.toLowerCase();
|
||||
if (t === 'text' || t === 'tspan') continue;
|
||||
const f = parse(getComputedStyle(k).fill as string);
|
||||
if (f && f.a >= 0.9) hit = f;
|
||||
}
|
||||
return hit;
|
||||
};
|
||||
|
||||
const effectiveBg = (el: Element): Rgba => {
|
||||
const canvas = bgOfAncestors(el);
|
||||
if (isSvgText(el)) {
|
||||
const shape = shapeUnder(el);
|
||||
if (shape) return over(shape, canvas);
|
||||
}
|
||||
return canvas;
|
||||
};
|
||||
|
||||
const pathOf = (el: Element): string => {
|
||||
const parts: string[] = [];
|
||||
let n: Element | null = el;
|
||||
while (n && n.nodeType === 1 && parts.length < 4) {
|
||||
let s = n.id ? `#${n.id}` : n.tagName.toLowerCase();
|
||||
if (!n.id && typeof n.className === 'string' && n.className.trim() !== '') {
|
||||
const c = n.className.trim().split(/\s+/).filter(Boolean).slice(0, 2);
|
||||
if (c.length > 0) s += `.${c.join('.')}`;
|
||||
}
|
||||
parts.unshift(s);
|
||||
n = n.parentElement;
|
||||
}
|
||||
return parts.join(' > ');
|
||||
};
|
||||
|
||||
const hasDirectText = (el: Element): boolean =>
|
||||
Array.from(el.childNodes).some((n) => n.nodeType === 3 && (n.textContent ?? '').trim().length > 0);
|
||||
|
||||
const visible = (el: Element): boolean => {
|
||||
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;
|
||||
};
|
||||
|
||||
interface Offender {
|
||||
path: string;
|
||||
ratio: number;
|
||||
need: number;
|
||||
fg: string;
|
||||
bg: string;
|
||||
font: string;
|
||||
text: string;
|
||||
hidden: boolean;
|
||||
decorative: boolean;
|
||||
}
|
||||
|
||||
const out: Offender[] = [];
|
||||
const seen = new Set<string>();
|
||||
// 分母计数:实际评估过的「可见且直接含文字」元素数。
|
||||
// 为什么单独数:`out` 只收**低于判据**的项,全绿时它是 0 —— 用 `out.length > 0` 当金丝雀
|
||||
// 会让「扫描器什么都没看到」与「扫描器看到 423 个元素且全达标」显示成同一个 0(本仓反复踩)。
|
||||
let scanned = 0;
|
||||
for (const el of Array.from(document.querySelectorAll('body *'))) {
|
||||
if (!hasDirectText(el) || !visible(el)) continue;
|
||||
const st = getComputedStyle(el);
|
||||
const fg = fgOf(el, st);
|
||||
if (!fg) continue;
|
||||
scanned += 1;
|
||||
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(见文件头口径 ①)
|
||||
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 推断豁免等于给「整块藏起来」开后门。
|
||||
decorative: !!el.closest('[data-audit-decorative]'),
|
||||
});
|
||||
}
|
||||
|
||||
out.sort((a, b) => a.ratio - b.ratio);
|
||||
// 同色检测在全量 out 上做,不能被 worst 的截断吃掉
|
||||
const sameColor = out.filter((o) => o.fg === o.bg);
|
||||
// 装饰豁免两条缺一不可:主动标注 ∧ 在 aria-hidden 子树内;同色永不受豁免
|
||||
const isDeco = (o: Offender): boolean => 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),
|
||||
/** 实际评估过的「可见且直接含文字」元素数(分母金丝雀用)。 */
|
||||
scanned,
|
||||
total: real.length,
|
||||
belowFail: real.filter((o) => o.ratio < failMin).length,
|
||||
belowWarn: real.filter((o) => o.ratio < warnMin).length,
|
||||
minRatio: real.length > 0 ? 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,
|
||||
decorative: deco.length,
|
||||
decorativeItems: deco.map((o) => ({ path: o.path, ratio: o.ratio, text: o.text })),
|
||||
};
|
||||
}
|
||||
|
||||
/** 结构项(P1)+ 焦点指示(P2)。 */
|
||||
async function structuralChecks(page: Page): Promise<{ blocking: string[]; warnings: string[] }> {
|
||||
const blocking: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
const scrollW = await page.evaluate(() => document.documentElement.scrollWidth);
|
||||
const clientW = await page.evaluate(() => window.innerWidth);
|
||||
if (scrollW > clientW) blocking.push(`horizontal overflow: ${scrollW} > ${clientW}`);
|
||||
|
||||
const imgNoAlt = await page.evaluate(() =>
|
||||
[...document.querySelectorAll('img')]
|
||||
.filter((img) => img.getAttribute('alt') === null)
|
||||
.map((img) => img.getAttribute('src') ?? ''),
|
||||
);
|
||||
for (const src of imgNoAlt) blocking.push(`img missing alt: src=${src}`);
|
||||
|
||||
const noName = await 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() ??
|
||||
'';
|
||||
const fallback = (el as HTMLInputElement).getAttribute?.('placeholder') ?? '';
|
||||
return (name === '' || name === null) && fallback === '';
|
||||
})
|
||||
.map((el) => el.outerHTML.slice(0, 120));
|
||||
});
|
||||
for (const b of noName.slice(0, 5)) blocking.push(`interactive element without accessible name: ${b}`);
|
||||
|
||||
const h1Count = await page.locator('h1').count();
|
||||
if (h1Count !== 1) blocking.push(`heading hierarchy: ${h1Count} h1`);
|
||||
|
||||
for (const sel of ['.nav-links a', '#navToggle']) {
|
||||
const loc = page.locator(sel).first();
|
||||
try {
|
||||
if (!(await loc.isVisible())) continue;
|
||||
await loc.focus();
|
||||
const outline = await loc.evaluate((el) => getComputedStyle(el).outlineWidth);
|
||||
if (outline === '0px') warnings.push(`focus indicator missing on ${sel}`);
|
||||
} catch {
|
||||
// 元素不存在或不可聚焦:跳过(与迁移前一致)
|
||||
}
|
||||
}
|
||||
|
||||
return { blocking, warnings };
|
||||
}
|
||||
|
||||
test.describe('landing ④ 结构与对比度', () => {
|
||||
for (const vp of VIEWPORTS) {
|
||||
test(`结构与全量对比度 @ ${vp.name} (${vp.width}×${vp.height})`, async ({ page }) => {
|
||||
await page.setViewportSize({ width: vp.width, height: vp.height });
|
||||
await page.goto(LANDING_URL, { waitUntil: 'networkidle' });
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const structural = await structuralChecks(page);
|
||||
const revealed = await page.evaluate(revealAll);
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
expect(revealed.panels, `${vp.name}: .showcase-panel 一个都没展开(判据分母为空)`).toBeGreaterThan(0);
|
||||
|
||||
const scan = await page.evaluate(contrastScan, { failMin: FAIL_MIN, warnMin: WARN_MIN });
|
||||
|
||||
// 分母金丝雀:扫描器必须真的看到东西,否则「0 条违规」是空跑。
|
||||
// 用 `scanned`(实际评估过的元素数)而不是 `total`(低于判据的条数)——
|
||||
// 后者在全绿时恒为 0,拿它当金丝雀等于把「没扫到」和「扫到了且全达标」判成同一个数。
|
||||
expect(
|
||||
scan.scanned,
|
||||
`${vp.name}: 对比度扫描没有评估到任何元素(分母为空 ⇒ 通过无意义)`,
|
||||
).toBeGreaterThan(0);
|
||||
|
||||
const sameKeys = new Set(scan.sameColorKeys);
|
||||
// 阻断级 = 对比度 < FAIL_MIN ∪ 同色(同色无条件阻断,见文件头口径 ②)
|
||||
const blocking = scan.worst.filter(
|
||||
(o) => o.ratio < FAIL_MIN || sameKeys.has(`${o.path}|${o.text}`),
|
||||
);
|
||||
const blockingMessages = blocking.map((o) => {
|
||||
const same = sameKeys.has(`${o.path}|${o.text}`);
|
||||
return same
|
||||
? `P1 同色前景/背景 ${o.fg} on ${o.bg}(对比度 ${o.ratio})@${o.font} — ${o.path} «${o.text}»`
|
||||
: `P1 contrast ${o.ratio} < ${FAIL_MIN} (需 ${o.need}) ${o.fg} on ${o.bg} @${o.font} — ${o.path} «${o.text}»`;
|
||||
});
|
||||
|
||||
// P2 只打印不判红(迁移前口径:exit 0)
|
||||
const band = scan.worst.filter(
|
||||
(o) => o.ratio >= FAIL_MIN && o.ratio < WARN_MIN && !sameKeys.has(`${o.path}|${o.text}`),
|
||||
);
|
||||
if (band.length > 0) {
|
||||
console.log(
|
||||
`[${vp.name}] P2 警告(不判红,须人工定夺):\n` +
|
||||
band
|
||||
.slice(0, 20)
|
||||
.map((o) => ` contrast ${o.ratio} < ${WARN_MIN} — ${o.path} «${o.text}»`)
|
||||
.join('\n'),
|
||||
);
|
||||
}
|
||||
// 装饰豁免逐条打印为 NOTE(即使全绿也打印:豁免必须可审计,不能因为「没红」就从报告里消失)
|
||||
if (scan.decorativeItems.length > 0) {
|
||||
console.log(
|
||||
`[${vp.name}] NOTE 装饰豁免(作者以 data-audit-decorative 标注 ∧ aria-hidden 子树内,不计入):\n` +
|
||||
scan.decorativeItems.map((o) => ` contrast ${o.ratio} — ${o.path} «${o.text}»`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
expect(
|
||||
[...structural.blocking, ...blockingMessages],
|
||||
`${vp.name}: P1 阻断项(\n${[...structural.blocking, ...blockingMessages].join('\n')}\n)`,
|
||||
).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('axe 无障碍扫描:无 critical/serious 违规', async ({ page }) => {
|
||||
await page.goto(LANDING_URL, { waitUntil: 'networkidle' });
|
||||
await page.waitForTimeout(600);
|
||||
await page.evaluate(revealAll);
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
const results = await new AxeBuilder({ page })
|
||||
/*
|
||||
* 排除**已登记的装饰豁免**节点:`.process-step-number`(流程卡右上角的 01/02/03 水印数字)
|
||||
* 同时满足本仓装饰豁免的两条(作者 `data-audit-decorative` 主动标注 ∧ 在 `aria-hidden`
|
||||
* 子树内,见 `scripts/landing/README` 与上一组用例的 NOTE 输出),对比度约 1.08:1 是
|
||||
* 刻意淡化。axe 的 `color-contrast` 不认识这套豁免,会把它报成 serious。
|
||||
*
|
||||
* 为什么不干脆关掉整条 color-contrast 规则:本组用例的自写扫描虽更严(含 alpha 合成、
|
||||
* 覆盖 aria-hidden 子树),但它是**本仓自研口径**;axe 是标准无障碍树口径,两者互补。
|
||||
* 只排除登记过的节点,其余仍由 axe 判 —— 排除面越小,假绿空间越小。
|
||||
*/
|
||||
.exclude('[data-audit-decorative][aria-hidden="true"]')
|
||||
.analyze();
|
||||
const serious = results.violations.filter(
|
||||
(v) => v.impact === 'critical' || v.impact === 'serious',
|
||||
);
|
||||
expect(
|
||||
serious.map((v) => `${v.id} (${v.impact}, ${v.nodes.length} nodes): ${v.help}`),
|
||||
`axe critical/serious 违规`,
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Landing 门禁 ③:首屏演示剧本 + 无 JS 降级 + reduced-motion(移植自
|
||||
* `novavis-authority/scripts/landing-demo-verify.py`)
|
||||
*
|
||||
* ## 这道门禁守的是「内容在、但看不见」
|
||||
*
|
||||
* 2026-11-04 的 Blocking①(屏 2 白底白字)与 2026-11-07 的 BLOCKING-2(nojs 断言只读
|
||||
* `textContent` + computed `display`,注入 `opacity:0;visibility:hidden` 后仍 PASS)是同一
|
||||
* 失效模式。所以无 JS 断言必须是**四层真实可见性**,缺一不可:
|
||||
*
|
||||
* ① `checkVisibility({checkOpacity, checkVisibilityCSS})` —— 浏览器自己的口径
|
||||
* ② 祖先链上 opacity 有效值 > 0.05(旧内核 checkVisibility 对 opacity 的处理不一致)
|
||||
* ③ 元素矩形有面积(排除被 layout 折叠)
|
||||
* ④ 文字非空
|
||||
*
|
||||
* 另加两条**防恒真**的断言(本仓反复踩过「判据通过态是 0 或空集时,0 本身不是证据」):
|
||||
* - 反向:仅动画层的步骤徽标在无 JS 时必须**不可见**(`badge_visible === 0`);
|
||||
* - 金丝雀:徽标选择器必须真的命中元素(`badge_count > 0`),否则上一条恒真。
|
||||
*
|
||||
* ## 采样时刻未改
|
||||
*
|
||||
* `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 的
|
||||
* 采样点落在各自的步内。**时刻不改**,因为改动时刻会让「脚本采样点」与「动画真实时间轴」
|
||||
* 脱钩,那是判据自伤而不是适配(原脚本注释原文)。
|
||||
*/
|
||||
|
||||
const LANDING_URL = '/novavis';
|
||||
|
||||
/** 采样时刻(秒,相对页面 load 完成)。 */
|
||||
const STEPS = [
|
||||
{ name: 'step1-create', at: 1.4 },
|
||||
{ name: 'step2-open', at: 4.4 },
|
||||
{ name: 'step3-import', at: 7.6 },
|
||||
{ name: 'step4-ready', at: 11.6 },
|
||||
{ name: 'loop-restart', at: 16.4 },
|
||||
] as const;
|
||||
|
||||
/** 步号 → 该步应显示的徽标文案(与 index.html 的 `data-badge` 一一对应)。 */
|
||||
const BADGE_OF_STEP: Record<string, string> = {
|
||||
'demo-step-1': '新建任务',
|
||||
'demo-step-2': '打开任务',
|
||||
'demo-step-3': '导入数据',
|
||||
'demo-step-4': '就绪',
|
||||
};
|
||||
|
||||
async function heroClass(page: Page): Promise<string> {
|
||||
return page.evaluate(() => document.getElementById('heroDemo')?.className ?? '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前**真实可见**的徽标文案(三层可见性,与 nojs 判定同口径)。
|
||||
*/
|
||||
async function visibleBadges(page: Page): Promise<string[]> {
|
||||
return page.evaluate(() => {
|
||||
const els = [...document.querySelectorAll<HTMLElement>('.demo-chrome-badge-item')];
|
||||
return els
|
||||
.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;
|
||||
let n: Element | null = 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());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 徽标正向断言:每个采样点上当前步必须**恰好显示 1 个**徽标,且文案与该步同义。
|
||||
*
|
||||
* 为什么是「恰好 1 个」而不是「>= 1」:同时显示两个说明映射有重叠(正是 2026-11-07 首轮
|
||||
* 「徽标错位一整步」的伴生症状),那会让观众同时看到两个互斥的进度。
|
||||
*/
|
||||
function checkBadgeMatchesStep(
|
||||
classSamples: Record<string, string>,
|
||||
badgeSamples: Record<string, string[]>,
|
||||
): string[] {
|
||||
const problems: string[] = [];
|
||||
for (const [name, cls] of Object.entries(classSamples)) {
|
||||
const step = Object.keys(BADGE_OF_STEP).find((st) => cls.includes(st));
|
||||
if (step === undefined) continue; // loop-restart 采样点落在复位瞬间,不判
|
||||
const want = BADGE_OF_STEP[step];
|
||||
const got = badgeSamples[name] ?? [];
|
||||
if (got.length !== 1) {
|
||||
problems.push(`${name}: ${step} 应恰好显示 1 个徽标,实测 ${got.length} 个 ${JSON.stringify(got)}`);
|
||||
} else if (got[0] !== want) {
|
||||
problems.push(`${name}: ${step} 应显示「${want}」,实测「${got[0]}」`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
test.describe('landing ③ 首屏剧本与降级', () => {
|
||||
test('剧本四步推进 + 徽标一一对应 + 循环复位', async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
page.on('pageerror', (e) => pageErrors.push(String(e)));
|
||||
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
const start = Date.now();
|
||||
|
||||
const classSamples: Record<string, string> = {};
|
||||
const badgeSamples: Record<string, string[]> = {};
|
||||
|
||||
for (const step of STEPS) {
|
||||
const delta = step.at * 1000 - (Date.now() - start);
|
||||
if (delta > 0) await page.waitForTimeout(delta);
|
||||
classSamples[step.name] = await heroClass(page);
|
||||
badgeSamples[step.name] = await visibleBadges(page);
|
||||
}
|
||||
|
||||
expect(pageErrors, `landing 页有 JS 运行时错误:${pageErrors.join(' | ')}`).toEqual([]);
|
||||
|
||||
// 循环复位:采样到第 1 步说明时间轴在循环
|
||||
expect(
|
||||
classSamples['loop-restart'],
|
||||
`剧本未循环复位到 demo-step-1:实测 ${classSamples['loop-restart']}`,
|
||||
).toContain('demo-step-1');
|
||||
|
||||
const problems = checkBadgeMatchesStep(classSamples, badgeSamples);
|
||||
expect(problems, problems.join('\n')).toEqual([]);
|
||||
});
|
||||
|
||||
test('无 JS 降级:内容在且看得见(四层真实可见性)', async ({ browser }) => {
|
||||
// 独立 context 关掉 JS:用 browser 而不是 page fixture(后者已带 JS)
|
||||
const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1440, height: 900 } });
|
||||
const page = await context.newPage();
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const nojs = await page.evaluate(() => {
|
||||
const rows = [...document.querySelectorAll<HTMLElement>('.nv-home-row')];
|
||||
const visibleRows = rows.filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
// ② 祖先链有效 opacity
|
||||
let op = 1;
|
||||
let n: Element | null = 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 (
|
||||
el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) &&
|
||||
r.width > 0 &&
|
||||
r.height > 0 &&
|
||||
(el.textContent ?? '').trim().length > 0
|
||||
);
|
||||
}).length;
|
||||
|
||||
const badgeItems = [...document.querySelectorAll<HTMLElement>('.demo-chrome-badge-item')];
|
||||
const visibleBadge = badgeItems.filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) && r.width > 0 && r.height > 0;
|
||||
}).length;
|
||||
|
||||
const pager = document.querySelector<HTMLElement>('.nv-home-pager b');
|
||||
const cols = document.querySelector<HTMLElement>('.nv-home-cols');
|
||||
|
||||
return {
|
||||
taskTotal: pager?.textContent ?? null,
|
||||
currentRow: document.querySelectorAll('.nv-home-row.is-current').length,
|
||||
colsVisible: cols ? cols.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) : false,
|
||||
demoRowsSeen: rows.length,
|
||||
rowsVisible: visibleRows,
|
||||
badgeCount: badgeItems.length,
|
||||
badgeVisible: visibleBadge,
|
||||
// 状态栏的静态读数:无 JS 时也应直接可见
|
||||
bodyText: (document.body.textContent ?? '').length,
|
||||
};
|
||||
});
|
||||
|
||||
// 台账读数是**静态数据**(6 个任务),不是动画指标 —— 它旁边就列着 4 行真实任务,
|
||||
// 若写成 0 就与内容自相矛盾。故无 JS 时必须等于 6。
|
||||
expect(nojs.taskTotal, `无 JS 时任务总数应为 6,实测 ${nojs.taskTotal}`).toBe('6');
|
||||
expect(nojs.currentRow, '无 JS 时当前行(is-current 是静态类,不靠 JS 加)应恰有 1 行').toBe(1);
|
||||
expect(nojs.colsVisible, '无 JS 时列头不可见(视口锁定后列头只渲染一次,它是纯静态结构)').toBe(true);
|
||||
expect(nojs.demoRowsSeen, '无 JS 时一行任务都没渲染(判据分母为空)').toBeGreaterThan(0);
|
||||
expect(
|
||||
nojs.rowsVisible,
|
||||
`无 JS 时任务行不可见:${nojs.rowsVisible}/${nojs.demoRowsSeen}(内容在、但被 opacity/visibility 藏起来)`,
|
||||
).toBe(nojs.demoRowsSeen);
|
||||
|
||||
// 反向断言 + 金丝雀:仅动画层的徽标无 JS 时不得可见;选择器必须非空否则上一条恒真
|
||||
expect(nojs.badgeCount, '徽标选择器零命中(反向断言会恒真)').toBeGreaterThan(0);
|
||||
expect(nojs.badgeVisible, `仅动画层的徽标在无 JS 时不得可见,实测 ${nojs.badgeVisible} 个`).toBe(0);
|
||||
|
||||
await context.close();
|
||||
});
|
||||
|
||||
test('prefers-reduced-motion:直达终态、不排时间轴', async ({ page }) => {
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(1200);
|
||||
|
||||
const hero = await heroClass(page);
|
||||
expect(hero, `reduced-motion 下应挂 demo-final,实测 className="${hero}"`).toContain('demo-final');
|
||||
|
||||
const readings = await page.evaluate(() => ({
|
||||
taskTotal: document.querySelector<HTMLElement>('.nv-home-pager b')?.textContent ?? null,
|
||||
currentRow: document.querySelectorAll('.nv-home-row.is-current').length,
|
||||
}));
|
||||
expect(readings.taskTotal, 'reduced-motion 下任务总数应为 6').toBe('6');
|
||||
expect(readings.currentRow, 'reduced-motion 下当前行应恰有 1 行').toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Landing 门禁 ①:布局几何与焦点管理(移植自 `novavis-authority/scripts/verify-landing-layout.py`)
|
||||
*
|
||||
* ## 判据来源与迁移口径
|
||||
*
|
||||
* 迁移前的脚本是 python + playwright,只在 authority 仓手动跑、从不在任何门禁链里
|
||||
* (本仓反复记录过那个失效模式:**门禁不在链里就等于没有**)。2026-12-03 landing 迁入本仓,
|
||||
* 四道门禁一并移植为 Playwright spec,由 `npm run test:landing` 承载并进 `test:all`。
|
||||
*
|
||||
* **判据一个不放宽**,逐条对应原脚本:
|
||||
*
|
||||
* | 原检查项 | 本文件 |
|
||||
* |---|---|
|
||||
* | 1 tabs:各视口下 `.showcase-tabs` 每个 tab 中心不被 `#showcasePause` 覆盖,且无横向溢出 | `showcase tab 行与暂停按钮几何` |
|
||||
* | 2a focus:焦点进入卡片后轮播让位 | `焦点进入卡片后轮播让位` |
|
||||
* | 2b focus:持焦 tab 不被摘掉 tabindex | 同上 |
|
||||
* | 2c focus:失焦后轮播恢复(证明 2a 不是「轮播整体坏了」的假通过) | 同上 |
|
||||
* | 3 roving:方向键后整组只留一只可 Tab 到达,且该只即 active、焦点跟随 | `键盘 roving tabindex 单点不变量` |
|
||||
* | 4 cta:nav 转化入口与信息链接有可视分层 | `nav 转化入口与信息链接分层` |
|
||||
*
|
||||
* ## 两个必须知道的操作前提(原脚本注释里踩过)
|
||||
*
|
||||
* 1. **悬停会冻结轮播**(既有设计)。focus 项全程把鼠标移到 (0,0),否则测的是 hover 冻结
|
||||
* 而不是 focusin 暂停。
|
||||
* 2. **视口是被测对象**:每条用例自己 `setViewportSize`,不依赖 project 的 viewport。
|
||||
*/
|
||||
|
||||
const LANDING_URL = '/novavis';
|
||||
|
||||
/** 与迁移前一致的五个视口(桌面 / 笔记本 / 平板竖屏 / 手机 480 / 手机 375)。 */
|
||||
const VIEWPORTS = [
|
||||
{ name: '桌面 1440', width: 1440, height: 900 },
|
||||
{ name: '笔记本 1024', width: 1024, height: 768 },
|
||||
{ name: '平板竖屏 768', width: 768, height: 1024 },
|
||||
{ name: '手机 480', width: 480, height: 900 },
|
||||
{ name: '手机 375', width: 375, height: 812 },
|
||||
] as const;
|
||||
|
||||
/** 轮播周期 5500ms + 余量:等待窗口内若未暂停,active tab 必定已切换。 */
|
||||
const CYCLE_MS = 5500;
|
||||
const WAIT_MS = CYCLE_MS + 2000;
|
||||
|
||||
/**
|
||||
* tab 行的几何读数(与迁移前 `TAB_INFO` 逐字同义)。
|
||||
*
|
||||
* 注意这里必须是**真函数**而不是字符串:Playwright 的 JS 版 `page.evaluate(string)` 把入参
|
||||
* 当「表达式」求值,`"() => {...}"` 求值结果是一个函数对象、序列化成 undefined
|
||||
* (python 版把字符串当函数体,所以原脚本能用字符串;两个绑定语义不同)。
|
||||
*/
|
||||
function readTabInfo() {
|
||||
const pause = document.querySelector<HTMLElement>('#showcasePause');
|
||||
const pr = pause && getComputedStyle(pause).display !== 'none' ? pause.getBoundingClientRect() : null;
|
||||
const covers = (r: DOMRect): boolean => {
|
||||
if (!pr) return false;
|
||||
const cx = r.left + r.width / 2;
|
||||
const cy = r.top + r.height / 2;
|
||||
return pr.left <= cx && cx <= pr.right && pr.top <= cy && cy <= pr.bottom;
|
||||
};
|
||||
return [...document.querySelectorAll<HTMLElement>('.showcase-tab')].map((t) => {
|
||||
const r = t.getBoundingClientRect();
|
||||
const cx = r.left + r.width / 2;
|
||||
const cy = r.top + r.height / 2;
|
||||
return {
|
||||
id: t.id,
|
||||
covered: covers(r),
|
||||
centerInViewport: cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
interface TabInfo {
|
||||
id: string;
|
||||
covered: boolean;
|
||||
centerInViewport: boolean;
|
||||
}
|
||||
|
||||
async function gotoLanding(page: Page): Promise<void> {
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
// CSS 与 main.js 都是同源静态资源,等 1.2s 让 scroll-spy / 轮播完成首轮初始化
|
||||
// (迁移前脚本同样 sleep 1.2s,理由相同:过早采样会读到轮播尚未挂上的中间态)。
|
||||
await page.waitForTimeout(1200);
|
||||
}
|
||||
|
||||
async function activeTabId(page: Page): Promise<string | null> {
|
||||
return page.evaluate(() => document.querySelector<HTMLElement>('.showcase-tab.active')?.id ?? null);
|
||||
}
|
||||
|
||||
async function focusedTabState(page: Page): Promise<{ id: string; tabindex: string | null } | null> {
|
||||
return page.evaluate(() => {
|
||||
const el = document.activeElement;
|
||||
if (!el || !el.classList || !el.classList.contains('showcase-tab')) return null;
|
||||
return { id: (el as HTMLElement).id, tabindex: el.getAttribute('tabindex') };
|
||||
});
|
||||
}
|
||||
|
||||
test.describe('landing ① 布局几何与焦点', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await gotoLanding(page);
|
||||
});
|
||||
|
||||
test('showcase tab 行与暂停按钮几何(五视口)', async ({ page }) => {
|
||||
const failures: string[] = [];
|
||||
|
||||
for (const vp of VIEWPORTS) {
|
||||
await page.setViewportSize({ width: vp.width, height: vp.height });
|
||||
await page.evaluate(() => window.scrollTo(0, 0));
|
||||
await page.mouse.move(0, 0);
|
||||
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
const tabs = (await page.evaluate(readTabInfo)) as TabInfo[];
|
||||
expect(tabs.length, `${vp.name}: .showcase-tab 一个都没选中(判据的分母为空)`).toBeGreaterThan(0);
|
||||
|
||||
const covered = tabs.filter((t) => t.covered).map((t) => t.id);
|
||||
const offscreen = tabs.filter((t) => !t.centerInViewport).map((t) => t.id);
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
);
|
||||
|
||||
if (covered.length > 0) failures.push(`${vp.name}: tab 被 #showcasePause 覆盖 ${covered.join(',')}`);
|
||||
if (offscreen.length > 0) failures.push(`${vp.name}: tab 中心不在视口内 ${offscreen.join(',')}`);
|
||||
if (overflow > 1) failures.push(`${vp.name}: 页面横向溢出 ${overflow}px`);
|
||||
}
|
||||
|
||||
expect(failures, failures.join('\n')).toEqual([]);
|
||||
});
|
||||
|
||||
test('焦点进入卡片后轮播让位、持焦不被摘 tabindex、失焦后恢复', async ({ page }) => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(600);
|
||||
await page.mouse.move(0, 0);
|
||||
|
||||
const before = await activeTabId(page);
|
||||
expect(before, 'showcase 轮播没有 active tab(用例前提不成立)').not.toBeNull();
|
||||
|
||||
await page.evaluate(() => {
|
||||
const t = document.querySelector<HTMLElement>('.showcase-tab.active');
|
||||
t?.focus();
|
||||
});
|
||||
|
||||
const state = await focusedTabState(page);
|
||||
expect(state, '未能把焦点放进 tablist(用例前提不成立)').not.toBeNull();
|
||||
|
||||
// 2a:持焦期间轮播必须让位
|
||||
await page.waitForTimeout(WAIT_MS);
|
||||
const after = await activeTabId(page);
|
||||
expect(after, `焦点在卡片内时轮播未让位:active ${before} → ${after}`).toBe(before);
|
||||
|
||||
// 2b:持焦 tab 不得被摘成 tabindex="-1"(摘掉即被移出 tab 序列,键盘焦点无处可回)
|
||||
const held = await focusedTabState(page);
|
||||
if (held) {
|
||||
expect(held.tabindex, `持焦 tab ${held.id} 的 tabindex 被摘成 -1`).not.toBe('-1');
|
||||
}
|
||||
|
||||
// 2c:失焦后必须恢复轮播 —— 否则上一条「不变」可能只是轮播整体失效的假通过
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
await page.evaluate(() => window.scrollTo(0, 0));
|
||||
await page.mouse.move(0, 0);
|
||||
await page.locator('#nav').scrollIntoViewIfNeeded();
|
||||
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
|
||||
|
||||
await expect
|
||||
.poll(async () => await activeTabId(page), {
|
||||
timeout: WAIT_MS + 1000,
|
||||
message: `失焦后轮播未恢复:active 恒为 ${before}(前一条「持焦不变」可能是轮播整体失效的假通过)`,
|
||||
})
|
||||
.not.toBe(before);
|
||||
});
|
||||
|
||||
test('键盘 roving tabindex 单点不变量', async ({ page }) => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.locator('.showcase-tabs').scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(400);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const t = document.querySelector<HTMLElement>('.showcase-tab.active');
|
||||
t?.focus();
|
||||
});
|
||||
expect(await focusedTabState(page), '未能把焦点放进 tablist(roving 不变量前提不成立)').not.toBeNull();
|
||||
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
const state = await page.evaluate(() => {
|
||||
const tabs = [...document.querySelectorAll<HTMLElement>('.showcase-tab')];
|
||||
const isTab = (el: Element | null): el is HTMLElement =>
|
||||
!!el && 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,
|
||||
};
|
||||
});
|
||||
|
||||
// 单点不变量:整组只能有一只 tab 可被 Tab 键到达
|
||||
expect(
|
||||
state.zero.length,
|
||||
`方向键切换后整组有 ${state.zero.length} 只 tab 可被 Tab 键到达(${state.zero.join(',')}),违反 roving tabindex 单点(旧 tab 仍留在序列里)`,
|
||||
).toBe(1);
|
||||
|
||||
expect(state.active.length, '方向键切换后无 active tab').toBeGreaterThan(0);
|
||||
expect(state.zero[0], `可被 Tab 键到达的 tab(${state.zero[0]})不是 active tab(${state.active[0]})`).toBe(
|
||||
state.active[0],
|
||||
);
|
||||
expect(state.focused, `方向键切换后焦点未跟随 active tab(持焦 ${state.focused})`).toBe(state.active[0]);
|
||||
});
|
||||
|
||||
test('nav 转化入口与信息链接分层', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await page.evaluate(() => window.scrollTo(0, 0));
|
||||
|
||||
const styles = await page.evaluate(() => {
|
||||
const links = [...document.querySelectorAll<HTMLElement>('.nav-links a')];
|
||||
const info = links.find((a) => a.getAttribute('href') === '#features');
|
||||
const cta = links.find((a) => a.getAttribute('href') === '#contact');
|
||||
const pick = (el: HTMLElement | undefined) => {
|
||||
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) };
|
||||
});
|
||||
|
||||
expect(styles.info, 'nav 信息链接(#features)不存在').not.toBeNull();
|
||||
expect(styles.cta, 'nav 转化入口(#contact)不存在').not.toBeNull();
|
||||
expect(
|
||||
styles.cta,
|
||||
'nav 转化入口与信息链接样式完全相同(无分层)',
|
||||
).not.toEqual(styles.info);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Landing 门禁 ②:渐进生长动效(移植自 `novavis-authority/scripts/verify-landing-motion.py`)
|
||||
*
|
||||
* ## 判据(与迁移前逐条对应,一条不放宽)
|
||||
*
|
||||
* 1. `html.js-grow` 已挂载 —— CSS 初始隐藏态生效的前提(没挂上时所有元素本来就是可见的,
|
||||
* 后面的「生长」判据会退化成恒真)。
|
||||
* 2. Hero 首屏演示推进:`demo-step-1..4` 按序出现且单向(不回头)。
|
||||
* hero 在 2026-11-07 改画 `/home` 任务工作台后不再有 `data-grow` 元素,
|
||||
* 「动画在跑」这件事改由步骤类推进来证明(原脚本的等价迁移)。
|
||||
* 3. Showcase 四个 panel 切 tab 后各自重播到**峰值 = 目标总数**(不锁死具体数字)。
|
||||
* 4. 离开视口后 `is-grown` 复位为 0(否则「重播」可能是残留态)。
|
||||
* 5. `prefers-reduced-motion` 下直达终态(`is-grown == 总数`)。
|
||||
* 6. 装饰性图形对 AT 隐藏(`aria-hidden="true"`),且其子树内**无可聚焦元素**
|
||||
* (axe `aria-hidden-focus` 的静态等价物);暂停控件存在且带 `aria-pressed`。
|
||||
* 7. 无 JS 运行时错误。
|
||||
*
|
||||
* ## 为什么用「密集采样取峰值」而不是末次快照
|
||||
*
|
||||
* 剧本播完会循环复位,固定短窗口采样会读到复位后的 0 而假失败。原脚本的 `watch_growth`
|
||||
* 就是为此写的,这里保持同口径:峰值须等于总数。
|
||||
*/
|
||||
|
||||
const LANDING_URL = '/novavis';
|
||||
|
||||
const PANELS = [
|
||||
{ tab: '#showcase-tab-graph', panel: '#showcase-panel-graph', name: '账户综合关联' },
|
||||
{ tab: '#showcase-tab-flow', panel: '#showcase-panel-flow', name: '进出统计分析' },
|
||||
{ tab: '#showcase-tab-ai', panel: '#showcase-panel-ai', name: '智能问答' },
|
||||
{ tab: '#showcase-tab-process', panel: '#showcase-panel-process', name: '生成分析报告' },
|
||||
] as const;
|
||||
|
||||
/** 待点亮目标总数(与 `main.js` 的 targetsOf 同规则:`<g>` 按子元素数计,其余算 1)。 */
|
||||
async function totalTargets(page: Page, selector: string): Promise<number> {
|
||||
return page.evaluate((sel) => {
|
||||
const root = document.querySelector(sel);
|
||||
if (!root) return 0;
|
||||
let n = 0;
|
||||
root.querySelectorAll('[data-grow]').forEach((el) => {
|
||||
n += el.tagName.toLowerCase() === 'g' ? el.children.length : 1;
|
||||
});
|
||||
return n;
|
||||
}, selector);
|
||||
}
|
||||
|
||||
async function grown(page: Page, selector: string): Promise<number> {
|
||||
return page.locator(`${selector} .is-grown`).count();
|
||||
}
|
||||
|
||||
/** 密集采样到峰值(剧本会循环复位,故以「是否曾到达终态」判定)。 */
|
||||
async function watchGrowth(
|
||||
page: Page,
|
||||
selector: string,
|
||||
total: number,
|
||||
windowMs = 12000,
|
||||
intervalMs = 400,
|
||||
): Promise<{ peak: number; samples: number[] }> {
|
||||
const samples: number[] = [];
|
||||
let peak = 0;
|
||||
const deadline = Date.now() + windowMs;
|
||||
while (Date.now() < deadline) {
|
||||
const cur = await grown(page, selector);
|
||||
peak = Math.max(peak, cur);
|
||||
samples.push(cur);
|
||||
if (peak === total) break;
|
||||
await page.waitForTimeout(intervalMs);
|
||||
}
|
||||
return { peak, samples };
|
||||
}
|
||||
|
||||
/** 采样 `demo-step-*` 的推进序列(去重、保序)。 */
|
||||
async function watchDemoSteps(page: Page, selector: string, windowMs = 14000): Promise<string[]> {
|
||||
const seen: string[] = [];
|
||||
const deadline = Date.now() + windowMs;
|
||||
while (Date.now() < deadline) {
|
||||
const cls = await page.evaluate(
|
||||
(sel) => document.querySelector<HTMLElement>(sel)?.className ?? '',
|
||||
selector,
|
||||
);
|
||||
const cur = ['demo-step-1', 'demo-step-2', 'demo-step-3', 'demo-step-4'].find((s) => cls.includes(s));
|
||||
if (cur && !seen.includes(cur)) seen.push(cur);
|
||||
await page.waitForTimeout(250);
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
test.describe('landing ② 动效与生长', () => {
|
||||
test('js-grow 挂载 + hero 剧本单向推进 + 四屏重播 + 离开复位', async ({ page }) => {
|
||||
const pageErrors: string[] = [];
|
||||
page.on('pageerror', (e) => pageErrors.push(String(e)));
|
||||
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// 1. js-grow 挂载
|
||||
const jsGrow = await page.evaluate(() => document.documentElement.classList.contains('js-grow'));
|
||||
expect(jsGrow, 'html.js-grow 未挂载(CSS 初始隐藏态不生效 ⇒ 后续「生长」判据会退化成恒真)').toBe(true);
|
||||
|
||||
// 2. hero 剧本推进
|
||||
const heroTotal = await totalTargets(page, '.hero-visual');
|
||||
const stepsSeen = await watchDemoSteps(page, '#heroDemo');
|
||||
expect(
|
||||
stepsSeen.length,
|
||||
`Hero 剧本未推进:只观察到 ${JSON.stringify(stepsSeen)}`,
|
||||
).toBeGreaterThanOrEqual(3);
|
||||
expect(stepsSeen[0], `Hero 剧本未从第 1 步开始:${JSON.stringify(stepsSeen)}`).toBe('demo-step-1');
|
||||
expect(
|
||||
stepsSeen.some((s) => s === 'demo-step-3' || s === 'demo-step-4'),
|
||||
`Hero 剧本未走完前半程:${JSON.stringify(stepsSeen)}`,
|
||||
).toBe(true);
|
||||
// hero 上出现 data-grow 目标说明 DOM 又画回了图窗形态,此时期望值需重钉(原脚本同样打印该提示)
|
||||
expect(heroTotal, `hero 上出现 ${heroTotal} 个 data-grow 目标,与「/home 剧本无生长目标」的口径不符`).toBe(0);
|
||||
|
||||
// 3. 四屏重播
|
||||
await page.locator('#showcase').scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(500);
|
||||
for (const { tab, panel, name } of PANELS) {
|
||||
await page.click(tab);
|
||||
await page.waitForTimeout(200);
|
||||
const total = await totalTargets(page, panel);
|
||||
expect(total, `${name}: data-grow 目标总数为 0(判据分母为空)`).toBeGreaterThan(0);
|
||||
const before = await grown(page, panel);
|
||||
const { peak } = await watchGrowth(page, panel, total);
|
||||
expect(
|
||||
peak === total || before < peak,
|
||||
`${name} 切换后未重播:峰值 ${peak}(切换后 ${before},总数 ${total})`,
|
||||
).toBe(true);
|
||||
expect(peak, `${name} 未跑完:峰值 ${peak}/${total}`).toBe(total);
|
||||
}
|
||||
|
||||
// 4. 离开视口复位
|
||||
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
|
||||
await page.waitForTimeout(1000);
|
||||
const afterLeave = await grown(page, '#showcase-panel-process');
|
||||
expect(afterLeave, `离开视口未复位: ${afterLeave}(期望 0)`).toBe(0);
|
||||
|
||||
// 7. 无 JS 运行时错误
|
||||
expect(pageErrors, `landing 页有 JS 运行时错误:${pageErrors.join(' | ')}`).toEqual([]);
|
||||
});
|
||||
|
||||
test('reduced-motion 直达终态 + 装饰图形对 AT 隐藏', async ({ page }) => {
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await page.goto(LANDING_URL, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(1200);
|
||||
await page.locator('#showcase').scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(400);
|
||||
|
||||
const rTotal = await totalTargets(page, '#showcase-panel-graph');
|
||||
const rGrown = await grown(page, '#showcase-panel-graph');
|
||||
expect(rTotal, 'reduced-motion 下 showcase 目标总数为 0(判据分母为空)').toBeGreaterThan(0);
|
||||
expect(rGrown, `reduced-motion 未直达终态: ${rGrown}/${rTotal}`).toBe(rTotal);
|
||||
|
||||
// 6. 装饰性图形无障碍属性
|
||||
const a11y = await page.evaluate(() => {
|
||||
const FOCUSABLE = 'a[href], button, input, select, textarea, [tabindex]';
|
||||
const heroDemo = document.querySelector('#heroDemo')?.getAttribute('aria-hidden') ?? null;
|
||||
const showcaseVisuals = [...document.querySelectorAll('.showcase-visual')].map((e) =>
|
||||
e.getAttribute('aria-hidden'),
|
||||
);
|
||||
const heroVisual = document.querySelector('.hero-visual')?.getAttribute('aria-hidden') ?? null;
|
||||
const focusableInHidden = [...document.querySelectorAll('[aria-hidden="true"]')]
|
||||
.flatMap((root) => [...root.querySelectorAll(FOCUSABLE)])
|
||||
.filter((e) => !e.hasAttribute('disabled') && (e as HTMLElement).tabIndex >= 0)
|
||||
.map((e) => `${e.tagName.toLowerCase()}#${e.id}`);
|
||||
const btn = document.querySelector('#demoPause');
|
||||
const demoPause = btn
|
||||
? {
|
||||
exists: true,
|
||||
label: btn.getAttribute('aria-label'),
|
||||
pressed: btn.getAttribute('aria-pressed'),
|
||||
}
|
||||
: { exists: false, label: null, pressed: null };
|
||||
return { heroDemo, showcaseVisuals, heroVisual, focusableInHidden, demoPause };
|
||||
});
|
||||
|
||||
expect(a11y.heroDemo, `演示层未对 AT 隐藏: ${a11y.heroDemo}`).toBe('true');
|
||||
expect(a11y.showcaseVisuals.length, '.showcase-visual 一个都没选中(判据分母为空)').toBeGreaterThan(0);
|
||||
expect(
|
||||
new Set(a11y.showcaseVisuals),
|
||||
`.showcase-visual aria-hidden 应全为 true,实测 ${JSON.stringify(a11y.showcaseVisuals)}`,
|
||||
).toEqual(new Set(['true']));
|
||||
// .hero-visual 承载暂停按钮,隐藏会连带隐藏控件 ⇒ 必须为 null
|
||||
expect(a11y.heroVisual, '.hero-visual 不应 aria-hidden(它承载暂停控件)').toBeNull();
|
||||
expect(a11y.focusableInHidden, `aria-hidden 子树内有可聚焦元素: ${a11y.focusableInHidden.join(',')}`).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(a11y.demoPause.exists, '暂停控件 #demoPause 不存在(WCAG 2.2.2 要求自动播放内容可暂停)').toBe(true);
|
||||
expect(a11y.demoPause.label, '暂停控件缺 aria-label').toBeTruthy();
|
||||
expect(a11y.demoPause.pressed, '暂停控件缺 aria-pressed 状态').not.toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user