audit.test.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import { spawnSync } from "node:child_process";
  2. import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath, pathToFileURL } from "node:url";
  6. import { describe, expect, it } from "vitest";
  7. // 页面审查脚本在小夹具上的检出与误报;没有 Playwright/Chromium 时跳过浏览器用例并打印原因,设了 CI 时直接失败。
  8. const repoRoot = fileURLToPath(new URL("../", import.meta.url));
  9. const scripts = join(repoRoot, "skills", "design", "scripts");
  10. const fixture = (name: string) => join(repoRoot, "test", "fixtures", "audit", name);
  11. const skeletons = join(repoRoot, "skills", "design", "design-resources", "design-skeletons");
  12. const text = (...args: string[]) => spawnSync(process.execPath, [join(scripts, "audit.mjs"), ...args], { cwd: repoRoot, encoding: "utf8", timeout: 200_000 }).stdout;
  13. function audit(...args: string[]) {
  14. const run = spawnSync(process.execPath.includes("bun") ? "node" : process.execPath, [join(scripts, "audit.mjs"), ...args, "--json"], { cwd: repoRoot, encoding: "utf8", timeout: 120_000 });
  15. return { status: run.status, stdout: run.stdout, stderr: run.stderr, report: run.status === 0 ? JSON.parse(run.stdout) : null };
  16. }
  17. const available = audit(fixture("base.html"), "1440").status === 0;
  18. if (!available) {
  19. if (process.env.CI) throw new Error("audit.mjs 找不到 Playwright 或 Chromium,CI 上不允许跳过浏览器用例");
  20. console.warn("audit.test.ts: 没有 Playwright 或 Chromium,跳过浏览器用例");
  21. }
  22. const keys = (r: { report: Array<{ mustFix: Record<string, string[]> }> }) => new Set(r.report.flatMap((w) => Object.keys(w.mustFix)));
  23. describe("audit.mjs", () => {
  24. it("classify:按签名计数,先继承基线原有内容上的命中;骨架基线的样式键按签名存在继承;对比度变差算新增;外链和报错永不继承", async () => {
  25. const { classify, summarize } = await import(pathToFileURL(join(scripts, "audit.mjs")).href);
  26. const base = summarize({
  27. smallText: [["smallText|span|11", '11px span "c" @0,0']],
  28. lowContrast: [["lowContrast|p", '3.00:1 16px p "x" @0,0', 3]],
  29. edge: [["edge|p|L", 'L4 R0 p "x" @0,0']],
  30. externalResource: [["externalResource|fonts.googleapis.com", "e"]],
  31. consoleError: [["consoleError|x", "f"]],
  32. });
  33. const hits = {
  34. smallText: [["smallText|span|11", '11px span "a" @0,0'], ["smallText|span|11", '11px span "b" @0,9'], ["smallText|span|11", '11px span "c" @5,5'], ["smallText|p.note|10", "d"]],
  35. lowContrast: [["lowContrast|p", '2.95:1 16px p "y" @0,0', 2.95], ["lowContrast|p", '2.50:1 16px p "z" @0,0', 2.5]],
  36. edge: [["edge|p|L", "g"], ["edge|p|L", "h"]],
  37. externalResource: [["externalResource|fonts.googleapis.com", "e"]],
  38. consoleError: [["consoleError|x", "f"]],
  39. };
  40. const counted = classify(hits, base);
  41. expect(counted.own).toEqual({ smallText: ['11px span "a" @0,0', '11px span "b" @0,9', "d"], lowContrast: ['2.50:1 16px p "z" @0,0'], edge: ["h"], externalResource: ["e"], consoleError: ["f"] });
  42. expect(counted.inherited).toEqual({ smallText: 1, lowContrast: 1, edge: 1 });
  43. const skeleton = classify(hits, base, true);
  44. expect(skeleton.own).toEqual({ smallText: ["d"], lowContrast: ['2.50:1 16px p "z" @0,0'], edge: ["h"], externalResource: ["e"], consoleError: ["f"] });
  45. expect(counted.items.edge).toEqual(["g"]);
  46. const project = classify(hits, base, false, true);
  47. expect(project.own.externalResource).toBeUndefined();
  48. expect(project.items).toMatchObject({ externalResource: ["e"], consoleError: ["f"] });
  49. expect(classify(hits, base, true, true).own.externalResource).toEqual(["e"]);
  50. });
  51. it.skipIf(!available)("坏例:每类可测缺陷都检出,echoLabel 只进 advisory", () => {
  52. const { report } = audit(fixture("bad.html"), "1440");
  53. const found = keys(report);
  54. for (const k of ["smallText", "lowContrast", "truncated", "tightLeading", "textCollision", "edge", "externalResource"]) expect(found.has(k), k).toBe(true);
  55. expect(report.report[0].advisory.echoLabel?.length).toBe(1);
  56. }, 120_000);
  57. it.skipIf(!available)("干净例:等价定价档、深色定位层上的标题、横向滚动表、SVG 缩放文字、表情和换行标签组都不报 must-fix", () => {
  58. const { report } = audit(fixture("clean.html"), "1440,390");
  59. expect(report.total, JSON.stringify(report.report.map((w: { mustFix: unknown }) => w.mustFix))).toBe(0);
  60. expect(report.report[0].advisory.echoLabel).toBeUndefined();
  61. expect(report.report[0].advisory.repeatedText).toBeUndefined();
  62. expect(report.report[0].echoes).toEqual([]);
  63. // 等价的定价档不再报 identicalPeers:原来的提示自己又说"档位本来就该一样",等于把自己撤回。
  64. expect(report.report[0].advisory.identicalPeers).toBeUndefined();
  65. }, 120_000);
  66. it.skipIf(!available)("回声清单:装饰性副本按页比对,aria-hidden 和 data-audit-skip 都关不掉它,抑制标记进报告", () => {
  67. const { report } = audit(fixture("echo-deco.html"));
  68. const w = report.report[0];
  69. expect(w.slides).toBe(3);
  70. expect(w.mustFix, JSON.stringify(w.mustFix)).toEqual({});
  71. // 第 1 页 aria-hidden 的 196px 副本,第 2 页带 data-audit-skip 的最大号字:两种装饰依据各报一条。
  72. expect(w.echoes.map((e: string[]) => e[0])).toEqual(["decorativeEcho", "decorativeEcho"]);
  73. expect(w.echoes[0][1]).toContain("div.shout");
  74. expect(w.echoes[0][1]).toContain("repeats h1");
  75. expect(w.echoes[1][1]).toContain("div.motif");
  76. expect(w.echoes[1][1]).toContain("repeats h2");
  77. // 第 3 页的 div.motif 只和第 1 页的标题同文:跨页不是同一视图,页脚也不当参照。
  78. expect(w.echoes.map((e: string[]) => e[1]).join()).not.toContain("Permissions");
  79. expect(w.suppressed.ariaHidden.count).toBe(1);
  80. expect(w.suppressed.auditSkip.count).toBe(1);
  81. expect(w.suppressed.auditSkip.at.join()).toContain("div.motif");
  82. }, 120_000);
  83. it.skipIf(!available)("回声清单:标题不是紧邻兄弟、同节的另一个标题、控件文案、图表标签各报一次,同文两处进 repeatedText,清单按具体程度排序", () => {
  84. const w = audit(fixture("echo-wide.html"), "1440").report.report[0];
  85. expect(w.mustFix, JSON.stringify(w.mustFix)).toEqual({});
  86. const msgs = w.echoes.map((e: string[]) => e[1]);
  87. expect(msgs, JSON.stringify(w.echoes)).toHaveLength(5);
  88. expect(w.echoes.map((e: string[]) => e[0])).toEqual(["echoLabel", "echoLabel", "echoLabel", "echoLabel", "repeatedText"]);
  89. expect(msgs[0]).toContain("Latency budget");
  90. expect(msgs[0]).toContain("repeats h2");
  91. expect(msgs.find((m: string) => m.includes("Quarterly revenue"))).toContain("repeats h2");
  92. expect(msgs.find((m: string) => m.includes("Export CSV"))).toContain("repeats button");
  93. expect(msgs.find((m: string) => m.includes("Tail latency"))).toContain("repeats text");
  94. expect(msgs[4]).toContain("uptime");
  95. }, 120_000);
  96. it.skipIf(!available)("回声清单不误报:目录项、标签页名、页眉页脚、sr-only、图例与数据标签、每张卡上的同一按钮、不同句子里的同一个词、以及无障碍名已给出的数值", () => {
  97. const w = audit(fixture("echo-ok.html"), "1440").report.report[0];
  98. expect(w.mustFix, JSON.stringify(w.mustFix)).toEqual({});
  99. expect(w.echoes, JSON.stringify(w.echoes)).toEqual([]);
  100. // 骨架和项目都会用 aria-hidden,报告要把认下的抑制标记数出来。
  101. expect(w.suppressed.ariaHidden.count).toBe(4);
  102. }, 120_000);
  103. it.skipIf(!available)("幻灯片:逐页审查,非当前页的缺陷也检出", () => {
  104. const { report } = audit(fixture("deck.html"));
  105. expect(report.report.map((w: { width: number }) => w.width)).toEqual([1920]);
  106. expect(report.report[0].slides).toBe(3);
  107. expect(report.report[0].mustFix.smallText?.length).toBe(1);
  108. expect(audit(fixture("deck-label.html")).report.report[0].slides).toBe(2);
  109. }, 120_000);
  110. it.skipIf(!available)("幻灯片行为:→ 不翻页、没有打印样式、讲者备注画在页上都是 must-fix,基线不继承;合格的幻灯片不报", () => {
  111. const bad = audit(fixture("deck.html")).report.report[0].mustFix;
  112. for (const k of ["deckPaging", "deckPrint", "notesOnScreen"]) expect(bad[k]?.length, k).toBe(1);
  113. expect(audit(fixture("deck.html"), "--baseline", fixture("deck-label.html")).report.report[0].mustFix.deckPaging?.length).toBe(1);
  114. const ok = audit(fixture("deck-ok.html")).report;
  115. expect(ok.total, JSON.stringify(ok.report[0].mustFix)).toBe(0);
  116. expect(ok.report[0].slides).toBe(2);
  117. }, 120_000);
  118. it.skipIf(!available)("独立文件:../ 路径、加载失败的图、禁止缩放是 must-fix;跳级标题和手机宽度上的小触控目标进 advisory,正文内联链接不算", () => {
  119. const [desk, mob] = audit(fixture("assets.html"), "1440,390").report.report;
  120. expect(desk.mustFix.localPath, JSON.stringify(desk.mustFix)).toEqual(["img ../outside.png"]);
  121. expect(desk.mustFix.brokenImage?.length).toBe(2);
  122. expect(desk.mustFix.noZoom?.length).toBe(1);
  123. expect(desk.advisory.headingSkip?.length).toBe(1);
  124. expect(desk.advisory.smallTarget).toBeUndefined();
  125. expect(mob.advisory.smallTarget, JSON.stringify(mob.advisory)).toHaveLength(1);
  126. expect(mob.advisory.smallTarget[0]).toContain("button.x");
  127. }, 120_000);
  128. it.skipIf(!available)("越滚越长的页面:预滚动跟着页面变长,最多 50 屏;无限加载照常结束并报扫描不完整,有限加载扫到尾部", () => {
  129. const r = audit(fixture("growing.html"), "1440");
  130. expect(r.status).toBe(0);
  131. expect(r.report.report[0].scrollCapped).toBe(true);
  132. // 只长两屏的懒加载:尾部滚到才出现的 9px 小字必须被检出,且不算扫描不完整。
  133. const once = audit(fixture("growing-once.html"), "1440");
  134. expect(once.report.report[0].scrollCapped).toBe(false);
  135. expect(Object.keys(once.report.report[0].mustFix)).toContain("smallText");
  136. // 滚到底后 200ms 才异步追加的一屏:预滚动要等一下再复查高度,跟上去检出尾部小字。
  137. const late = audit(fixture("growing-late.html"), "1440");
  138. expect(late.report.report[0].scrollCapped).toBe(false);
  139. expect(Object.keys(late.report.report[0].mustFix)).toContain("smallText");
  140. // 900ms 后才到的一屏错过了复查:没扫到就必须报扫描不完整,不能装作扫完。
  141. expect(audit(fixture("growing-too-late.html"), "1440").report.report[0].scrollCapped).toBe(true);
  142. // 晚到且不足半屏的一条:scrollTo 被夹在旧底部,这条从没进过视口,也要报扫描不完整。
  143. expect(audit(fixture("growing-tiny-late.html"), "1440").report.report[0].scrollCapped).toBe(true);
  144. expect(audit(fixture("clean.html"), "1440").report.report[0].scrollCapped).toBe(false);
  145. // 文档流里的页头滚动后收起、回到顶部又变高:页面没长出新内容,不能报扫描不完整。
  146. expect(audit(fixture("collapsing-header.html"), "1440").report.report[0].scrollCapped).toBe(false);
  147. }, 300_000);
  148. it.skipIf(!available)("文本输出以 next: 收尾:must-fix 数、看截图、用真实指针加 probe.js 操作;幻灯片多一条翻页与打印", () => {
  149. const run = spawnSync(process.execPath, [join(scripts, "audit.mjs"), fixture("deck.html")], { cwd: repoRoot, encoding: "utf8", timeout: 120_000 });
  150. const next = run.stdout.slice(run.stdout.indexOf("\nnext:"));
  151. expect(next, run.stdout).toContain("fix the 4 must-fix");
  152. expect(next).toContain(join(scripts, "probe.js"));
  153. expect(next).toContain("page.mouse.click");
  154. expect(next).toContain("print preview");
  155. const page = spawnSync(process.execPath, [join(scripts, "audit.mjs"), fixture("clean.html"), "1440"], { cwd: repoRoot, encoding: "utf8", timeout: 120_000 }).stdout;
  156. expect(page).toContain("must-fix is 0");
  157. expect(page).not.toContain("print preview");
  158. // --json 也要带上 next:不然 probe.js 和整个交互检查在这条路径上就没了。
  159. expect(audit(fixture("clean.html"), "1440").report.next).toContain(join(scripts, "probe.js"));
  160. }, 120_000);
  161. it.skipIf(!available)("--baseline:骨架带来的命中只计继承,同签名超出基线条数的和新加的才是 must-fix", () => {
  162. const { report } = audit(fixture("derived.html"), "1440", "--baseline", fixture("base.html"));
  163. const w = report.report[0];
  164. expect(w.mustFix.smallText).toHaveLength(2);
  165. expect(w.mustFix.smallText.join()).toContain("p.note");
  166. expect(w.mustFix.lowContrast).toHaveLength(1);
  167. expect(w.inherited).toEqual({ smallText: 1, lowContrast: 1 });
  168. }, 120_000);
  169. it.skipIf(!available)("--baseline:不变差的改色继承对比度命中,变差的算新增;多出的同类小字和外链字体仍是 must-fix", () => {
  170. const better = audit(fixture("palette-better.html"), "1440", "--baseline", fixture("palette-base.html")).report.report[0];
  171. expect(Object.keys(better.mustFix).sort()).toEqual(["externalResource", "smallText"]);
  172. expect(better.mustFix.smallText).toHaveLength(3);
  173. expect(better.inherited).toEqual({ smallText: 1, lowContrast: 3 });
  174. const worse = audit(fixture("palette-recolor.html"), "1440", "--baseline", fixture("palette-base.html")).report.report[0];
  175. expect(worse.mustFix.lowContrast).toHaveLength(3);
  176. expect(worse.inherited).toEqual({ smallText: 1 });
  177. }, 120_000);
  178. it.skipIf(!available)("骨架基线:骨架自身类名多出的卡片按签名继承样式键,只有新加的小字是 must-fix", () => {
  179. const w = audit(fixture("skeleton-derived.html"), "1440", "--baseline", fixture("skeleton/example.html")).report.report[0];
  180. expect(Object.keys(w.mustFix)).toEqual(["smallText"]);
  181. expect(w.mustFix.smallText).toHaveLength(1);
  182. expect(w.mustFix.smallText[0]).toContain("p.fine");
  183. }, 120_000);
  184. it.skipIf(!available)("不误报:sr-only 文字、带内边距的整宽行和段落;full-bleed 里的文字仍守边距,媒体不算", () => {
  185. expect(audit(fixture("a11y-rows.html"), "1440,390").report.total).toBe(0);
  186. const bleed = audit(fixture("full-bleed.html"), "1440,390").report;
  187. for (const w of bleed.report) expect(Object.keys(w.mustFix)).toEqual(["edge"]);
  188. for (const w of bleed.report) expect(w.mustFix.edge).toHaveLength(1);
  189. expect(bleed.report[0].mustFix.edge[0]).toContain("h1");
  190. }, 120_000);
  191. it.skipIf(!available)("轮播不算幻灯片:按页面在 1440 和 390 审;居中收缩的海报按海报本身当画布", () => {
  192. const car = audit(fixture("carousel.html")).report;
  193. expect(car.report.map((w: { width: number; kind: string }) => [w.width, w.kind])).toEqual([[1440, "page"], [390, "page"]]);
  194. expect(car.report[1].mustFix.smallText).toHaveLength(1);
  195. const poster = audit(fixture("poster-flex.html")).report.report;
  196. expect(poster).toHaveLength(1);
  197. expect(poster[0].kind).toBe("canvas");
  198. expect(Object.keys(poster[0].mustFix)).toEqual(["canvasBounds"]);
  199. expect(poster[0].mustFix.canvasBounds[0]).toContain("p.over");
  200. }, 120_000);
  201. it("--baseline 指向被审页面本身:警告并丢掉基线,缺陷不会被算成继承而把 must-fix 清零", () => {
  202. const self = audit(fixture("bad.html"), "1440", "--baseline", fixture("bad.html"));
  203. expect(self.stderr).toContain("is the audited page itself");
  204. if (!available) return;
  205. const plain = audit(fixture("bad.html"), "1440");
  206. expect(self.report.total).toBe(plain.report.total);
  207. expect(self.report.total).toBeGreaterThan(0);
  208. expect(self.report.report[0].inherited).toEqual({});
  209. expect(self.report.baselineIgnored).toContain("ignored");
  210. }, 200_000);
  211. it.skipIf(!available)("内容相同的另一份基线仍然继承:无限动画的光标和定时刷新的数据连跑三次都是 0", () => {
  212. const dir = mkdtempSync(join(tmpdir(), "zcode-design-baseline-"));
  213. try {
  214. const copy = join(dir, "live-copy.html");
  215. copyFileSync(fixture("live.html"), copy);
  216. for (let i = 0; i < 3; i++) expect(audit(fixture("live.html"), "--baseline", copy).report.total).toBe(0);
  217. } finally {
  218. rmSync(dir, { force: true, recursive: true });
  219. }
  220. }, 200_000);
  221. it.skipIf(!available)("文字密度:信息堆成段落的页面进 advisory;文章和结构化页面不报", () => {
  222. const dense = audit(fixture("dense.html"), "1440").report.report[0].advisory;
  223. expect(dense.textWall?.length).toBeGreaterThanOrEqual(4);
  224. expect(dense.denseFirstView).toHaveLength(1);
  225. for (const f of ["article.html", "structured.html"]) {
  226. for (const w of audit(fixture(f), "1440,390").report.report) {
  227. expect(w.advisory.textWall, f).toBeUndefined();
  228. expect(w.advisory.denseFirstView, f).toBeUndefined();
  229. }
  230. }
  231. }, 120_000);
  232. it.skipIf(!available)("不误报:禁用控件、sup、SVG 标签叠放、紧行高的展示标题和 18px 以上的中文标题", () => {
  233. expect(audit(fixture("disabled.html"), "1440,390").report.total).toBe(0);
  234. expect(audit(fixture("tight-heading.html"), "1440,390").report.total).toBe(0);
  235. const svg = audit(fixture("svg-labels.html"), "1440").report.report[0];
  236. expect(Object.keys(svg.mustFix)).toEqual(["textCollision"]);
  237. }, 120_000);
  238. it.skipIf(!available)("补检:占位符对比度为 must-fix,透明度 0 的文字、左边缘不齐、长页无分区导航进 advisory", () => {
  239. const w = audit(fixture("misses.html"), "1440").report.report[0];
  240. expect(w.mustFix.lowContrast?.[0]).toContain("placeholder");
  241. for (const k of ["invisibleText", "leftEdge", "noSectionNav"]) expect(w.advisory[k]?.length, k).toBe(1);
  242. }, 120_000);
  243. it.skipIf(!available)("固定画布:只按画布自身尺寸审一次,查越界而不查视口边距", () => {
  244. const { report } = audit(fixture("canvas.html"));
  245. expect(report.report).toHaveLength(1);
  246. expect(report.report[0].kind).toBe("canvas");
  247. expect(Object.keys(report.report[0].mustFix)).toEqual(["canvasBounds"]);
  248. expect(report.report[0].mustFix.canvasBounds).toHaveLength(1);
  249. }, 120_000);
  250. it.skipIf(!available)("截断:title 含全文不报;卡片里旁边有打开链接的进 advisory;链接里或无从得知全文的仍是 must-fix", () => {
  251. for (const w of audit(fixture("truncate-reachable.html"), "1440,390").report.report) {
  252. expect(w.mustFix.truncated).toHaveLength(2);
  253. expect(w.mustFix.truncated.join()).toContain("unreachable");
  254. expect(w.advisory.truncated).toHaveLength(1);
  255. }
  256. }, 120_000);
  257. it.skipIf(!available)("截断:按钮、导航、菜单项自己的标签被截是 must-fix;aria-label 含全文不报;title 不含全文不算", () => {
  258. for (const w of audit(fixture("truncate-control.html"), "1440,390").report.report) {
  259. expect(w.mustFix.truncated.map((m: string) => m.split(" ")[0])).toEqual(["button.cut", "span.cut", "div.cut"]);
  260. expect(w.mustFix.truncated.join()).not.toContain("Annual");
  261. }
  262. }, 120_000);
  263. it.skipIf(!available)("没跑的 opacity-0 揭示即使绝对定位且 pointer-events:none 也报;role=tooltip 不报;真实溢出推出右边的文字算 edge", () => {
  264. const [desk, mob] = audit(fixture("reveal-overflow.html"), "1440,390").report.report;
  265. for (const w of [desk, mob]) expect(w.advisory.invisibleText?.join(), JSON.stringify(w.advisory)).toContain("hero claim");
  266. for (const w of [desk, mob]) expect(w.advisory.invisibleText).toHaveLength(1);
  267. expect(mob.mustFix.edge).toHaveLength(3);
  268. }, 120_000);
  269. it.skipIf(!available)("noSectionNav:一排重复的 logo 不算看板,长落地页照报", () => {
  270. for (const w of audit(fixture("landing-logos.html"), "1440,390").report.report) expect(w.advisory.noSectionNav).toHaveLength(1);
  271. }, 120_000);
  272. it.skipIf(!available)("边距:按被 overflow 裁掉之后实际画出的文字量,390 下省略号单元格不报", () => {
  273. expect(audit(fixture("edge-clipped.html"), "1440,390").report.total).toBe(0);
  274. }, 120_000);
  275. it.skipIf(!available)("已折叠:max-height:0 手风琴、移出屏幕的抽屉、pointer-events:none 的提示不计入文字墙和不可见文字", () => {
  276. for (const w of audit(fixture("folded.html"), "1440,390").report.report) {
  277. expect(w.mustFix, JSON.stringify(w.mustFix)).toEqual({});
  278. for (const k of ["textWall", "denseFirstView", "invisibleText"]) expect(w.advisory[k], k).toBeUndefined();
  279. }
  280. }, 120_000);
  281. it.skipIf(!available)("真实项目对改版基线:项目自己的外链和报错继承并列出;独立 HTML 交付不继承", () => {
  282. const args = [fixture("project-new.html"), "1440", "--baseline", fixture("project-base.html")];
  283. const proj = audit(...args, "--project").report.report[0];
  284. expect(proj.mustFix).toEqual({});
  285. expect(proj.inherited).toEqual({ externalResource: 1, consoleError: 1 });
  286. expect(proj.inheritedItems.consoleError[0]).toContain("legacy prop");
  287. expect(Object.keys(audit(...args).report.report[0].mustFix).sort()).toEqual(["consoleError", "externalResource"]);
  288. }, 120_000);
  289. it.skipIf(!available)("probe.js:视口外的结果不算可见;原地小计数变化算;环境动画、定时器、慢刷新数据和上一个控件留下的焦点悬停都不算;label 里复选框的伪元素开关算控件变化,只有 :focus 样式的死按钮不算;watch 之前调用 changes 不抛错", () => {
  290. const code = `
  291. import fs from "node:fs";
  292. const { loadPlaywright, launch } = await import(${JSON.stringify(pathToFileURL(join(scripts, "audit.mjs")).href)});
  293. const browser = await launch(loadPlaywright());
  294. const page = await browser.newPage({ viewport: { width: 1000, height: 700 } });
  295. const out = {};
  296. // No mouse parking: focus and hover stay on the last control, as in real multi-action use.
  297. for (const [file, ids] of [["probe.html", ["hidden", "shown"]], ["probe-counter.html", ["add"]], ["probe-ambient.html", ["noop"]], ["probe-multi.html", ["t2", "dead", "t1", "dead"]], ["probe-switch.html", ["sw"]], ["probe-toggle.html", ["tg", "dead"]], ["probe-motion.html", ["soft", "snap"]], ["probe-instant.html", ["tab2", "sw", "more"]], ["probe-filter.html", ["filter", "drop", "fold"]]]) {
  298. await page.goto(${JSON.stringify(pathToFileURL(fixture("x")).href.slice(0, -1))} + file);
  299. await page.evaluate(fs.readFileSync(${JSON.stringify(join(scripts, "probe.js"))}, "utf8"));
  300. out.early ||= await page.evaluate(() => designProbe.changes());
  301. for (const [n, id] of ids.entries()) {
  302. await page.evaluate(() => designProbe.watch());
  303. const box = await page.locator("#" + id).boundingBox();
  304. await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
  305. await page.waitForTimeout(150);
  306. out[file + ":" + n + ":" + id] = await page.evaluate(() => designProbe.changes());
  307. }
  308. }
  309. console.log(JSON.stringify(out));
  310. await browser.close();`;
  311. const run = spawnSync("node", ["--input-type=module", "-e", code], { cwd: repoRoot, encoding: "utf8", timeout: 110_000 });
  312. const out = JSON.parse(run.stdout || "{}");
  313. expect(out.early?.error, run.stderr).toContain("watch");
  314. const v = (k: string) => out[k]?.visible;
  315. expect(v("probe.html:0:hidden"), JSON.stringify(out)).toBe(false);
  316. expect(v("probe.html:1:shown")).toBe(true);
  317. expect(v("probe-counter.html:0:add")).toBe(true);
  318. expect(v("probe-ambient.html:0:noop")).toBe(false);
  319. expect(out["probe-switch.html:0:sw"]?.controlChangedOnly, JSON.stringify(out)).toBe(true);
  320. expect(out["probe-toggle.html:0:tg"]?.controlChangedOnly, JSON.stringify(out)).toBe(true);
  321. expect(out["probe-toggle.html:1:dead"]?.controlChangedOnly, JSON.stringify(out)).toBe(false);
  322. expect([0, 1, 2, 3].map((n) => v(`probe-multi.html:${n}:${["t2", "dead", "t1", "dead"][n]}`)), JSON.stringify(out)).toEqual([true, false, true, false]);
  323. expect(out["probe.html:0:hidden"]?.hints?.join()).toContain("no result in view");
  324. expect(out["probe-motion.html:0:soft"]?.animated, JSON.stringify(out)).toBe(true);
  325. expect(out["probe-motion.html:1:snap"]?.animated, JSON.stringify(out)).toBe(false);
  326. expect(out["probe-motion.html:1:snap"]?.hints?.join()).toContain("no transition");
  327. // Hover box-shadow on the control is not its toggle animation; tab content swaps get no transition hint; an instant menu does.
  328. expect(out["probe-instant.html:0:tab2"]?.hints?.join() || "", JSON.stringify(out)).not.toContain("no transition");
  329. expect(out["probe-instant.html:1:sw"]?.animated, JSON.stringify(out)).toBe(false);
  330. expect(out["probe-instant.html:1:sw"]?.hints?.join()).toContain("no transition");
  331. expect(out["probe-instant.html:2:more"]?.hints?.join(), JSON.stringify(out)).toContain("no transition");
  332. // Filtering or shrinking a list is a content swap; collapsing a region is not.
  333. expect(out["probe-filter.html:0:filter"]?.hints?.join() || "", JSON.stringify(out)).not.toContain("no transition");
  334. expect(out["probe-filter.html:1:drop"]?.hints?.join() || "", JSON.stringify(out)).not.toContain("no transition");
  335. expect(out["probe-filter.html:2:fold"]?.hints?.join(), JSON.stringify(out)).toContain("no transition");
  336. }, 120_000);
  337. it.skipIf(!available)("probe.js:点在透明遮罩上、没有真实指针输入时,hints 说出原因和做法", () => {
  338. const code = `
  339. import fs from "node:fs";
  340. const { loadPlaywright, launch } = await import(${JSON.stringify(pathToFileURL(join(scripts, "audit.mjs")).href)});
  341. const browser = await launch(loadPlaywright());
  342. const page = await browser.newPage({ viewport: { width: 1000, height: 700 } });
  343. const probe = fs.readFileSync(${JSON.stringify(join(scripts, "probe.js"))}, "utf8"), out = {};
  344. await page.goto(${JSON.stringify(pathToFileURL(fixture("probe-ghost.html")).href)});
  345. await page.evaluate(probe);
  346. await page.evaluate(() => designProbe.watch());
  347. const box = await page.locator("#open").boundingBox();
  348. await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
  349. out.ghost = await page.evaluate(() => designProbe.changes());
  350. await page.goto(${JSON.stringify(pathToFileURL(fixture("probe.html")).href)});
  351. await page.evaluate(probe);
  352. await page.evaluate(() => designProbe.watch());
  353. await page.evaluate(() => document.querySelector("#shown").click());
  354. out.synthetic = await page.evaluate(() => designProbe.changes());
  355. await page.evaluate(() => designProbe.watch());
  356. const b2 = await page.locator("#shown").boundingBox();
  357. await page.mouse.click(b2.x + b2.width / 2, b2.y + b2.height / 2);
  358. out.real = await page.evaluate(() => designProbe.changes());
  359. console.log(JSON.stringify(out));
  360. await browser.close();`;
  361. const run = spawnSync("node", ["--input-type=module", "-e", code], { cwd: repoRoot, encoding: "utf8", timeout: 110_000 });
  362. const out = JSON.parse(run.stdout || "{}");
  363. expect(out.ghost?.hints?.join(), run.stderr).toContain("invisible layer (div#scrim");
  364. expect(out.ghost.hints.join()).toContain("pointer-events:none");
  365. expect(out.synthetic?.hints?.join()).toContain("no pointer input reached the page");
  366. expect(out.real?.visible).toBe(true);
  367. expect(out.real?.hints?.join() || "").not.toMatch(/pointer input|invisible layer/);
  368. }, 120_000);
  369. it.skipIf(!available)("动效:减弱动效下仍在循环是 must-fix;transition all、布局属性、无减弱规则、两条跑马灯、首尾帧不一致、无暂停的大循环、脚本驱动的移动进 advisory;缓动、起始缩放这类画法不再判定;克制的动效不报", () => {
  370. const [desk, mob] = audit(fixture("motion-bad.html")).report.report;
  371. expect(Object.keys(desk.mustFix).sort(), JSON.stringify(desk.mustFix)).toEqual(["reducedMotion"]);
  372. expect(desk.mustFix.reducedMotion).toHaveLength(3);
  373. expect(Object.keys(mob.mustFix).sort()).toEqual([]);
  374. expect(desk.advisory.slowTransition).toHaveLength(1);
  375. for (const k of ["transitionAll", "layoutAnimation", "noReducedMotion", "marquee", "loopSeam", "noPauseControl"]) expect(desk.advisory[k], k).toHaveLength(1);
  376. // 画法交给设计者:ease-in、回弹缓动、scale(0) 起始在规则层已无依据,审查不再报。
  377. for (const k of ["easeIn", "bouncyEase", "scaleFromZero"]) expect(desk.advisory[k], k).toBeUndefined();
  378. expect(desk.advisory.reducedMotionScript?.join()).toContain("div.orb");
  379. for (const w of audit(fixture("motion-clean.html")).report.report) {
  380. expect(w.mustFix, JSON.stringify(w.mustFix)).toEqual({});
  381. expect(w.advisory, JSON.stringify(w.advisory)).toEqual({});
  382. }
  383. }, 120_000);
  384. it.skipIf(!available)("slowTransition:产品界面(推断或 --surface operate)是 must-fix;落地页、未知表面和 --surface persuade 是 advisory", () => {
  385. const at = (f: string, ...a: string[]) => audit(fixture(f), "1440", ...a).report.report[0];
  386. expect(at("slow-app.html").mustFix.slowTransition).toHaveLength(1);
  387. expect(at("slow-app.html", "--surface", "persuade").mustFix.slowTransition).toBeUndefined();
  388. expect(at("slow-landing.html").mustFix.slowTransition).toBeUndefined();
  389. expect(at("slow-landing.html").advisory.slowTransition).toHaveLength(1);
  390. expect(at("slow-landing.html", "--surface", "operate").mustFix.slowTransition).toHaveLength(1);
  391. // Docs with a side rail and a toolbar are not product UI; link color fades stay advisory even on operate.
  392. expect(at("slow-docs.html").mustFix.slowTransition).toBeUndefined();
  393. expect(at("slow-docs.html").advisory.slowTransition).toHaveLength(1);
  394. expect(at("slow-docs.html", "--surface", "operate").mustFix.slowTransition).toBeUndefined();
  395. const warn = spawnSync("node", [join(scripts, "audit.mjs"), fixture("slow-docs.html"), "1440", "--surface", "docs", "--json"], { cwd: repoRoot, encoding: "utf8", timeout: 110_000 });
  396. expect(warn.stderr).toContain('unknown --surface "docs"');
  397. // An unknown surface still infers: the app stays must-fix; the must-fix move is not hidden behind an earlier color fade.
  398. expect(at("slow-app.html", "--surface", "docs").mustFix.slowTransition).toHaveLength(1);
  399. expect(at("slow-mixed.html").mustFix.slowTransition?.join()).toContain("transform");
  400. }, 120_000);
  401. it.skipIf(!available)("reducedMotion:进度指示(role=status/progressbar/aria-busy 下、只转圈、3 秒内的背景位移微光)继续跑不报;装饰循环照报", () => {
  402. const [desk] = audit(fixture("reduced-progress.html"), "1440").report.report;
  403. expect(desk.mustFix.reducedMotion, JSON.stringify(desk.mustFix)).toEqual([expect.stringContaining("div.blob")]);
  404. }, 120_000);
  405. it.skipIf(!available)("整卡链接里被截的标题和摘要算内容,进 advisory 而非 must-fix", () => {
  406. for (const w of audit(fixture("truncate-card.html"), "1440,390").report.report) {
  407. expect(w.mustFix.truncated).toBeUndefined();
  408. expect(w.advisory.truncated).toHaveLength(16);
  409. }
  410. }, 120_000);
  411. it.skipIf(!available)("noSectionNav:三栏评价墙不算看板照报;带列标题的看板列不报", () => {
  412. for (const w of audit(fixture("testimonial-wall.html"), "1440,390").report.report) expect(w.advisory.noSectionNav).toHaveLength(1);
  413. for (const w of audit(fixture("board.html"), "1440,390").report.report) expect(w.advisory.noSectionNav).toBeUndefined();
  414. }, 120_000);
  415. it("classify:签名带 core 的(正文、控件标签、手机宽度横向溢出)永不继承,骨架基线也不行;装饰性小字照旧继承", async () => {
  416. const { classify, summarize } = await import(pathToFileURL(join(scripts, "audit.mjs")).href);
  417. const hits = {
  418. smallText: [["smallText|p.body|13|core", '13px p.body "long copy" @0,0'], ["smallText|span.tag|11", '11px span.tag "tag" @0,0']],
  419. lowContrast: [["lowContrast|button.cta|core", '3.00:1 14px button.cta "Buy" @0,0', 3]],
  420. horizontalOverflow: [["horizontalOverflow|page|core", "scrollWidth 500 > 390"]],
  421. };
  422. const base = summarize(hits);
  423. for (const skeleton of [false, true]) {
  424. const c = classify(hits, base, skeleton);
  425. expect(c.own.smallText, `skeleton=${skeleton}`).toEqual(['13px p.body "long copy" @0,0']);
  426. expect(c.own.lowContrast).toHaveLength(1);
  427. expect(c.own.horizontalOverflow).toHaveLength(1);
  428. expect(c.inherited).toEqual({ smallText: 1 });
  429. }
  430. });
  431. it.skipIf(!available)("must-fix 总数按缺陷算:两档视口看到的同一条只算一次,只在一档出现的标出来", () => {
  432. const one = audit(fixture("bad.html"), "1440").report;
  433. const two = audit(fixture("bad.html"), "1440,390").report;
  434. expect(one.total).toBeGreaterThan(0);
  435. expect(two.total, JSON.stringify(two.perWidth)).toBe(one.total);
  436. expect(two.perWidth).toEqual([[1440, one.total], [390, one.total]]);
  437. const out = text(fixture("bad.html"));
  438. expect(out).toContain(`must-fix total: ${one.total} distinct`);
  439. expect(out).toContain(`fix the ${one.total} must-fix finding(s)`);
  440. // 只有手机宽度溢出的那三条要标清楚,别让人以为两档都有。
  441. expect(text(fixture("reveal-overflow.html"))).toContain("[this width only]");
  442. }, 200_000);
  443. it.skipIf(!available)("边距:全宽媒体不标记也不算缺陷,video 和 h5/h6 进检查范围,命中说出是哪一边", () => {
  444. const { report, total } = audit(fixture("edge-media.html"), "1440,390").report;
  445. expect(total).toBe(2);
  446. for (const w of report) {
  447. expect(Object.keys(w.mustFix), JSON.stringify(w.mustFix)).toEqual(["edge"]);
  448. expect(w.mustFix.edge).toHaveLength(2);
  449. expect(w.mustFix.edge[0]).toContain("4px from the left video.inset");
  450. expect(w.mustFix.edge[1]).toContain("h6");
  451. }
  452. // 旧格式 "L4 R1325" 看着像两处违例。
  453. expect(report[0].mustFix.edge.join()).not.toMatch(/\bR\d/);
  454. }, 120_000);
  455. it.skipIf(!available)("advisory:默认列第一处并说还剩几处,--all 全部列出", () => {
  456. const plain = text(fixture("truncate-card.html"), "1440");
  457. expect(plain).toContain("... 15 more (--all)");
  458. const all = text(fixture("truncate-card.html"), "1440", "--all");
  459. expect(all).not.toContain("more (--all)");
  460. expect(all.split("\n").filter((l) => l.includes("truncate") || l.includes("full rebr")).length).toBeGreaterThan(5);
  461. }, 200_000);
  462. it("没跑起来的时候不让看不存在的截图", async () => {
  463. const { nextSteps } = await import(pathToFileURL(join(scripts, "audit.mjs")).href);
  464. const t = nextSteps({ notRun: true });
  465. expect(t).not.toContain("look at the screenshots");
  466. expect(t).toContain("capture the page yourself");
  467. expect(t).toContain("took no screenshots");
  468. expect(nextSteps({ total: 2 })).toContain("look at the screenshots");
  469. });
  470. it("--baseline 是占位符或不存在的路径:警告后照常审,不再 exit 1", () => {
  471. const ph = audit(fixture("bad.html"), "1440", "--baseline", "<skeleton example.html or the original's snapshot>");
  472. expect(ph.stderr).toContain("placeholder");
  473. expect(ph.stderr).toContain("--baseline ignored");
  474. if (!available) return;
  475. expect(ph.status).toBe(0);
  476. expect(ph.report.total).toBe(audit(fixture("bad.html"), "1440").report.total);
  477. // 被审页面本身不存在还是用法错误。
  478. const miss = audit(join(tmpdir(), "no-such-page.html"), "1440");
  479. expect(miss.status).toBe(1);
  480. }, 200_000);
  481. it.skipIf(!available)("继承不是已解决:抄骨架的页面先看到 --baseline 提示,再看到命中;继承条数要写进交付", () => {
  482. const dir = mkdtempSync(join(tmpdir(), "zcode-design-skeleton-"));
  483. try {
  484. const ex = join(skeletons, "docs-page", "example.html");
  485. const copy = join(dir, "page.html");
  486. copyFileSync(ex, copy);
  487. const out = text(copy, "1440");
  488. expect(out.indexOf("looks derived from"), out.slice(0, 400)).toBe(0);
  489. expect(out.indexOf("looks derived from")).toBeLessThan(out.indexOf("== 1440px"));
  490. expect(out).toContain(`re-run with --baseline ${ex}`);
  491. const based = text(copy, "1440", "--baseline", ex);
  492. expect(based).toContain("reported and not resolved");
  493. expect(based).toMatch(/inherited hit\(s\) are reported, not resolved/);
  494. } finally {
  495. rmSync(dir, { force: true, recursive: true });
  496. }
  497. }, 200_000);
  498. it.skipIf(!available)("reducedMotion:同名循环的两个元素各带坐标,不再是两条一模一样的话", () => {
  499. const d = audit(fixture("motion-bad.html")).report.report[0];
  500. expect(d.mustFix.reducedMotion).toHaveLength(3);
  501. expect(new Set(d.mustFix.reducedMotion).size).toBe(3);
  502. for (const m of d.mustFix.reducedMotion) expect(m).toMatch(/@-?\d+,-?\d+$/);
  503. expect(d.advisory.reducedMotionScript[0]).toMatch(/@-?\d+,-?\d+$/);
  504. }, 120_000);
  505. it("截图目录有上限:一天前的清掉,一天内保留最近 N 个,别人的目录不动", async () => {
  506. const { sweepShots } = await import(pathToFileURL(join(scripts, "audit.mjs")).href);
  507. const dir = mkdtempSync(join(tmpdir(), "zcode-design-shots-"));
  508. try {
  509. const old = join(dir, "design-audit-old");
  510. mkdirSync(old);
  511. const then = (Date.now() - 3 * 864e5) / 1000;
  512. utimesSync(old, then, then);
  513. const fresh = ["design-audit-a", "design-audit-b", "design-audit-c"].map((n) => join(dir, n));
  514. fresh.forEach((d, i) => { mkdirSync(d); const t = (Date.now() - (3 - i) * 60_000) / 1000; utimesSync(d, t, t); });
  515. mkdirSync(join(dir, "someone-else"));
  516. expect(sweepShots(dir, 864e5, 2)).toBe(2);
  517. expect(existsSync(old)).toBe(false);
  518. expect(readdirSync(dir).sort()).toEqual(["design-audit-b", "design-audit-c", "someone-else"]);
  519. expect(sweepShots(join(dir, "gone"))).toBe(0);
  520. } finally {
  521. rmSync(dir, { force: true, recursive: true });
  522. }
  523. });
  524. });