archivo del paquete→ .shtukbase/packages/shtukbase-style/test/shtukbase-style.test.ts
test/shtukbase-style.test.ts
283 líneas, 15.9 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The Shtukbase style: its tokens fill the token contract (the list of section 2 of the build contract, or
- // /design/contract.json of design-tokens when that package brings it), are readable and even; the build and the
- // checks work, each with a passing and a failing fixture. Run: `bun test` in the package.
- import { describe, expect, test } from 'bun:test';
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { join } from 'node:path';
- import { loadFolder } from '../../../../shtuk/src/manifest.ts';
- import { contrast, parseColor } from '../../design-base/lib/color.ts';
- import { resolveVars, themes } from '../../design-base/lib/css.ts';
- import { adopt } from '../actions/adopt.ts';
- import { checkUnits as background } from '../checks/background.ts';
- import { checkUnits as cardRatio } from '../checks/card-ratio.ts';
- import { check as fresh } from '../checks/fresh.ts';
- import { checkUnits as shadowEven, offsets } from '../checks/shadow-even.ts';
- import { unitsOf } from '../lib/scan.ts';
- import { buildStyle, DIR } from '../lib/stylelib.ts';
- const PKG = join(import.meta.dir, '..');
- const STYLE = join(PKG, 'pages', DIR);
- const read = (f: string) => readFileSync(join(STYLE, f), 'utf8');
- /** The contract of section 2 of the build contract (design-tokens 0.2.0 brings the same as /design/contract.json). */
- const COLORS = ['background', 'foreground', 'card', 'card-foreground', 'popover', 'popover-foreground', 'primary', 'primary-foreground', 'secondary', 'secondary-foreground', 'muted', 'muted-foreground', 'accent', 'accent-foreground', 'destructive', 'border', 'input', 'ring', 'chart-1', 'chart-2', 'chart-3', 'chart-4', 'chart-5', 'sidebar', 'sidebar-foreground', 'sidebar-primary', 'sidebar-primary-foreground', 'sidebar-accent', 'sidebar-accent-foreground', 'sidebar-border', 'sidebar-ring'];
- const REQUIRED = [...COLORS, 'radius', 'font-sans', 'font-mono', 'shadow-sm', 'shadow-md', 'shadow-lg'];
- const EXTENSION = ['font-display', 'sb-shadow-lift', 'sb-shadow-sheet', 'sb-glow', 'sb-edge', 'sb-ease', 'sb-dur', ...Array.from({ length: 12 }, (_, i) => i + 1).flatMap((n) => [`sb-hue-${n}`, `sb-hue-${n}-soft`, `sb-hue-${n}-tint`, `sb-hue-${n}-ink`])];
- /** A scratch project with the style's pages laid in it. */
- function project(): string {
- const root = mkdtempSync(join(tmpdir(), 'sbs-test-'));
- mkdirSync(join(root, 'design'), { recursive: true });
- for (const f of ['tokens.json', 'tokens.dark.json', 'tokens.css']) {
- mkdirSync(join(root, DIR), { recursive: true });
- writeFileSync(join(root, DIR, f), read(f));
- }
- return root;
- }
- const css = themes([{ rel: 'tokens.css', text: read('tokens.css') }]).themes;
- const light = css.get('base') as Map<string, string>;
- const dark = css.get('dark') as Map<string, string>;
- const val = (vars: Map<string, string>, name: string) => resolveVars(`var(--${name})`, vars);
- const ratio = (vars: Map<string, string>, fg: string, bg: string) => contrast(parseColor(val(vars, fg) as string)!, parseColor(val(vars, bg) as string)!);
- describe('the tokens fill the contract', () => {
- test('the tokens are valid and the build has no problems', () => {
- expect(buildStyle(project()).problems).toEqual([]);
- });
- test('every required name is in the light theme', () => {
- for (const n of REQUIRED) expect(light.has(`--${n}`), n).toBe(true);
- });
- test('every colour name is in the dark theme too', () => {
- for (const n of COLORS) expect(dark.has(`--${n}`), n).toBe(true);
- for (let i = 1; i <= 12; i++) for (const s of ['', '-tint', '-soft', '-ink']) expect(dark.has(`--sb-hue-${i}${s}`), `sb-hue-${i}${s}`).toBe(true);
- });
- test('the dark shadows are set again, so a nested dark block gets its own', () => {
- const d = JSON.parse(read('tokens.dark.json'));
- for (const n of ['shadow-sm', 'shadow-md', 'shadow-lg']) expect(d[n], n).toBeDefined();
- for (const n of ['edge', 'shadow-lift', 'shadow-sheet', 'glow']) expect(d.sb[n], n).toBeDefined();
- });
- test('the extension names are all there', () => {
- for (const n of EXTENSION) expect(light.has(`--${n}`), n).toBe(true);
- });
- test('every value resolves to something real', () => {
- for (const [name, vars] of [['light', light], ['dark', dark]] as const)
- for (const k of vars.keys()) expect(resolveVars(`var(${k})`, vars), `${name} ${k}`).not.toBeNull();
- });
- test('the dark theme is selected by .dark and by [data-theme="dark"]', () => {
- expect(read('tokens.css')).toContain('.dark, [data-theme="dark"] {');
- });
- test('the document is white, the ground of the dark theme is graphite', () => {
- expect(val(light, 'background')).toBe('#ffffff');
- expect(val(dark, 'background')).toBe('#191919');
- });
- test('the twelve hues are in the order of the palette', () => {
- const first = ['#e04a72', '#e85339', '#ef7f16', '#f0ad15', '#61b341', '#01a26f', '#0ca4a0', '#05a0cf', '#2383e2', '#5b64db', '#975cdc', '#cf4eb6'];
- first.forEach((h, i) => expect(val(light, `sb-hue-${i + 1}`)).toBe(h));
- });
- });
- describe('the colours are readable (WCAG, at least 4.5:1)', () => {
- const pairs: [string, string][] = [['foreground', 'background'], ['card-foreground', 'card'], ['popover-foreground', 'popover'], ['primary-foreground', 'primary'], ['secondary-foreground', 'secondary'], ['muted-foreground', 'background'], ['muted-foreground', 'muted'], ['accent-foreground', 'accent'], ['sidebar-foreground', 'sidebar'], ['sidebar-primary-foreground', 'sidebar-primary'], ['sidebar-accent-foreground', 'sidebar-accent']];
- for (const [theme, vars] of [['light', light], ['dark', dark]] as const) {
- test(`${theme}: the pairs of the theme`, () => {
- for (const [fg, bg] of pairs) expect(ratio(vars, fg, bg), `${fg} on ${bg}`).toBeGreaterThanOrEqual(4.5);
- });
- test(`${theme}: text on --primary is white, at 4.5:1 at least (the brand raspberry would give 3.9:1)`, () => {
- expect(val(vars, 'primary-foreground')).toBe('#ffffff');
- expect(ratio(vars, 'primary-foreground', 'primary')).toBeGreaterThanOrEqual(4.5);
- // the failing fixture: white on the brand raspberry, the old --primary
- expect(contrast(parseColor('#ffffff')!, parseColor(val(vars, 'sb-hue-1') as string)!)).toBeLessThan(4.5);
- });
- test(`${theme}: ink on tint and on soft, for each hue`, () => {
- for (let i = 1; i <= 12; i++) for (const s of ['tint', 'soft']) expect(ratio(vars, `sb-hue-${i}-ink`, `sb-hue-${i}-${s}`), `hue ${i} ink on ${s}`).toBeGreaterThanOrEqual(4.5);
- });
- }
- });
- describe('shadows are even (SBS-R04)', () => {
- test('every shadow token has no offset', () => {
- for (const f of ['tokens.json', 'tokens.dark.json']) {
- const walk = (n: any, path: string) => {
- if (!n || typeof n !== 'object') return;
- if (Array.isArray(n.$value) && n.$value.length && n.$value.every((l: any) => l && typeof l === 'object' && 'offsetX' in l))
- for (const l of n.$value) { expect(l.offsetX.value, `${f} ${path}`).toBe(0); expect(l.offsetY.value, `${f} ${path}`).toBe(0); }
- for (const [k, v] of Object.entries(n)) if (!k.startsWith('$')) walk(v, `${path}.${k}`);
- };
- walk(JSON.parse(read(f)), '');
- }
- });
- test('the checks pass on the style\'s own CSS', () => {
- const units = unitsOf('style.css', read('style.css'), false);
- expect(shadowEven(units)).toEqual([]);
- expect(background(units)).toEqual([]);
- expect(cardRatio(units)).toEqual([]);
- });
- test('the built tokens.css has only offset-free shadows', () => {
- const units = unitsOf('tokens.css', read('tokens.css'), false);
- for (const u of units) for (const d of u.decls) if (d.prop.startsWith('--') && /^0px 0px /.test(d.value)) expect(offsets(d.value).every((o) => o.x === 0 && o.y === 0), d.prop).toBe(true);
- });
- });
- describe('build and fresh (SBS-R05)', () => {
- test('the committed tokens.css is what build writes', () => {
- const root = project();
- expect(fresh(root)).toEqual([]);
- });
- test('a hand-edited tokens.css fails', () => {
- const root = project();
- const p = join(root, DIR, 'tokens.css');
- writeFileSync(p, readFileSync(p, 'utf8').replace('--radius: 8px', '--radius: 9px'));
- const found = fresh(root);
- expect(found.length).toBe(1);
- expect(found[0]).toContain('does not match');
- });
- test('a missing tokens.css fails', () => {
- const root = project();
- rmSync(join(root, DIR, 'tokens.css'));
- expect((fresh(root))[0]).toContain('the file is missing');
- });
- test('a changed token needs a rebuild', () => {
- const root = project();
- const p = join(root, DIR, 'tokens.json');
- writeFileSync(p, readFileSync(p, 'utf8').replace('"value": 8,', '"value": 10,'));
- expect((fresh(root)).length).toBe(1);
- });
- test('broken tokens are reported by the build, and fresh stays quiet', () => {
- const root = project();
- writeFileSync(join(root, DIR, 'tokens.json'), '{ "x": ');
- const b = buildStyle(root);
- expect(b.problems.length).toBeGreaterThan(0);
- expect(b.problems[0]).toContain('design/shtukbase-style/tokens.json');
- expect(fresh(root)).toEqual([]);
- });
- test('a project without the style has nothing to check', () => {
- const root = mkdtempSync(join(tmpdir(), 'sbs-test-'));
- expect(fresh(root)).toEqual([]);
- });
- });
- describe('SBS-R01: the document is white', () => {
- const css = (t: string) => unitsOf('a.css', t, false);
- test('white and the token pass', () => {
- expect(background(css('body { background: var(--background); } html { background-color: #fff; } :root { background: white; }'))).toEqual([]);
- });
- test('a grey body fails', () => {
- const f = background(css('body {\n background: #fafaf9;\n}'));
- expect(f.length).toBe(1);
- expect(f[0]).toContain('a.css:2');
- });
- test('dots and gradients on the document fail', () => {
- expect(background(css('body { background: #fff radial-gradient(circle, #ddd 1px, transparent 1px) 0 0/22px 22px; }')).length).toBe(1);
- expect(background(css('html { background-image: linear-gradient(red, blue); }')).length).toBe(1);
- });
- test('a canvas element, another selector and the dark theme pass', () => {
- expect(background(css('.sb-canvas { background: #eee; } .dark body { background: #191919; } @media (prefers-color-scheme: dark) { body { background: #000; } }'))).toEqual([]);
- });
- test('HTML: a <style> block and an attribute on body', () => {
- const html = '<html><head><style>\nbody { background: #f3f3f3 }\n</style></head>\n<body style="background: #eee"><p>x</p></body></html>';
- const f = background(unitsOf('a.html', html, true));
- expect(f.length).toBe(2);
- expect(f[0]).toContain('a.html:2');
- expect(f[1]).toContain('a.html:4');
- });
- test('the allow marker skips a line', () => {
- expect(background(css('body {\n background: #eee; /* shtukbase-style: allow */\n}'))).toEqual([]);
- });
- });
- describe('SBS-R03: a card is at most 3:1', () => {
- const css = (t: string) => unitsOf('a.css', t, false);
- test('a 3:1 and a 3:2 card pass', () => {
- expect(cardRatio(css('.card { aspect-ratio: 3 / 1; } .pkg-card { width: 300px; height: 200px; } .card[data-size=s] { aspect-ratio: 1.5; }'))).toEqual([]);
- });
- test('a 4:1 aspect ratio fails', () => {
- const f = cardRatio(css('.card {\n aspect-ratio: 4 / 1;\n}'));
- expect(f.length).toBe(1);
- expect(f[0]).toContain('a.css:2');
- expect(f[0]).toContain('4.0:1');
- });
- test('a fixed 600 x 100 card fails; the tall one fails too', () => {
- expect(cardRatio(css('.card { width: 600px; height: 100px; }')).length).toBe(1);
- expect(cardRatio(css('[data-slot=card] { width: 100px; height: 400px; }')).length).toBe(1);
- });
- test('parts of a card, other elements and unknown sizes are not judged', () => {
- expect(cardRatio(css('.card-header { width: 600px; height: 20px; } .card .icon { width: 600px; height: 10px; } .row { aspect-ratio: 8/1; } .card { width: 100%; height: 10px; }'))).toEqual([]);
- });
- test('HTML: a card element with a long inline size fails', () => {
- const f = cardRatio(unitsOf('a.html', '<div class="pkg-card" style="width: 500px; height: 80px">x</div>', true));
- expect(f.length).toBe(1);
- });
- });
- describe('SBS-R04: shadows even on all sides', () => {
- const css = (t: string) => unitsOf('a.css', t, false);
- test('tokens, a ring and a halo pass', () => {
- expect(shadowEven(css('.a { box-shadow: var(--sb-edge); } .b { box-shadow: 0 0 0 1px rgb(15 15 15 / .06), 0 0 16px rgb(15 15 15 / .05); } .c { box-shadow: none; } .d { box-shadow: inset 0 1px 0 var(--border); }'))).toEqual([]);
- });
- test('a shadow pushed down fails, with the line', () => {
- const f = shadowEven(css('.a {\n box-shadow: 0 4px 12px rgb(0 0 0 / .1);\n}'));
- expect(f.length).toBe(1);
- expect(f[0]).toContain('a.css:2');
- expect(f[0]).toContain('down');
- });
- test('a pulled-in negative spread that shows one side fails', () => {
- expect(shadowEven(css('.a { box-shadow: 0 8px 12px -6px rgb(0 0 0 / .2); }')).length).toBe(1);
- });
- test('a sideways shadow, drop-shadow() and rem offsets fail', () => {
- expect(shadowEven(css('.a { box-shadow: 3px 0 4px #000; }'))[0]).toContain('right');
- expect(shadowEven(css('.a { filter: drop-shadow(0 6px 4px rgb(0 0 0 / .3)); }')).length).toBe(1);
- expect(shadowEven(css('.a { box-shadow: 0 0.5rem 1rem var(--x); }')).length).toBe(1);
- });
- test('only the bad layer of a list is named', () => {
- expect(shadowEven(css('.a { box-shadow: 0 0 0 1px var(--border), 0 10px 20px rgb(0 0 0 / .1); }')).length).toBe(1);
- });
- test('1 px of offset is allowed, the marker skips a line', () => {
- expect(shadowEven(css('.a { box-shadow: 0 1px 2px rgb(0 0 0 / .05); }'))).toEqual([]);
- expect(shadowEven(css('.a { box-shadow: 0 9px 9px #000; } /* shtukbase-style: allow */'))).toEqual([]);
- });
- });
- describe('adopt', () => {
- test('sets the style when the header has none, or an empty one', () => {
- expect(adopt('---\ntitle: D\nstyle: ""\nlibraries: []\n---\nbody\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\nlibraries: []\n---\nbody\n');
- expect(adopt('---\ntitle: D\nstyle:\n---\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\n---\n');
- expect(adopt('---\ntitle: D\n---\nbody\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\n---\nbody\n');
- });
- test('leaves a page that names a style alone', () => {
- expect(adopt('---\nstyle: keer-style\n---\n')).toBeNull();
- expect(adopt('---\nstyle: shtukbase-style\n---\n')).toBeNull();
- });
- test('a page with no header gets one', () => {
- expect(adopt('text\n')).toBe('---\nstyle: shtukbase-style\n---\ntext\n');
- });
- });
- describe('the package', () => {
- test('the manifest loads and every action file exists', () => {
- const p = loadFolder(PKG);
- expect(p.id).toBe('shtukbase-style');
- expect(p.version).toBe('0.1.2');
- expect(p.actions.map((a) => a.name).sort()).toEqual(['adopt', 'background', 'build', 'card-ratio', 'fresh', 'shadow-even']);
- expect(p.requires['design-tokens']).toBe('^0.2.0');
- });
- test('the norms exist, each check names its norm', () => {
- const p = loadFolder(PKG);
- for (const n of ['SBS-R01', 'SBS-R02', 'SBS-R03', 'SBS-R04', 'SBS-R05', 'SBS-R06']) expect(existsSync(join(PKG, 'pages/norms/rules/shtukbase-style', `${n}.md`)), n).toBe(true);
- for (const a of p.actions.filter((x) => x.check)) expect(a.norm, a.name).toBeTruthy();
- });
- test('the assets are there', () => {
- for (const f of ['assets/mark.svg', 'assets/wordmark.svg', 'assets/favicon.svg', 'assets/icons/core.svg', 'fonts.css', 'style.css', 'style.md']) expect(existsSync(join(STYLE, f)), f).toBe(true);
- expect(read('fonts.css')).toContain('SIL Open Font License');
- });
- test('the style CSS uses only tokens for colour', () => {
- expect(read('style.css')).not.toMatch(/#[0-9a-f]{3,8}\b|rgba?\(|hsla?\(|oklch\(/i);
- });
- test('no Cyrillic in the package', () => {
- for (const f of ['package.md', 'style.md', 'surfaces.md', 'mark.md', 'icons.md', 'style.css', 'fonts.css']) {
- const text = existsSync(join(PKG, f)) ? readFileSync(join(PKG, f), 'utf8') : read(f);
- expect(/[а-яА-ЯёЁ]/.test(text), f).toBe(false);
- }
- });
- });