review-management-prototype.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. /** 容器/技能管理原型配色同步与隔离视觉核验;不访问账号、设备或线上服务。 */
  2. import assert from 'node:assert/strict';
  3. import { existsSync } from 'node:fs';
  4. import { mkdir, readFile, writeFile } from 'node:fs/promises';
  5. import { resolve, dirname } from 'node:path';
  6. import { fileURLToPath } from 'node:url';
  7. import { chromium } from 'playwright';
  8. const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  9. const target = resolve(root, 'docs/02-design/prototypes/2026-11-29-container-skills-management.html');
  10. const out = resolve(root, 'test-results/management-prototype-colors-20261129');
  11. const baselinePath = resolve(out, 'before.html');
  12. const read = path => readFile(resolve(root, path), 'utf8');
  13. const stripComments = value => value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/[\t ]+$/gm, '').trim();
  14. const theme = [await read('src/app/core/styles/_base.scss'), await read('src/app/core/styles/_palette.scss')]
  15. .map(stripComments).join('\n');
  16. const themeBlock = `/* project-theme:start — generated from application token sources */\n${theme}\n/* project-theme:end */`;
  17. let html = await readFile(target, 'utf8');
  18. await mkdir(out, { recursive: true });
  19. if (process.argv.includes('--apply')) {
  20. assert(!html.includes('project-theme:start'), '已同步过配色,禁止覆盖原始基线;仅运行核验即可');
  21. assert(!existsSync(baselinePath), '已有修订前基线,先核实状态,不覆盖证据');
  22. await writeFile(baselinePath, html);
  23. html = html.replace('<html lang="zh-CN">', '<html lang="zh-CN" data-palette="platinum">');
  24. html = html.replace(/ :root \{[\s\S]*?\n \}/, `${themeBlock}\n :root {\n color-scheme: light;\n --radius: 18px;\n font-family: "Segoe UI", "Microsoft YaHei UI", sans-serif;\n background: var(--canvas);\n color: var(--ink);\n }\n .dark { color-scheme: dark; }`);
  25. html = html.replaceAll('var(--primary-soft)', 'var(--primary-subtle)');
  26. const replacements = {
  27. '.desktop-shell': [['box-shadow: 0 18px 54px #1d2b3810', 'box-shadow: var(--shadow)']],
  28. '.rail': [['background: #fbfcfd', 'background: var(--nav-surface); color: var(--nav-ink)'], ['border-right: 1px solid var(--edge)', 'border-right: 1px solid var(--nav-line)']],
  29. '.brand-mark': [['color: white; background: var(--primary)', 'color: var(--nav-on-brand); background: var(--nav-brand)']],
  30. '.nav-caption': [['color: #98a3ad', 'color: var(--nav-muted)']],
  31. '.nav-item': [['color: var(--ink-2)', 'color: var(--nav-text)']],
  32. '.nav-item.active': [['background: var(--primary-subtle); color: var(--primary)', 'background: var(--nav-active); color: var(--nav-accent)']],
  33. '.profile': [['border-top: 1px solid var(--edge)', 'border-top: 1px solid var(--nav-line)']],
  34. '.avatar': [['color: #275044; background: #dbece5', 'color: var(--nav-on-brand); background: var(--nav-brand)']],
  35. '.profile-sub': [['color: var(--muted)', 'color: var(--nav-muted)']],
  36. '.btn-primary': [['color: white', 'color: var(--primary-content)']],
  37. '.btn-primary:hover': [['background: #115b4b', 'border-color: var(--primary-hover); background: var(--primary-hover)']],
  38. '.container-card.primary-card': [['border-color: #b8d9ce; box-shadow: 0 0 0 3px #e8f4f033', 'border-color: var(--edge-strong); box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-subtle) 20%, transparent)']],
  39. '.status': [['background: #edf7f1', 'background: var(--success-subtle)']],
  40. '.search': [['background: #fff', 'background: var(--surface)']],
  41. '.skill-row.selected': [['border: 1px solid #c4ded4', 'border: 1px solid var(--edge-strong)'], ['background: #f5faf8', 'background: var(--primary-subtle)']],
  42. '.skill-mark': [['color: #426b5d; background: #edf4f1', 'color: var(--avatar-ink); background: var(--avatar-bg)']],
  43. '.toggle': [['background: #ccd4db', 'background: var(--muted)']],
  44. '.toggle::after': [['background: white', 'background: var(--surface)'], ['box-shadow: 0 1px 3px #0002', 'box-shadow: var(--shadow-soft)']],
  45. '.scope-note': [['color: #775a25; background: var(--warning-soft)', 'color: var(--ink-2); background: var(--surface-2)']],
  46. '.mobile-stage': [['background: #e8ecef', 'background: var(--rail-surface)']],
  47. '.phone': [['border: 9px solid #1b232b', 'border: 9px solid var(--nav-surface)'], ['box-shadow: 0 18px 48px #13222d24', 'box-shadow: var(--shadow)']],
  48. '.mobile-summary': [['background: #e6f2ed', 'background: var(--surface-2)']],
  49. '.mobile-summary p': [['color: #61746d', 'color: var(--muted)']],
  50. '.summary-icon': [['color: var(--primary); background: #d5e9e0', 'color: var(--avatar-ink); background: var(--avatar-bg)']],
  51. '.mobile-tab.active': [['color: white', 'color: var(--primary-content)']],
  52. '.mobile-search': [['background: white', 'background: var(--surface); color: var(--ink)']],
  53. '.mobile-detail': [['background: white', 'background: var(--surface)']],
  54. '.mobile-fab': [['color: white; background: #1d292e', 'color: var(--primary-content); background: var(--primary)'], ['box-shadow: 0 5px 15px #13222d32', 'box-shadow: var(--shadow-card)']],
  55. '.phone-nav': [['background: #ffffffed', 'background: var(--surface)']],
  56. };
  57. for (const [selector, edits] of Object.entries(replacements)) {
  58. const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  59. const pattern = new RegExp(`(^ ${escaped} \\{)([^}]*)(\\})`, 'm');
  60. assert(pattern.test(html), `缺少选择器 ${selector}`);
  61. html = html.replace(pattern, (_, start, body, end) => {
  62. for (const [from, to] of edits) {
  63. assert(body.includes(from), `${selector} 中缺少 ${from}`);
  64. body = body.replace(from, to);
  65. }
  66. return start + body + end;
  67. });
  68. }
  69. html = html.replace(' </style>', ` .category.active .count { color: inherit; }\n .skill-row.selected :is(.tag, .skill-desc) { color: var(--ink-2); }\n .nav-item:hover:not(.active) { background: var(--nav-hover); }\n .btn:active { background: var(--surface-hover); }\n .btn-primary:active { border-color: var(--primary-hover); background: var(--primary-hover); }\n :where(.btn, .nav-item, .mobile-tab, .round-back, .mobile-fab):focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }\n .nav-item:focus-visible { outline-color: var(--nav-accent); }\n </style>`);
  70. // 全部替换成功后一次写入,避免中途异常形成半版原型。
  71. await writeFile(target, html);
  72. console.log('已同步原型配色,原始基线已留存。');
  73. }
  74. assert(html.includes(themeBlock), '内嵌主题与应用真源不一致');
  75. const baseline = await readFile(baselinePath, 'utf8');
  76. assert.equal(html.slice(html.indexOf('<body')), baseline.slice(baseline.indexOf('<body')), '正文或原型脚本发生变化');
  77. const styles = html.match(/<style>([\s\S]*?)<\/style>/)[1].replace(themeBlock, '');
  78. assert(!/#[\da-f]{3,8}\b|\b(?:white|black)\b(?=\s*[;}])/i.test(styles), '业务样式存在脱离主题的固定颜色');
  79. const chrome = ['C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'].find(existsSync);
  80. const browser = await chromium.launch({ headless: true, ...(chrome ? { executablePath: chrome } : {}) });
  81. const results = [];
  82. try {
  83. const page = await browser.newPage();
  84. await page.route('**/*', route => route.abort());
  85. const measure = async (source, view, palette, dark) => {
  86. await page.setContent(source);
  87. await page.evaluate(({ view, palette, dark }) => {
  88. document.body.dataset.view = view;
  89. document.documentElement.dataset.palette = palette;
  90. document.documentElement.classList.toggle('dark', dark);
  91. }, { view, palette, dark });
  92. await page.evaluate(() => document.fonts.ready);
  93. return page.evaluate(() => [...document.body.querySelectorAll('*')].flatMap((el, index) => {
  94. const r = el.getBoundingClientRect();
  95. return r.width && r.height ? [{ index, x: r.x, y: r.y, w: r.width, h: r.height }] : [];
  96. }));
  97. };
  98. for (const [view, width] of [['containers', 1440], ['skills', 1440], ['mobile', 450], ['containers', 960], ['skills', 960]]) {
  99. await page.setViewportSize({ width, height: 1040 });
  100. const before = await measure(baseline, view, 'platinum', false);
  101. for (const palette of ['platinum', 'ice', 'clay', 'slate']) {
  102. for (const dark of [false, true]) {
  103. const after = await measure(html, view, palette, dark);
  104. assert.deepEqual(after, before, `${view}/${palette}/${dark} 布局发生变化`);
  105. const contrast = await page.evaluate(() => {
  106. const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
  107. const c = canvas.getContext('2d', { willReadFrequently: true });
  108. const rgba = color => { c.clearRect(0, 0, 1, 1); c.fillStyle = color; c.fillRect(0, 0, 1, 1); return [...c.getImageData(0, 0, 1, 1).data].map((x, i) => i === 3 ? x / 255 : x); };
  109. const blend = (fg, bg) => fg.slice(0, 3).map((v, i) => v * fg[3] + bg[i] * (1 - fg[3])).concat(1);
  110. const lum = color => color.slice(0, 3).map(v => { v /= 255; return v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4; }).reduce((s, v, i) => s + v * [.2126, .7152, .0722][i], 0);
  111. const failures = []; let checked = 0; let minimum = 100;
  112. for (const el of document.body.querySelectorAll('*')) {
  113. const r = el.getBoundingClientRect();
  114. if (!r.width || !r.height || (!el.matches('input[value]') && ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()))) continue;
  115. const ancestors = []; for (let p = el; p; p = p.parentElement) ancestors.unshift(p);
  116. let bg = [255, 255, 255, 1];
  117. for (const p of ancestors) bg = blend(rgba(getComputedStyle(p).backgroundColor), bg);
  118. const s = getComputedStyle(el), fg = blend(rgba(s.color), bg);
  119. const a = lum(fg), b = lum(bg), ratio = (Math.max(a, b) + .05) / (Math.min(a, b) + .05);
  120. const large = parseFloat(s.fontSize) >= 24 || (parseFloat(s.fontSize) >= 18.66 && parseInt(s.fontWeight) >= 700);
  121. checked++; minimum = Math.min(minimum, ratio);
  122. if (ratio < (large ? 3 : 4.5)) failures.push({ selector: el.className, text: el.textContent.trim().slice(0, 35), ratio });
  123. }
  124. return { checked, minimum, failures };
  125. });
  126. const name = `${view}-${palette}-${dark ? 'dark' : 'light'}${width === 960 ? '-narrow' : ''}`;
  127. await page.screenshot({ path: resolve(out, `${name}.png`), fullPage: true });
  128. results.push({ name, geometryUnchanged: true, ...contrast });
  129. }
  130. }
  131. }
  132. const report = { time: new Date().toISOString(), scope: '仅原型配色;正文、脚本与可见元素几何均对照修改前基线', tokenSourcesMatch: true, bodyUnchanged: true, fixedColorsOutsideTokens: false, results };
  133. await writeFile(resolve(out, 'report.json'), JSON.stringify(report, null, 2) + '\n');
  134. const failed = results.filter(r => r.failures.length);
  135. assert.equal(failed.length, 0, JSON.stringify(failed, null, 2));
  136. console.log(`通过:${results.length} 组主题/视图,${results.reduce((n, r) => n + r.checked, 0)} 项文字对比度,布局与正文不变。`);
  137. console.log(`证据:${out}`);
  138. } finally {
  139. await browser.close();
  140. }