ShtukbaseStandard
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.

  1. // The Shtukbase style: its tokens fill the token contract (the list of section 2 of the build contract, or
  2. // /design/contract.json of design-tokens when that package brings it), are readable and even; the build and the
  3. // checks work, each with a passing and a failing fixture. Run: `bun test` in the package.
  4. import { describe, expect, test } from 'bun:test';
  5. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
  6. import { tmpdir } from 'node:os';
  7. import { join } from 'node:path';
  8. import { loadFolder } from '../../../../shtuk/src/manifest.ts';
  9. import { contrast, parseColor } from '../../design-base/lib/color.ts';
  10. import { resolveVars, themes } from '../../design-base/lib/css.ts';
  11. import { adopt } from '../actions/adopt.ts';
  12. import { checkUnits as background } from '../checks/background.ts';
  13. import { checkUnits as cardRatio } from '../checks/card-ratio.ts';
  14. import { check as fresh } from '../checks/fresh.ts';
  15. import { checkUnits as shadowEven, offsets } from '../checks/shadow-even.ts';
  16. import { unitsOf } from '../lib/scan.ts';
  17. import { buildStyle, DIR } from '../lib/stylelib.ts';
  18. const PKG = join(import.meta.dir, '..');
  19. const STYLE = join(PKG, 'pages', DIR);
  20. const read = (f: string) => readFileSync(join(STYLE, f), 'utf8');
  21. /** The contract of section 2 of the build contract (design-tokens 0.2.0 brings the same as /design/contract.json). */
  22. 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'];
  23. const REQUIRED = [...COLORS, 'radius', 'font-sans', 'font-mono', 'shadow-sm', 'shadow-md', 'shadow-lg'];
  24. 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`])];
  25. /** A scratch project with the style's pages laid in it. */
  26. function project(): string {
  27. const root = mkdtempSync(join(tmpdir(), 'sbs-test-'));
  28. mkdirSync(join(root, 'design'), { recursive: true });
  29. for (const f of ['tokens.json', 'tokens.dark.json', 'tokens.css']) {
  30. mkdirSync(join(root, DIR), { recursive: true });
  31. writeFileSync(join(root, DIR, f), read(f));
  32. }
  33. return root;
  34. }
  35. const css = themes([{ rel: 'tokens.css', text: read('tokens.css') }]).themes;
  36. const light = css.get('base') as Map<string, string>;
  37. const dark = css.get('dark') as Map<string, string>;
  38. const val = (vars: Map<string, string>, name: string) => resolveVars(`var(--${name})`, vars);
  39. const ratio = (vars: Map<string, string>, fg: string, bg: string) => contrast(parseColor(val(vars, fg) as string)!, parseColor(val(vars, bg) as string)!);
  40. describe('the tokens fill the contract', () => {
  41. test('the tokens are valid and the build has no problems', () => {
  42. expect(buildStyle(project()).problems).toEqual([]);
  43. });
  44. test('every required name is in the light theme', () => {
  45. for (const n of REQUIRED) expect(light.has(`--${n}`), n).toBe(true);
  46. });
  47. test('every colour name is in the dark theme too', () => {
  48. for (const n of COLORS) expect(dark.has(`--${n}`), n).toBe(true);
  49. 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);
  50. });
  51. test('the dark shadows are set again, so a nested dark block gets its own', () => {
  52. const d = JSON.parse(read('tokens.dark.json'));
  53. for (const n of ['shadow-sm', 'shadow-md', 'shadow-lg']) expect(d[n], n).toBeDefined();
  54. for (const n of ['edge', 'shadow-lift', 'shadow-sheet', 'glow']) expect(d.sb[n], n).toBeDefined();
  55. });
  56. test('the extension names are all there', () => {
  57. for (const n of EXTENSION) expect(light.has(`--${n}`), n).toBe(true);
  58. });
  59. test('every value resolves to something real', () => {
  60. for (const [name, vars] of [['light', light], ['dark', dark]] as const)
  61. for (const k of vars.keys()) expect(resolveVars(`var(${k})`, vars), `${name} ${k}`).not.toBeNull();
  62. });
  63. test('the dark theme is selected by .dark and by [data-theme="dark"]', () => {
  64. expect(read('tokens.css')).toContain('.dark, [data-theme="dark"] {');
  65. });
  66. test('the document is white, the ground of the dark theme is graphite', () => {
  67. expect(val(light, 'background')).toBe('#ffffff');
  68. expect(val(dark, 'background')).toBe('#191919');
  69. });
  70. test('the twelve hues are in the order of the palette', () => {
  71. const first = ['#e04a72', '#e85339', '#ef7f16', '#f0ad15', '#61b341', '#01a26f', '#0ca4a0', '#05a0cf', '#2383e2', '#5b64db', '#975cdc', '#cf4eb6'];
  72. first.forEach((h, i) => expect(val(light, `sb-hue-${i + 1}`)).toBe(h));
  73. });
  74. });
  75. describe('the colours are readable (WCAG, at least 4.5:1)', () => {
  76. 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']];
  77. for (const [theme, vars] of [['light', light], ['dark', dark]] as const) {
  78. test(`${theme}: the pairs of the theme`, () => {
  79. for (const [fg, bg] of pairs) expect(ratio(vars, fg, bg), `${fg} on ${bg}`).toBeGreaterThanOrEqual(4.5);
  80. });
  81. test(`${theme}: text on --primary is white, at 4.5:1 at least (the brand raspberry would give 3.9:1)`, () => {
  82. expect(val(vars, 'primary-foreground')).toBe('#ffffff');
  83. expect(ratio(vars, 'primary-foreground', 'primary')).toBeGreaterThanOrEqual(4.5);
  84. // the failing fixture: white on the brand raspberry, the old --primary
  85. expect(contrast(parseColor('#ffffff')!, parseColor(val(vars, 'sb-hue-1') as string)!)).toBeLessThan(4.5);
  86. });
  87. test(`${theme}: ink on tint and on soft, for each hue`, () => {
  88. 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);
  89. });
  90. }
  91. });
  92. describe('shadows are even (SBS-R04)', () => {
  93. test('every shadow token has no offset', () => {
  94. for (const f of ['tokens.json', 'tokens.dark.json']) {
  95. const walk = (n: any, path: string) => {
  96. if (!n || typeof n !== 'object') return;
  97. if (Array.isArray(n.$value) && n.$value.length && n.$value.every((l: any) => l && typeof l === 'object' && 'offsetX' in l))
  98. for (const l of n.$value) { expect(l.offsetX.value, `${f} ${path}`).toBe(0); expect(l.offsetY.value, `${f} ${path}`).toBe(0); }
  99. for (const [k, v] of Object.entries(n)) if (!k.startsWith('$')) walk(v, `${path}.${k}`);
  100. };
  101. walk(JSON.parse(read(f)), '');
  102. }
  103. });
  104. test('the checks pass on the style\'s own CSS', () => {
  105. const units = unitsOf('style.css', read('style.css'), false);
  106. expect(shadowEven(units)).toEqual([]);
  107. expect(background(units)).toEqual([]);
  108. expect(cardRatio(units)).toEqual([]);
  109. });
  110. test('the built tokens.css has only offset-free shadows', () => {
  111. const units = unitsOf('tokens.css', read('tokens.css'), false);
  112. 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);
  113. });
  114. });
  115. describe('build and fresh (SBS-R05)', () => {
  116. test('the committed tokens.css is what build writes', () => {
  117. const root = project();
  118. expect(fresh(root)).toEqual([]);
  119. });
  120. test('a hand-edited tokens.css fails', () => {
  121. const root = project();
  122. const p = join(root, DIR, 'tokens.css');
  123. writeFileSync(p, readFileSync(p, 'utf8').replace('--radius: 8px', '--radius: 9px'));
  124. const found = fresh(root);
  125. expect(found.length).toBe(1);
  126. expect(found[0]).toContain('does not match');
  127. });
  128. test('a missing tokens.css fails', () => {
  129. const root = project();
  130. rmSync(join(root, DIR, 'tokens.css'));
  131. expect((fresh(root))[0]).toContain('the file is missing');
  132. });
  133. test('a changed token needs a rebuild', () => {
  134. const root = project();
  135. const p = join(root, DIR, 'tokens.json');
  136. writeFileSync(p, readFileSync(p, 'utf8').replace('"value": 8,', '"value": 10,'));
  137. expect((fresh(root)).length).toBe(1);
  138. });
  139. test('broken tokens are reported by the build, and fresh stays quiet', () => {
  140. const root = project();
  141. writeFileSync(join(root, DIR, 'tokens.json'), '{ "x": ');
  142. const b = buildStyle(root);
  143. expect(b.problems.length).toBeGreaterThan(0);
  144. expect(b.problems[0]).toContain('design/shtukbase-style/tokens.json');
  145. expect(fresh(root)).toEqual([]);
  146. });
  147. test('a project without the style has nothing to check', () => {
  148. const root = mkdtempSync(join(tmpdir(), 'sbs-test-'));
  149. expect(fresh(root)).toEqual([]);
  150. });
  151. });
  152. describe('SBS-R01: the document is white', () => {
  153. const css = (t: string) => unitsOf('a.css', t, false);
  154. test('white and the token pass', () => {
  155. expect(background(css('body { background: var(--background); } html { background-color: #fff; } :root { background: white; }'))).toEqual([]);
  156. });
  157. test('a grey body fails', () => {
  158. const f = background(css('body {\n background: #fafaf9;\n}'));
  159. expect(f.length).toBe(1);
  160. expect(f[0]).toContain('a.css:2');
  161. });
  162. test('dots and gradients on the document fail', () => {
  163. expect(background(css('body { background: #fff radial-gradient(circle, #ddd 1px, transparent 1px) 0 0/22px 22px; }')).length).toBe(1);
  164. expect(background(css('html { background-image: linear-gradient(red, blue); }')).length).toBe(1);
  165. });
  166. test('a canvas element, another selector and the dark theme pass', () => {
  167. expect(background(css('.sb-canvas { background: #eee; } .dark body { background: #191919; } @media (prefers-color-scheme: dark) { body { background: #000; } }'))).toEqual([]);
  168. });
  169. test('HTML: a <style> block and an attribute on body', () => {
  170. const html = '<html><head><style>\nbody { background: #f3f3f3 }\n</style></head>\n<body style="background: #eee"><p>x</p></body></html>';
  171. const f = background(unitsOf('a.html', html, true));
  172. expect(f.length).toBe(2);
  173. expect(f[0]).toContain('a.html:2');
  174. expect(f[1]).toContain('a.html:4');
  175. });
  176. test('the allow marker skips a line', () => {
  177. expect(background(css('body {\n background: #eee; /* shtukbase-style: allow */\n}'))).toEqual([]);
  178. });
  179. });
  180. describe('SBS-R03: a card is at most 3:1', () => {
  181. const css = (t: string) => unitsOf('a.css', t, false);
  182. test('a 3:1 and a 3:2 card pass', () => {
  183. expect(cardRatio(css('.card { aspect-ratio: 3 / 1; } .pkg-card { width: 300px; height: 200px; } .card[data-size=s] { aspect-ratio: 1.5; }'))).toEqual([]);
  184. });
  185. test('a 4:1 aspect ratio fails', () => {
  186. const f = cardRatio(css('.card {\n aspect-ratio: 4 / 1;\n}'));
  187. expect(f.length).toBe(1);
  188. expect(f[0]).toContain('a.css:2');
  189. expect(f[0]).toContain('4.0:1');
  190. });
  191. test('a fixed 600 x 100 card fails; the tall one fails too', () => {
  192. expect(cardRatio(css('.card { width: 600px; height: 100px; }')).length).toBe(1);
  193. expect(cardRatio(css('[data-slot=card] { width: 100px; height: 400px; }')).length).toBe(1);
  194. });
  195. test('parts of a card, other elements and unknown sizes are not judged', () => {
  196. 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([]);
  197. });
  198. test('HTML: a card element with a long inline size fails', () => {
  199. const f = cardRatio(unitsOf('a.html', '<div class="pkg-card" style="width: 500px; height: 80px">x</div>', true));
  200. expect(f.length).toBe(1);
  201. });
  202. });
  203. describe('SBS-R04: shadows even on all sides', () => {
  204. const css = (t: string) => unitsOf('a.css', t, false);
  205. test('tokens, a ring and a halo pass', () => {
  206. 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([]);
  207. });
  208. test('a shadow pushed down fails, with the line', () => {
  209. const f = shadowEven(css('.a {\n box-shadow: 0 4px 12px rgb(0 0 0 / .1);\n}'));
  210. expect(f.length).toBe(1);
  211. expect(f[0]).toContain('a.css:2');
  212. expect(f[0]).toContain('down');
  213. });
  214. test('a pulled-in negative spread that shows one side fails', () => {
  215. expect(shadowEven(css('.a { box-shadow: 0 8px 12px -6px rgb(0 0 0 / .2); }')).length).toBe(1);
  216. });
  217. test('a sideways shadow, drop-shadow() and rem offsets fail', () => {
  218. expect(shadowEven(css('.a { box-shadow: 3px 0 4px #000; }'))[0]).toContain('right');
  219. expect(shadowEven(css('.a { filter: drop-shadow(0 6px 4px rgb(0 0 0 / .3)); }')).length).toBe(1);
  220. expect(shadowEven(css('.a { box-shadow: 0 0.5rem 1rem var(--x); }')).length).toBe(1);
  221. });
  222. test('only the bad layer of a list is named', () => {
  223. expect(shadowEven(css('.a { box-shadow: 0 0 0 1px var(--border), 0 10px 20px rgb(0 0 0 / .1); }')).length).toBe(1);
  224. });
  225. test('1 px of offset is allowed, the marker skips a line', () => {
  226. expect(shadowEven(css('.a { box-shadow: 0 1px 2px rgb(0 0 0 / .05); }'))).toEqual([]);
  227. expect(shadowEven(css('.a { box-shadow: 0 9px 9px #000; } /* shtukbase-style: allow */'))).toEqual([]);
  228. });
  229. });
  230. describe('adopt', () => {
  231. test('sets the style when the header has none, or an empty one', () => {
  232. expect(adopt('---\ntitle: D\nstyle: ""\nlibraries: []\n---\nbody\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\nlibraries: []\n---\nbody\n');
  233. expect(adopt('---\ntitle: D\nstyle:\n---\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\n---\n');
  234. expect(adopt('---\ntitle: D\n---\nbody\n')).toBe('---\ntitle: D\nstyle: shtukbase-style\n---\nbody\n');
  235. });
  236. test('leaves a page that names a style alone', () => {
  237. expect(adopt('---\nstyle: keer-style\n---\n')).toBeNull();
  238. expect(adopt('---\nstyle: shtukbase-style\n---\n')).toBeNull();
  239. });
  240. test('a page with no header gets one', () => {
  241. expect(adopt('text\n')).toBe('---\nstyle: shtukbase-style\n---\ntext\n');
  242. });
  243. });
  244. describe('the package', () => {
  245. test('the manifest loads and every action file exists', () => {
  246. const p = loadFolder(PKG);
  247. expect(p.id).toBe('shtukbase-style');
  248. expect(p.version).toBe('0.1.2');
  249. expect(p.actions.map((a) => a.name).sort()).toEqual(['adopt', 'background', 'build', 'card-ratio', 'fresh', 'shadow-even']);
  250. expect(p.requires['design-tokens']).toBe('^0.2.0');
  251. });
  252. test('the norms exist, each check names its norm', () => {
  253. const p = loadFolder(PKG);
  254. 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);
  255. for (const a of p.actions.filter((x) => x.check)) expect(a.norm, a.name).toBeTruthy();
  256. });
  257. test('the assets are there', () => {
  258. 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);
  259. expect(read('fonts.css')).toContain('SIL Open Font License');
  260. });
  261. test('the style CSS uses only tokens for colour', () => {
  262. expect(read('style.css')).not.toMatch(/#[0-9a-f]{3,8}\b|rgba?\(|hsla?\(|oklch\(/i);
  263. });
  264. test('no Cyrillic in the package', () => {
  265. for (const f of ['package.md', 'style.md', 'surfaces.md', 'mark.md', 'icons.md', 'style.css', 'fonts.css']) {
  266. const text = existsSync(join(PKG, f)) ? readFileSync(join(PKG, f), 'utf8') : read(f);
  267. expect(/[а-яА-ЯёЁ]/.test(text), f).toBe(false);
  268. }
  269. });
  270. });