包文件→ .shtukbase/packages/design-components/lib/outputs.ts
lib/outputs.ts
256 行, 12.5 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // What `sync` writes from the headers, as text, so that `fresh` can compute the same and compare (build contract of
- // the wave DSN, sections 4 and 6):
- // design/components/<id>.md one page per id (html and react implementations joined); the text under the
- // page's header is the author's and is kept
- // lib/design/components.data.js window.SB_COMPONENTS, read by the lenses
- // design/custom-elements.json Custom Elements Manifest, one module per component
- // design/stories/<id>.stories.js Storybook CSF 3, one story per state
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- import { type Control, type Header, REGISTRY_TYPES, pascal } from './header.ts';
- import { type Collected, type Comp, DESIGN, PAGES, UI_CSS, cssFor, frontMatter, pageIds, resolvedCss } from './project.ts';
- import { emit } from './yaml.ts';
- export const DATA = 'lib/design/components.data.js';
- export const CEM = 'design/custom-elements.json';
- export const STORIES = 'design/stories';
- export const BANNER = 'Generated by design-components sync';
- /** Keys of a page's front matter that `sync` owns; any other key an author adds is kept. */
- export const GENERATED = ['type', 'title', 'id', 'registry', 'level', 'description', 'uses', 'parts', 'states', 'status', 'controls', 'cssProperties', 'html', 'css', 'react', 'source'];
- export const pagePath = (id: string) => `/${PAGES}/${id}.md`;
- /** The data of a page header for a component (what sync owns). */
- export function pageHead(c: Comp): Record<string, unknown> {
- const h = c.header;
- return {
- type: 'Component', title: h.title, id: h.id, registry: REGISTRY_TYPES[h.level], level: h.level, description: h.description,
- uses: h.uses.map((u) => `/${PAGES}/${u}`), parts: h.parts, states: h.states, status: h.status, controls: h.controls, cssProperties: h.cssProperties,
- html: c.html?.source, css: c.html?.css ?? undefined, react: c.react?.source, source: `/${c.source}`,
- };
- }
- /** `---` front matter `---` and the body after it (the text of an existing page, or the starter for a new one). */
- export function splitPage(text: string): { head: string; body: string } | null {
- const t = text.replace(/^/, '');
- if (!t.startsWith('---')) return null;
- const lines = t.split('\n');
- const end = lines.findIndex((l, i) => i > 0 && l.trimEnd() === '---');
- if (end < 0) return null;
- return { head: lines.slice(1, end).join('\n'), body: lines.slice(end + 1).join('\n') };
- }
- export type PagePlan = { rel: string; head: Record<string, unknown>; text: string };
- /** The page of a component: generated keys first, then the keys an author added, then the kept body. */
- export function planPage(root: string, c: Comp): PagePlan {
- const rel = `${PAGES}/${c.id}.md`;
- const head = pageHead(c);
- let extra: Record<string, unknown> = {};
- let body = `\n${c.header.description ? `${c.header.description}\n` : ''}`;
- const abs = join(root, rel);
- if (existsSync(abs)) {
- const parts = splitPage(readFileSync(abs, 'utf8'));
- if (parts) {
- body = parts.body;
- try {
- const old = Bun.YAML.parse(parts.head);
- if (old && typeof old === 'object' && !Array.isArray(old)) extra = Object.fromEntries(Object.entries(old).filter(([k]) => !GENERATED.includes(k)));
- } catch { /* an unreadable header is rewritten */ }
- }
- }
- const text = `---\n${emit({ ...head, ...extra })}\n---\n${body}`;
- return { rel, head, text };
- }
- const sortKeys = (v: unknown): unknown =>
- Array.isArray(v) ? v.map(sortKeys) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined).sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, x]) => [k, sortKeys(x)])) : v;
- /** A page's generated keys in a form that compares the same however the YAML was written. */
- export function canonicalHead(head: Record<string, unknown>): string {
- return JSON.stringify(sortKeys(Object.fromEntries(Object.entries(head).filter(([k]) => GENERATED.includes(k)))));
- }
- /** The component as the lenses read it (section 6). */
- export function dataComponent(c: Comp) {
- const h = c.header;
- return {
- id: c.id, title: h.title, level: h.level, description: h.description, uses: h.uses, parts: h.parts, states: h.states, status: h.status,
- controls: h.controls, cssProperties: h.cssProperties, html: c.html, react: c.react, page: pagePath(c.id),
- };
- }
- export function dataFile(root: string, col: Collected): string {
- const css = cssFor(root, col);
- const id = frontMatter(root, DESIGN).layout;
- const base = typeof id === 'string' && /^[A-Za-z0-9][\w.-]*$/.test(id.trim()) ? `design/${id.trim()}` : '';
- const layout = base && ['layout.css', 'layout.js'].every((file) => {
- const path = join(root, base, file);
- return existsSync(path) && statSync(path).isFile();
- }) ? { id: id.trim(), css: `/${base}/layout.css`, js: `/${base}/layout.js` } : null;
- if (layout) css.push(layout.css);
- const data = { version: 1, style: col.settings.style, css, ...(layout ? { layout } : {}), components: col.comps.map(dataComponent) };
- return `// ${BANNER}. Do not edit: change a component header and run \`shtuk run design-components sync\`.\nwindow.SB_COMPONENTS = ${JSON.stringify(data, null, 2)};\n`;
- }
- const optionType = (c: Control): string => {
- switch (c.kind) {
- case 'select': case 'segment': return (c.options ?? []).map((o) => (typeof o === 'string' ? `'${o}'` : String(o))).join(' | ') || 'string';
- case 'bool': return 'boolean';
- case 'range': return 'number';
- default: return 'string';
- }
- };
- const defaultText = (c: Control): string | undefined =>
- c.default === undefined ? undefined : typeof c.default === 'string' ? `'${c.default}'` : String(c.default);
- /** Custom Elements Manifest 2.1: one module per component; attributes come from the controls (`data-<control>`). */
- export function cemFile(col: Collected): string {
- const modules = col.comps.map((c) => {
- const h = c.header;
- const attributes = Object.entries(h.controls).map(([name, ctl]) => ({
- name: `data-${name}`, fieldName: name, type: { text: optionType(ctl) },
- ...(defaultText(ctl) !== undefined ? { default: defaultText(ctl) } : {}),
- ...(ctl.label ? { description: ctl.label } : {}),
- }));
- if (h.status.length) attributes.push({ name: 'data-status', fieldName: 'status', type: { text: h.status.map((s) => `'${s}'`).join(' | ') }, description: 'The data state shown' } as never);
- const path = c.source;
- return {
- kind: 'javascript-module',
- path,
- declarations: [{
- kind: 'class', name: pascal(c.id), tagName: c.id, customElement: true, description: h.description || h.title,
- attributes,
- cssProperties: h.cssProperties.map((name) => ({ name })),
- cssParts: h.parts.map((name) => ({ name })),
- cssStates: [...h.states, ...h.status].filter((s, i, a) => a.indexOf(s) === i).map((name) => ({ name })),
- members: [],
- }],
- exports: [{ kind: 'custom-element-definition', name: c.id, declaration: { name: pascal(c.id), module: path } }],
- };
- });
- return `${JSON.stringify({ schemaVersion: '2.1.0', readme: '', modules }, null, 2)}\n`;
- }
- const jsKey = (s: string) => (/^[A-Za-z_$][\w$]*$/.test(s) ? s : JSON.stringify(s));
- function argType(c: Control): Record<string, unknown> {
- const base: Record<string, unknown> = {};
- if (c.label) base.description = c.label;
- if (c.section) base.table = { category: c.section };
- switch (c.kind) {
- case 'select': return { ...base, control: 'select', options: c.options };
- case 'segment': return { ...base, control: 'radio', options: c.options };
- case 'bool': return { ...base, control: 'boolean' };
- case 'range': return { ...base, control: { type: 'range', min: c.min, max: c.max, ...(c.step ? { step: c.step } : {}) } };
- case 'swatch': return { ...base, control: { type: 'color', presetColors: c.options } };
- default: return { ...base, control: 'text' };
- }
- }
- function exportName(label: string, used: Set<string>): string {
- let n = pascal(label.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '')) || 'Story';
- if (/^\d/.test(n)) n = `S${n}`;
- let out = n;
- for (let i = 2; used.has(out); i++) out = `${n}${i}`;
- used.add(out);
- return out;
- }
- /** The CSF 3 file of a component, or null when it has no HTML templates to render. */
- export function storiesFile(c: Comp, css: string[]): string | null {
- if (!c.html || !Object.keys(c.html.templates).length) return null;
- const h: Header = c.header;
- const t = c.html.templates;
- const args: Record<string, unknown> = {};
- for (const [name, ctl] of Object.entries(h.controls)) if (ctl.default !== undefined) args[name] = ctl.default;
- const argTypes = Object.fromEntries(Object.entries(h.controls).map(([n, ctl]) => [n, argType(ctl)]));
- const controls = Object.fromEntries(Object.entries(h.controls).map(([n, ctl]) => [n, { kind: ctl.kind, ...(ctl.unit ? { unit: ctl.unit } : {}) }]));
- const used = new Set<string>(['default']);
- const stories: string[] = [];
- const states = h.states.length ? h.states : ['default'];
- for (const s of states) {
- const ex = exportName(s, used);
- stories.push(`export const ${ex} = { name: ${JSON.stringify(s)}, render: (args) => render(${JSON.stringify(s)}, null, args) };`);
- }
- for (const s of h.status) {
- const ex = exportName(`status-${s}`, used);
- stories.push(`export const ${ex} = { name: ${JSON.stringify(`status: ${s}`)}, render: (args) => render(null, ${JSON.stringify(s)}, args) };`);
- }
- const level = h.level.charAt(0).toUpperCase() + h.level.slice(1);
- return `// ${BANNER} from ${c.source}. Do not edit: change the component header and run \`shtuk run design-components sync\`.
- // Storybook Component Story Format 3, for the HTML framework. The CSS the stories need is in parameters.sb.css.
- const ID = ${JSON.stringify(c.id)};
- const TEMPLATES = ${JSON.stringify(t, null, 2)};
- const CONTROLS = ${JSON.stringify(controls)};
- function render(state, status, args) {
- const host = document.createElement('div');
- const first = Object.keys(TEMPLATES)[0];
- host.innerHTML = TEMPLATES[state ?? status] ?? TEMPLATES.default ?? TEMPLATES[first] ?? '';
- const el = host.firstElementChild;
- if (!el) return host;
- if (status) el.setAttribute('data-status', status);
- for (const [name, c] of Object.entries(CONTROLS)) {
- const v = args[name];
- if (v === undefined) continue;
- if (c.kind === 'bool') el.toggleAttribute('data-' + name, !!v);
- else if (c.kind === 'range') el.style.setProperty('--' + ID + '-' + name, v + (c.unit || ''));
- else el.setAttribute('data-' + name, v);
- }
- return el;
- }
- export default {
- title: ${JSON.stringify(`${level}/${h.title}`)},
- tags: ['autodocs'],
- parameters: { sb: { id: ID, level: ${JSON.stringify(h.level)}, css: ${JSON.stringify(css)}, page: ${JSON.stringify(pagePath(c.id))} } },
- argTypes: ${indentJson(argTypes)},
- args: ${indentJson(args)},
- };
- ${stories.join('\n')}
- `;
- }
- const indentJson = (v: unknown): string => JSON.stringify(v, null, 2).replace(/\n/g, '\n ');
- export type Plan = {
- pages: PagePlan[];
- /** Other generated files: path → full text. */
- files: Map<string, string>;
- /** Existing generated pages (they have a `source` key) whose component has no header any more. */
- orphanPages: string[];
- /** Existing generated stories whose component has no header any more. */
- orphanStories: string[];
- };
- export function plan(root: string, col: Collected): Plan {
- const pages = col.comps.map((c) => planPage(root, c));
- const files = new Map<string, string>();
- files.set(DATA, dataFile(root, col));
- files.set(UI_CSS, resolvedCss(root, col));
- files.set(CEM, cemFile(col));
- const css = cssFor(root, col);
- for (const c of col.comps) {
- const s = storiesFile(c, css);
- if (s) files.set(`${STORIES}/${c.id}.stories.js`, s);
- }
- const ids = new Set(col.comps.map((c) => c.id));
- const orphanPages: string[] = [];
- for (const id of pageIds(root)) {
- if (ids.has(id)) continue;
- const parts = splitPage(readFileSync(join(root, PAGES, `${id}.md`), 'utf8'));
- let src: unknown;
- try { src = parts ? (Bun.YAML.parse(parts.head) as Record<string, unknown> | null)?.source : undefined; } catch { src = undefined; }
- if (typeof src === 'string' && src) orphanPages.push(`${PAGES}/${id}.md`);
- }
- const orphanStories: string[] = [];
- const sd = join(root, STORIES);
- if (existsSync(sd))
- for (const n of readdirSync(sd).sort()) {
- if (!n.endsWith('.stories.js') || files.has(`${STORIES}/${n}`)) continue;
- if (readFileSync(join(sd, n), 'utf8').startsWith(`// ${BANNER}`)) orphanStories.push(`${STORIES}/${n}`);
- }
- return { pages, files, orphanPages, orphanStories };
- }