包文件→ .shtukbase/packages/shtukbase-ui-html/lib/components.ts
lib/components.ts
157 行, 7.3 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The components of the library: find them, read their headers (section 4 of the design build contract) and
- // templates, check the format. Pure functions over text, plus `scan` that reads a folder. No dependencies: Bun's YAML.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join, relative } from 'node:path';
- export const LIB = 'shtukbase-ui-html';
- /** Where the library lives in a project (and under `pages/` in the package). */
- export const LIB_DIR = `design/${LIB}`;
- export const LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'] as const;
- export const KINDS = ['select', 'segment', 'bool', 'range', 'swatch', 'text'] as const;
- export type Control = {
- kind: (typeof KINDS)[number];
- label?: string;
- options?: (string | number)[];
- default?: unknown;
- min?: number;
- max?: number;
- step?: number;
- unit?: string;
- section?: string;
- colors?: unknown;
- };
- export type Header = {
- id: string;
- title: string;
- level: (typeof LEVELS)[number];
- description: string;
- uses: string[];
- parts: string[];
- states: string[];
- status: string[];
- controls: Record<string, Control>;
- cssProperties: string[];
- };
- export type Component = {
- header: Header;
- /** Paths relative to the scanned root. */
- html: string;
- css: string | null;
- /** state or status → markup */
- templates: Record<string, string>;
- problems: string[];
- };
- const HEAD = /^\s*<!---\n([\s\S]*?)\n--->/;
- const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
- /** The header of an HTML component file, or the problem that stops reading it. */
- export function parseHeader(text: string): { header?: Header; problem?: string } {
- const m = HEAD.exec(text);
- if (!m) return { problem: 'no header: the file must start with a <!--- … ---> YAML block' };
- let y: any;
- try {
- y = Bun.YAML.parse(m[1]);
- } catch (e) {
- return { problem: `the header is not valid YAML: ${(e as Error).message}` };
- }
- if (!y || typeof y !== 'object') return { problem: 'the header is empty' };
- return {
- header: {
- id: String(y.id ?? ''),
- title: String(y.title ?? ''),
- level: y.level,
- description: String(y.description ?? ''),
- uses: list(y.uses),
- parts: list(y.parts),
- states: list(y.states),
- status: list(y.status),
- controls: y.controls && typeof y.controls === 'object' ? y.controls : {},
- cssProperties: list(y.cssProperties),
- },
- };
- }
- /** `<template data-state="x">` / `<template data-status="x">` → markup (trimmed). */
- export function parseTemplates(text: string): { templates: Record<string, string>; problems: string[] } {
- const templates: Record<string, string> = {}, problems: string[] = [];
- const re = /<template\s+data-(state|status)="([^"]+)"\s*>([\s\S]*?)<\/template>/g;
- for (let m; (m = re.exec(text)); ) {
- if (templates[m[2]] !== undefined) problems.push(`two templates for "${m[2]}"`);
- templates[m[2]] = m[3].trim();
- }
- return { templates, problems };
- }
- /** Everything wrong with one component file (its header, templates, markup); [] when it follows the format. */
- export function validate(text: string, where: { level?: string; id?: string } = {}): string[] {
- const { header: h, problem } = parseHeader(text);
- if (!h) return [problem!];
- const out: string[] = [];
- if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(h.id)) out.push(`id "${h.id}" is not kebab-case`);
- if (where.id && h.id !== where.id) out.push(`id "${h.id}" does not match the folder "${where.id}"`);
- if (!h.title) out.push('no title');
- if (!LEVELS.includes(h.level)) out.push(`level "${h.level}" is not one of ${LEVELS.join(', ')}`);
- if (where.level && h.level !== where.level) out.push(`level "${h.level}" does not match the folder "${where.level}"`);
- if (!h.description) out.push('no description');
- if (!h.states.length) out.push('no states: list at least "default"');
- for (const p of h.parts) if (!p.startsWith(`${h.id}-`)) out.push(`part "${p}" does not start with "${h.id}-"`);
- for (const [name, c] of Object.entries(h.controls)) {
- if (!/^[a-z][a-z0-9-]*$/.test(name)) out.push(`control "${name}" is not kebab-case`);
- if (!c || !KINDS.includes(c.kind)) { out.push(`control "${name}": kind "${c?.kind}" is not one of ${KINDS.join(', ')}`); continue; }
- if (['select', 'segment', 'swatch'].includes(c.kind) && !(Array.isArray(c.options) && c.options.length))
- out.push(`control "${name}": a ${c.kind} needs options`);
- if (c.kind === 'segment' && (c.options?.length ?? 0) > 4) out.push(`control "${name}": a segment has 2-4 options, use a select`);
- if (c.default !== undefined && c.options && !c.options.map(String).includes(String(c.default)))
- out.push(`control "${name}": the default "${c.default}" is not among the options`);
- if (c.kind === 'range' && !(typeof c.min === 'number' && typeof c.max === 'number')) out.push(`control "${name}": a range needs min and max`);
- }
- for (const p of h.cssProperties) if (!p.startsWith('--')) out.push(`cssProperties: "${p}" is not a custom property`);
- const { templates, problems } = parseTemplates(text);
- out.push(...problems);
- for (const s of [...h.states, ...h.status]) if (templates[s] === undefined) out.push(`no <template> for "${s}"`);
- for (const k of Object.keys(templates))
- if (!h.states.includes(k) && !h.status.includes(k)) out.push(`template "${k}" is neither in states nor in status`);
- for (const [k, t] of Object.entries(templates)) {
- const root = /^<([a-z][a-z0-9-]*)\b([^>]*)>/i.exec(t);
- if (!root) { out.push(`template "${k}": no root element`); continue; }
- if (!new RegExp(`\\bdata-slot="${h.id}"`).test(root[2])) out.push(`template "${k}": the root has no data-slot="${h.id}"`);
- if (!new RegExp(`\\bclass="(?:[^"]*\\s)?${h.id}(?:\\s[^"]*)?"`).test(root[2])) out.push(`template "${k}": the root has no class "${h.id}"`);
- 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}"`);
- }
- return out;
- }
- function walk(dir: string, out: string[] = []): string[] {
- if (!existsSync(dir)) return out;
- for (const n of readdirSync(dir).sort()) {
- const p = join(dir, n);
- if (statSync(p).isDirectory()) walk(p, out);
- else out.push(p);
- }
- return out;
- }
- /** The components under `<root>/<libDir>/components/<level>/<id>/<id>.html`, sorted by level then id. */
- export function scan(root: string, libDir = LIB_DIR): Component[] {
- const base = join(root, libDir, 'components');
- const out: Component[] = [];
- for (const f of walk(base).filter((p) => p.endsWith('.html'))) {
- const rel = relative(base, f).split('/');
- const [level, id, file] = rel;
- const text = readFileSync(f, 'utf8');
- const problems = rel.length === 3 && file === `${id}.html` ? validate(text, { level, id }) : [`not at components/<level>/<id>/<id>.html`];
- const { header } = parseHeader(text);
- const cssPath = join(base, level, id ?? '', `${id}.css`);
- out.push({
- header: header ?? ({ id: id ?? '', level: level as any } as Header),
- html: relative(root, f),
- css: existsSync(cssPath) ? relative(root, cssPath) : null,
- templates: parseTemplates(text).templates,
- problems,
- });
- }
- const order = (l: string) => (LEVELS as readonly string[]).indexOf(l);
- return out.sort((a, b) => order(a.header.level) - order(b.header.level) || a.header.id.localeCompare(b.header.id));
- }