ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/design-components/lib/outputs.ts

lib/outputs.ts

256 líneas, 12.5 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // What `sync` writes from the headers, as text, so that `fresh` can compute the same and compare (build contract of
  2. // the wave DSN, sections 4 and 6):
  3. // design/components/<id>.md one page per id (html and react implementations joined); the text under the
  4. // page's header is the author's and is kept
  5. // lib/design/components.data.js window.SB_COMPONENTS, read by the lenses
  6. // design/custom-elements.json Custom Elements Manifest, one module per component
  7. // design/stories/<id>.stories.js Storybook CSF 3, one story per state
  8. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  9. import { join } from 'node:path';
  10. import { type Control, type Header, REGISTRY_TYPES, pascal } from './header.ts';
  11. import { type Collected, type Comp, DESIGN, PAGES, UI_CSS, cssFor, frontMatter, pageIds, resolvedCss } from './project.ts';
  12. import { emit } from './yaml.ts';
  13. export const DATA = 'lib/design/components.data.js';
  14. export const CEM = 'design/custom-elements.json';
  15. export const STORIES = 'design/stories';
  16. export const BANNER = 'Generated by design-components sync';
  17. /** Keys of a page's front matter that `sync` owns; any other key an author adds is kept. */
  18. export const GENERATED = ['type', 'title', 'id', 'registry', 'level', 'description', 'uses', 'parts', 'states', 'status', 'controls', 'cssProperties', 'html', 'css', 'react', 'source'];
  19. export const pagePath = (id: string) => `/${PAGES}/${id}.md`;
  20. /** The data of a page header for a component (what sync owns). */
  21. export function pageHead(c: Comp): Record<string, unknown> {
  22. const h = c.header;
  23. return {
  24. type: 'Component', title: h.title, id: h.id, registry: REGISTRY_TYPES[h.level], level: h.level, description: h.description,
  25. uses: h.uses.map((u) => `/${PAGES}/${u}`), parts: h.parts, states: h.states, status: h.status, controls: h.controls, cssProperties: h.cssProperties,
  26. html: c.html?.source, css: c.html?.css ?? undefined, react: c.react?.source, source: `/${c.source}`,
  27. };
  28. }
  29. /** `---` front matter `---` and the body after it (the text of an existing page, or the starter for a new one). */
  30. export function splitPage(text: string): { head: string; body: string } | null {
  31. const t = text.replace(/^/, '');
  32. if (!t.startsWith('---')) return null;
  33. const lines = t.split('\n');
  34. const end = lines.findIndex((l, i) => i > 0 && l.trimEnd() === '---');
  35. if (end < 0) return null;
  36. return { head: lines.slice(1, end).join('\n'), body: lines.slice(end + 1).join('\n') };
  37. }
  38. export type PagePlan = { rel: string; head: Record<string, unknown>; text: string };
  39. /** The page of a component: generated keys first, then the keys an author added, then the kept body. */
  40. export function planPage(root: string, c: Comp): PagePlan {
  41. const rel = `${PAGES}/${c.id}.md`;
  42. const head = pageHead(c);
  43. let extra: Record<string, unknown> = {};
  44. let body = `\n${c.header.description ? `${c.header.description}\n` : ''}`;
  45. const abs = join(root, rel);
  46. if (existsSync(abs)) {
  47. const parts = splitPage(readFileSync(abs, 'utf8'));
  48. if (parts) {
  49. body = parts.body;
  50. try {
  51. const old = Bun.YAML.parse(parts.head);
  52. if (old && typeof old === 'object' && !Array.isArray(old)) extra = Object.fromEntries(Object.entries(old).filter(([k]) => !GENERATED.includes(k)));
  53. } catch { /* an unreadable header is rewritten */ }
  54. }
  55. }
  56. const text = `---\n${emit({ ...head, ...extra })}\n---\n${body}`;
  57. return { rel, head, text };
  58. }
  59. const sortKeys = (v: unknown): unknown =>
  60. 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;
  61. /** A page's generated keys in a form that compares the same however the YAML was written. */
  62. export function canonicalHead(head: Record<string, unknown>): string {
  63. return JSON.stringify(sortKeys(Object.fromEntries(Object.entries(head).filter(([k]) => GENERATED.includes(k)))));
  64. }
  65. /** The component as the lenses read it (section 6). */
  66. export function dataComponent(c: Comp) {
  67. const h = c.header;
  68. return {
  69. id: c.id, title: h.title, level: h.level, description: h.description, uses: h.uses, parts: h.parts, states: h.states, status: h.status,
  70. controls: h.controls, cssProperties: h.cssProperties, html: c.html, react: c.react, page: pagePath(c.id),
  71. };
  72. }
  73. export function dataFile(root: string, col: Collected): string {
  74. const css = cssFor(root, col);
  75. const id = frontMatter(root, DESIGN).layout;
  76. const base = typeof id === 'string' && /^[A-Za-z0-9][\w.-]*$/.test(id.trim()) ? `design/${id.trim()}` : '';
  77. const layout = base && ['layout.css', 'layout.js'].every((file) => {
  78. const path = join(root, base, file);
  79. return existsSync(path) && statSync(path).isFile();
  80. }) ? { id: id.trim(), css: `/${base}/layout.css`, js: `/${base}/layout.js` } : null;
  81. if (layout) css.push(layout.css);
  82. const data = { version: 1, style: col.settings.style, css, ...(layout ? { layout } : {}), components: col.comps.map(dataComponent) };
  83. 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`;
  84. }
  85. const optionType = (c: Control): string => {
  86. switch (c.kind) {
  87. case 'select': case 'segment': return (c.options ?? []).map((o) => (typeof o === 'string' ? `'${o}'` : String(o))).join(' | ') || 'string';
  88. case 'bool': return 'boolean';
  89. case 'range': return 'number';
  90. default: return 'string';
  91. }
  92. };
  93. const defaultText = (c: Control): string | undefined =>
  94. c.default === undefined ? undefined : typeof c.default === 'string' ? `'${c.default}'` : String(c.default);
  95. /** Custom Elements Manifest 2.1: one module per component; attributes come from the controls (`data-<control>`). */
  96. export function cemFile(col: Collected): string {
  97. const modules = col.comps.map((c) => {
  98. const h = c.header;
  99. const attributes = Object.entries(h.controls).map(([name, ctl]) => ({
  100. name: `data-${name}`, fieldName: name, type: { text: optionType(ctl) },
  101. ...(defaultText(ctl) !== undefined ? { default: defaultText(ctl) } : {}),
  102. ...(ctl.label ? { description: ctl.label } : {}),
  103. }));
  104. 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);
  105. const path = c.source;
  106. return {
  107. kind: 'javascript-module',
  108. path,
  109. declarations: [{
  110. kind: 'class', name: pascal(c.id), tagName: c.id, customElement: true, description: h.description || h.title,
  111. attributes,
  112. cssProperties: h.cssProperties.map((name) => ({ name })),
  113. cssParts: h.parts.map((name) => ({ name })),
  114. cssStates: [...h.states, ...h.status].filter((s, i, a) => a.indexOf(s) === i).map((name) => ({ name })),
  115. members: [],
  116. }],
  117. exports: [{ kind: 'custom-element-definition', name: c.id, declaration: { name: pascal(c.id), module: path } }],
  118. };
  119. });
  120. return `${JSON.stringify({ schemaVersion: '2.1.0', readme: '', modules }, null, 2)}\n`;
  121. }
  122. const jsKey = (s: string) => (/^[A-Za-z_$][\w$]*$/.test(s) ? s : JSON.stringify(s));
  123. function argType(c: Control): Record<string, unknown> {
  124. const base: Record<string, unknown> = {};
  125. if (c.label) base.description = c.label;
  126. if (c.section) base.table = { category: c.section };
  127. switch (c.kind) {
  128. case 'select': return { ...base, control: 'select', options: c.options };
  129. case 'segment': return { ...base, control: 'radio', options: c.options };
  130. case 'bool': return { ...base, control: 'boolean' };
  131. case 'range': return { ...base, control: { type: 'range', min: c.min, max: c.max, ...(c.step ? { step: c.step } : {}) } };
  132. case 'swatch': return { ...base, control: { type: 'color', presetColors: c.options } };
  133. default: return { ...base, control: 'text' };
  134. }
  135. }
  136. function exportName(label: string, used: Set<string>): string {
  137. let n = pascal(label.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '')) || 'Story';
  138. if (/^\d/.test(n)) n = `S${n}`;
  139. let out = n;
  140. for (let i = 2; used.has(out); i++) out = `${n}${i}`;
  141. used.add(out);
  142. return out;
  143. }
  144. /** The CSF 3 file of a component, or null when it has no HTML templates to render. */
  145. export function storiesFile(c: Comp, css: string[]): string | null {
  146. if (!c.html || !Object.keys(c.html.templates).length) return null;
  147. const h: Header = c.header;
  148. const t = c.html.templates;
  149. const args: Record<string, unknown> = {};
  150. for (const [name, ctl] of Object.entries(h.controls)) if (ctl.default !== undefined) args[name] = ctl.default;
  151. const argTypes = Object.fromEntries(Object.entries(h.controls).map(([n, ctl]) => [n, argType(ctl)]));
  152. const controls = Object.fromEntries(Object.entries(h.controls).map(([n, ctl]) => [n, { kind: ctl.kind, ...(ctl.unit ? { unit: ctl.unit } : {}) }]));
  153. const used = new Set<string>(['default']);
  154. const stories: string[] = [];
  155. const states = h.states.length ? h.states : ['default'];
  156. for (const s of states) {
  157. const ex = exportName(s, used);
  158. stories.push(`export const ${ex} = { name: ${JSON.stringify(s)}, render: (args) => render(${JSON.stringify(s)}, null, args) };`);
  159. }
  160. for (const s of h.status) {
  161. const ex = exportName(`status-${s}`, used);
  162. stories.push(`export const ${ex} = { name: ${JSON.stringify(`status: ${s}`)}, render: (args) => render(null, ${JSON.stringify(s)}, args) };`);
  163. }
  164. const level = h.level.charAt(0).toUpperCase() + h.level.slice(1);
  165. return `// ${BANNER} from ${c.source}. Do not edit: change the component header and run \`shtuk run design-components sync\`.
  166. // Storybook Component Story Format 3, for the HTML framework. The CSS the stories need is in parameters.sb.css.
  167. const ID = ${JSON.stringify(c.id)};
  168. const TEMPLATES = ${JSON.stringify(t, null, 2)};
  169. const CONTROLS = ${JSON.stringify(controls)};
  170. function render(state, status, args) {
  171. const host = document.createElement('div');
  172. const first = Object.keys(TEMPLATES)[0];
  173. host.innerHTML = TEMPLATES[state ?? status] ?? TEMPLATES.default ?? TEMPLATES[first] ?? '';
  174. const el = host.firstElementChild;
  175. if (!el) return host;
  176. if (status) el.setAttribute('data-status', status);
  177. for (const [name, c] of Object.entries(CONTROLS)) {
  178. const v = args[name];
  179. if (v === undefined) continue;
  180. if (c.kind === 'bool') el.toggleAttribute('data-' + name, !!v);
  181. else if (c.kind === 'range') el.style.setProperty('--' + ID + '-' + name, v + (c.unit || ''));
  182. else el.setAttribute('data-' + name, v);
  183. }
  184. return el;
  185. }
  186. export default {
  187. title: ${JSON.stringify(`${level}/${h.title}`)},
  188. tags: ['autodocs'],
  189. parameters: { sb: { id: ID, level: ${JSON.stringify(h.level)}, css: ${JSON.stringify(css)}, page: ${JSON.stringify(pagePath(c.id))} } },
  190. argTypes: ${indentJson(argTypes)},
  191. args: ${indentJson(args)},
  192. };
  193. ${stories.join('\n')}
  194. `;
  195. }
  196. const indentJson = (v: unknown): string => JSON.stringify(v, null, 2).replace(/\n/g, '\n ');
  197. export type Plan = {
  198. pages: PagePlan[];
  199. /** Other generated files: path → full text. */
  200. files: Map<string, string>;
  201. /** Existing generated pages (they have a `source` key) whose component has no header any more. */
  202. orphanPages: string[];
  203. /** Existing generated stories whose component has no header any more. */
  204. orphanStories: string[];
  205. };
  206. export function plan(root: string, col: Collected): Plan {
  207. const pages = col.comps.map((c) => planPage(root, c));
  208. const files = new Map<string, string>();
  209. files.set(DATA, dataFile(root, col));
  210. files.set(UI_CSS, resolvedCss(root, col));
  211. files.set(CEM, cemFile(col));
  212. const css = cssFor(root, col);
  213. for (const c of col.comps) {
  214. const s = storiesFile(c, css);
  215. if (s) files.set(`${STORIES}/${c.id}.stories.js`, s);
  216. }
  217. const ids = new Set(col.comps.map((c) => c.id));
  218. const orphanPages: string[] = [];
  219. for (const id of pageIds(root)) {
  220. if (ids.has(id)) continue;
  221. const parts = splitPage(readFileSync(join(root, PAGES, `${id}.md`), 'utf8'));
  222. let src: unknown;
  223. try { src = parts ? (Bun.YAML.parse(parts.head) as Record<string, unknown> | null)?.source : undefined; } catch { src = undefined; }
  224. if (typeof src === 'string' && src) orphanPages.push(`${PAGES}/${id}.md`);
  225. }
  226. const orphanStories: string[] = [];
  227. const sd = join(root, STORIES);
  228. if (existsSync(sd))
  229. for (const n of readdirSync(sd).sort()) {
  230. if (!n.endsWith('.stories.js') || files.has(`${STORIES}/${n}`)) continue;
  231. if (readFileSync(join(sd, n), 'utf8').startsWith(`// ${BANNER}`)) orphanStories.push(`${STORIES}/${n}`);
  232. }
  233. return { pages, files, orphanPages, orphanStories };
  234. }