包文件→ .shtukbase/packages/design-components/lib/project.ts
lib/project.ts
261 行, 12.3 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Reading the components of a project: where the component files are, their headers, the templates and CSS next to them,
- // grouped by id. The working directory is the project root; paths are relative to it, without a leading slash
- // (`toRoot` adds the slash the data files use). Read-only.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join, posix } from 'node:path';
- import { type Header, type Level, LEVELS, findHeader, kindOf, parseHeader } from './header.ts';
- export const COLLECTION = 'design/components.md';
- export const PAGES = 'design/components';
- export const DESIGN = 'design/design.md';
- const SKIP = new Set(['node_modules', '.git', '.shtukbase', 'dist', 'build', 'out', '.next', 'coverage', 'target', 'storybook-static']);
- export const toRoot = (rel: string) => `/${rel}`;
- const isObj = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v);
- /** Front matter of a project page as data ({} when there is no page or it has no readable front matter). */
- export function frontMatter(root: string, rel: string): Record<string, any> {
- const p = join(root, rel);
- if (!existsSync(p)) return {};
- const text = readFileSync(p, 'utf8').replace(/^/, '');
- if (!text.startsWith('---')) return {};
- const lines = text.split('\n');
- const end = lines.findIndex((l, i) => i > 0 && l.trimEnd() === '---');
- if (end < 0) return {};
- try {
- const d = Bun.YAML.parse(lines.slice(1, end).join('\n'));
- return isObj(d) ? d : {};
- } catch {
- return {};
- }
- }
- const list = (v: unknown): string[] =>
- (Array.isArray(v) ? v : typeof v === 'string' ? [v] : []).map((x) => String(x).trim().replace(/^\/+|\/+$/g, '')).filter(Boolean);
- export type Settings = { sources: string[]; style: string; libraries: string[] };
- /** `sources:` of /design/components.md; `style:` and `libraries:` of /design/design.md. */
- export function settings(root: string): Settings {
- const d = frontMatter(root, DESIGN);
- return {
- sources: list(frontMatter(root, COLLECTION).sources),
- style: typeof d.style === 'string' ? d.style.trim() : '',
- libraries: list(d.libraries),
- };
- }
- export function walk(root: string, rel: string, out: string[]): void {
- const abs = join(root, rel);
- if (!existsSync(abs)) return;
- if (!statSync(abs).isDirectory()) { out.push(rel); return; }
- for (const name of readdirSync(abs).sort()) if (!SKIP.has(name)) walk(root, `${rel}/${name}`, out);
- }
- export type Place = { dir: string; lib: string; local?: boolean };
- /** The folders that hold components: `design/<lib>/components` for every library, then the `sources:` folders. */
- export function places(root: string, s: Settings): Place[] {
- const out: Place[] = [];
- const dir = join(root, 'design');
- const targets = new Map<string, string>();
- for (const name of existsSync(dir) ? readdirSync(dir).sort() : []) {
- const base = `design/${name}`;
- if (existsSync(join(root, base, 'components'))) out.push({ dir: `${base}/components`, lib: name });
- if (!name.endsWith('.md') || !statSync(join(dir, name)).isFile()) continue;
- const [target] = list(frontMatter(root, base).target);
- if (s.sources.includes(target)) targets.set(target, name.slice(0, -3));
- }
- for (const src of s.sources) {
- if (!existsSync(join(root, src))) continue;
- const lib = targets.get(src);
- out.push(lib ? { dir: src, lib } : { dir: src, lib: src, local: true });
- }
- const rank = (p: Place) => s.libraries.includes(p.lib) ? s.libraries.indexOf(p.lib) : s.libraries.length;
- return out.sort((a, b) => rank(a) - rank(b));
- }
- export type Impl = { file: string; lib: string; kind: 'html' | 'react'; header: Header };
- type Origin = { source: string; library: string; overrides?: string };
- export type Html = Origin & { css: string | null; templates: Record<string, string> };
- export type Comp = {
- id: string;
- header: Header;
- /** The primary source (the HTML file when there is one). */
- source: string;
- html: Html | null;
- react: Origin | null;
- };
- export type Collected = {
- settings: Settings;
- comps: Comp[];
- /** Header problems (a file with a header comment that does not parse): they stop `sync`. */
- problems: string[];
- /** Things worth saying that do not stop anything. */
- notes: string[];
- overrideWarnings: { library: string; message: string }[];
- /** Every CSS file inside the component folders, for `tokens-only`. */
- cssFiles: string[];
- /** The folders that were scanned. */
- places: Place[];
- };
- /** The inner markup of each top-level `<template data-state|data-status="…">` of an HTML component file. */
- export function templatesOf(html: string): Record<string, string> {
- const out: Record<string, string> = {};
- const re = /<template\b([^>]*)>|<\/template\s*>/gi;
- let depth = 0, start = 0, attrs = '';
- for (let m = re.exec(html); m; m = re.exec(html)) {
- if (m[0][1] !== '/') {
- if (depth === 0) { start = m.index + m[0].length; attrs = m[1] ?? ''; }
- depth++;
- } else if (depth > 0 && --depth === 0) {
- const name = /\bdata-(?:status|state)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i.exec(attrs);
- const key = name ? name[1] ?? name[2] ?? name[3] : '';
- if (key && !(key in out)) out[key] = dedentMarkup(html.slice(start, m.index));
- }
- }
- return out;
- }
- function dedentMarkup(s: string): string {
- const lines = s.replace(/\r\n?/g, '\n').split('\n');
- while (lines.length && !lines[0].trim()) lines.shift();
- while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
- const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^[ \t]*/.exec(l)![0].length));
- return lines.map((l) => (Number.isFinite(indent) ? l.slice(Math.min(indent, /^[ \t]*/.exec(l)![0].length)) : l).trimEnd()).join('\n');
- }
- const sameShape = (a: Header, b: Header): string[] => {
- const diff: string[] = [];
- 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));
- if (a.level !== b.level) diff.push(`level ${a.level} / ${b.level}`);
- if (j(a.states) !== j(b.states)) diff.push('states');
- if (j(a.status) !== j(b.status)) diff.push('status');
- if (j(a.controls) !== j(b.controls)) diff.push('controls');
- return diff;
- };
- function overrideGaps(root: string, winner: Impl, base: Impl): string[] {
- const missing = (actual: Iterable<string>, wanted: Iterable<string>) => {
- const have = new Set(actual);
- return [...new Set(wanted)].filter((name) => !have.has(name));
- };
- const slots = (text: string) => [...text.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["']([^"']+)["']/g)].map((m) => m[1]);
- const source = (impl: Impl) => readFileSync(join(root, impl.file), 'utf8');
- const actual = source(winner), expected = source(base);
- const diff = sameShape(winner.header, base.header);
- const missingSlots = missing(winner.header.parts, base.header.parts);
- if (winner.kind === 'react') missingSlots.push(...missing(slots(actual), slots(expected)));
- if (missingSlots.length) diff.push(`slots ${[...new Set(missingSlots)].join(', ')}`);
- if (winner.kind === 'html') {
- const shown = templatesOf(actual), wanted = templatesOf(expected);
- for (const key of missing(Object.keys(shown), Object.keys(wanted))) diff.push(`template ${key}`);
- for (const [key, markup] of Object.entries(wanted)) {
- if (!(key in shown)) continue;
- const gaps = missing(slots(shown[key]), slots(markup));
- if (gaps.length) diff.push(`slots in ${key}: ${gaps.join(', ')}`);
- }
- }
- return diff;
- }
- export function collect(root = process.cwd()): Collected {
- const s = settings(root);
- const where = places(root, s).filter((p) => !s.libraries.length || p.local || s.libraries.includes(p.lib));
- const problems: string[] = [];
- const notes: string[] = [];
- const overrideWarnings: Collected['overrideWarnings'] = [];
- const cssFiles: string[] = [];
- const impls: Impl[] = [];
- const seen = new Set<string>();
- for (const pl of where) {
- const files: string[] = [];
- walk(root, pl.dir, files);
- for (const file of files) {
- if (seen.has(file)) continue;
- seen.add(file);
- if (file.endsWith('.css')) { cssFiles.push(file); continue; }
- const kind = kindOf(file);
- if (!kind) continue;
- const text = readFileSync(join(root, file), 'utf8');
- if (!findHeader(text)) continue;
- const p = parseHeader(text, file);
- if (!p.header) problems.push(...p.problems);
- else impls.push({ file, lib: pl.lib, kind, header: p.header });
- }
- }
- const byId = new Map<string, Impl[]>();
- for (const i of impls) byId.set(i.header.id, [...(byId.get(i.header.id) ?? []), i]);
- const comps: Comp[] = [];
- for (const [id, all] of byId) {
- const html = all.find((i) => i.kind === 'html');
- const react = all.find((i) => i.kind === 'react');
- const origin = (winner: Impl): Origin => {
- const lower = all.filter((i) => i.kind === winner.kind && i !== winner);
- for (const candidate of lower) {
- if (s.libraries.includes(winner.lib) && s.libraries.includes(candidate.lib) && winner.lib !== candidate.lib) {
- const diff = overrideGaps(root, winner, candidate);
- if (diff.length) overrideWarnings.push({
- library: winner.lib, message: `${id} (${winner.kind}) overrides ${candidate.lib} with different ${diff.join('; ')}`,
- });
- } else {
- notes.push(`${candidate.file}: another "${id}" (${candidate.kind}) is already taken from ${winner.file}; this file is ignored`);
- }
- }
- const base = lower.find((i) => i.lib !== winner.lib && s.libraries.includes(i.lib));
- return { source: toRoot(winner.file), library: winner.lib, ...(base && { overrides: base.lib }) };
- };
- const primary = (html ?? react)!;
- if (html && react) {
- const diff = sameShape(html.header, react.header);
- 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`);
- }
- let h: Html | null = null;
- if (html) {
- const cssRel = html.file.replace(/\.html?$/i, '.css');
- h = {
- ...origin(html),
- css: existsSync(join(root, cssRel)) ? toRoot(cssRel) : null,
- templates: templatesOf(readFileSync(join(root, html.file), 'utf8')),
- };
- }
- comps.push({ id, header: primary.header, source: primary.file, html: h, react: react ? origin(react) : null });
- }
- const order = (c: Comp) => LEVELS.indexOf(c.header.level as Level);
- comps.sort((a, b) => order(a) - order(b) || (a.id < b.id ? -1 : 1));
- return { settings: s, comps, problems, notes, overrideWarnings, cssFiles: cssFiles.sort(), places: where };
- }
- /** Ids of the pages in /design/components (hand-written and generated). */
- export function pageIds(root: string): string[] {
- const d = join(root, PAGES);
- return existsSync(d) ? readdirSync(d).filter((n) => n.endsWith('.md') && !n.startsWith('.')).map((n) => n.slice(0, -3)).sort() : [];
- }
- export const UI_CSS = 'lib/design/ui.css';
- /** Component CSS in level and id order, with exactly one owner per component. */
- export function resolvedCss(root: string, c: Collected): string {
- const components = c.comps.flatMap((comp) => comp.html?.css ? [{ id: comp.id, level: comp.header.level, css: comp.html.css }] : []);
- if (!components.length) return '';
- const ids = new Set(components.map(({ id }) => id));
- const hasLensParts = ['sidebar', 'panel', 'panel-section', 'button', 'select', 'layout-document', 'layout-grid',
- 'layout-canvas', 'settings-group', 'switch', 'slider', 'swatches', 'tree-item'].every((id) => ids.has(id));
- return [
- hasLensParts ? '/* Lens components included */' : '',
- '/* Generated by design-components sync. */',
- ...components.map(({ id, level, css }) => `/* ---- ${level}/${id} ---- */\n${readFileSync(join(root, css), 'utf8').trim()}`),
- ].filter(Boolean).join('\n\n') + '\n';
- }
- /** The style's files, followed by the same resolved CSS the lens kit uses. */
- export function cssFor(root: string, c: Collected): string[] {
- const out: string[] = [];
- const add = (rel: string) => { if (existsSync(join(root, rel)) && !out.includes(toRoot(rel))) out.push(toRoot(rel)); };
- const st = c.settings.style;
- if (st) for (const f of ['tokens.css', 'fonts.css', 'style.css']) add(posix.join('design', st, f));
- if (c.comps.some((comp) => comp.html?.css)) out.push(toRoot(UI_CSS));
- return out;
- }