archivo del paquete→ .shtukbase/packages/shtukbase-style/checks/shadow-even.ts
checks/shadow-even.ts
48 líneas, 2.7 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // SBS-R04. Edges and shadows are even on all sides: a `box-shadow` (and `filter: drop-shadow`) is not pushed to one
- // side. Every layer written with numbers has an offset of at most 1 px on both axes; layers that are a var(--…) are
- // fine (the style's own tokens are built that way). A shadow pushed down by 4 px, or pulled in with a negative
- // spread so that only the bottom shows, is a violation. Lengths in px, rem and em are read; others are skipped.
- import { splitTop } from '../../design-base/lib/css.ts';
- import { report } from '../../design-base/lib/files.ts';
- import { type Unit, allUnits, lenPx } from '../lib/scan.ts';
- export const RULE = { id: 'sbs-r04', title: 'Shadows are even on all sides' };
- export const MAX_OFFSET_PX = 1;
- /** The layers of a shadow value with their two offsets in px; layers that are not plain numbers are left out. */
- export function offsets(value: string): { layer: string; x: number; y: number }[] {
- const out: { layer: string; x: number; y: number }[] = [];
- for (const layer of splitTop(value.replace(/\s+/g, ' ').trim(), ',')) {
- if (/^(none|inherit|initial|unset|revert)$/i.test(layer) || /^var\(/.test(layer)) continue;
- // Take the lengths that stand outside of parentheses: colours like rgb(15 15 15 / .1) must not be read as lengths.
- let depth = 0, flat = '';
- for (const c of layer) { if (c === '(') depth++; else if (c === ')') depth--; else if (depth === 0) flat += c; }
- const lens = flat.split(' ').filter((t) => /^-?\d*\.?\d+(px|rem|em)?$/.test(t));
- if (lens.length < 2) continue;
- const x = lenPx(lens[0]), y = lenPx(lens[1]);
- if (x !== null && y !== null) out.push({ layer: layer.trim(), x, y });
- }
- return out;
- }
- export function checkUnits(units: Unit[]): string[] {
- const out: string[] = [];
- for (const u of units) {
- for (const d of u.decls) {
- let value: string | null = null;
- if (d.prop === 'box-shadow') value = d.value;
- else if (d.prop === 'filter' || d.prop === 'backdrop-filter') value = [...d.value.matchAll(/drop-shadow\(((?:[^()]|\([^()]*\))*)\)/gi)].map((m) => m[1]).join(', ') || null;
- if (!value || u.allowed(d.line)) continue;
- for (const o of offsets(value))
- if (Math.abs(o.x) > MAX_OFFSET_PX || Math.abs(o.y) > MAX_OFFSET_PX)
- out.push(`${u.file}:${d.line}: shadow "${o.layer.slice(0, 70)}" is pushed ${Math.abs(o.y) > MAX_OFFSET_PX ? (o.y > 0 ? 'down' : 'up') : o.x > 0 ? 'right' : 'left'} by ${Math.max(Math.abs(o.x), Math.abs(o.y))} px — an edge or a shadow is even on all sides: offset 0, or use var(--sb-edge), var(--sb-shadow-sheet)`);
- }
- }
- return out;
- }
- export function check(): string[] {
- return checkUnits(allUnits());
- }
- if (import.meta.main) report(check());