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 ``,且按真实背景合成), * 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('.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'); }); document.querySelectorAll('.showcase-panel').forEach((p) => { p.hidden = false; p.classList.add('active'); p.style.display = 'grid'; }); 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` 逐条同义)。 * * 参数是普通对象: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(); // 分母计数:实际评估过的「可见且直接含文字」元素数。 // 为什么单独数:`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([]); }); });