semanticSurfaceContrast.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import { createElement } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  4. import { SourceServerUpdateActivity } from "@/settings/SourceServerUpdateActivity.js";
  5. import { readFileSync } from "node:fs";
  6. import { createRequire } from "node:module";
  7. import { describe, expect, it } from "vitest";
  8. /**
  9. * 合同 §8.3 / 审计 §9 门禁:36 组合对比度单测必须以 styles.css 的真实 token 链取值——
  10. * 主题块 → :root 级联 → Tailwind v4 调色板(oklch),token 改值测试必须变红。
  11. * 解析不了的构造一律抛错失败,禁止静默跳过或回退硬编码近似值。
  12. */
  13. const stylesCss = stripComments(
  14. readFileSync(new URL("../src/styles.css", import.meta.url), "utf8"),
  15. );
  16. const tailwindThemeCss = stripComments(
  17. readFileSync(createRequire(import.meta.url).resolve("tailwindcss/theme.css"), "utf8"),
  18. );
  19. function stripComments(css: string): string {
  20. return css.replace(/\/\*[\s\S]*?\*\//g, "");
  21. }
  22. /** 提取选择器的首个规则块(花括号深度配对),找不到即抛错。 */
  23. function extractBlock(css: string, selector: string): string {
  24. const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  25. const match = new RegExp(`(?:^|\\n)\\s*${escaped}\\s*\\{`).exec(css);
  26. if (!match) throw new Error(`selector not found in styles.css: ${selector}`);
  27. const start = match.index + match[0].length;
  28. let depth = 1;
  29. for (let index = start; index < css.length; index += 1) {
  30. if (css[index] === "{") depth += 1;
  31. else if (css[index] === "}") {
  32. depth -= 1;
  33. if (depth === 0) return css.slice(start, index);
  34. }
  35. }
  36. throw new Error(`unclosed block for selector: ${selector}`);
  37. }
  38. function parseDeclarations(block: string): Map<string, string> {
  39. const declarations = new Map<string, string>();
  40. for (const statement of block.split(";")) {
  41. const match = /^\s*(--[\w-]+)\s*:\s*([\s\S]+)$/.exec(statement);
  42. if (match) declarations.set(match[1]!, match[2]!.trim());
  43. }
  44. return declarations;
  45. }
  46. interface Rgba {
  47. red: number;
  48. green: number;
  49. blue: number;
  50. alpha: number;
  51. }
  52. type Scope = ReadonlyArray<Map<string, string>>;
  53. function resolveToken(name: string, scopes: Scope): Rgba {
  54. for (const scope of scopes) {
  55. const value = scope.get(name);
  56. if (value !== undefined) return parseColorValue(value, scopes);
  57. }
  58. throw new Error(`token not defined in any scope: ${name}`);
  59. }
  60. function parseColorValue(rawValue: string, scopes: Scope): Rgba {
  61. const value = rawValue.replace(/\s+/g, " ").trim();
  62. if (value === "transparent") return { red: 0, green: 0, blue: 0, alpha: 0 };
  63. const varMatch = /^var\((--[\w-]+)\)$/.exec(value);
  64. if (varMatch) return resolveToken(varMatch[1]!, scopes);
  65. if (value.startsWith("#")) return parseHexColor(value);
  66. const rgbaMatch = /^rgba?\(([^)]+)\)$/.exec(value);
  67. if (rgbaMatch) {
  68. const parts = rgbaMatch[1]!.split(",").map((part) => Number(part.trim()));
  69. if (parts.length < 3 || parts.some(Number.isNaN)) {
  70. throw new Error(`unsupported rgba() value: ${value}`);
  71. }
  72. return {
  73. red: parts[0]!,
  74. green: parts[1]!,
  75. blue: parts[2]!,
  76. alpha: parts[3] ?? 1,
  77. };
  78. }
  79. const oklchMatch = /^oklch\(([^)]+)\)$/.exec(value);
  80. if (oklchMatch) return parseOklch(oklchMatch[1]!);
  81. const mixMatch =
  82. /^color-mix\(\s*in\s+(srgb|oklab)\s*,\s*([\s\S]+?)\s+([\d.]+)%\s*,\s*transparent\s*\)$/.exec(
  83. value,
  84. );
  85. if (mixMatch) {
  86. // 与 transparent 的 premultiplied 混合只缩放 alpha、不改变色度分量,
  87. // srgb 与 oklab 插值空间在该形态下结果一致;两色混合形态当前 token 不存在,直接拒绝。
  88. const base = parseColorValue(mixMatch[2]!, scopes);
  89. return { ...base, alpha: base.alpha * (Number(mixMatch[3]) / 100) };
  90. }
  91. throw new Error(`unsupported color value: ${value}`);
  92. }
  93. function parseHexColor(value: string): Rgba {
  94. const hex = value.slice(1);
  95. if (hex.length === 3) {
  96. return {
  97. red: Number.parseInt(hex[0]! + hex[0]!, 16),
  98. green: Number.parseInt(hex[1]! + hex[1]!, 16),
  99. blue: Number.parseInt(hex[2]! + hex[2]!, 16),
  100. alpha: 1,
  101. };
  102. }
  103. if (hex.length === 6) {
  104. return {
  105. red: Number.parseInt(hex.slice(0, 2), 16),
  106. green: Number.parseInt(hex.slice(2, 4), 16),
  107. blue: Number.parseInt(hex.slice(4, 6), 16),
  108. alpha: 1,
  109. };
  110. }
  111. throw new Error(`unsupported hex color: ${value}`);
  112. }
  113. function parseOklch(body: string): Rgba {
  114. const [components, alphaPart] = body.split("/").map((part) => part.trim());
  115. const parts = components!.split(/\s+/);
  116. if (parts.length !== 3) throw new Error(`unsupported oklch() value: ${body}`);
  117. const lightness = parts[0]!.endsWith("%")
  118. ? Number(parts[0]!.slice(0, -1)) / 100
  119. : Number(parts[0]);
  120. const chroma = Number(parts[1]);
  121. const hue = parts[2] === "none" ? 0 : Number(parts[2]);
  122. const alpha = alphaPart
  123. ? alphaPart.endsWith("%")
  124. ? Number(alphaPart.slice(0, -1)) / 100
  125. : Number(alphaPart)
  126. : 1;
  127. if ([lightness, chroma, hue, alpha].some(Number.isNaN)) {
  128. throw new Error(`unsupported oklch() value: ${body}`);
  129. }
  130. return { ...oklchToSrgb(lightness, chroma, hue), alpha };
  131. }
  132. /** OKLCH → OKLab → LMS → linear sRGB → gamma sRGB(Björn Ottosson 参考实现系数)。 */
  133. function oklchToSrgb(
  134. lightness: number,
  135. chroma: number,
  136. hueDegrees: number,
  137. ): Pick<Rgba, "red" | "green" | "blue"> {
  138. const hue = (hueDegrees * Math.PI) / 180;
  139. const labA = chroma * Math.cos(hue);
  140. const labB = chroma * Math.sin(hue);
  141. const l = (lightness + 0.3963377774 * labA + 0.2158037573 * labB) ** 3;
  142. const m = (lightness - 0.1055613458 * labA - 0.0638541728 * labB) ** 3;
  143. const s = (lightness - 0.0894841775 * labA - 1.291485548 * labB) ** 3;
  144. const linear = [
  145. 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
  146. -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
  147. -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
  148. ].map((channel) => {
  149. const clamped = Math.min(1, Math.max(0, channel));
  150. return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
  151. });
  152. return {
  153. red: linear[0]! * 255,
  154. green: linear[1]! * 255,
  155. blue: linear[2]! * 255,
  156. };
  157. }
  158. /** 半透明前景按 alpha 叠到不透明底色上(sRGB 分量插值,即浏览器合成行为)。 */
  159. function flattenOver(top: Rgba, bottom: Rgba): Rgba {
  160. if (bottom.alpha !== 1) {
  161. throw new Error("flatten target must be opaque");
  162. }
  163. return {
  164. red: top.red * top.alpha + bottom.red * (1 - top.alpha),
  165. green: top.green * top.alpha + bottom.green * (1 - top.alpha),
  166. blue: top.blue * top.alpha + bottom.blue * (1 - top.alpha),
  167. alpha: 1,
  168. };
  169. }
  170. function wcagLuminance(color: Rgba): number {
  171. const channels = [color.red, color.green, color.blue].map((value) => {
  172. const normalized = value / 255;
  173. return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
  174. });
  175. return channels[0]! * 0.2126 + channels[1]! * 0.7152 + channels[2]! * 0.0722;
  176. }
  177. function contrastRatio(foreground: Rgba, background: Rgba): number {
  178. const light = Math.max(wcagLuminance(foreground), wcagLuminance(background));
  179. const dark = Math.min(wcagLuminance(foreground), wcagLuminance(background));
  180. return (light + 0.05) / (dark + 0.05);
  181. }
  182. const paletteScope = parseDeclarations(tailwindThemeCss);
  183. // 默认亮主题的语义 token 定义在 Tailwind v4 的 @theme 块,其余主题以类选择器覆盖级联。
  184. const baseThemeScope = parseDeclarations(extractBlock(stylesCss, "@theme"));
  185. const rootScope = parseDeclarations(extractBlock(stylesCss, ":root"));
  186. const themeSelectors = {
  187. defaultLight: "@theme",
  188. defaultDark: ".dark",
  189. zaiLight: ".theme-zai-light",
  190. zaiDark: ".theme-zai-dark",
  191. } as const;
  192. const parentBackgrounds = [
  193. "background",
  194. "surface",
  195. "card",
  196. "sidebar",
  197. "popover",
  198. "selected",
  199. ] as const;
  200. const semantics = ["warning", "destructive", "success", "progress"] as const;
  201. describe("remote UI semantic surface tokens", () => {
  202. it("keeps all 96 theme/background/semantic combinations readable with real token values", () => {
  203. const combinations: string[] = [];
  204. const violations: string[] = [];
  205. for (const [theme, selector] of Object.entries(themeSelectors)) {
  206. const themeScope = parseDeclarations(extractBlock(stylesCss, selector));
  207. const scopes: Scope = [themeScope, baseThemeScope, paletteScope];
  208. const pageBackground = resolveToken("--color-background", scopes);
  209. if (pageBackground.alpha !== 1) {
  210. throw new Error(`--color-background must be opaque in ${theme}`);
  211. }
  212. for (const parent of parentBackgrounds) {
  213. const parentColor = resolveToken(`--color-${parent}`, scopes);
  214. const resolvedParent =
  215. parent === "background" ? pageBackground : flattenOver(parentColor, pageBackground);
  216. for (const semantic of semantics) {
  217. const surface = resolveToken(`--color-${semantic}-surface`, scopes);
  218. const foreground = resolveToken(`--color-${semantic}-surface-foreground`, scopes);
  219. if (foreground.alpha !== 1) {
  220. throw new Error(`surface foreground must be opaque: ${theme}/${semantic}`);
  221. }
  222. const composedSurface = flattenOver(surface, resolvedParent);
  223. const ratio = contrastRatio(foreground, composedSurface);
  224. combinations.push(`${theme}/${parent}/${semantic}`);
  225. if (ratio < 4.5) {
  226. violations.push(`${theme}/${parent}/${semantic} contrast=${ratio.toFixed(2)}`);
  227. }
  228. }
  229. }
  230. }
  231. expect(combinations).toHaveLength(96);
  232. // 阈值 4.5:1 是 §8.3 合同的硬门禁;失败即 token 取值的规格缺陷,修 token 并回写文档。
  233. expect(violations).toEqual([]);
  234. });
  235. it("远程标签、侧栏和设置导航在四个主题中达到 4.5:1", () => {
  236. const violations: string[] = [];
  237. for (const [theme, selector] of Object.entries(themeSelectors)) {
  238. const scopes: Scope = [
  239. parseDeclarations(extractBlock(stylesCss, selector)),
  240. rootScope,
  241. baseThemeScope,
  242. paletteScope,
  243. ];
  244. const page = resolveToken("--color-background", scopes);
  245. for (const parent of ["sidebar", "popover", "surface", "card", "selected", "background"]) {
  246. const background = flattenOver(resolveToken(`--color-${parent}`, scopes), page);
  247. for (const text of ["foreground", "remote-foreground-muted"]) {
  248. const foreground = flattenOver(resolveToken(`--color-${text}`, scopes), background);
  249. const ratio = contrastRatio(foreground, background);
  250. if (ratio < 4.5) violations.push(`${theme}/${parent}/${text}: ${ratio.toFixed(2)}`);
  251. }
  252. for (const kind of ["ssh", "wsl", "docker"]) {
  253. const surface = flattenOver(
  254. resolveToken(`--color-remote-${kind}-surface`, scopes),
  255. background,
  256. );
  257. const foreground = flattenOver(
  258. resolveToken(`--color-remote-${kind}-foreground`, scopes),
  259. surface,
  260. );
  261. const ratio = contrastRatio(foreground, surface);
  262. if (ratio < 4.5) violations.push(`${theme}/${parent}/${kind}: ${ratio.toFixed(2)}`);
  263. }
  264. }
  265. }
  266. expect(violations).toEqual([]);
  267. });
  268. it("registers every remote descriptor token triplet in all four themes", () => {
  269. const descriptors = ["remote-ssh", "remote-wsl", "remote-docker"] as const;
  270. const channels = ["surface", "foreground", "border"] as const;
  271. for (const [theme, selector] of Object.entries(themeSelectors)) {
  272. const themeScope = parseDeclarations(extractBlock(stylesCss, selector));
  273. const scopes: Scope = [themeScope, rootScope, baseThemeScope, paletteScope];
  274. for (const descriptor of descriptors) {
  275. for (const channel of channels) {
  276. expect(
  277. () => resolveToken(`--color-${descriptor}-${channel}`, scopes),
  278. `${theme} ${descriptor}-${channel}`,
  279. ).not.toThrow();
  280. }
  281. }
  282. }
  283. });
  284. it("keeps the dedicated continuity panel readable in all four themes", () => {
  285. for (const [theme, selector] of Object.entries(themeSelectors)) {
  286. const themeScope = parseDeclarations(extractBlock(stylesCss, selector));
  287. const scopes: Scope = [themeScope, rootScope, baseThemeScope, paletteScope];
  288. const panel = resolveToken("--color-remote-continuity-panel", scopes);
  289. const surface = resolveToken("--color-remote-continuity-panel-surface", scopes);
  290. const foreground = resolveToken("--color-remote-continuity-panel-foreground", scopes);
  291. const subtle = resolveToken("--color-remote-continuity-panel-subtle", scopes);
  292. expect(contrastRatio(foreground, panel), `${theme} foreground`).toBeGreaterThanOrEqual(4.5);
  293. expect(contrastRatio(subtle, panel), `${theme} subtle`).toBeGreaterThanOrEqual(4.5);
  294. expect(contrastRatio(foreground, surface), `${theme} surface`).toBeGreaterThanOrEqual(4.5);
  295. }
  296. });
  297. });
  298. it("真实设备日志时间戳在四主题背景上达到 4.5:1", () => {
  299. const html = renderToStaticMarkup(
  300. createElement(
  301. ZCodeIntlProvider,
  302. { initialLocale: "en-US" },
  303. createElement(SourceServerUpdateActivity, {
  304. active: true,
  305. logs: [
  306. {
  307. profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d",
  308. operation: "connect",
  309. phase: "ready",
  310. level: "info",
  311. message: "ready",
  312. timestamp: 1,
  313. },
  314. ],
  315. }),
  316. ),
  317. );
  318. const classes = /data-source-server-log-timestamp="true" class="([^"]+)"/u.exec(html)?.[1];
  319. const token = classes
  320. ?.split(" ")
  321. .find((name) => name.startsWith("text-"))
  322. ?.slice(5);
  323. expect(token).toBeTruthy();
  324. for (const [theme, selector] of Object.entries(themeSelectors)) {
  325. const scopes: Scope = [
  326. parseDeclarations(extractBlock(stylesCss, selector)),
  327. rootScope,
  328. baseThemeScope,
  329. paletteScope,
  330. ];
  331. const background = resolveToken("--color-background", scopes);
  332. const text = flattenOver(resolveToken(`--color-${token}`, scopes), background);
  333. expect(contrastRatio(text, background), theme).toBeGreaterThanOrEqual(4.5);
  334. }
  335. });