package file→ .shtukbase/packages/shtukbase-style/checks/card-ratio.ts
checks/card-ratio.ts
47 lines, 2.5 KB.
- // SBS-R03. A card is at most 3:1: a card that is longer than that is a row of a list. The check reads CSS rules whose
- // selector names a card (a class or a data-slot containing "card") and style="…" of such elements; it sees
- // `aspect-ratio` and a fixed `width` with a fixed `height` in px, rem or em. A size with var(), %, calc() or auto
- // cannot be judged by text and is skipped (a person sees it in the catalog).
- import { report } from '../../design-base/lib/files.ts';
- import { type Unit, allUnits, lenPx } from '../lib/scan.ts';
- export const RULE = { id: 'sbs-r03', title: 'A card is at most 3:1' };
- export const MAX = 3;
- // A card itself, not its parts: `.card`, `.pkg-card`, `[data-slot=card]`, but not `.card-header`.
- const CARD = /(?:\.|#|\b)(?:[\w-]*-)?card(?![\w-])|\[data-slot[~|^$*]?=["']?(?:[\w-]*-)?card["'\]\s]/i;
- /** The last compound of a selector is the element the rule is about: `.card .icon` is an icon, not a card. */
- const subject = (s: string) => s.trim().split(/\s*[>+~]\s*|\s+/).pop() ?? '';
- const isCard = (u: Unit) =>
- u.selectors.some((s) => CARD.test(subject(s))) ||
- (u.tag !== undefined && (u.classes ?? []).some((c) => /(^|[-_])card$/i.test(c))) ||
- /(^|-)card$/.test(u.slot ?? '');
- function ratioOf(v: string): number | null {
- const m = /^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/.exec(v.trim().replace(/^auto\s+/, ''));
- if (!m) return null;
- const a = Number(m[1]), b = m[2] === undefined ? 1 : Number(m[2]);
- return a > 0 && b > 0 ? a / b : null;
- }
- export function checkUnits(units: Unit[]): string[] {
- const out: string[] = [];
- for (const u of units) {
- if (!isCard(u)) continue;
- const get = (p: string) => u.decls.find((d) => d.prop === p);
- const say = (line: number, r: number, how: string) => { if (!u.allowed(line)) out.push(`${u.file}:${line}: card ${how} is ${r >= 1 ? `${r.toFixed(1)}:1` : `1:${(1 / r).toFixed(1)}`} — a card is at most ${MAX}:1 (a longer one is a row of a list)`); };
- const ar = get('aspect-ratio');
- const r = ar ? ratioOf(ar.value) : null;
- if (ar && r !== null && (r > MAX || r < 1 / MAX)) say(ar.line, r, `aspect-ratio ${ar.value.trim()}`);
- const w = get('width'), h = get('height');
- const pw = w ? lenPx(w.value) : null, ph = h ? lenPx(h.value) : null;
- if (w && h && pw && ph && (pw / ph > MAX || ph / pw > MAX)) say(Math.min(w.line, h.line), pw / ph, `size ${w.value.trim()} × ${h.value.trim()}`);
- }
- return out;
- }
- export function check(): string[] {
- return checkUnits(allUnits());
- }
- if (import.meta.main) report(check());