Files
Harvey_Team_Page/design/halo-audit-2026-11-10/audit.cjs
T
FastD 9e7b1e3430 Serve planet and mascots from src/assets
- Move served planet (animated webp, posters, 300 frames) and team mascots into src/assets/
- Use relative paths (assets/...) that work in file://, on the dev server and with docroot=src
- Screenshot pipeline writes to src/assets/projects
- Halo audit: report and measurements, ticker ring fix, shadow rules in DESIGN.md and spec.md
2026-11-10 18:42:12 +03:00

330 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
/* audit.cjs — ревизия «ореолов» (свечение/гало) на src/index.html.
*
* Что делает:
* 1) инвентаризация: computed box-shadow / text-shadow / filter / backdrop-filter
* по всем элементам страницы + цвет эффективного фона под элементом;
* 2) применение двух «световых» теллов детектора impeccable к УЖЕ вычисленным
* значениям (нулевое смещение + хрома + blur>4; хроматическая тень на тёмном фоне);
* 3) пиксельный замер ореола вокруг целевых компонентов (lib/ring.cjs) — дельта по
* четырём сторонам, радиус спада, знак (темнее/светлее фона);
* 4) скриншоты «до» и «после» для каждого предложенного исправления (CSS-оверрайд
* инжектится в страницу, исходный файл НЕ меняется).
*
* Запуск: node design/halo-audit-2026-11-10/audit.cjs [url] [outDir]
*/
const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright-core');
const png = require('./lib/png.cjs');
const ring = require('./lib/ring.cjs');
const URL = process.argv[2] || 'http://127.0.0.1:8791/src/index.html';
const OUT = process.argv[3] || path.join(__dirname, 'out');
const SHOTS = path.join(OUT, 'shots');
const MARGIN = 24;
const EXEC = process.env.CHROME_EXE ||
'C:/Users/deeen/AppData/Local/ms-playwright/chromium_headless_shell-1223/chrome-headless-shell-win64/chrome-headless-shell.exe';
fs.mkdirSync(SHOTS, { recursive: true });
/* ── предложенные исправления (только для «после»; в src/index.html не попадают) ── */
const FIXES = {
'mark-hover-shadow': `
/* F1: у ссылки-иконки нет ни рамки, ни заливки — тень --shadow-btn рисует
тёмный прямоугольник 48×48 за знаком (гало без плашки). Hover-отклик
переносится на цвет, как у .btn--ghost:hover. */
.btn--mark:hover{background:none;border:0;box-shadow:none;color:var(--brand-ink)}`,
'ticker-toggle-ring': `
/* F2: box-shadow 0 0 0 6px var(--card) — непрозрачное кольцо цвета карточки.
Пока лента показана (та же --card) кольцо невидимо и работает маской: текст
бегущей строки не подходит к рамке кнопки. У выключенной ленты фон под кнопкой
--bg → кольцо читается светлым ореолом 6 px. Маска нужна только над лентой. */
.ticker-wrap.is-off .ticker-toggle{box-shadow:none}`,
'dark-card-edge': `
/* F3 (только для замера): чёрная ambient-тень в тёмной теме не отделяет
карточку — пробуем hairline-границу вместо широкой тени. */
[data-theme="dark"] .case-card,[data-theme="dark"] .team-card{border:1px solid var(--hairline)}`
};
function lum(c) {
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]);
}
function chroma(c) { return Math.max(c[0], c[1], c[2]) - Math.min(c[0], c[1], c[2]); }
function parseColor(s) {
if (!s) return null;
const m = s.match(/rgba?\(([^)]+)\)/);
if (!m) return null;
const p = m[1].split(/[\s,\/]+/).filter(Boolean).map(Number);
return [p[0], p[1], p[2], p.length > 3 ? p[3] : 1];
}
/* слой тени → {dx,dy,blur,spread,color} (офсеты/радиусы в px, em/rem ↓ 16) */
function shadowLayers(css) {
if (!css || css === 'none') return [];
const layers = css.split(/,(?![^(]*\))/).map(s => s.trim()).filter(Boolean);
const out = [];
for (const layer of layers) {
const inset = /\binset\b/.test(layer);
const colorMatch = layer.match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}|\btransparent\b/i);
const color = colorMatch ? (parseColor(colorMatch[0]) || [0, 0, 0, 0]) : [0, 0, 0, 1];
const nums = [];
const stripped = colorMatch ? layer.replace(colorMatch[0], ' ') : layer;
const re = /(-?\d*\.?\d+)(px|rem|em)?/g;
let m;
while ((m = re.exec(stripped)) !== null) {
let v = parseFloat(m[1]);
if (m[2] === 'rem' || m[2] === 'em') v *= 16;
nums.push(v);
}
out.push({ inset, color, dx: nums[0] || 0, dy: nums[1] || 0, blur: nums[2] || 0, spread: nums[3] || 0, raw: layer });
}
return out;
}
/* два «световых» телла impeccable (checks.mjs → checkGlow) */
function glowTell(layers, onDark) {
for (const L of layers) {
if (L.inset) continue;
if (chroma(L.color) < 30) continue;
if (L.blur <= 4) continue;
if (L.dx === 0 && L.dy === 0) return `zero-offset glow (${L.raw})`;
if (onDark) return `chromatic glow on dark bg (${L.raw})`;
}
return null;
}
/* ── сбор: инвентаризация по всем элементам ── */
function collectInventory() {
const all = Array.from(document.querySelectorAll('body *'));
const effBg = (el) => {
let n = el;
while (n && n !== document.documentElement) {
const bg = getComputedStyle(n).backgroundColor;
const c = bg.match(/rgba?\(([^)]+)\)/);
if (c) {
const p = c[1].split(/[\s,\/]+/).filter(Boolean).map(Number);
const a = p.length > 3 ? p[3] : 1;
if (a > 0.5) return bg;
}
n = n.parentElement;
}
return getComputedStyle(document.body).backgroundColor;
};
const sel = (el) => {
let s = el.tagName.toLowerCase();
if (el.id) s += '#' + el.id;
if (el.classList.length) s += '.' + Array.from(el.classList).slice(0, 3).join('.');
return s;
};
const rows = [];
for (const el of all) {
const cs = getComputedStyle(el);
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0) continue;
if (cs.boxShadow === 'none' && cs.textShadow === 'none' && cs.filter === 'none' && cs.backdropFilter === 'none') continue;
rows.push({
el: sel(el),
boxShadow: cs.boxShadow,
textShadow: cs.textShadow,
filter: cs.filter,
backdropFilter: cs.backdropFilter,
bg: effBg(el.parentElement || el),
ownBg: cs.backgroundColor,
w: Math.round(r.width), h: Math.round(r.height)
});
}
return rows;
}
/* ── замер одного компонента ── */
async function probe(page, spec) {
if (spec.prepare) await spec.prepare(page);
const loc = page.locator(spec.selector).first();
if (!(await loc.count())) return { name: spec.name, skipped: 'no element' };
await loc.evaluate((el) => el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })).catch(() => {});
await page.waitForTimeout(spec.settle || 420);
const box = await loc.evaluate((el) => {
const r = el.getBoundingClientRect();
return { x: r.x, y: r.y, w: r.width, h: r.height, sy: window.scrollY, sx: window.scrollX, vw: innerWidth, vh: innerHeight };
});
/* отступ съёмки ограничен свободным местом вокруг элемента в текущем вьюпорте:
за пределами вьюпорта Playwright снимать не умеет (clip вне кадра — ошибка). */
const mMax = Math.floor(Math.min(spec.marginCap || MARGIN, box.y, box.vh - (box.y + box.h), box.x, box.vw - (box.x + box.w)));
if (mMax < 4) return { name: spec.name, skipped: `no room for margin (m=${mMax})` };
const info = await loc.evaluate((el) => {
const s = getComputedStyle(el);
/* фон ПОД элементом: первый непрозрачный background-color у предка */
let n = el.parentElement, bg = null;
while (n && n !== document.documentElement) {
const b = getComputedStyle(n).backgroundColor;
const c = b.match(/rgba?\(([^)]+)\)/);
if (c) {
const p = c[1].split(/[\s,\/]+/).filter(Boolean).map(Number);
if ((p.length > 3 ? p[3] : 1) > 0.5) { bg = p.slice(0, 3); break; }
}
n = n.parentElement;
}
if (!bg) {
const c = getComputedStyle(document.body).backgroundColor.match(/rgba?\(([^)]+)\)/);
bg = c ? c[1].split(/[\s,\/]+/).filter(Boolean).map(Number).slice(0, 3) : [255, 255, 255];
}
return {
bg,
computed: { boxShadow: s.boxShadow, textShadow: s.textShadow, filter: s.filter, backdropFilter: s.backdropFilter, outline: s.outline, border: s.border, ownBg: s.backgroundColor }
};
});
const file = path.join(SHOTS, `${spec.file}.png`);
if (spec.shadowOnly) {
return { name: spec.name, margin: 0, rect: { w: Math.round(box.w), h: Math.round(box.h) }, bg: info.bg,
computed: info.computed, shadowLayers: shadowLayers(info.computed.boxShadow),
halo: { kind: 'n/a', note: spec.shadowOnly } };
}
const buf = await page.screenshot({
clip: { x: Math.round(box.x - mMax), y: Math.round(box.y - mMax), width: Math.round(box.w + mMax * 2), height: Math.round(box.h + mMax * 2) },
animations: 'disabled'
});
fs.writeFileSync(file, buf);
const img = png.decode(buf);
/* адаптивный отступ: берём наибольший, при котором дальнее поле каждой стороны
действительно фон (иначе соседние карточки/панель искажают базу). Если ни один
не прошёл — меряем с requireFar:false и помечаем замер как unreliable. */
let meas = null, m = mMax, tried = [];
for (const cand of [mMax, Math.min(mMax, 16), Math.min(mMax, 10)]) {
if (cand < 4) continue;
tried.push(cand);
/* элемент в снимке стоит на (mMax, mMax); при меньшем отступе его кромка
отстоит от края снимка на cand px */
const rect = { x: cand, y: cand, w: Math.round(box.w), h: Math.round(box.h) };
/* на отступе ≤8 px дальнего поля нет: кольцо/тень занимает всё поле.
Меряем без фильтра колонок (база — известный фон из DOM). */
const mm = ring.measure(img, rect, { margin: cand, bg: info.bg, requireFar: cand > 8 });
if (mm.kind !== 'unreliable') { meas = mm; m = cand; break; }
if (!meas) { meas = mm; m = cand; }
}
if (meas.kind === 'unreliable') {
const rect = { x: m, y: m, w: Math.round(box.w), h: Math.round(box.h) };
meas = ring.measure(img, rect, { margin: m, bg: info.bg, requireFar: false });
}
return {
name: spec.name, file: path.relative(OUT, file).replace(/\\/g, '/'),
rect: { w: Math.round(box.w), h: Math.round(box.h) }, margin: m, marginsTried: tried, bg: info.bg,
computed: info.computed, shadowLayers: shadowLayers(info.computed.boxShadow),
halo: { kind: meas.kind, bias: meas.bias, d2: meas.d2, d4: meas.d4, d16: meas.d16, dluma4: meas.dluma4, radius: meas.radius, edgeRun: meas.edgeRun, peakNear: meas.peakNear, peak: meas.peak, peakRaw: meas.peakRaw, stats: meas.stats }
};
}
/* ── целевые компоненты ── */
const TARGETS = [
{ name: 'planet-art', selector: '.planet__art', file: 'planet-art', marginCap: 8 },
{ name: 'planet-pill', file: 'planet-pill', selector: '.planet-tag__pill',
shadowOnly: 'под плашкой арт планеты (не заливка) — кольцевой замер по фону неприменим',
prepare: async (p) => { await p.evaluate(() => { const t = document.querySelector('.planet-tag'); if (t) t.classList.add('is-visible'); }); } },
{ name: 'case-card', selector: '.case-card', file: 'case-card' },
{ name: 'case-card-hover', selector: '.case-card', file: 'case-card-hover',
prepare: async (p) => { await p.locator('.case-card').first().hover(); } },
{ name: 'team-card', selector: '.team-card', file: 'team-card' },
{ name: 'btn-primary', selector: '.btn--primary', file: 'btn-primary' },
{ name: 'btn-ghost', selector: '.btn--ghost', file: 'btn-ghost' },
{ name: 'chip-fact', selector: '.chip', file: 'chip-fact' },
{ name: 'segment-chip-selected', selector: '.filters__segments .filter-chip[aria-pressed="true"]', file: 'filter-chip' },
{ name: 'ticker-toggle-on', selector: '#ticker-toggle', file: 'ticker-toggle-on' },
{ name: 'ticker-toggle-off', selector: '#ticker-toggle', file: 'ticker-toggle-off',
prepare: async (p) => {
await p.evaluate(() => { const b = document.getElementById('ticker-toggle'); if (b && b.getAttribute('aria-pressed') === 'true') b.click(); });
await p.waitForTimeout(500);
},
after: async (p) => { await p.evaluate(() => { const b = document.getElementById('ticker-toggle'); if (b && b.getAttribute('aria-pressed') === 'false') b.click(); }); } },
{ name: 'input-focus', selector: '.form-field input', file: 'input-focus',
prepare: async (p) => { await p.locator('.form-field input').first().focus({ force: true }); } },
{ name: 'case-card-focus', selector: '.case-card', file: 'case-card-focus',
prepare: async (p) => { await p.locator('.case-card').first().evaluate((el) => el.focus()); await p.keyboard.press('Shift'); } },
{ name: 'mark-link-hover', selector: '.case-card__link', file: 'mark-link-hover',
prepare: async (p) => { await p.locator('.case-card__link').first().hover(); } }
];
const FIX_TARGETS = [
{ name: 'mark-link-hover', selector: '.case-card__link', file: 'mark-link-hover-after', fix: 'mark-hover-shadow',
prepare: async (p) => { await p.locator('.case-card__link').first().hover(); } },
{ name: 'ticker-toggle-off', selector: '#ticker-toggle', file: 'ticker-toggle-off-after', fix: 'ticker-toggle-ring',
prepare: async (p) => {
await p.evaluate(() => { const b = document.getElementById('ticker-toggle'); if (b && b.getAttribute('aria-pressed') === 'true') b.click(); });
await p.waitForTimeout(400);
} },
{ name: 'case-card-dark', selector: '.case-card', file: 'case-card-dark-after', fix: 'dark-card-edge' }
];
(async () => {
const browser = await chromium.launch({ executablePath: EXEC, args: ['--force-color-profile=srgb', '--disable-lcd-text'] });
const result = { url: URL, when: new Date().toISOString(), margin: MARGIN, runs: [] };
for (const theme of ['light', 'dark']) {
for (const vp of [{ w: 1440, h: 900 }, { w: 820, h: 1000 }, { w: 390, h: 844 }]) {
const ctx = await browser.newContext({
viewport: { width: vp.w, height: vp.h }, deviceScaleFactor: 1,
reducedMotion: 'reduce', colorScheme: 'light'
});
await ctx.addInitScript((t) => {
try { localStorage.setItem('hm-theme', t); localStorage.setItem('hm-ticker', 'on'); localStorage.setItem('hm-cookie', 'rejected'); } catch (e) {}
}, theme);
const page = await ctx.newPage();
await page.goto(URL, { waitUntil: 'load' });
await page.evaluate((t) => {
if (t === 'dark') document.documentElement.setAttribute('data-theme', 'dark');
else document.documentElement.removeAttribute('data-theme');
}, theme);
await page.evaluate(() => document.fonts.ready);
await page.waitForTimeout(600);
const run = { theme, viewport: vp, inventory: null, probes: [], fixes: [] };
run.inventory = await page.evaluate(collectInventory);
run.inventory = run.inventory.map(row => {
const layers = shadowLayers(row.boxShadow);
const bgc = parseColor(row.bg);
const onDark = bgc ? lum(bgc) < 0.1 : false;
return { ...row, layers, onDark, tell: glowTell(layers, onDark) };
});
for (const t of TARGETS) {
const pr = await probe(page, { ...t, file: `${theme}-${vp.w}-${t.file}` });
pr.target = t.name;
run.probes.push(pr);
if (t.after) await t.after(page);
}
for (const f of FIX_TARGETS) {
const tag = await page.addStyleTag({ content: FIXES[f.fix] });
await page.waitForTimeout(120);
const pr = await probe(page, { ...f, file: `${theme}-${vp.w}-${f.file}` });
if (pr.skipped) { run.fixes.push({ target: f.name, skipped: pr.skipped }); }
else { pr.target = f.name; pr.fix = f.fix; run.fixes.push(pr); }
await page.evaluate((el) => el.remove(), tag).catch(() => {});
await page.waitForTimeout(80);
}
result.runs.push(run);
await ctx.close();
}
}
fs.writeFileSync(path.join(OUT, 'audit.json'), JSON.stringify(result, null, 2));
await browser.close();
/* краткая сводка в stdout */
for (const run of result.runs) {
const tells = run.inventory.filter(r => r.tell);
console.log(`\n=== ${run.theme} ${run.viewport.w}px — inventory rows: ${run.inventory.length}, glow-tells: ${tells.length}`);
for (const t of tells) console.log(' TELL', t.el, '→', t.tell, '| bg', t.bg);
for (const p of run.probes) {
if (p.skipped) { console.log(` · ${p.target}: skipped — ${p.skipped}`); continue; }
const h = p.halo;
if (h.kind === 'n/a') { console.log(` · ${p.target}: shadow-only — ${h.note} | ${(p.computed.boxShadow || '').slice(0, 90)}`); continue; }
console.log(` · ${p.target}: kind=${h.kind} m=${p.margin} d4[t/r/b/l]=${h.d4.top}/${h.d4.right}/${h.d4.bottom}/${h.d4.left} dluma4=${h.dluma4.top} bias=${h.bias} radius=${h.radius.top}/${h.radius.bottom} kept=${h.stats.top.kept}/${h.stats.top.total}`);
}
for (const p of run.fixes) {
if (p.skipped) { console.log(` ~ ${p.target} (after ${p.fix}): skipped — ${p.skipped}`); continue; }
const h = p.halo;
console.log(` ~ ${p.target} (after ${p.fix}): kind=${h.kind} d4=${h.d4.top}/${h.d4.right}/${h.d4.bottom}/${h.d4.left} radius=${h.radius.top}/${h.radius.bottom}`);
}
}
})().catch(e => { console.error(e); process.exit(1); });