包文件→ .shtukbase/packages/design-components/test/design-components.test.ts
test/design-components.test.ts
345 行, 20.1 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // sync and the four checks on a scratch project with a fixture library of three components. Run: `bun test` in the package.
- import { afterEach, describe, expect, test } from 'bun:test';
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { place } from '../actions/place.ts';
- import { check as fresh } from '../checks/fresh.ts';
- import { check as noLevelUp } from '../checks/no-level-up.ts';
- import { check as tokensOnly } from '../checks/tokens-only.ts';
- import { check as usesExist } from '../checks/uses-exist.ts';
- import { rawColours } from '../lib/css.ts';
- import { collect, templatesOf } from '../lib/project.ts';
- import { emit } from '../lib/yaml.ts';
- import { CARD_HTML, CHIP_HTML, drop, project, put } from './fixture.ts';
- const SYNC = join(import.meta.dir, '..', 'actions', 'sync.ts');
- const roots: string[] = [];
- const make = () => { const r = project(); roots.push(r); return r; };
- afterEach(() => { for (const r of roots.splice(0)) drop(r); });
- const sync = (root: string, ...args: string[]) => {
- const r = Bun.spawnSync([process.execPath, SYNC, ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe' });
- return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() };
- };
- const read = (root: string, rel: string) => readFileSync(join(root, rel), 'utf8');
- const json = (root: string, rel: string) => JSON.parse(read(root, rel));
- const dataOf = (root: string) => {
- const w: Record<string, any> = {};
- new Function('window', read(root, 'lib/design/components.data.js'))(w);
- return w.SB_COMPONENTS;
- };
- describe('sync', () => {
- test('writes a page per id, joining the HTML and the React implementation', () => {
- const root = make();
- const r = sync(root);
- expect(r.code).toBe(0);
- expect(r.out).toContain('3 components (3 html, 1 react)');
- for (const id of ['chip', 'card', 'card-grid']) expect(existsSync(join(root, `design/components/${id}.md`))).toBe(true);
- const chip = read(root, 'design/components/chip.md');
- const fm = Bun.YAML.parse(chip.split('---')[1]) as Record<string, any>;
- expect(fm).toMatchObject({
- type: 'Component', title: 'Chip', id: 'chip', level: 'primitive', registry: 'registry:ui', description: 'A small label.',
- parts: ['chip-label'], states: ['default', 'hover'], status: ['empty'], cssProperties: ['--sb-hue-1'],
- html: '/design/fix-ui-html/components/primitive/chip/chip.html', css: '/design/fix-ui-html/components/primitive/chip/chip.css',
- react: '/design/fix-ui-react/components/ui/chip.tsx', source: '/design/fix-ui-html/components/primitive/chip/chip.html',
- });
- expect(fm.controls.tone).toEqual({ kind: 'select', options: ['neutral', 'accent'], default: 'neutral', label: 'Tone' });
- const card = Bun.YAML.parse(read(root, 'design/components/card.md').split('---')[1]) as Record<string, any>;
- expect(card.uses).toEqual(['/design/components/chip']);
- expect(card.react).toBeUndefined();
- });
- test('keeps the text under the header and the keys an author added; running again changes nothing', () => {
- const root = make();
- sync(root);
- const p = join(root, 'design/components/card.md');
- writeFileSync(p, read(root, 'design/components/card.md').replace('\n---\n', '\nowner: me\n---\n') + '\nWhen to use: always.\n');
- expect(sync(root).out).toContain('0 files written');
- const text = read(root, 'design/components/card.md');
- expect(text).toContain('When to use: always.');
- expect(text).toContain('owner: me');
- expect(text.indexOf('owner: me')).toBeGreaterThan(text.indexOf('source:'));
- // the header changes: the page header follows, the body stays
- put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('A card with a chip.', 'A card, changed.'));
- expect(sync(root).code).toBe(0);
- const after = read(root, 'design/components/card.md');
- expect(after).toContain('description: "A card, changed."');
- expect(after).toContain('When to use: always.');
- expect(after).toContain('owner: me');
- });
- test('lib/design/components.data.js has the shape of section 6', () => {
- const root = make();
- sync(root);
- const d = dataOf(root);
- expect(d.version).toBe(1);
- expect(d.style).toBe('fixstyle');
- expect(d.css).toEqual(['/design/fixstyle/tokens.css', '/lib/design/ui.css']);
- expect(d.components.map((c: any) => c.id)).toEqual(['chip', 'card', 'card-grid']); // by level, then id
- const chip = d.components[0];
- expect(Object.keys(chip).sort()).toEqual(['controls', 'cssProperties', 'description', 'html', 'id', 'level', 'page', 'parts', 'react', 'states', 'status', 'title', 'uses']);
- expect(chip.page).toBe('/design/components/chip.md');
- expect(chip.html.source).toBe('/design/fix-ui-html/components/primitive/chip/chip.html');
- expect(chip.html.css).toBe('/design/fix-ui-html/components/primitive/chip/chip.css');
- expect(Object.keys(chip.html.templates)).toEqual(['default', 'hover', 'empty']);
- expect(chip.html.templates.default).toBe('<span data-slot="chip" class="chip"><span data-slot="chip-label">Label</span></span>');
- expect(chip.react).toEqual({ source: '/design/fix-ui-react/components/ui/chip.tsx', library: 'fix-ui-react' });
- expect(d.components[1].react).toBeNull();
- expect(d.components[1].uses).toEqual(['chip']);
- });
- test('custom-elements.json: a module per component, attributes from controls, parts and css properties', () => {
- const root = make();
- sync(root);
- const cem = json(root, 'design/custom-elements.json');
- expect(cem.schemaVersion).toBe('2.1.0');
- expect(cem.modules.map((m: any) => m.declarations[0].tagName)).toEqual(['chip', 'card', 'card-grid']);
- const chip = cem.modules[0].declarations[0];
- expect(chip.name).toBe('Chip');
- expect(chip.attributes[0]).toEqual({ name: 'data-tone', fieldName: 'tone', type: { text: "'neutral' | 'accent'" }, default: "'neutral'", description: 'Tone' });
- expect(chip.attributes[1]).toMatchObject({ name: 'data-soft', type: { text: 'boolean' }, default: 'false' });
- expect(chip.attributes.at(-1)).toMatchObject({ name: 'data-status', type: { text: "'empty'" } });
- expect(chip.cssProperties).toEqual([{ name: '--sb-hue-1' }]);
- expect(chip.cssParts).toEqual([{ name: 'chip-label' }]);
- expect(cem.modules[1].declarations[0].attributes[1]).toMatchObject({ name: 'data-gap', type: { text: 'number' }, default: '8' });
- });
- test('stories: CSF 3 with argTypes from controls and one story per state', async () => {
- const root = make();
- sync(root);
- const text = read(root, 'design/stories/card.stories.js');
- expect(text.startsWith('// Generated by design-components sync')).toBe(true);
- // load it as a module (a DOM is not needed to read the exports)
- const mod = await import(join(root, 'design/stories/card.stories.js'));
- expect(mod.default.title).toBe('Composite/Card');
- expect(mod.default.argTypes.preset).toEqual({ description: undefined, table: { category: 'Look' }, control: 'select', options: ['base', 'compact', 'cover'] });
- expect(mod.default.argTypes.gap.control).toEqual({ type: 'range', min: 0, max: 32, step: 4 });
- expect(mod.default.args).toEqual({ preset: 'base', gap: 8 });
- expect(Object.keys(mod).filter((k) => k !== 'default')).toEqual(['Default', 'Selected']);
- expect(mod.Selected.name).toBe('selected');
- const chip = await import(join(root, 'design/stories/chip.stories.js'));
- expect(Object.keys(chip).filter((k) => k !== 'default')).toEqual(['Default', 'Hover', 'StatusEmpty']);
- expect(chip.default.argTypes.soft.control).toBe('boolean');
- });
- test('stories render the template and apply the controls', async () => {
- const root = make();
- sync(root);
- const mod = await import(join(root, 'design/stories/card.stories.js'));
- // a tiny DOM stand-in: enough for render()
- const made: any[] = [];
- (globalThis as any).document = {
- createElement: () => {
- 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; } };
- el.child = { setAttribute(k: string, v: string) { el.attrs[k] = v; }, toggleAttribute() {}, style: { setProperty(k: string, v: string) { el.props[k] = v; } } };
- made.push(el);
- return el;
- },
- };
- const el = mod.Default.render({ preset: 'cover', gap: 12 });
- expect(made[0].html).toContain('data-slot="card"');
- expect(made[0].attrs['data-preset']).toBe('cover');
- expect(made[0].props['--card-gap']).toBe('12px');
- expect(el).toBe(made[0].child);
- delete (globalThis as any).document;
- });
- test('a header that does not parse stops the run and writes nothing', () => {
- const root = make();
- put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('level: composite', 'level: widget'));
- const r = sync(root);
- expect(r.code).toBe(1);
- expect(r.out).toContain('card.html: level "widget" is not one of');
- expect(existsSync(join(root, 'design/components'))).toBe(false);
- expect(existsSync(join(root, 'lib/design/components.data.js'))).toBe(false);
- });
- test('local sources are included and an unselected library is ignored', () => {
- const root = make();
- put(root, 'design/components.md', read(root, 'design/components.md').replace('sources: []', 'sources: [/src/ui]'));
- put(root, 'src/ui/badge.tsx', '/*---\nid: badge\nlevel: primitive\n---*/\nexport const Badge = 1;\n');
- put(root, 'src/ui/helper.ts', 'export const x = 1;\n');
- put(root, 'design/other-html/components/chip.html', '<!---\nid: chip\nlevel: invalid\n--->\n');
- const r = sync(root);
- expect(r.code).toBe(0);
- expect(r.out).toContain('4 components');
- expect(json(root, 'design/custom-elements.json').modules.map((m: any) => m.declarations[0].tagName)).toContain('badge');
- expect(dataOf(root).components.find((c: any) => c.id === 'badge')).toMatchObject({ html: null, react: { source: '/src/ui/badge.tsx' } });
- expect(existsSync(join(root, 'design/stories/badge.stories.js'))).toBe(false); // no HTML templates: no story
- });
- test('React targets use library priority and a missing slot, state or setting warns without stopping sync', () => {
- const root = make();
- const base = read(root, 'design/fix-ui-react/components/ui/chip.tsx')
- .replace('return null', 'return <span data-slot="chip-label" />');
- put(root, 'design/fix-ui-react/components/ui/chip.tsx', base);
- put(root, 'design/my-ui.md', '---\ntarget: src/my-ui\n---\n');
- put(root, 'design/components.md', read(root, 'design/components.md').replace('sources: []', 'sources: [/src/my-ui]'));
- put(root, 'src/my-ui/chip.tsx', base.replace('default, hover', 'default').replace(' soft: {kind: bool, default: false}\n', '')
- .replace('data-slot="chip-label"', 'data-slot="chip"'));
- const design = read(root, 'design/design.md');
- put(root, 'design/design.md', design.replace('[fix-ui-html', '[my-ui, fix-ui-html'));
- const result = sync(root);
- expect(result.code).toBe(0);
- expect(result.out).toContain('warning: my-ui: chip (react) overrides fix-ui-react with different states; controls; slots chip-label');
- const health = Bun.spawnSync([process.execPath, join(import.meta.dir, '../checks/health.ts'), '--lib', 'my-ui'], { cwd: root });
- expect(health.exitCode).toBe(0);
- expect(health.stdout.toString()).toContain('health component-library/my-ui: override: chip (react)');
- const chip = () => dataOf(root).components.find((c: any) => c.id === 'chip');
- expect(chip().html.library).toBe('fix-ui-html');
- expect(chip().react).toEqual({ source: '/src/my-ui/chip.tsx', library: 'my-ui', overrides: 'fix-ui-react' });
- put(root, 'design/design.md', design);
- expect(sync(root).code).toBe(0);
- expect(chip().react.library).toBe('fix-ui-react');
- });
- test('HTML override health checks templates even when the header repeats the base contract', () => {
- const root = make();
- const design = read(root, 'design/design.md');
- put(root, 'design/design.md', design.replace('[fix-ui-html', '[my-ui, fix-ui-html'));
- put(root, 'design/my-ui/components/primitive/chip/chip.html', CHIP_HTML
- .replace('data-slot="chip-label"', 'class="chip-label"')
- .replace(/<template data-state="hover">[\s\S]*?<\/template>\n/, ''));
- const result = sync(root);
- expect(result.code).toBe(0);
- expect(result.out).toContain('warning: my-ui: chip (html) overrides fix-ui-html with different template hover; slots in default: chip-label');
- expect(dataOf(root).components.find((c: any) => c.id === 'chip').html.library).toBe('my-ui');
- });
- test('a page whose header is gone stays, with a note, until --prune', () => {
- const root = make();
- sync(root);
- put(root, 'design/fix-ui-html/components/block/card-grid/card-grid.html', 'no header any more');
- expect(sync(root).out).toContain('note: design/components/card-grid.md has no component header any more');
- expect(existsSync(join(root, 'design/components/card-grid.md'))).toBe(true);
- expect(existsSync(join(root, 'design/stories/card-grid.stories.js'))).toBe(false); // stories are fully generated: removed
- sync(root, '--prune');
- expect(existsSync(join(root, 'design/components/card-grid.md'))).toBe(false);
- });
- });
- describe('fresh', () => {
- test('passes after sync, fails before it', () => {
- const root = make();
- expect(fresh(root).join('\n')).toContain('design/components/chip.md: the page is missing');
- sync(root);
- expect(fresh(root)).toEqual([]);
- });
- test('fails when a header changed, a generated file was edited by hand, or a page lost its source', () => {
- const root = make();
- sync(root);
- put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('states: [default, selected]', 'states: [default, selected, hover]'));
- expect(fresh(root).join('\n')).toMatch(/design\/components\/card\.md: the header does not match/);
- expect(fresh(root).join('\n')).toMatch(/lib\/design\/components\.data\.js: does not match/);
- sync(root);
- expect(fresh(root)).toEqual([]);
- writeFileSync(join(root, 'design/custom-elements.json'), '{}');
- 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)']);
- sync(root);
- put(root, 'design/fix-ui-html/components/block/card-grid/card-grid.html', 'gone');
- expect(fresh(root).join('\n')).toMatch(/card-grid\.md: its component has no header any more/);
- });
- test('is not troubled by text under the header, and names a broken header', () => {
- const root = make();
- sync(root);
- writeFileSync(join(root, 'design/components/chip.md'), read(root, 'design/components/chip.md') + '\nMore words.\n');
- expect(fresh(root)).toEqual([]);
- put(root, 'design/fix-ui-react/components/ui/chip.tsx', '/*---\nid: chip\nlevel: nope\n---*/\n');
- expect(fresh(root)[0]).toMatch(/chip\.tsx: level "nope".*sync cannot run/);
- });
- });
- describe('uses-exist', () => {
- test('passes on the fixture; fails on an unknown id; a hand-written page counts as existing', () => {
- const root = make();
- expect(usesExist(root)).toEqual([]);
- put(root, 'design/fix-ui-html/components/composite/card/card.html', CARD_HTML.replace('uses: [chip]', 'uses: [chip, chipp, planned]'));
- put(root, 'design/components/planned.md', '---\ntype: Component\ntitle: Planned\n---\n');
- const out = usesExist(root);
- expect(out).toHaveLength(1);
- expect(out[0]).toContain('"card" uses "chipp", and there is no component with that id');
- });
- });
- describe('no-level-up', () => {
- test('passes on the fixture; fails when a primitive uses a composite; names a circle', () => {
- const root = make();
- expect(noLevelUp(root)).toEqual([]);
- const chip = read(root, 'design/fix-ui-html/components/primitive/chip/chip.html');
- put(root, 'design/fix-ui-html/components/primitive/chip/chip.html', chip.replace('parts: [chip-label]', 'parts: [chip-label]\nuses: [card]'));
- const out = noLevelUp(root);
- expect(out.join('\n')).toContain('primitive "chip" uses composite "card"');
- expect(out.join('\n')).toMatch(/uses go in a circle: (chip → card → chip|card → chip → card)/);
- });
- test('the same level is fine', () => {
- const root = make();
- put(root, 'design/fix-ui-html/components/composite/row.html', '<!---\nid: row\nlevel: composite\nuses: [card]\n--->\n');
- expect(noLevelUp(root)).toEqual([]);
- });
- });
- describe('tokens-only', () => {
- test('passes on the fixture (a literal in a var() fallback is allowed); fails on raw colours with file and line', () => {
- const root = make();
- expect(tokensOnly(root)).toEqual([]);
- 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');
- const out = tokensOnly(root);
- expect(out).toEqual([
- 'design/fix-ui-html/components/primitive/chip/chip.css:3: raw colour #ff0000 in "background" — use a var(--…) of the token contract',
- 'design/fix-ui-html/components/primitive/chip/chip.css:4: raw colour rgb(…) in "border-color" — use a var(--…) of the token contract',
- 'design/fix-ui-html/components/primitive/chip/chip.css:5: raw colour oklch(…) in "box-shadow" — use a var(--…) of the token contract',
- ]);
- });
- test('rawColours: fallbacks, color-mix, custom properties, comments, selectors', () => {
- expect(rawColours('a { color: var(--x, #fff); b: var(--y, rgb(1 2 3)); c: var(--p, var(--q, #000)); }')).toEqual([]);
- expect(rawColours('a { color: color-mix(in oklch, var(--a) 30%, transparent); }')).toEqual([]);
- expect(rawColours('a { color: color-mix(in srgb, #fff 20%, var(--a)); }').map((r) => r.literal)).toEqual(['#fff']);
- expect(rawColours(':root { --brand: hsl(10 20% 30%); }').map((r) => r.prop)).toEqual(['--brand']);
- expect(rawColours('/* color: #fff; */ #main:hover { margin: 0; }')).toEqual([]);
- expect(rawColours('a { background: linear-gradient(var(--a), #123456) }').map((r) => r.literal)).toEqual(['#123456']);
- expect(rawColours('a { color: currentColor; background: transparent; width: 3px }')).toEqual([]);
- });
- });
- describe('place', () => {
- test('adds the Component kind to the placement map once', () => {
- const root = make();
- 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');
- expect(place(root)).toBe(true);
- const text = read(root, 'base/ontology/placement.md');
- expect(text).toContain(' - {itemType: Component, path: /design/components, writer: all, reader: all}');
- expect(text).toContain('| Design components | `Component` | `/design/components` |');
- expect(place(root)).toBe(false);
- expect(read(root, 'base/ontology/placement.md')).toBe(text);
- });
- });
- describe('helpers', () => {
- test('yaml: what emit writes reads back to the same data', () => {
- const data = {
- 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'],
- controls: { preset: { kind: 'select', options: ['base', 'x'], default: 'base' }, gap: { kind: 'range', min: 0, max: 8, unit: 'px' } },
- empty: [], path: '/design/components/chip',
- };
- expect(Bun.YAML.parse(emit(data))).toEqual(data);
- });
- test('templatesOf: nested templates stay inside, data-status and data-state both name a template', () => {
- 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>');
- expect(Object.keys(t)).toEqual(['a', 'b']);
- expect(t.a).toBe('<div><template><i></i></template></div>');
- });
- test('collect: the libraries come in the order of design.md', () => {
- const root = make();
- const col = collect(root);
- expect(col.places.map((p) => p.lib)).toEqual(['fix-ui-html', 'fix-ui-react']);
- expect(col.problems).toEqual([]);
- expect(col.cssFiles).toHaveLength(3);
- });
- });