ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/shtukbase-ui-html/lib/components.ts

lib/components.ts

157 líneas, 7.3 KB.

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

  1. // The components of the library: find them, read their headers (section 4 of the design build contract) and
  2. // templates, check the format. Pure functions over text, plus `scan` that reads a folder. No dependencies: Bun's YAML.
  3. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  4. import { join, relative } from 'node:path';
  5. export const LIB = 'shtukbase-ui-html';
  6. /** Where the library lives in a project (and under `pages/` in the package). */
  7. export const LIB_DIR = `design/${LIB}`;
  8. export const LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'] as const;
  9. export const KINDS = ['select', 'segment', 'bool', 'range', 'swatch', 'text'] as const;
  10. export type Control = {
  11. kind: (typeof KINDS)[number];
  12. label?: string;
  13. options?: (string | number)[];
  14. default?: unknown;
  15. min?: number;
  16. max?: number;
  17. step?: number;
  18. unit?: string;
  19. section?: string;
  20. colors?: unknown;
  21. };
  22. export type Header = {
  23. id: string;
  24. title: string;
  25. level: (typeof LEVELS)[number];
  26. description: string;
  27. uses: string[];
  28. parts: string[];
  29. states: string[];
  30. status: string[];
  31. controls: Record<string, Control>;
  32. cssProperties: string[];
  33. };
  34. export type Component = {
  35. header: Header;
  36. /** Paths relative to the scanned root. */
  37. html: string;
  38. css: string | null;
  39. /** state or status → markup */
  40. templates: Record<string, string>;
  41. problems: string[];
  42. };
  43. const HEAD = /^\s*<!---\n([\s\S]*?)\n--->/;
  44. const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
  45. /** The header of an HTML component file, or the problem that stops reading it. */
  46. export function parseHeader(text: string): { header?: Header; problem?: string } {
  47. const m = HEAD.exec(text);
  48. if (!m) return { problem: 'no header: the file must start with a <!--- … ---> YAML block' };
  49. let y: any;
  50. try {
  51. y = Bun.YAML.parse(m[1]);
  52. } catch (e) {
  53. return { problem: `the header is not valid YAML: ${(e as Error).message}` };
  54. }
  55. if (!y || typeof y !== 'object') return { problem: 'the header is empty' };
  56. return {
  57. header: {
  58. id: String(y.id ?? ''),
  59. title: String(y.title ?? ''),
  60. level: y.level,
  61. description: String(y.description ?? ''),
  62. uses: list(y.uses),
  63. parts: list(y.parts),
  64. states: list(y.states),
  65. status: list(y.status),
  66. controls: y.controls && typeof y.controls === 'object' ? y.controls : {},
  67. cssProperties: list(y.cssProperties),
  68. },
  69. };
  70. }
  71. /** `<template data-state="x">` / `<template data-status="x">` → markup (trimmed). */
  72. export function parseTemplates(text: string): { templates: Record<string, string>; problems: string[] } {
  73. const templates: Record<string, string> = {}, problems: string[] = [];
  74. const re = /<template\s+data-(state|status)="([^"]+)"\s*>([\s\S]*?)<\/template>/g;
  75. for (let m; (m = re.exec(text)); ) {
  76. if (templates[m[2]] !== undefined) problems.push(`two templates for "${m[2]}"`);
  77. templates[m[2]] = m[3].trim();
  78. }
  79. return { templates, problems };
  80. }
  81. /** Everything wrong with one component file (its header, templates, markup); [] when it follows the format. */
  82. export function validate(text: string, where: { level?: string; id?: string } = {}): string[] {
  83. const { header: h, problem } = parseHeader(text);
  84. if (!h) return [problem!];
  85. const out: string[] = [];
  86. if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(h.id)) out.push(`id "${h.id}" is not kebab-case`);
  87. if (where.id && h.id !== where.id) out.push(`id "${h.id}" does not match the folder "${where.id}"`);
  88. if (!h.title) out.push('no title');
  89. if (!LEVELS.includes(h.level)) out.push(`level "${h.level}" is not one of ${LEVELS.join(', ')}`);
  90. if (where.level && h.level !== where.level) out.push(`level "${h.level}" does not match the folder "${where.level}"`);
  91. if (!h.description) out.push('no description');
  92. if (!h.states.length) out.push('no states: list at least "default"');
  93. for (const p of h.parts) if (!p.startsWith(`${h.id}-`)) out.push(`part "${p}" does not start with "${h.id}-"`);
  94. for (const [name, c] of Object.entries(h.controls)) {
  95. if (!/^[a-z][a-z0-9-]*$/.test(name)) out.push(`control "${name}" is not kebab-case`);
  96. if (!c || !KINDS.includes(c.kind)) { out.push(`control "${name}": kind "${c?.kind}" is not one of ${KINDS.join(', ')}`); continue; }
  97. if (['select', 'segment', 'swatch'].includes(c.kind) && !(Array.isArray(c.options) && c.options.length))
  98. out.push(`control "${name}": a ${c.kind} needs options`);
  99. if (c.kind === 'segment' && (c.options?.length ?? 0) > 4) out.push(`control "${name}": a segment has 2-4 options, use a select`);
  100. if (c.default !== undefined && c.options && !c.options.map(String).includes(String(c.default)))
  101. out.push(`control "${name}": the default "${c.default}" is not among the options`);
  102. if (c.kind === 'range' && !(typeof c.min === 'number' && typeof c.max === 'number')) out.push(`control "${name}": a range needs min and max`);
  103. }
  104. for (const p of h.cssProperties) if (!p.startsWith('--')) out.push(`cssProperties: "${p}" is not a custom property`);
  105. const { templates, problems } = parseTemplates(text);
  106. out.push(...problems);
  107. for (const s of [...h.states, ...h.status]) if (templates[s] === undefined) out.push(`no <template> for "${s}"`);
  108. for (const k of Object.keys(templates))
  109. if (!h.states.includes(k) && !h.status.includes(k)) out.push(`template "${k}" is neither in states nor in status`);
  110. for (const [k, t] of Object.entries(templates)) {
  111. const root = /^<([a-z][a-z0-9-]*)\b([^>]*)>/i.exec(t);
  112. if (!root) { out.push(`template "${k}": no root element`); continue; }
  113. if (!new RegExp(`\\bdata-slot="${h.id}"`).test(root[2])) out.push(`template "${k}": the root has no data-slot="${h.id}"`);
  114. if (!new RegExp(`\\bclass="(?:[^"]*\\s)?${h.id}(?:\\s[^"]*)?"`).test(root[2])) out.push(`template "${k}": the root has no class "${h.id}"`);
  115. if (h.status.includes(k) && !new RegExp(`\\bdata-status="${k}"`).test(t)) out.push(`template "${k}": the data state is not set as data-status="${k}"`);
  116. }
  117. return out;
  118. }
  119. function walk(dir: string, out: string[] = []): string[] {
  120. if (!existsSync(dir)) return out;
  121. for (const n of readdirSync(dir).sort()) {
  122. const p = join(dir, n);
  123. if (statSync(p).isDirectory()) walk(p, out);
  124. else out.push(p);
  125. }
  126. return out;
  127. }
  128. /** The components under `<root>/<libDir>/components/<level>/<id>/<id>.html`, sorted by level then id. */
  129. export function scan(root: string, libDir = LIB_DIR): Component[] {
  130. const base = join(root, libDir, 'components');
  131. const out: Component[] = [];
  132. for (const f of walk(base).filter((p) => p.endsWith('.html'))) {
  133. const rel = relative(base, f).split('/');
  134. const [level, id, file] = rel;
  135. const text = readFileSync(f, 'utf8');
  136. const problems = rel.length === 3 && file === `${id}.html` ? validate(text, { level, id }) : [`not at components/<level>/<id>/<id>.html`];
  137. const { header } = parseHeader(text);
  138. const cssPath = join(base, level, id ?? '', `${id}.css`);
  139. out.push({
  140. header: header ?? ({ id: id ?? '', level: level as any } as Header),
  141. html: relative(root, f),
  142. css: existsSync(cssPath) ? relative(root, cssPath) : null,
  143. templates: parseTemplates(text).templates,
  144. problems,
  145. });
  146. }
  147. const order = (l: string) => (LEVELS as readonly string[]).indexOf(l);
  148. return out.sort((a, b) => order(a.header.level) - order(b.header.level) || a.header.id.localeCompare(b.header.id));
  149. }