| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- /** 容器/技能管理原型配色同步与隔离视觉核验;不访问账号、设备或线上服务。 */
- import assert from 'node:assert/strict';
- import { existsSync } from 'node:fs';
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
- import { resolve, dirname } from 'node:path';
- import { fileURLToPath } from 'node:url';
- import { chromium } from 'playwright';
- const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
- const target = resolve(root, 'docs/02-design/prototypes/2026-11-29-container-skills-management.html');
- const out = resolve(root, 'test-results/management-prototype-colors-20261129');
- const baselinePath = resolve(out, 'before.html');
- const read = path => readFile(resolve(root, path), 'utf8');
- const stripComments = value => value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/[\t ]+$/gm, '').trim();
- const theme = [await read('src/app/core/styles/_base.scss'), await read('src/app/core/styles/_palette.scss')]
- .map(stripComments).join('\n');
- const themeBlock = `/* project-theme:start — generated from application token sources */\n${theme}\n/* project-theme:end */`;
- let html = await readFile(target, 'utf8');
- await mkdir(out, { recursive: true });
- if (process.argv.includes('--apply')) {
- assert(!html.includes('project-theme:start'), '已同步过配色,禁止覆盖原始基线;仅运行核验即可');
- assert(!existsSync(baselinePath), '已有修订前基线,先核实状态,不覆盖证据');
- await writeFile(baselinePath, html);
- html = html.replace('<html lang="zh-CN">', '<html lang="zh-CN" data-palette="platinum">');
- 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; }`);
- html = html.replaceAll('var(--primary-soft)', 'var(--primary-subtle)');
- const replacements = {
- '.desktop-shell': [['box-shadow: 0 18px 54px #1d2b3810', 'box-shadow: var(--shadow)']],
- '.rail': [['background: #fbfcfd', 'background: var(--nav-surface); color: var(--nav-ink)'], ['border-right: 1px solid var(--edge)', 'border-right: 1px solid var(--nav-line)']],
- '.brand-mark': [['color: white; background: var(--primary)', 'color: var(--nav-on-brand); background: var(--nav-brand)']],
- '.nav-caption': [['color: #98a3ad', 'color: var(--nav-muted)']],
- '.nav-item': [['color: var(--ink-2)', 'color: var(--nav-text)']],
- '.nav-item.active': [['background: var(--primary-subtle); color: var(--primary)', 'background: var(--nav-active); color: var(--nav-accent)']],
- '.profile': [['border-top: 1px solid var(--edge)', 'border-top: 1px solid var(--nav-line)']],
- '.avatar': [['color: #275044; background: #dbece5', 'color: var(--nav-on-brand); background: var(--nav-brand)']],
- '.profile-sub': [['color: var(--muted)', 'color: var(--nav-muted)']],
- '.btn-primary': [['color: white', 'color: var(--primary-content)']],
- '.btn-primary:hover': [['background: #115b4b', 'border-color: var(--primary-hover); background: var(--primary-hover)']],
- '.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)']],
- '.status': [['background: #edf7f1', 'background: var(--success-subtle)']],
- '.search': [['background: #fff', 'background: var(--surface)']],
- '.skill-row.selected': [['border: 1px solid #c4ded4', 'border: 1px solid var(--edge-strong)'], ['background: #f5faf8', 'background: var(--primary-subtle)']],
- '.skill-mark': [['color: #426b5d; background: #edf4f1', 'color: var(--avatar-ink); background: var(--avatar-bg)']],
- '.toggle': [['background: #ccd4db', 'background: var(--muted)']],
- '.toggle::after': [['background: white', 'background: var(--surface)'], ['box-shadow: 0 1px 3px #0002', 'box-shadow: var(--shadow-soft)']],
- '.scope-note': [['color: #775a25; background: var(--warning-soft)', 'color: var(--ink-2); background: var(--surface-2)']],
- '.mobile-stage': [['background: #e8ecef', 'background: var(--rail-surface)']],
- '.phone': [['border: 9px solid #1b232b', 'border: 9px solid var(--nav-surface)'], ['box-shadow: 0 18px 48px #13222d24', 'box-shadow: var(--shadow)']],
- '.mobile-summary': [['background: #e6f2ed', 'background: var(--surface-2)']],
- '.mobile-summary p': [['color: #61746d', 'color: var(--muted)']],
- '.summary-icon': [['color: var(--primary); background: #d5e9e0', 'color: var(--avatar-ink); background: var(--avatar-bg)']],
- '.mobile-tab.active': [['color: white', 'color: var(--primary-content)']],
- '.mobile-search': [['background: white', 'background: var(--surface); color: var(--ink)']],
- '.mobile-detail': [['background: white', 'background: var(--surface)']],
- '.mobile-fab': [['color: white; background: #1d292e', 'color: var(--primary-content); background: var(--primary)'], ['box-shadow: 0 5px 15px #13222d32', 'box-shadow: var(--shadow-card)']],
- '.phone-nav': [['background: #ffffffed', 'background: var(--surface)']],
- };
- for (const [selector, edits] of Object.entries(replacements)) {
- const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const pattern = new RegExp(`(^ ${escaped} \\{)([^}]*)(\\})`, 'm');
- assert(pattern.test(html), `缺少选择器 ${selector}`);
- html = html.replace(pattern, (_, start, body, end) => {
- for (const [from, to] of edits) {
- assert(body.includes(from), `${selector} 中缺少 ${from}`);
- body = body.replace(from, to);
- }
- return start + body + end;
- });
- }
- 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>`);
- // 全部替换成功后一次写入,避免中途异常形成半版原型。
- await writeFile(target, html);
- console.log('已同步原型配色,原始基线已留存。');
- }
- assert(html.includes(themeBlock), '内嵌主题与应用真源不一致');
- const baseline = await readFile(baselinePath, 'utf8');
- assert.equal(html.slice(html.indexOf('<body')), baseline.slice(baseline.indexOf('<body')), '正文或原型脚本发生变化');
- const styles = html.match(/<style>([\s\S]*?)<\/style>/)[1].replace(themeBlock, '');
- assert(!/#[\da-f]{3,8}\b|\b(?:white|black)\b(?=\s*[;}])/i.test(styles), '业务样式存在脱离主题的固定颜色');
- const chrome = ['C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'].find(existsSync);
- const browser = await chromium.launch({ headless: true, ...(chrome ? { executablePath: chrome } : {}) });
- const results = [];
- try {
- const page = await browser.newPage();
- await page.route('**/*', route => route.abort());
- const measure = async (source, view, palette, dark) => {
- await page.setContent(source);
- await page.evaluate(({ view, palette, dark }) => {
- document.body.dataset.view = view;
- document.documentElement.dataset.palette = palette;
- document.documentElement.classList.toggle('dark', dark);
- }, { view, palette, dark });
- await page.evaluate(() => document.fonts.ready);
- return page.evaluate(() => [...document.body.querySelectorAll('*')].flatMap((el, index) => {
- const r = el.getBoundingClientRect();
- return r.width && r.height ? [{ index, x: r.x, y: r.y, w: r.width, h: r.height }] : [];
- }));
- };
- for (const [view, width] of [['containers', 1440], ['skills', 1440], ['mobile', 450], ['containers', 960], ['skills', 960]]) {
- await page.setViewportSize({ width, height: 1040 });
- const before = await measure(baseline, view, 'platinum', false);
- for (const palette of ['platinum', 'ice', 'clay', 'slate']) {
- for (const dark of [false, true]) {
- const after = await measure(html, view, palette, dark);
- assert.deepEqual(after, before, `${view}/${palette}/${dark} 布局发生变化`);
- const contrast = await page.evaluate(() => {
- const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
- const c = canvas.getContext('2d', { willReadFrequently: true });
- 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); };
- const blend = (fg, bg) => fg.slice(0, 3).map((v, i) => v * fg[3] + bg[i] * (1 - fg[3])).concat(1);
- 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);
- const failures = []; let checked = 0; let minimum = 100;
- for (const el of document.body.querySelectorAll('*')) {
- const r = el.getBoundingClientRect();
- if (!r.width || !r.height || (!el.matches('input[value]') && ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()))) continue;
- const ancestors = []; for (let p = el; p; p = p.parentElement) ancestors.unshift(p);
- let bg = [255, 255, 255, 1];
- for (const p of ancestors) bg = blend(rgba(getComputedStyle(p).backgroundColor), bg);
- const s = getComputedStyle(el), fg = blend(rgba(s.color), bg);
- const a = lum(fg), b = lum(bg), ratio = (Math.max(a, b) + .05) / (Math.min(a, b) + .05);
- const large = parseFloat(s.fontSize) >= 24 || (parseFloat(s.fontSize) >= 18.66 && parseInt(s.fontWeight) >= 700);
- checked++; minimum = Math.min(minimum, ratio);
- if (ratio < (large ? 3 : 4.5)) failures.push({ selector: el.className, text: el.textContent.trim().slice(0, 35), ratio });
- }
- return { checked, minimum, failures };
- });
- const name = `${view}-${palette}-${dark ? 'dark' : 'light'}${width === 960 ? '-narrow' : ''}`;
- await page.screenshot({ path: resolve(out, `${name}.png`), fullPage: true });
- results.push({ name, geometryUnchanged: true, ...contrast });
- }
- }
- }
- const report = { time: new Date().toISOString(), scope: '仅原型配色;正文、脚本与可见元素几何均对照修改前基线', tokenSourcesMatch: true, bodyUnchanged: true, fixedColorsOutsideTokens: false, results };
- await writeFile(resolve(out, 'report.json'), JSON.stringify(report, null, 2) + '\n');
- const failed = results.filter(r => r.failures.length);
- assert.equal(failed.length, 0, JSON.stringify(failed, null, 2));
- console.log(`通过:${results.length} 组主题/视图,${results.reduce((n, r) => n + r.checked, 0)} 项文字对比度,布局与正文不变。`);
- console.log(`证据:${out}`);
- } finally {
- await browser.close();
- }
|