archivo del paquete→ .shtukbase/packages/design-lenses/lib/project.ts
lib/project.ts
110 líneas, 5.2 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The IO shell of the style specimen's data: reads the project (the root is the working directory of an action)
- // and gives the object of lib/design/style.data.js. Pure work is in style-data.ts.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- import { type StyleData, type StyleRef, parseTokensCss, sortTokens, styleDataJs, styleTokens } from './style-data.ts';
- export const OUT = 'lib/design/style.data.js';
- const DESIGN = 'design';
- // Folders under /design/ that are not styles even when they hold CSS.
- const NOT_STYLES = new Set(['components', 'stories', 'assets']);
- const read = (p: string) => readFileSync(p, 'utf8');
- const json = (p: string, problems: string[]): unknown => {
- try { return JSON.parse(read(p)); } catch (e) { problems.push(`${p}: not JSON (${(e as Error).message})`); return null; }
- };
- /** The YAML header of a markdown page as flat `key: value` strings (enough for `style:`, `title:`). */
- export function header(text: string): Record<string, string> {
- const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
- const out: Record<string, string> = {};
- if (!m) return out;
- for (const line of m[1].split(/\r?\n/)) {
- const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
- if (kv) out[kv[1]] = kv[2].trim().replace(/^(["'])(.*)\1$/, '$2');
- }
- return out;
- }
- /** The chosen style: the field `style` in the header of /design/design.md. */
- export function chosenStyle(root: string): string {
- const p = join(root, DESIGN, 'design.md');
- return existsSync(p) ? (header(read(p)).style ?? '') : '';
- }
- /** The title of a package from its installed package.md, else ''. */
- function packageTitle(root: string, id: string): string {
- const p = join(root, '.shtukbase', 'packages', id, 'package.md');
- return existsSync(p) ? (header(read(p)).title ?? '') : '';
- }
- const files = (dir: string) => (existsSync(dir) ? readdirSync(dir).sort() : []);
- const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
- /** The CSS files of a style, from the root, in the order a page links them. */
- export function styleCss(root: string, id: string): string[] {
- return ['fonts.css', 'tokens.css', 'style.css'].filter((f) => existsSync(join(root, DESIGN, id, f))).map((f) => `/${DESIGN}/${id}/${f}`);
- }
- /** Every style installed in the project: a folder /design/<id>/ with tokens.json or tokens.css. */
- export function installedStyles(root: string): StyleRef[] {
- return files(join(root, DESIGN))
- .filter((id) => !NOT_STYLES.has(id) && isDir(join(root, DESIGN, id)))
- .filter((id) => existsSync(join(root, DESIGN, id, 'tokens.json')) || existsSync(join(root, DESIGN, id, 'tokens.css')))
- .map((id) => ({ id, title: packageTitle(root, id) || id, css: styleCss(root, id) }));
- }
- /** The pictures of a style (the mark, icons): image files under /design/<id>/assets/, from the root. */
- function styleAssets(root: string, id: string): string[] {
- const out: string[] = [];
- const go = (dir: string, rel: string) => {
- for (const f of files(dir)) {
- const abs = join(dir, f);
- if (isDir(abs)) go(abs, `${rel}/${f}`);
- else if (/\.(svg|png|jpe?g|webp|gif)$/i.test(f)) out.push(`${rel}/${f}`);
- }
- };
- go(join(root, DESIGN, id, 'assets'), `/${DESIGN}/${id}/assets`);
- return out;
- }
- /** The style's pages /design/<id>/*.md: the specimen shows them as extra sections. */
- function styleSections(root: string, id: string) {
- return files(join(root, DESIGN, id)).filter((f) => f.endsWith('.md')).map((f) => {
- const text = read(join(root, DESIGN, id, f));
- const h1 = /^#\s+(.+)$/m.exec(text.replace(/^---[\s\S]*?\n---/, ''));
- return { title: header(text).title || (h1 ? h1[1].trim() : f.replace(/\.md$/, '')), page: `/${DESIGN}/${id}/${f}` };
- });
- }
- /** The data of the specimen for the project at `root`, or a reason why there is none. */
- export function buildStyle(root: string): { data: StyleData | null; error: string } {
- const id = chosenStyle(root);
- if (!id) return { data: null, error: 'no style is chosen: set `style: <id>` in the header of /design/design.md' };
- const dir = join(root, DESIGN, id);
- if (!isDir(dir)) return { data: null, error: `the chosen style ${id} is not installed: there is no /design/${id}/` };
- const problems: string[] = [];
- const lightP = join(dir, 'tokens.json');
- const darkP = join(dir, 'tokens.dark.json');
- const cssP = join(dir, 'tokens.css');
- let tokens;
- if (existsSync(lightP)) {
- tokens = styleTokens(json(lightP, problems), existsSync(darkP) ? json(darkP, problems) : null, problems);
- } else if (existsSync(cssP)) {
- tokens = parseTokensCss(read(cssP));
- } else {
- return { data: null, error: `the style ${id} has neither /design/${id}/tokens.json nor tokens.css` };
- }
- const data: StyleData = {
- version: 1, id, title: packageTitle(root, id) || id, tokens: sortTokens(tokens), sections: styleSections(root, id),
- css: styleCss(root, id), assets: styleAssets(root, id), styles: installedStyles(root),
- problems: problems.map((p) => p.replace(root, '').replace(/^\/+/, '')),
- };
- return { data, error: '' };
- }
- /** The text lib/design/style.data.js should have, or the error. */
- export function expectedText(root: string): { text: string; error: string } {
- const { data, error } = buildStyle(root);
- return { text: data ? styleDataJs(data) : '', error };
- }