ShtukbaseStandard
файл пакета→ .shtukbase/packages/design-tokens/test/contract.test.ts

test/contract.test.ts

193 строки, 11.8 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // The token contract v1 and its check `contract` (DTK-R03): the data, the reader other packages call, passing and failing
  2. // style fixtures, the project's choice, `--css`, and the style build. Run: `bun test` in the package.
  3. import { afterAll, describe, expect, test } from 'bun:test';
  4. import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
  5. import { tmpdir } from 'node:os';
  6. import { dirname, join } from 'node:path';
  7. import { buildStyle } from '../actions/build.ts';
  8. import { check } from '../checks/contract.ts';
  9. import { checkCss, defaultsCss, fallbackLine, fallbacks, parseContract, readContract, styleChoice, styleCssPath } from '../lib/contract.ts';
  10. const pkg = join(import.meta.dir, '..');
  11. const fixture = (n: string) => readFileSync(join(import.meta.dir, 'fixtures', n), 'utf8');
  12. const tmps: string[] = [];
  13. function project(files: Record<string, string>): string {
  14. const dir = mkdtempSync(join(tmpdir(), 'dtk-contract-'));
  15. tmps.push(dir);
  16. for (const [rel, text] of Object.entries(files)) {
  17. mkdirSync(dirname(join(dir, rel)), { recursive: true });
  18. writeFileSync(join(dir, rel), text);
  19. }
  20. return dir;
  21. }
  22. afterAll(() => { for (const d of tmps) rmSync(d, { recursive: true, force: true }); });
  23. const contract = readContract(project({}));
  24. const designPage = (style: string) => `---\ntype: Page\ntitle: Design\nstyle: ${style}\nlibraries: []\n---\n`;
  25. describe('the contract data', () => {
  26. test('the page copy equals the packaged contract', () => {
  27. expect(readFileSync(join(pkg, 'pages/design/contract.json'), 'utf8')).toBe(readFileSync(join(pkg, 'lib/contract.json'), 'utf8'));
  28. });
  29. test('required names: the shadcn theme; colours are the required names with a dark value', () => {
  30. const r = new Set(contract.required);
  31. for (const n of ['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', 'radius'])
  32. expect(r.has(`--${n}`)).toBe(true);
  33. expect(contract.required.length).toBe(32);
  34. expect(contract.colors.length).toBe(31);
  35. expect(contract.colors.every((n) => r.has(n))).toBe(true);
  36. for (const n of ['--radius', '--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.colors).not.toContain(n);
  37. for (const n of ['--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.required).not.toContain(n);
  38. });
  39. test('the extension has --font-display, 12 hues with -soft/-tint/-ink and the sb names, all with a default', () => {
  40. const e = Object.keys(contract.extension);
  41. expect(e).toContain('--font-display');
  42. for (let i = 1; i <= 12; i++) for (const s of ['', '-soft', '-tint', '-ink']) expect(e).toContain(`--sb-hue-${i}${s}`);
  43. for (const n of ['--sb-shadow-lift', '--sb-shadow-sheet', '--sb-glow', '--sb-edge', '--sb-ease', '--sb-dur']) expect(e).toContain(n);
  44. expect(e.length).toBe(5 + 1 + 48 + 6);
  45. for (const n of ['--font-sans', '--font-mono', '--shadow-sm', '--shadow-md', '--shadow-lg']) expect(contract.extension[n]).toBeTruthy();
  46. expect(contract.extension['--font-display']).toBe('var(--font-sans)');
  47. });
  48. test('parseContract names the problem of a bad contract', () => {
  49. expect(parseContract(null).problem).toMatch(/not a JSON object/);
  50. expect(parseContract({ version: 1, required: ['card'], colors: [], extension: {} }).problem).toMatch(/required/);
  51. expect(parseContract({ version: 1, required: ['--a'], colors: ['--b'], extension: {} }).problem).toMatch(/not required/);
  52. expect(parseContract({ version: 1, required: ['--a'], colors: ['--a'], extension: { '--x': '' } }).problem).toMatch(/extension/);
  53. expect(parseContract({ version: 1, required: ['--a'], colors: ['--a'], extension: { '--x': '1px' } }).problem).toBeNull();
  54. });
  55. test("the project's own /design/contract.json wins when valid; a broken one falls back to the packaged", () => {
  56. const own = { version: 1, required: ['--a'], colors: ['--a'], extension: {} };
  57. expect(readContract(project({ 'design/contract.json': JSON.stringify(own) })).required).toEqual(['--a']);
  58. expect(readContract(project({ 'design/contract.json': '{ not json' })).required.length).toBe(32);
  59. });
  60. });
  61. describe('checkCss', () => {
  62. test('a style that meets the contract passes', () => {
  63. expect(checkCss(fixture('pass.css'), 'pass.css', contract)).toEqual([]);
  64. });
  65. test('missing names are named, in :root and in the dark scheme', () => {
  66. const out = checkCss(fixture('fail-missing.css'), 'f.css', contract);
  67. expect(out).toContain('f.css: :root has no --ring');
  68. expect(out).toContain('f.css: the dark scheme has no --card');
  69. expect(out).toContain('f.css: the dark scheme has no --sidebar-ring');
  70. expect(out.length).toBe(3);
  71. });
  72. test('no dark scheme at all is one finding', () => {
  73. const out = checkCss(fixture('fail-no-dark.css'), 'f.css', contract);
  74. expect(out.length).toBe(1);
  75. expect(out[0]).toMatch(/no dark scheme/);
  76. });
  77. test('[data-theme="dark"] alone, and a prefers-color-scheme: dark block, count as the dark scheme', () => {
  78. const pass = fixture('pass.css');
  79. expect(checkCss(pass.replace('.dark, [data-theme="dark"]', '[data-theme="dark"]'), 'a.css', contract)).toEqual([]);
  80. expect(checkCss(pass.replace('.dark, [data-theme="dark"] {', '@media (prefers-color-scheme: dark) {\n:root {').replace(/\}\n$/, '}\n}\n'), 'b.css', contract)).toEqual([]);
  81. });
  82. test('light-dark() in the light value carries the dark value', () => {
  83. const light = fixture('fail-no-dark.css').replace(/(--card): [^;]+;/, '$1: light-dark(white, black);');
  84. const dark = ':root {} .dark { --background: black; }';
  85. const out = checkCss(`${light}\n${dark}`, 'l.css', contract);
  86. expect(out).not.toContain('l.css: the dark scheme has no --card');
  87. expect(out).toContain('l.css: the dark scheme has no --foreground');
  88. });
  89. test('a colour that refers to a variable that does not exist is a finding', () => {
  90. const css = fixture('pass.css').replace(/(--primary): [^;]+;/, '$1: var(--nope);');
  91. expect(checkCss(css, 'v.css', contract)).toEqual(['v.css: light scheme: --primary refers to a variable that does not exist']);
  92. });
  93. test('a variable that resolves inside the stylesheet is fine', () => {
  94. const css = fixture('pass.css').replace(/(--sidebar): [^;]+;/, '$1: var(--card);');
  95. expect(checkCss(css, 'r.css', contract)).toEqual([]);
  96. });
  97. });
  98. describe('the extension fallbacks', () => {
  99. test('a style with no extension falls back to every default; the note groups the hues', () => {
  100. const miss = fallbacks(fixture('pass.css'), contract);
  101. expect(miss.length).toBe(55);
  102. expect(fallbackLine(miss)).toBe('--font-display, --sb-shadow-lift, --sb-shadow-sheet, --sb-glow, --sb-edge, --sb-ease, --sb-dur, --sb-hue-1 … --sb-hue-12 with -soft, -tint, -ink (48 names)');
  103. });
  104. test('names the style sets are not fallbacks', () => {
  105. const css = `${fixture('pass.css')}\n:root { --font-display: Outfit; --sb-glow: 0 0 0 1px red; }`;
  106. const miss = fallbacks(css, contract);
  107. expect(miss).not.toContain('--font-display');
  108. expect(miss).not.toContain('--sb-glow');
  109. expect(miss).toContain('--sb-edge');
  110. });
  111. test('defaultsCss writes the defaults of the missing names', () => {
  112. const css = defaultsCss(['--font-display', '--sb-dur', '--card'], contract);
  113. expect(css).toBe(':root {\n --font-display: var(--font-sans);\n --sb-dur: 160ms;\n}\n');
  114. expect(defaultsCss([], contract)).toBe('');
  115. });
  116. });
  117. describe('the check in a project', () => {
  118. test('no style chosen: silent', () => {
  119. expect(check(project({ 'design/design.md': designPage('""') }))).toEqual({ findings: [], notes: [] });
  120. expect(check(project({}))).toEqual({ findings: [], notes: [] });
  121. });
  122. test('the chosen style is read from /design/design.md', () => {
  123. const root = project({ 'design/design.md': designPage('demo-style'), 'design/demo-style/tokens.css': fixture('pass.css') });
  124. expect(styleChoice(root)).toEqual({ style: 'demo-style', libraries: [] });
  125. expect(styleCssPath(root)).toBe('design/demo-style/tokens.css');
  126. const r = check(root);
  127. expect(r.findings).toEqual([]);
  128. expect(r.notes.length).toBe(1);
  129. expect(r.notes[0]).toMatch(/^note: design\/demo-style\/tokens\.css leaves out optional names;.*--font-display/);
  130. });
  131. test('the libraries list is read', () => {
  132. const root = project({ 'design/design.md': '---\ntype: Page\nstyle: s\nlibraries: [ui-html, ui-react]\n---\n' });
  133. expect(styleChoice(root).libraries).toEqual(['ui-html', 'ui-react']);
  134. });
  135. test('a chosen style with no tokens.css is a finding', () => {
  136. const r = check(project({ 'design/design.md': designPage('demo-style') }));
  137. expect(r.findings.length).toBe(1);
  138. expect(r.findings[0]).toMatch(/^design\/demo-style\/tokens\.css: the file is missing/);
  139. });
  140. test('a chosen style that misses names fails', () => {
  141. const r = check(project({ 'design/design.md': designPage('demo-style'), 'design/demo-style/tokens.css': fixture('fail-missing.css') }));
  142. expect(r.findings.length).toBe(3);
  143. });
  144. test('a style with no extension but all of the extension set has no note', () => {
  145. const ext = Object.entries(contract.extension).map(([k, v]) => ` ${k}: ${v};`).join('\n');
  146. const root = project({ 'design/design.md': designPage('s'), 'design/s/tokens.css': `${fixture('pass.css')}\n:root {\n${ext}\n}\n` });
  147. expect(check(root)).toEqual({ findings: [], notes: [] });
  148. });
  149. test('--css judges a file by hand; a relative path is from the project root', () => {
  150. const root = project({ 'themes/x.css': fixture('fail-no-dark.css') });
  151. expect(check(root, 'themes/x.css').findings.length).toBe(1);
  152. const run = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css', 'themes/x.css'], { cwd: root });
  153. expect(run.exitCode).toBe(1);
  154. expect(run.stdout.toString()).toMatch(/themes\/x\.css: no dark scheme/);
  155. const ok = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css', 'themes/ok.css'], { cwd: project({ 'themes/ok.css': fixture('pass.css') }) });
  156. expect(ok.exitCode).toBe(0);
  157. expect(ok.stdout.toString()).toMatch(/^note: /);
  158. const bare = Bun.spawnSync(['bun', join(pkg, 'checks/contract.ts'), '--css'], { cwd: root });
  159. expect(bare.exitCode).toBe(1);
  160. });
  161. });
  162. describe('building a style', () => {
  163. const tokens = {
  164. $type: 'color',
  165. background: { $value: '#ffffff' },
  166. sb: { hue: { 1: { $value: '#aa3366' } } },
  167. radius: { $type: 'dimension', $value: { value: 0.5, unit: 'rem' } },
  168. 'font-sans': { $type: 'fontFamily', $value: ['Inter', 'sans-serif'] },
  169. };
  170. const dark = { background: { $value: '#000000' }, sb: { hue: { 1: { $value: '#ff77aa' } } } };
  171. test('buildStyle writes /design/<id>/tokens.css with contract names and the dark scheme on both selectors', () => {
  172. const root = project({ 'design/demo/tokens.json': JSON.stringify(tokens), 'design/demo/tokens.dark.json': JSON.stringify(dark) });
  173. const r = buildStyle('demo', root);
  174. expect(r.ok).toBe(true);
  175. const css = readFileSync(join(root, 'design/demo/tokens.css'), 'utf8');
  176. expect(css).toContain(' --background: #ffffff;');
  177. expect(css).toContain(' --sb-hue-1: #aa3366;');
  178. expect(css).toContain(' --font-sans: Inter, sans-serif;');
  179. expect(css).toContain('.dark, [data-theme="dark"] {\n --background: #000000;');
  180. });
  181. test('invalid tokens write nothing', () => {
  182. const root = project({ 'design/demo/tokens.json': JSON.stringify({ a: { $type: 'color', $value: 'red' } }), 'design/demo/tokens.dark.json': '{}' });
  183. const r = buildStyle('demo', root);
  184. expect(r.ok).toBe(false);
  185. expect(r.message).toMatch(/not built/);
  186. });
  187. });