Files
Harvey_Team_Page/design/halo-audit-2026-11-10/lib/ring.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

162 lines
7.7 KiB
JavaScript

'use strict';
/* ring.cjs — измерение «ореола» по пикселям вокруг прямоугольника.
Метод: элемент снимается вместе с полем m px со всех сторон. Для каждой стороны
берётся полоса на расстоянии d от кромки. Колонка полосы участвует в замере,
только если на дальнем поле (d = m-2 … m) её цвет совпадает с ожидаемым фоном
под элементом (ancestor background, передаётся из DOM) — так из замера
выкидываются соседние карточки, чипы и текст, которые иначе дают ложные дельты.
Для каждой стороны: медиана цвета по оставшимся колонкам, дельта к ожидаемому
фону (максимум по каналам, 0…255) и знак по яркости:
Δluma > 0 — полоса ТЕМНЕЕ фона (тень), Δluma < 0 — СВЕТЛЕЕ (свечение).
Разделение случаев:
• контактная тень — дельта сосредоточена снизу (top/bottom ≪ 1), спад быстрый;
• ореол/гало — дельта примерно равна со всех сторон, спад медленный.
*/
const { px } = require('./png.cjs');
function median(arr) {
if (!arr.length) return null;
const a = arr.slice().sort((x, y) => x - y);
const m = a.length >> 1;
return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
}
function luma(c) { return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; }
function maxDelta(a, b) { return Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]), Math.abs(a[2] - b[2])); }
function near(a, b, tol) { return maxDelta(a, b) <= tol; }
function r2(v) { return v == null ? null : Math.round(v * 100) / 100; }
/* rect — {x,y,w,h} в пикселях снимка; img — {width,height,data} из png.cjs */
function measure(img, rect, opts) {
opts = opts || {};
const m = opts.margin || 40;
const bg = opts.bg || null; // ожидаемый фон [r,g,b] под элементом
const tol = opts.tol == null ? 3 : opts.tol;
const inset = 0.2; // углы исключены: там встречаются две тени
function columns(side) {
const cols = [];
if (side === 'top' || side === 'bottom') {
const x0 = Math.ceil(rect.x + rect.w * inset), x1 = Math.floor(rect.x + rect.w * (1 - inset));
for (let x = x0; x < x1; x++) {
const samples = [];
for (let d = 1; d <= m; d++) {
const y = side === 'top' ? rect.y - d : rect.y + rect.h + d - 1;
samples.push(px(img, x, y));
}
cols.push(samples);
}
} else {
const y0 = Math.ceil(rect.y + rect.h * inset), y1 = Math.floor(rect.y + rect.h * (1 - inset));
for (let y = y0; y < y1; y++) {
const samples = [];
for (let d = 1; d <= m; d++) {
const x = side === 'left' ? rect.x - d : rect.x + rect.w + d - 1;
samples.push(px(img, x, y));
}
cols.push(samples);
}
}
return cols;
}
const sides = ['top', 'right', 'bottom', 'left'];
const profile = {}, stats = {};
for (const s of sides) {
const cols = columns(s);
const kept = cols.filter(c => {
if (!bg || opts.requireFar === false) return true;
const far = c.slice(Math.max(0, m - 1)); // d = m-1 … m
return far.every(p1 => near(p1, bg, tol));
});
stats[s] = { kept: kept.length, total: cols.length, reliable: cols.length ? kept.length / cols.length >= 0.4 : false };
profile[s] = [];
for (let d = 1; d <= m; d++) {
const cr = median(kept.map(c => c[d - 1][0]));
const cg = median(kept.map(c => c[d - 1][1]));
const cb = median(kept.map(c => c[d - 1][2]));
const has = cr != null;
const color = has ? [cr, cg, cb] : null;
const base = bg || color;
profile[s].push({
d,
color: color && color.map(Math.round),
delta: has && base ? r2(maxDelta(color, base)) : null,
dluma: has && base ? r2(luma(base) - luma(color)) : null
});
}
}
const at = (s, d) => profile[s].find(p => p.d === d) || { delta: null, dluma: null };
/* d=1 не используем: при дробном положении элемента кромка попадает в полосу
(субпиксельное округление) — начинаем с d=2 */
const START = 2;
const radius = (s) => {
let r = 0;
for (const p of profile[s]) if (p.d >= START && p.delta != null && p.delta >= 1) r = p.d;
return r;
};
/* локальный спад: идём от кромки наружу, пока дельта ≥2 (пропускаем не более
2 промахов подряд). Всё, что дальше, — соседний блок, а не тень элемента. */
const edgeRun = (s) => {
let run = 0, misses = 0, hit = false;
for (const p of profile[s]) {
if (p.d < START) continue;
if (p.delta != null && p.delta >= 2) { run = p.d; misses = 0; hit = true; }
else if (hit) { if (++misses > 2) break; }
else if (p.d > START + 1) break;
}
return run;
};
const peakLocal = (s) => {
const lim = Math.max(edgeRun(s), START);
return profile[s].filter(p => p.d >= START && p.d <= lim && p.delta != null)
.reduce((a, p) => (a.delta == null || p.delta > a.delta) ? p : a, { d: 0, delta: null, dluma: null });
};
const peak = (s) => profile[s].filter(p => p.d >= START)
.reduce((a, p) => (p.delta != null && (a.delta == null || p.delta > a.delta)) ? p : a, { d: 0, delta: null, dluma: null });
const d2 = Object.fromEntries(sides.map(s => [s, at(s, 2).delta]));
const d4 = Object.fromEntries(sides.map(s => [s, at(s, 4).delta]));
const d16 = Object.fromEntries(sides.map(s => [s, at(s, 16).delta]));
const dluma4 = Object.fromEntries(sides.map(s => [s, at(s, 4).dluma]));
const nums = Object.values(d4).filter(v => v != null);
const maxD4 = nums.length ? Math.max(...nums) : 0;
const minD4 = nums.length ? Math.min(...nums) : 0;
const allReliable = sides.every(s => stats[s].reliable);
let kind;
if (!allReliable) kind = 'unreliable';
else if (maxD4 < 2) kind = 'none';
else {
const lighter = Object.values(dluma4).every(v => v != null && v < 0);
const bias = d4.bottom ? d4.top / d4.bottom : null;
const symmetric = minD4 >= maxD4 * 0.5;
if (lighter && symmetric) kind = 'glow';
else if (bias != null && bias < 0.5) kind = 'contact-shadow';
else if (symmetric) kind = 'halo';
else kind = 'mixed';
}
return {
margin: m, bg, profile, stats,
radius: Object.fromEntries(sides.map(s => [s, radius(s)])),
edgeRun: Object.fromEntries(sides.map(s => [s, edgeRun(s)])),
d2,
/* пик только в ближней зоне (2…6 px): за её пределами в кадр попадают соседи */
peakNear: Object.fromEntries(sides.map(s => [s, (() => {
const q = profile[s].filter(p => p.d >= START && p.d <= 6 && p.delta != null)
.reduce((a, p) => (a.delta == null || p.delta > a.delta) ? p : a, { d: 0, delta: null });
return { d: q.d, delta: r2(q.delta) };
})()])),
peak: Object.fromEntries(sides.map(s => [s, { d: peakLocal(s).d, delta: r2(peakLocal(s).delta), dluma: peakLocal(s).dluma }])),
peakRaw: Object.fromEntries(sides.map(s => [s, { d: peak(s).d, delta: r2(peak(s).delta) }])),
d4, d16, dluma4, kind,
bias: (d4.bottom && d4.top != null) ? r2(d4.top / d4.bottom) : null
};
}
module.exports = { measure, maxDelta, luma };