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

test/design-components.test.ts

345 строк, 20.1 КБ.

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

  1. // sync and the four checks on a scratch project with a fixture library of three components. Run: `bun test` in the package.
  2. import { afterEach, describe, expect, test } from 'bun:test';
  3. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. import { place } from '../actions/place.ts';
  6. import { check as fresh } from '../checks/fresh.ts';
  7. import { check as noLevelUp } from '../checks/no-level-up.ts';
  8. import { check as tokensOnly } from '../checks/tokens-only.ts';
  9. import { check as usesExist } from '../checks/uses-exist.ts';
  10. import { rawColours } from '../lib/css.ts';
  11. import { collect, templatesOf } from '../lib/project.ts';
  12. import { emit } from '../lib/yaml.ts';
  13. import { CARD_HTML, CHIP_HTML, drop, project, put } from './fixture.ts';
  14. const SYNC = join(import.meta.dir, '..', 'actions', 'sync.ts');
  15. const roots: string[] = [];
  16. const make = () => { const r = project(); roots.push(r); return r; };
  17. afterEach(() => { for (const r of roots.splice(0)) drop(r); });
  18. const sync = (root: string, ...args: string[]) => {
  19. const r = Bun.spawnSync([process.execPath, SYNC, ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe' });
  20. return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() };
  21. };
  22. const read = (root: string, rel: string) => readFileSync(join(root, rel), 'utf8');
  23. const json = (root: string, rel: string) => JSON.parse(read(root, rel));
  24. const dataOf = (root: string) => {
  25. const w: Record<string, any> = {};
  26. new Function('window', read(root, 'lib/design/components.data.js'))(w);
  27. return w.SB_COMPONENTS;
  28. };
  29. describe('sync', () => {
  30. test('writes a page per id, joining the HTML and the React implementation', () => {
  31. const root = make();
  32. const r = sync(root);
  33. expect(r.code).toBe(0);
  34. expect(r.out).toContain('3 components (3 html, 1 react)');
  35. for (const id of ['chip', 'card', 'card-grid']) expect(existsSync(join(root, `design/components/${id}.md`))).toBe(true);
  36. const chip = read(root, 'design/components/chip.md');
  37. const fm = Bun.YAML.parse(chip.split('---')[1]) as Record<string, any>;
  38. expect(fm).toMatchObject({
  39. type: 'Component', title: 'Chip', id: 'chip', level: 'primitive', registry: 'registry:ui', description: 'A small label.',
  40. parts: ['chip-label'], states: ['default', 'hover'], status: ['empty'], cssProperties: ['--sb-hue-1'],
  41. html: '/design/fix-ui-html/components/primitive/chip/chip.html', css: '/design/fix-ui-html/components/primitive/chip/chip.css',
  42. react: '/design/fix-ui-react/components/ui/chip.tsx', source: '/design/fix-ui-html/components/primitive/chip/chip.html',
  43. });
  44. expect(fm.controls.tone).toEqual({ kind: 'select', options: ['neutral', 'accent'], default: 'neutral', label: 'Tone' });
  45. const card = Bun.YAML.parse(read(root, 'design/components/card.md').split('---')[1]) as Record<string, any>;
  46. expect(card.uses).toEqual(['/design/components/chip']);
  47. expect(card.react).toBeUndefined();
  48. });
  49. test('keeps the text under the header and the keys an author added; running again changes nothing', () => {
  50. const root = make();
  51. sync(root);
  52. const p = join(root, 'design/components/card.md');
  53. writeFileSync(p, read(root, 'design/components/card.md').replace('\n---\n', '\nowner: me\n---\n') + '\nWhen to use: always.\n');
  54. expect(sync(root).out).toContain('0 files written');
  55. const text = read(root, 'design/components/card.md');
  56. expect(text).toContain('When to use: always.');
  57. expect(text).toContain('owner: me');
  58. expect(text.indexOf('owner: me')).toBeGreaterThan(text.indexOf('source:'));
  59. // the header changes: the page header follows, the body stays
  60. put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('A card with a chip.', 'A card, changed.'));
  61. expect(sync(root).code).toBe(0);
  62. const after = read(root, 'design/components/card.md');
  63. expect(after).toContain('description: "A card, changed."');
  64. expect(after).toContain('When to use: always.');
  65. expect(after).toContain('owner: me');
  66. });
  67. test('lib/design/components.data.js has the shape of section 6', () => {
  68. const root = make();
  69. sync(root);
  70. const d = dataOf(root);
  71. expect(d.version).toBe(1);
  72. expect(d.style).toBe('fixstyle');
  73. expect(d.css).toEqual(['/design/fixstyle/tokens.css', '/lib/design/ui.css']);
  74. expect(d.components.map((c: any) => c.id)).toEqual(['chip', 'card', 'card-grid']); // by level, then id
  75. const chip = d.components[0];
  76. expect(Object.keys(chip).sort()).toEqual(['controls', 'cssProperties', 'description', 'html', 'id', 'level', 'page', 'parts', 'react', 'states', 'status', 'title', 'uses']);
  77. expect(chip.page).toBe('/design/components/chip.md');
  78. expect(chip.html.source).toBe('/design/fix-ui-html/components/primitive/chip/chip.html');
  79. expect(chip.html.css).toBe('/design/fix-ui-html/components/primitive/chip/chip.css');
  80. expect(Object.keys(chip.html.templates)).toEqual(['default', 'hover', 'empty']);
  81. expect(chip.html.templates.default).toBe('<span data-slot="chip" class="chip"><span data-slot="chip-label">Label</span></span>');
  82. expect(chip.react).toEqual({ source: '/design/fix-ui-react/components/ui/chip.tsx', library: 'fix-ui-react' });
  83. expect(d.components[1].react).toBeNull();
  84. expect(d.components[1].uses).toEqual(['chip']);
  85. });
  86. test('custom-elements.json: a module per component, attributes from controls, parts and css properties', () => {
  87. const root = make();
  88. sync(root);
  89. const cem = json(root, 'design/custom-elements.json');
  90. expect(cem.schemaVersion).toBe('2.1.0');
  91. expect(cem.modules.map((m: any) => m.declarations[0].tagName)).toEqual(['chip', 'card', 'card-grid']);
  92. const chip = cem.modules[0].declarations[0];
  93. expect(chip.name).toBe('Chip');
  94. expect(chip.attributes[0]).toEqual({ name: 'data-tone', fieldName: 'tone', type: { text: "'neutral' | 'accent'" }, default: "'neutral'", description: 'Tone' });
  95. expect(chip.attributes[1]).toMatchObject({ name: 'data-soft', type: { text: 'boolean' }, default: 'false' });
  96. expect(chip.attributes.at(-1)).toMatchObject({ name: 'data-status', type: { text: "'empty'" } });
  97. expect(chip.cssProperties).toEqual([{ name: '--sb-hue-1' }]);
  98. expect(chip.cssParts).toEqual([{ name: 'chip-label' }]);
  99. expect(cem.modules[1].declarations[0].attributes[1]).toMatchObject({ name: 'data-gap', type: { text: 'number' }, default: '8' });
  100. });
  101. test('stories: CSF 3 with argTypes from controls and one story per state', async () => {
  102. const root = make();
  103. sync(root);
  104. const text = read(root, 'design/stories/card.stories.js');
  105. expect(text.startsWith('// Generated by design-components sync')).toBe(true);
  106. // load it as a module (a DOM is not needed to read the exports)
  107. const mod = await import(join(root, 'design/stories/card.stories.js'));
  108. expect(mod.default.title).toBe('Composite/Card');
  109. expect(mod.default.argTypes.preset).toEqual({ description: undefined, table: { category: 'Look' }, control: 'select', options: ['base', 'compact', 'cover'] });
  110. expect(mod.default.argTypes.gap.control).toEqual({ type: 'range', min: 0, max: 32, step: 4 });
  111. expect(mod.default.args).toEqual({ preset: 'base', gap: 8 });
  112. expect(Object.keys(mod).filter((k) => k !== 'default')).toEqual(['Default', 'Selected']);
  113. expect(mod.Selected.name).toBe('selected');
  114. const chip = await import(join(root, 'design/stories/chip.stories.js'));
  115. expect(Object.keys(chip).filter((k) => k !== 'default')).toEqual(['Default', 'Hover', 'StatusEmpty']);
  116. expect(chip.default.argTypes.soft.control).toBe('boolean');
  117. });
  118. test('stories render the template and apply the controls', async () => {
  119. const root = make();
  120. sync(root);
  121. const mod = await import(join(root, 'design/stories/card.stories.js'));
  122. // a tiny DOM stand-in: enough for render()
  123. const made: any[] = [];
  124. (globalThis as any).document = {
  125. createElement: () => {
  126. const el: any = { attrs: {} as Record<string, string>, props: {} as Record<string, string>, firstElementChild: null, set innerHTML(h: string) { this.html = h; this.firstElementChild = this.html ? this.child : null; } };
  127. el.child = { setAttribute(k: string, v: string) { el.attrs[k] = v; }, toggleAttribute() {}, style: { setProperty(k: string, v: string) { el.props[k] = v; } } };
  128. made.push(el);
  129. return el;
  130. },
  131. };
  132. const el = mod.Default.render({ preset: 'cover', gap: 12 });
  133. expect(made[0].html).toContain('data-slot="card"');
  134. expect(made[0].attrs['data-preset']).toBe('cover');
  135. expect(made[0].props['--card-gap']).toBe('12px');
  136. expect(el).toBe(made[0].child);
  137. delete (globalThis as any).document;
  138. });
  139. test('a header that does not parse stops the run and writes nothing', () => {
  140. const root = make();
  141. put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('level: composite', 'level: widget'));
  142. const r = sync(root);
  143. expect(r.code).toBe(1);
  144. expect(r.out).toContain('card.html: level "widget" is not one of');
  145. expect(existsSync(join(root, 'design/components'))).toBe(false);
  146. expect(existsSync(join(root, 'lib/design/components.data.js'))).toBe(false);
  147. });
  148. test('local sources are included and an unselected library is ignored', () => {
  149. const root = make();
  150. put(root, 'design/components.md', read(root, 'design/components.md').replace('sources: []', 'sources: [/src/ui]'));
  151. put(root, 'src/ui/badge.tsx', '/*---\nid: badge\nlevel: primitive\n---*/\nexport const Badge = 1;\n');
  152. put(root, 'src/ui/helper.ts', 'export const x = 1;\n');
  153. put(root, 'design/other-html/components/chip.html', '<!---\nid: chip\nlevel: invalid\n--->\n');
  154. const r = sync(root);
  155. expect(r.code).toBe(0);
  156. expect(r.out).toContain('4 components');
  157. expect(json(root, 'design/custom-elements.json').modules.map((m: any) => m.declarations[0].tagName)).toContain('badge');
  158. expect(dataOf(root).components.find((c: any) => c.id === 'badge')).toMatchObject({ html: null, react: { source: '/src/ui/badge.tsx' } });
  159. expect(existsSync(join(root, 'design/stories/badge.stories.js'))).toBe(false); // no HTML templates: no story
  160. });
  161. test('React targets use library priority and a missing slot, state or setting warns without stopping sync', () => {
  162. const root = make();
  163. const base = read(root, 'design/fix-ui-react/components/ui/chip.tsx')
  164. .replace('return null', 'return <span data-slot="chip-label" />');
  165. put(root, 'design/fix-ui-react/components/ui/chip.tsx', base);
  166. put(root, 'design/my-ui.md', '---\ntarget: src/my-ui\n---\n');
  167. put(root, 'design/components.md', read(root, 'design/components.md').replace('sources: []', 'sources: [/src/my-ui]'));
  168. put(root, 'src/my-ui/chip.tsx', base.replace('default, hover', 'default').replace(' soft: {kind: bool, default: false}\n', '')
  169. .replace('data-slot="chip-label"', 'data-slot="chip"'));
  170. const design = read(root, 'design/design.md');
  171. put(root, 'design/design.md', design.replace('[fix-ui-html', '[my-ui, fix-ui-html'));
  172. const result = sync(root);
  173. expect(result.code).toBe(0);
  174. expect(result.out).toContain('warning: my-ui: chip (react) overrides fix-ui-react with different states; controls; slots chip-label');
  175. const health = Bun.spawnSync([process.execPath, join(import.meta.dir, '../checks/health.ts'), '--lib', 'my-ui'], { cwd: root });
  176. expect(health.exitCode).toBe(0);
  177. expect(health.stdout.toString()).toContain('health component-library/my-ui: override: chip (react)');
  178. const chip = () => dataOf(root).components.find((c: any) => c.id === 'chip');
  179. expect(chip().html.library).toBe('fix-ui-html');
  180. expect(chip().react).toEqual({ source: '/src/my-ui/chip.tsx', library: 'my-ui', overrides: 'fix-ui-react' });
  181. put(root, 'design/design.md', design);
  182. expect(sync(root).code).toBe(0);
  183. expect(chip().react.library).toBe('fix-ui-react');
  184. });
  185. test('HTML override health checks templates even when the header repeats the base contract', () => {
  186. const root = make();
  187. const design = read(root, 'design/design.md');
  188. put(root, 'design/design.md', design.replace('[fix-ui-html', '[my-ui, fix-ui-html'));
  189. put(root, 'design/my-ui/components/primitive/chip/chip.html', CHIP_HTML
  190. .replace('data-slot="chip-label"', 'class="chip-label"')
  191. .replace(/<template data-state="hover">[\s\S]*?<\/template>\n/, ''));
  192. const result = sync(root);
  193. expect(result.code).toBe(0);
  194. expect(result.out).toContain('warning: my-ui: chip (html) overrides fix-ui-html with different template hover; slots in default: chip-label');
  195. expect(dataOf(root).components.find((c: any) => c.id === 'chip').html.library).toBe('my-ui');
  196. });
  197. test('a page whose header is gone stays, with a note, until --prune', () => {
  198. const root = make();
  199. sync(root);
  200. put(root, 'design/fix-ui-html/components/block/card-grid/card-grid.html', 'no header any more');
  201. expect(sync(root).out).toContain('note: design/components/card-grid.md has no component header any more');
  202. expect(existsSync(join(root, 'design/components/card-grid.md'))).toBe(true);
  203. expect(existsSync(join(root, 'design/stories/card-grid.stories.js'))).toBe(false); // stories are fully generated: removed
  204. sync(root, '--prune');
  205. expect(existsSync(join(root, 'design/components/card-grid.md'))).toBe(false);
  206. });
  207. });
  208. describe('fresh', () => {
  209. test('passes after sync, fails before it', () => {
  210. const root = make();
  211. expect(fresh(root).join('\n')).toContain('design/components/chip.md: the page is missing');
  212. sync(root);
  213. expect(fresh(root)).toEqual([]);
  214. });
  215. test('fails when a header changed, a generated file was edited by hand, or a page lost its source', () => {
  216. const root = make();
  217. sync(root);
  218. put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('states: [default, selected]', 'states: [default, selected, hover]'));
  219. expect(fresh(root).join('\n')).toMatch(/design\/components\/card\.md: the header does not match/);
  220. expect(fresh(root).join('\n')).toMatch(/lib\/design\/components\.data\.js: does not match/);
  221. sync(root);
  222. expect(fresh(root)).toEqual([]);
  223. writeFileSync(join(root, 'design/custom-elements.json'), '{}');
  224. expect(fresh(root)).toEqual(['design/custom-elements.json: does not match the component headers — run: shtuk run design-components sync (this file is not edited by hand)']);
  225. sync(root);
  226. put(root, 'design/fix-ui-html/components/block/card-grid/card-grid.html', 'gone');
  227. expect(fresh(root).join('\n')).toMatch(/card-grid\.md: its component has no header any more/);
  228. });
  229. test('is not troubled by text under the header, and names a broken header', () => {
  230. const root = make();
  231. sync(root);
  232. writeFileSync(join(root, 'design/components/chip.md'), read(root, 'design/components/chip.md') + '\nMore words.\n');
  233. expect(fresh(root)).toEqual([]);
  234. put(root, 'design/fix-ui-react/components/ui/chip.tsx', '/*---\nid: chip\nlevel: nope\n---*/\n');
  235. expect(fresh(root)[0]).toMatch(/chip\.tsx: level "nope".*sync cannot run/);
  236. });
  237. });
  238. describe('uses-exist', () => {
  239. test('passes on the fixture; fails on an unknown id; a hand-written page counts as existing', () => {
  240. const root = make();
  241. expect(usesExist(root)).toEqual([]);
  242. put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('uses: [chip]', 'uses: [chip, chipp, planned]'));
  243. put(root, 'design/components/planned.md', '---\ntype: Component\ntitle: Planned\n---\n');
  244. const out = usesExist(root);
  245. expect(out).toHaveLength(1);
  246. expect(out[0]).toContain('"card" uses "chipp", and there is no component with that id');
  247. });
  248. });
  249. describe('no-level-up', () => {
  250. test('passes on the fixture; fails when a primitive uses a composite; names a circle', () => {
  251. const root = make();
  252. expect(noLevelUp(root)).toEqual([]);
  253. const chip = read(root, 'design/fix-ui-html/components/primitive/chip/chip.html');
  254. put(root, 'design/fix-ui-html/components/primitive/chip/chip.html', chip.replace('parts: [chip-label]', 'parts: [chip-label]\nuses: [card]'));
  255. const out = noLevelUp(root);
  256. expect(out.join('\n')).toContain('primitive "chip" uses composite "card"');
  257. expect(out.join('\n')).toMatch(/uses go in a circle: (chip → card → chip|card → chip → card)/);
  258. });
  259. test('the same level is fine', () => {
  260. const root = make();
  261. put(root, 'design/fix-ui-html/components/composite/row.html', '<!---\nid: row\nlevel: composite\nuses: [card]\n--->\n');
  262. expect(noLevelUp(root)).toEqual([]);
  263. });
  264. });
  265. describe('tokens-only', () => {
  266. test('passes on the fixture (a literal in a var() fallback is allowed); fails on raw colours with file and line', () => {
  267. const root = make();
  268. expect(tokensOnly(root)).toEqual([]);
  269. put(root, 'design/fix-ui-html/components/primitive/chip/chip.css', '.chip {\n color: var(--foreground);\n background: #ff0000;\n border-color: rgb(0 0 0 / 0.1);\n box-shadow: 0 0 0 1px oklch(0.5 0.1 20);\n}\n');
  270. const out = tokensOnly(root);
  271. expect(out).toEqual([
  272. 'design/fix-ui-html/components/primitive/chip/chip.css:3: raw colour #ff0000 in "background" — use a var(--…) of the token contract',
  273. 'design/fix-ui-html/components/primitive/chip/chip.css:4: raw colour rgb(…) in "border-color" — use a var(--…) of the token contract',
  274. 'design/fix-ui-html/components/primitive/chip/chip.css:5: raw colour oklch(…) in "box-shadow" — use a var(--…) of the token contract',
  275. ]);
  276. });
  277. test('rawColours: fallbacks, color-mix, custom properties, comments, selectors', () => {
  278. expect(rawColours('a { color: var(--x, #fff); b: var(--y, rgb(1 2 3)); c: var(--p, var(--q, #000)); }')).toEqual([]);
  279. expect(rawColours('a { color: color-mix(in oklch, var(--a) 30%, transparent); }')).toEqual([]);
  280. expect(rawColours('a { color: color-mix(in srgb, #fff 20%, var(--a)); }').map((r) => r.literal)).toEqual(['#fff']);
  281. expect(rawColours(':root { --brand: hsl(10 20% 30%); }').map((r) => r.prop)).toEqual(['--brand']);
  282. expect(rawColours('/* color: #fff; */ #main:hover { margin: 0; }')).toEqual([]);
  283. expect(rawColours('a { background: linear-gradient(var(--a), #123456) }').map((r) => r.literal)).toEqual(['#123456']);
  284. expect(rawColours('a { color: currentColor; background: transparent; width: 3px }')).toEqual([]);
  285. });
  286. });
  287. describe('place', () => {
  288. test('adds the Component kind to the placement map once', () => {
  289. const root = make();
  290. put(root, 'base/ontology/placement.md', '---\ntype: Page\nplacement:\n - {itemType: Bug, path: /work/bugs, writer: all, reader: all}\n---\n\n| Kind | itemType | Place |\n|---|---|---|\n| Bugs | `Bug` | `/work/bugs` |\n');
  291. expect(place(root)).toBe(true);
  292. const text = read(root, 'base/ontology/placement.md');
  293. expect(text).toContain(' - {itemType: Component, path: /design/components, writer: all, reader: all}');
  294. expect(text).toContain('| Design components | `Component` | `/design/components` |');
  295. expect(place(root)).toBe(false);
  296. expect(read(root, 'base/ontology/placement.md')).toBe(text);
  297. });
  298. });
  299. describe('helpers', () => {
  300. test('yaml: what emit writes reads back to the same data', () => {
  301. const data = {
  302. title: 'Package card: "x"', id: 'a-b', level: 'composite', n: 3, flag: false, none: null, words: ['a', 'b c', '--sb-glow', '12-3', 'true', '/design/x'],
  303. controls: { preset: { kind: 'select', options: ['base', 'x'], default: 'base' }, gap: { kind: 'range', min: 0, max: 8, unit: 'px' } },
  304. empty: [], path: '/design/components/chip',
  305. };
  306. expect(Bun.YAML.parse(emit(data))).toEqual(data);
  307. });
  308. test('templatesOf: nested templates stay inside, data-status and data-state both name a template', () => {
  309. const t = templatesOf('<!--- x --->\n<template data-state="a"><div><template><i></i></template></div></template>\n<TEMPLATE data-status=\'b\'><b></b></TEMPLATE><template><u></u></template>');
  310. expect(Object.keys(t)).toEqual(['a', 'b']);
  311. expect(t.a).toBe('<div><template><i></i></template></div>');
  312. });
  313. test('collect: the libraries come in the order of design.md', () => {
  314. const root = make();
  315. const col = collect(root);
  316. expect(col.places.map((p) => p.lib)).toEqual(['fix-ui-html', 'fix-ui-react']);
  317. expect(col.problems).toEqual([]);
  318. expect(col.cssFiles).toHaveLength(3);
  319. });
  320. });