design-lint.test.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { spawnSync } from "node:child_process";
  2. import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { describe, expect, it } from "vitest";
  7. import { lintDesign } from "../skills/design/scripts/design-lint.mjs";
  8. import { parseColor, colorKey, parseDesignSystem } from "../skills/design/scripts/design-tokens.mjs";
  9. // design-lint:设计稿里的颜色 / 字体 / 间距是否都出自设计系统文件。机判在前,人工只看它管不到的部分。
  10. const skillRoot = fileURLToPath(new URL("../skills/design/", import.meta.url));
  11. const fixtures = fileURLToPath(new URL("./fixtures/lint/", import.meta.url));
  12. const script = join(skillRoot, "scripts", "design-lint.mjs");
  13. const fixture = (name: string) => join(fixtures, name);
  14. const system = () => parseDesignSystem(readFileSync(fixture("system.md"), "utf8"), "system.md");
  15. const run = (...args: string[]) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8", timeout: 20000 });
  16. describe("design-lint", () => {
  17. it("颜色字面量统一成同一种写法:hex 大小写与简写、rgb 新旧语法、hsl", () => {
  18. expect(colorKey(parseColor("#FFF"))).toBe("#ffffff");
  19. expect(colorKey(parseColor("rgb(231 111 81 / 40%)"))).toBe("#e76f5166");
  20. expect(colorKey(parseColor("rgba(231, 111, 81, 1)"))).toBe("#e76f51");
  21. expect(colorKey(parseColor("hsl(0, 100%, 50%)"))).toBe("#ff0000");
  22. expect(parseColor("#12345")).toBeNull();
  23. });
  24. it("读 markdown 设计系统文件的四张 token 表", () => {
  25. const parsed = system();
  26. expect(parsed.name).toBe("harbor");
  27. expect(parsed.colors.map((t: { token: string }) => t.token)).toEqual(["--ink", "--paper", "--accent", "--line"]);
  28. expect(parsed.fonts[1].value).toBe('"Source Sans 3", "PingFang SC", "Microsoft YaHei", sans-serif');
  29. expect(parsed.spacing).toHaveLength(4);
  30. expect(parsed.radii[0].value).toBe("6px");
  31. expect(parsed.usage).toContain("Accent only");
  32. });
  33. it("含 3 个违规色值的样例报 3 处:变量定义、样式表、内联样式各一,带行号和最近的合法 token", () => {
  34. const html = readFileSync(fixture("violations.html"), "utf8");
  35. const { violations } = lintDesign(html, system());
  36. expect(violations.map((v: { value: string; line: number }) => [v.value, v.line])).toEqual([
  37. ["#6366f1", 7],
  38. ["hsl(262, 83%, 58%)", 10],
  39. ["rgb(17, 24, 39)", 14],
  40. ]);
  41. expect(violations.every((v: { kind: string }) => v.kind === "color")).toBe(true);
  42. // rgb(17,24,39) 最接近墨色 --ink。
  43. expect(violations[2].suggestion).toBe("--ink (#14213d)");
  44. });
  45. it("干净样例报 0:大小写、rgb/rgba、带透明度的同色、var()、注释里的色值、#id 选择器、SVG 属性都不误报", () => {
  46. const html = readFileSync(fixture("clean.html"), "utf8");
  47. const result = lintDesign(html, system(), { spacing: true });
  48. expect(result.violations).toEqual([]);
  49. expect(result.stats.colors).toBeGreaterThanOrEqual(4);
  50. });
  51. it("字体与间距:主字体不在系统里报 font;--spacing 时不在刻度上的 px/rem 报 spacing", () => {
  52. const html = `<style>p { font-family: Inter, sans-serif; margin: 12px 8px; padding: 0 1rem; }</style>`;
  53. const kinds = (spacing: boolean) =>
  54. lintDesign(html, system(), { spacing }).violations.map((v: { kind: string; value: string }) => `${v.kind}:${v.value}`);
  55. expect(kinds(false)).toEqual(["font:Inter"]);
  56. expect(kinds(true)).toEqual(["font:Inter", "spacing:12px"]);
  57. });
  58. it("字体写在任意名字的自定义属性里(如 --app-font-sans)再 var() 引用,也照样检查", () => {
  59. const html = `<style>:root { --app-font-sans: Inter, sans-serif; --font-size-lg: 18px; --font-weight-bold: 700; } p { font-family: var(--app-font-sans); }</style>`;
  60. const result = lintDesign(html, system());
  61. expect(result.violations.map((v: { kind: string; value: string }) => `${v.kind}:${v.value}`)).toEqual(["font:Inter"]);
  62. expect(result.stats.families).toBe(1);
  63. });
  64. it("名字带 font 但值不是字体栈的自定义属性不报(颜色、数字、关键字、font 简写)", () => {
  65. const html = `<style>:root { --font-color: #333; --font-display: swap; --font-lh: 1.5; --font-tracking: -0.01em; --fa-font-solid: normal 900 1em/1 "Font Awesome 6 Free"; --font-sans-fallback: Inter, sans-serif; }</style>`;
  66. const fonts = lintDesign(html, system())
  67. .violations.filter((v: { kind: string }) => v.kind === "font")
  68. .map((v: { value: string }) => v.value);
  69. expect(fonts).toEqual(["Inter"]);
  70. });
  71. it("JSON 形式的设计系统文件同样可读", () => {
  72. const json = parseDesignSystem(readFileSync(fixture("system.json"), "utf8"), "system.json");
  73. expect(json.fonts[0].value).toBe("Source Sans 3, sans-serif");
  74. const html = readFileSync(fixture("violations.html"), "utf8");
  75. expect(lintDesign(html, json).violations).toHaveLength(3);
  76. });
  77. it("CLI:有违规退出 1 并逐条打印 文件:行;干净退出 0", () => {
  78. const bad = run(fixture("violations.html"), fixture("system.md"));
  79. expect(bad.status).toBe(1);
  80. expect(bad.stdout).toContain(`${fixture("violations.html")}:7 [color] --brand: #6366f1 -> nearest token:`);
  81. expect(bad.stdout).toContain("3 violation(s)");
  82. const clean = run(fixture("clean.html"), fixture("system.md"), "--spacing");
  83. expect(clean.status, clean.stdout + clean.stderr).toBe(0);
  84. const json = JSON.parse(run(fixture("violations.html"), fixture("system.md"), "--json").stdout);
  85. expect(json.violations).toHaveLength(3);
  86. });
  87. it("没给设计系统时只做通用检查并说明,不判违规", () => {
  88. const generic = run(fixture("violations.html"));
  89. expect(generic.status, generic.stdout + generic.stderr).toBe(0);
  90. expect(generic.stdout).toContain("generic checks only");
  91. // 通用检查:不经 CSS 变量直接写的色值给 warning。
  92. expect(generic.stdout).toMatch(/warning: .*#fbf8f1 -> fix: define it once/);
  93. expect(run().status).toBe(2);
  94. });
  95. it("显式给了读得到但不是设计系统的文件(空文件、README、缺四个 token 区段、JSON 不合格式):退出 2", () => {
  96. const dir = mkdtempSync(join(tmpdir(), "zcode-design-lint-"));
  97. try {
  98. const cases: Record<string, string> = {
  99. "empty.md": "",
  100. "README.md": "# Harbor App\n\nA budgeting app. Run `pnpm dev` to start.\n\n## Install\n\n- node: 24\n",
  101. "no-sections.md": "---\nname: harbor\n---\n\n# Harbor\n\n## Usage\n\nAccent is for primary actions only.\n",
  102. "bad.json": JSON.stringify({ name: "harbor", palette: { brand: "#1b2a41" } }),
  103. };
  104. for (const [name, text] of Object.entries(cases)) {
  105. writeFileSync(join(dir, name), text);
  106. const result = run(fixture("violations.html"), join(dir, name));
  107. expect(result.status, name).toBe(2);
  108. expect(result.stderr, name).toContain(name);
  109. expect(result.stdout, name).not.toContain("violation(s)");
  110. }
  111. // 有效的 .md / .json 行为不变。
  112. expect(run(fixture("violations.html"), fixture("system.json")).status).toBe(1);
  113. expect(run(fixture("clean.html"), fixture("system.md")).status).toBe(0);
  114. } finally {
  115. rmSync(dir, { force: true, recursive: true });
  116. }
  117. });
  118. it("显式给了读不到的设计系统文件:退出 2,不降级成通用检查当通过", () => {
  119. // violations.html 对着真设计系统有 3 处违规;路径写错不能让它以 0 混过去。
  120. const missing = run(fixture("violations.html"), fixture("does-not-exist.md"));
  121. expect(missing.status).toBe(2);
  122. expect(missing.stderr).toContain("does-not-exist.md");
  123. expect(missing.stdout).not.toContain("violation(s)");
  124. });
  125. });