包文件→ .shtukbase/packages/icons/lib/iconlib.ts
lib/iconlib.ts
212 行, 10.7 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The project side of page icons: settings, the icon style, tiers and what each page carries.
- // Read only. The working directory is the project root. Builds on the collections check library.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join, posix } from 'node:path';
- import { type Head, readPage } from '../../collections/checks/lib/pages.ts';
- import { ctx } from '../../collections/checks/lib/schemalib.ts';
- import { Project } from '../../collections/checks/lib/speclib.ts';
- import { type StyleRules, isGlyph, isSvgPath, normHex } from './svg.ts';
- export const PKG = 'icons';
- export const TIERS = ['none', 'kind', 'pick', 'bespoke'] as const;
- export type Tier = (typeof TIERS)[number];
- export const rank = (t: Tier) => TIERS.indexOf(t);
- export type Settings = {
- folder: string; // where icon files live, from the root
- set: string; // the shared set: uniform icons any page of tier pick may use
- maxBytes: number;
- defaultTier: Tier; // a collection without `icons:`
- looseTier: Tier; // a page outside every collection
- collectionTier: Tier; // a collection page itself
- max: number; // bespoke files per collection unless the collection says otherwise
- heroes: string[]; // pages allowed bespoke art whatever their tier
- style: string; // the IconStyle page; empty: the first base one under /design
- sets: string[]; // the icon registries; empty: every /design/<set>/registry.json
- };
- const DEFAULTS: Settings = {
- folder: '/assets/icons', set: '/assets/icons/set', maxBytes: 4096,
- defaultTier: 'pick', looseTier: 'pick', collectionTier: 'bespoke', max: 100, heroes: [], style: '', sets: [],
- };
- export const SETTINGS_PAGE = '/design/icons.md';
- const asTier = (v: unknown, d: Tier): Tier => (TIERS as readonly string[]).includes(String(v)) ? (String(v) as Tier) : d;
- const slash = (p: string) => '/' + String(p).trim().replace(/^\/+|\/+$/g, '');
- export function settings(root: string): Settings {
- const fm = fmOf(root, SETTINGS_PAGE);
- const s: Settings = { ...DEFAULTS };
- if (typeof fm.folder === 'string' && fm.folder.trim()) s.folder = slash(fm.folder);
- s.set = typeof fm.set === 'string' && fm.set.trim() ? slash(fm.set) : s.folder + '/set';
- if (Number(fm.maxBytes) > 0) s.maxBytes = Number(fm.maxBytes);
- if (Number(fm.max) >= 0 && fm.max != null) s.max = Number(fm.max);
- s.defaultTier = asTier(fm.defaultTier, s.defaultTier);
- s.looseTier = asTier(fm.looseTier, s.looseTier);
- s.collectionTier = asTier(fm.collectionTier, s.collectionTier);
- if (Array.isArray(fm.heroes)) s.heroes = fm.heroes.map((x: unknown) => slash(String(x)));
- if (typeof fm.style === 'string') s.style = fm.style.trim();
- if (Array.isArray(fm.sets)) s.sets = fm.sets.map((x: unknown) => slash(String(x)));
- return s;
- }
- export function fmOf(root: string, page: string): Head {
- const p = join(root, page.replace(/^\/+/, ''));
- if (!existsSync(p)) return {};
- try { return readPage(p).fm; } catch { return {}; }
- }
- /**
- * The icon style a style package supplies: a page with `type: IconStyle`. Null: no style, the contract alone.
- * `role`: `base` (or none) may be held by default; `variant` and `reserve` are shown and rendered but never chosen by
- * default. `render` is the block the renderer (lib/render.js) takes; `set` is the registry of the drawings it renders.
- */
- export type IconStyle = {
- page: string; id: string; title: string; role: string; rules: StyleRules; palette: Record<string, string>;
- rawPalette: Record<string, unknown>; render: Record<string, unknown> | null; set: string; prompt: string[]; examples: string[];
- };
- /** Every IconStyle page under /design (three levels deep), in path order. */
- export function iconStylePages(root: string): string[] {
- const found: string[] = [];
- const walk = (dir: string, depth: number) => {
- const abs = join(root, dir);
- if (!existsSync(abs) || depth > 3) return;
- for (const n of readdirSync(abs).sort()) {
- if (n.startsWith('.')) continue;
- const rel = dir + '/' + n;
- const st = statSync(join(root, rel), { throwIfNoEntry: false });
- if (st?.isDirectory()) walk(rel, depth + 1);
- else if (n.endsWith('.md') && /^type:\s*["']?IconStyle["']?\s*$/m.test(readFileSync(join(root, rel), 'utf8').slice(0, 2048))) found.push(rel);
- }
- };
- walk('/design', 0);
- return found;
- }
- export function readIconStyle(root: string, page: string): IconStyle | null {
- const fm = fmOf(root, page);
- if (fm.type !== 'IconStyle') return null;
- const palette: Record<string, string> = {};
- const raw = fm.palette && typeof fm.palette === 'object' ? (fm.palette as Record<string, unknown>) : {};
- for (const [k, v] of Object.entries(raw)) {
- if (Array.isArray(v)) v.forEach((x, i) => (palette[`${k}${i ? '-' + i : ''}`] = normHex(String(x))));
- else palette[k] = normHex(String(v));
- }
- const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === 'string' && v ? [v] : []);
- return {
- page: slash(page), id: String(fm.styleId ?? page.split('/').pop()?.replace(/\.md$/, '') ?? ''), title: String(fm.title ?? page),
- role: String(fm.role ?? 'base'), palette, rawPalette: raw,
- render: fm.render && typeof fm.render === 'object' ? (fm.render as Record<string, unknown>) : null,
- set: typeof fm.set === 'string' && fm.set.trim() ? slash(fm.set) : '',
- rules: { viewBox: typeof fm.viewBox === 'string' ? fm.viewBox.trim().replace(/\s+/g, ' ') : undefined, colors: Object.values(palette), gradients: fm.gradients === true },
- prompt: list(fm.rules), examples: list(fm.examples).map(slash),
- };
- }
- /** The style the checks and the prompt hold: the one `style:` names in the settings, else the first base style. */
- export function iconStyle(root: string, s: Settings): IconStyle | null {
- if (s.style) return readIconStyle(root, s.style);
- for (const p of iconStylePages(root)) {
- const st = readIconStyle(root, p);
- if (st && st.role === 'base') return st;
- }
- return null;
- }
- /** Every installed icon style, the one the project holds first. */
- export function iconStyles(root: string, s: Settings): IconStyle[] {
- const all = iconStylePages(root).map((p) => readIconStyle(root, p)).filter((x): x is IconStyle => !!x);
- const d = iconStyle(root, s);
- return d ? [d, ...all.filter((x) => x.page !== d.page)] : all;
- }
- /** A page as the icon rules see it. */
- export type PageIcons = {
- id: string; // /work/tasks/x.md
- fm: Head;
- coll: string | null; // the collection the page is a record of
- tier: Tier;
- why: string; // where the tier comes from
- item: string; // the inherited (kind) icon, '' if none
- required: boolean;
- };
- export type CollIcons = { coll: string; tier: Tier; item: string; required: boolean; max: number; declared: boolean; fm: Head };
- export class Icons {
- readonly root: string;
- readonly s: Settings;
- private readonly proj: Project;
- private colls: Record<string, CollIcons> | null = null;
- constructor(root = process.cwd()) {
- this.proj = new Project(root);
- this.root = this.proj.root;
- this.s = settings(this.root);
- }
- collections(): Record<string, CollIcons> {
- if (this.colls) return this.colls;
- const out: Record<string, CollIcons> = {};
- for (const coll of ctx(this.proj).collections()) {
- const fm = fmOf(this.root, coll + '.md');
- const ic = fm.icons && typeof fm.icons === 'object' && !Array.isArray(fm.icons) ? (fm.icons as Head) : {};
- out[coll] = {
- coll, fm, declared: 'tier' in ic, tier: asTier(ic.tier, this.s.defaultTier),
- item: typeof ic.item === 'string' ? ic.item.trim() : '', required: ic.required === true,
- max: Number(ic.max) >= 0 && ic.max != null ? Number(ic.max) : this.s.max,
- };
- }
- return (this.colls = out);
- }
- /** Every page of the project with its tier. */
- pages(): PageIcons[] {
- const c = ctx(this.proj);
- const colls = this.collections();
- const inColl = new Map<string, string>();
- for (const coll of Object.keys(colls)) for (const r of c.records(coll)) inColl.set(r.id, coll);
- const out: PageIcons[] = [];
- for (const id of [...c.files()].sort()) {
- const fm = fmOf(this.root, id);
- out.push(this.classify(id, fm, inColl.get(id) ?? null));
- }
- return out;
- }
- classify(id: string, fm: Head, coll: string | null): PageIcons {
- const ci = coll ? this.collections()[coll] : null;
- const base = { id, fm, coll, item: ci?.item ?? '', required: ci?.required ?? false };
- if (this.s.heroes.includes(id)) return { ...base, tier: 'bespoke', why: `a hero page in ${SETTINGS_PAGE}` };
- if (fm.type === 'Collection') return { ...base, tier: this.s.collectionTier, why: 'a collection page (collectionTier)' };
- if (ci) return { ...base, tier: ci.tier, why: ci.declared ? `icons.tier of ${coll}.md` : `no icons.tier in ${coll}.md, defaultTier` };
- return { ...base, tier: this.s.looseTier, why: 'a page outside collections (looseTier)' };
- }
- /** The record of a collection by its page path, or a loose page. */
- page(id: string): PageIcons {
- const c = ctx(this.proj);
- const p = slash(id).replace(/(?<!\.md)$/, '.md');
- for (const coll of Object.keys(this.collections())) if (c.records(coll).some((r) => r.id === p)) return this.classify(p, fmOf(this.root, p), coll);
- return this.classify(p, fmOf(this.root, p), null);
- }
- /** A file path of an icon value as written on a page: root-absolute or relative to the page's folder. */
- resolve(page: string, v: string): string {
- const s = v.trim();
- return s.startsWith('/') ? posix.normalize(s) : posix.normalize(posix.join(posix.dirname(page), s));
- }
- inFolder = (path: string) => path.startsWith(this.s.folder + '/');
- inSet = (path: string) => path.startsWith(this.s.set + '/');
- }
- /** What a page's own `icon` and `art` are. */
- export function ownIcons(p: PageIcons): { icon: string; art: string } {
- const str = (v: unknown) => (typeof v === 'string' ? v.trim() : v == null ? '' : String(v));
- return { icon: str(p.fm.icon), art: str(p.fm.art) };
- }
- export { isGlyph, isSvgPath };
- // ---- the norm as the project holds it -------------------------------------------------
- export type Norm = { id: string; mode: string; active: boolean };
- export function norm(root: string, id: string, fallback = 'enforce'): Norm {
- const fm = fmOf(root, `/norms/rules/${PKG}/${id}.md`);
- if (!Object.keys(fm).length) return { id, mode: fallback, active: true };
- return { id, mode: String(fm.mode ?? fallback).trim(), active: String(fm.status ?? 'active').trim() === 'active' };
- }
- /** Prints the findings; only a norm in force in enforce mode fails. */
- export function finish(n: Norm, findings: string[]): void {
- if (!n.active) return void (process.exitCode = 0);
- const soft = n.mode !== 'enforce';
- if (findings.length) console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
- process.exitCode = findings.length && !soft ? 1 : 0;
- }