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

lib/project.ts

261 líneas, 12.3 KB.

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

  1. // Reading the components of a project: where the component files are, their headers, the templates and CSS next to them,
  2. // grouped by id. The working directory is the project root; paths are relative to it, without a leading slash
  3. // (`toRoot` adds the slash the data files use). Read-only.
  4. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  5. import { join, posix } from 'node:path';
  6. import { type Header, type Level, LEVELS, findHeader, kindOf, parseHeader } from './header.ts';
  7. export const COLLECTION = 'design/components.md';
  8. export const PAGES = 'design/components';
  9. export const DESIGN = 'design/design.md';
  10. const SKIP = new Set(['node_modules', '.git', '.shtukbase', 'dist', 'build', 'out', '.next', 'coverage', 'target', 'storybook-static']);
  11. export const toRoot = (rel: string) => `/${rel}`;
  12. const isObj = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v);
  13. /** Front matter of a project page as data ({} when there is no page or it has no readable front matter). */
  14. export function frontMatter(root: string, rel: string): Record<string, any> {
  15. const p = join(root, rel);
  16. if (!existsSync(p)) return {};
  17. const text = readFileSync(p, 'utf8').replace(/^/, '');
  18. if (!text.startsWith('---')) return {};
  19. const lines = text.split('\n');
  20. const end = lines.findIndex((l, i) => i > 0 && l.trimEnd() === '---');
  21. if (end < 0) return {};
  22. try {
  23. const d = Bun.YAML.parse(lines.slice(1, end).join('\n'));
  24. return isObj(d) ? d : {};
  25. } catch {
  26. return {};
  27. }
  28. }
  29. const list = (v: unknown): string[] =>
  30. (Array.isArray(v) ? v : typeof v === 'string' ? [v] : []).map((x) => String(x).trim().replace(/^\/+|\/+$/g, '')).filter(Boolean);
  31. export type Settings = { sources: string[]; style: string; libraries: string[] };
  32. /** `sources:` of /design/components.md; `style:` and `libraries:` of /design/design.md. */
  33. export function settings(root: string): Settings {
  34. const d = frontMatter(root, DESIGN);
  35. return {
  36. sources: list(frontMatter(root, COLLECTION).sources),
  37. style: typeof d.style === 'string' ? d.style.trim() : '',
  38. libraries: list(d.libraries),
  39. };
  40. }
  41. export function walk(root: string, rel: string, out: string[]): void {
  42. const abs = join(root, rel);
  43. if (!existsSync(abs)) return;
  44. if (!statSync(abs).isDirectory()) { out.push(rel); return; }
  45. for (const name of readdirSync(abs).sort()) if (!SKIP.has(name)) walk(root, `${rel}/${name}`, out);
  46. }
  47. export type Place = { dir: string; lib: string; local?: boolean };
  48. /** The folders that hold components: `design/<lib>/components` for every library, then the `sources:` folders. */
  49. export function places(root: string, s: Settings): Place[] {
  50. const out: Place[] = [];
  51. const dir = join(root, 'design');
  52. const targets = new Map<string, string>();
  53. for (const name of existsSync(dir) ? readdirSync(dir).sort() : []) {
  54. const base = `design/${name}`;
  55. if (existsSync(join(root, base, 'components'))) out.push({ dir: `${base}/components`, lib: name });
  56. if (!name.endsWith('.md') || !statSync(join(dir, name)).isFile()) continue;
  57. const [target] = list(frontMatter(root, base).target);
  58. if (s.sources.includes(target)) targets.set(target, name.slice(0, -3));
  59. }
  60. for (const src of s.sources) {
  61. if (!existsSync(join(root, src))) continue;
  62. const lib = targets.get(src);
  63. out.push(lib ? { dir: src, lib } : { dir: src, lib: src, local: true });
  64. }
  65. const rank = (p: Place) => s.libraries.includes(p.lib) ? s.libraries.indexOf(p.lib) : s.libraries.length;
  66. return out.sort((a, b) => rank(a) - rank(b));
  67. }
  68. export type Impl = { file: string; lib: string; kind: 'html' | 'react'; header: Header };
  69. type Origin = { source: string; library: string; overrides?: string };
  70. export type Html = Origin & { css: string | null; templates: Record<string, string> };
  71. export type Comp = {
  72. id: string;
  73. header: Header;
  74. /** The primary source (the HTML file when there is one). */
  75. source: string;
  76. html: Html | null;
  77. react: Origin | null;
  78. };
  79. export type Collected = {
  80. settings: Settings;
  81. comps: Comp[];
  82. /** Header problems (a file with a header comment that does not parse): they stop `sync`. */
  83. problems: string[];
  84. /** Things worth saying that do not stop anything. */
  85. notes: string[];
  86. overrideWarnings: { library: string; message: string }[];
  87. /** Every CSS file inside the component folders, for `tokens-only`. */
  88. cssFiles: string[];
  89. /** The folders that were scanned. */
  90. places: Place[];
  91. };
  92. /** The inner markup of each top-level `<template data-state|data-status="…">` of an HTML component file. */
  93. export function templatesOf(html: string): Record<string, string> {
  94. const out: Record<string, string> = {};
  95. const re = /<template\b([^>]*)>|<\/template\s*>/gi;
  96. let depth = 0, start = 0, attrs = '';
  97. for (let m = re.exec(html); m; m = re.exec(html)) {
  98. if (m[0][1] !== '/') {
  99. if (depth === 0) { start = m.index + m[0].length; attrs = m[1] ?? ''; }
  100. depth++;
  101. } else if (depth > 0 && --depth === 0) {
  102. const name = /\bdata-(?:status|state)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i.exec(attrs);
  103. const key = name ? name[1] ?? name[2] ?? name[3] : '';
  104. if (key && !(key in out)) out[key] = dedentMarkup(html.slice(start, m.index));
  105. }
  106. }
  107. return out;
  108. }
  109. function dedentMarkup(s: string): string {
  110. const lines = s.replace(/\r\n?/g, '\n').split('\n');
  111. while (lines.length && !lines[0].trim()) lines.shift();
  112. while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
  113. const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^[ \t]*/.exec(l)![0].length));
  114. return lines.map((l) => (Number.isFinite(indent) ? l.slice(Math.min(indent, /^[ \t]*/.exec(l)![0].length)) : l).trimEnd()).join('\n');
  115. }
  116. const sameShape = (a: Header, b: Header): string[] => {
  117. const diff: string[] = [];
  118. const j = (v: unknown) => JSON.stringify(v, (_k, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => (p < q ? -1 : 1))) : x));
  119. if (a.level !== b.level) diff.push(`level ${a.level} / ${b.level}`);
  120. if (j(a.states) !== j(b.states)) diff.push('states');
  121. if (j(a.status) !== j(b.status)) diff.push('status');
  122. if (j(a.controls) !== j(b.controls)) diff.push('controls');
  123. return diff;
  124. };
  125. function overrideGaps(root: string, winner: Impl, base: Impl): string[] {
  126. const missing = (actual: Iterable<string>, wanted: Iterable<string>) => {
  127. const have = new Set(actual);
  128. return [...new Set(wanted)].filter((name) => !have.has(name));
  129. };
  130. const slots = (text: string) => [...text.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["']([^"']+)["']/g)].map((m) => m[1]);
  131. const source = (impl: Impl) => readFileSync(join(root, impl.file), 'utf8');
  132. const actual = source(winner), expected = source(base);
  133. const diff = sameShape(winner.header, base.header);
  134. const missingSlots = missing(winner.header.parts, base.header.parts);
  135. if (winner.kind === 'react') missingSlots.push(...missing(slots(actual), slots(expected)));
  136. if (missingSlots.length) diff.push(`slots ${[...new Set(missingSlots)].join(', ')}`);
  137. if (winner.kind === 'html') {
  138. const shown = templatesOf(actual), wanted = templatesOf(expected);
  139. for (const key of missing(Object.keys(shown), Object.keys(wanted))) diff.push(`template ${key}`);
  140. for (const [key, markup] of Object.entries(wanted)) {
  141. if (!(key in shown)) continue;
  142. const gaps = missing(slots(shown[key]), slots(markup));
  143. if (gaps.length) diff.push(`slots in ${key}: ${gaps.join(', ')}`);
  144. }
  145. }
  146. return diff;
  147. }
  148. export function collect(root = process.cwd()): Collected {
  149. const s = settings(root);
  150. const where = places(root, s).filter((p) => !s.libraries.length || p.local || s.libraries.includes(p.lib));
  151. const problems: string[] = [];
  152. const notes: string[] = [];
  153. const overrideWarnings: Collected['overrideWarnings'] = [];
  154. const cssFiles: string[] = [];
  155. const impls: Impl[] = [];
  156. const seen = new Set<string>();
  157. for (const pl of where) {
  158. const files: string[] = [];
  159. walk(root, pl.dir, files);
  160. for (const file of files) {
  161. if (seen.has(file)) continue;
  162. seen.add(file);
  163. if (file.endsWith('.css')) { cssFiles.push(file); continue; }
  164. const kind = kindOf(file);
  165. if (!kind) continue;
  166. const text = readFileSync(join(root, file), 'utf8');
  167. if (!findHeader(text)) continue;
  168. const p = parseHeader(text, file);
  169. if (!p.header) problems.push(...p.problems);
  170. else impls.push({ file, lib: pl.lib, kind, header: p.header });
  171. }
  172. }
  173. const byId = new Map<string, Impl[]>();
  174. for (const i of impls) byId.set(i.header.id, [...(byId.get(i.header.id) ?? []), i]);
  175. const comps: Comp[] = [];
  176. for (const [id, all] of byId) {
  177. const html = all.find((i) => i.kind === 'html');
  178. const react = all.find((i) => i.kind === 'react');
  179. const origin = (winner: Impl): Origin => {
  180. const lower = all.filter((i) => i.kind === winner.kind && i !== winner);
  181. for (const candidate of lower) {
  182. if (s.libraries.includes(winner.lib) && s.libraries.includes(candidate.lib) && winner.lib !== candidate.lib) {
  183. const diff = overrideGaps(root, winner, candidate);
  184. if (diff.length) overrideWarnings.push({
  185. library: winner.lib, message: `${id} (${winner.kind}) overrides ${candidate.lib} with different ${diff.join('; ')}`,
  186. });
  187. } else {
  188. notes.push(`${candidate.file}: another "${id}" (${candidate.kind}) is already taken from ${winner.file}; this file is ignored`);
  189. }
  190. }
  191. const base = lower.find((i) => i.lib !== winner.lib && s.libraries.includes(i.lib));
  192. return { source: toRoot(winner.file), library: winner.lib, ...(base && { overrides: base.lib }) };
  193. };
  194. const primary = (html ?? react)!;
  195. if (html && react) {
  196. const diff = sameShape(html.header, react.header);
  197. if (diff.length) notes.push(`${react.file}: differs from ${html.file} in ${diff.join(', ')} — the same component should have the same levels, states and controls in both libraries`);
  198. }
  199. let h: Html | null = null;
  200. if (html) {
  201. const cssRel = html.file.replace(/\.html?$/i, '.css');
  202. h = {
  203. ...origin(html),
  204. css: existsSync(join(root, cssRel)) ? toRoot(cssRel) : null,
  205. templates: templatesOf(readFileSync(join(root, html.file), 'utf8')),
  206. };
  207. }
  208. comps.push({ id, header: primary.header, source: primary.file, html: h, react: react ? origin(react) : null });
  209. }
  210. const order = (c: Comp) => LEVELS.indexOf(c.header.level as Level);
  211. comps.sort((a, b) => order(a) - order(b) || (a.id < b.id ? -1 : 1));
  212. return { settings: s, comps, problems, notes, overrideWarnings, cssFiles: cssFiles.sort(), places: where };
  213. }
  214. /** Ids of the pages in /design/components (hand-written and generated). */
  215. export function pageIds(root: string): string[] {
  216. const d = join(root, PAGES);
  217. return existsSync(d) ? readdirSync(d).filter((n) => n.endsWith('.md') && !n.startsWith('.')).map((n) => n.slice(0, -3)).sort() : [];
  218. }
  219. export const UI_CSS = 'lib/design/ui.css';
  220. /** Component CSS in level and id order, with exactly one owner per component. */
  221. export function resolvedCss(root: string, c: Collected): string {
  222. const components = c.comps.flatMap((comp) => comp.html?.css ? [{ id: comp.id, level: comp.header.level, css: comp.html.css }] : []);
  223. if (!components.length) return '';
  224. const ids = new Set(components.map(({ id }) => id));
  225. const hasLensParts = ['sidebar', 'panel', 'panel-section', 'button', 'select', 'layout-document', 'layout-grid',
  226. 'layout-canvas', 'settings-group', 'switch', 'slider', 'swatches', 'tree-item'].every((id) => ids.has(id));
  227. return [
  228. hasLensParts ? '/* Lens components included */' : '',
  229. '/* Generated by design-components sync. */',
  230. ...components.map(({ id, level, css }) => `/* ---- ${level}/${id} ---- */\n${readFileSync(join(root, css), 'utf8').trim()}`),
  231. ].filter(Boolean).join('\n\n') + '\n';
  232. }
  233. /** The style's files, followed by the same resolved CSS the lens kit uses. */
  234. export function cssFor(root: string, c: Collected): string[] {
  235. const out: string[] = [];
  236. const add = (rel: string) => { if (existsSync(join(root, rel)) && !out.includes(toRoot(rel))) out.push(toRoot(rel)); };
  237. const st = c.settings.style;
  238. if (st) for (const f of ['tokens.css', 'fonts.css', 'style.css']) add(posix.join('design', st, f));
  239. if (c.comps.some((comp) => comp.html?.css)) out.push(toRoot(UI_CSS));
  240. return out;
  241. }