ShtukbaseStandard
包文件→ .shtukbase/packages/icons/lib/iconlib.ts

lib/iconlib.ts

212 行, 10.7 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // The project side of page icons: settings, the icon style, tiers and what each page carries.
  2. // Read only. The working directory is the project root. Builds on the collections check library.
  3. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  4. import { join, posix } from 'node:path';
  5. import { type Head, readPage } from '../../collections/checks/lib/pages.ts';
  6. import { ctx } from '../../collections/checks/lib/schemalib.ts';
  7. import { Project } from '../../collections/checks/lib/speclib.ts';
  8. import { type StyleRules, isGlyph, isSvgPath, normHex } from './svg.ts';
  9. export const PKG = 'icons';
  10. export const TIERS = ['none', 'kind', 'pick', 'bespoke'] as const;
  11. export type Tier = (typeof TIERS)[number];
  12. export const rank = (t: Tier) => TIERS.indexOf(t);
  13. export type Settings = {
  14. folder: string; // where icon files live, from the root
  15. set: string; // the shared set: uniform icons any page of tier pick may use
  16. maxBytes: number;
  17. defaultTier: Tier; // a collection without `icons:`
  18. looseTier: Tier; // a page outside every collection
  19. collectionTier: Tier; // a collection page itself
  20. max: number; // bespoke files per collection unless the collection says otherwise
  21. heroes: string[]; // pages allowed bespoke art whatever their tier
  22. style: string; // the IconStyle page; empty: the first base one under /design
  23. sets: string[]; // the icon registries; empty: every /design/<set>/registry.json
  24. };
  25. const DEFAULTS: Settings = {
  26. folder: '/assets/icons', set: '/assets/icons/set', maxBytes: 4096,
  27. defaultTier: 'pick', looseTier: 'pick', collectionTier: 'bespoke', max: 100, heroes: [], style: '', sets: [],
  28. };
  29. export const SETTINGS_PAGE = '/design/icons.md';
  30. const asTier = (v: unknown, d: Tier): Tier => (TIERS as readonly string[]).includes(String(v)) ? (String(v) as Tier) : d;
  31. const slash = (p: string) => '/' + String(p).trim().replace(/^\/+|\/+$/g, '');
  32. export function settings(root: string): Settings {
  33. const fm = fmOf(root, SETTINGS_PAGE);
  34. const s: Settings = { ...DEFAULTS };
  35. if (typeof fm.folder === 'string' && fm.folder.trim()) s.folder = slash(fm.folder);
  36. s.set = typeof fm.set === 'string' && fm.set.trim() ? slash(fm.set) : s.folder + '/set';
  37. if (Number(fm.maxBytes) > 0) s.maxBytes = Number(fm.maxBytes);
  38. if (Number(fm.max) >= 0 && fm.max != null) s.max = Number(fm.max);
  39. s.defaultTier = asTier(fm.defaultTier, s.defaultTier);
  40. s.looseTier = asTier(fm.looseTier, s.looseTier);
  41. s.collectionTier = asTier(fm.collectionTier, s.collectionTier);
  42. if (Array.isArray(fm.heroes)) s.heroes = fm.heroes.map((x: unknown) => slash(String(x)));
  43. if (typeof fm.style === 'string') s.style = fm.style.trim();
  44. if (Array.isArray(fm.sets)) s.sets = fm.sets.map((x: unknown) => slash(String(x)));
  45. return s;
  46. }
  47. export function fmOf(root: string, page: string): Head {
  48. const p = join(root, page.replace(/^\/+/, ''));
  49. if (!existsSync(p)) return {};
  50. try { return readPage(p).fm; } catch { return {}; }
  51. }
  52. /**
  53. * The icon style a style package supplies: a page with `type: IconStyle`. Null: no style, the contract alone.
  54. * `role`: `base` (or none) may be held by default; `variant` and `reserve` are shown and rendered but never chosen by
  55. * default. `render` is the block the renderer (lib/render.js) takes; `set` is the registry of the drawings it renders.
  56. */
  57. export type IconStyle = {
  58. page: string; id: string; title: string; role: string; rules: StyleRules; palette: Record<string, string>;
  59. rawPalette: Record<string, unknown>; render: Record<string, unknown> | null; set: string; prompt: string[]; examples: string[];
  60. };
  61. /** Every IconStyle page under /design (three levels deep), in path order. */
  62. export function iconStylePages(root: string): string[] {
  63. const found: string[] = [];
  64. const walk = (dir: string, depth: number) => {
  65. const abs = join(root, dir);
  66. if (!existsSync(abs) || depth > 3) return;
  67. for (const n of readdirSync(abs).sort()) {
  68. if (n.startsWith('.')) continue;
  69. const rel = dir + '/' + n;
  70. const st = statSync(join(root, rel), { throwIfNoEntry: false });
  71. if (st?.isDirectory()) walk(rel, depth + 1);
  72. else if (n.endsWith('.md') && /^type:\s*["']?IconStyle["']?\s*$/m.test(readFileSync(join(root, rel), 'utf8').slice(0, 2048))) found.push(rel);
  73. }
  74. };
  75. walk('/design', 0);
  76. return found;
  77. }
  78. export function readIconStyle(root: string, page: string): IconStyle | null {
  79. const fm = fmOf(root, page);
  80. if (fm.type !== 'IconStyle') return null;
  81. const palette: Record<string, string> = {};
  82. const raw = fm.palette && typeof fm.palette === 'object' ? (fm.palette as Record<string, unknown>) : {};
  83. for (const [k, v] of Object.entries(raw)) {
  84. if (Array.isArray(v)) v.forEach((x, i) => (palette[`${k}${i ? '-' + i : ''}`] = normHex(String(x))));
  85. else palette[k] = normHex(String(v));
  86. }
  87. const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === 'string' && v ? [v] : []);
  88. return {
  89. page: slash(page), id: String(fm.styleId ?? page.split('/').pop()?.replace(/\.md$/, '') ?? ''), title: String(fm.title ?? page),
  90. role: String(fm.role ?? 'base'), palette, rawPalette: raw,
  91. render: fm.render && typeof fm.render === 'object' ? (fm.render as Record<string, unknown>) : null,
  92. set: typeof fm.set === 'string' && fm.set.trim() ? slash(fm.set) : '',
  93. rules: { viewBox: typeof fm.viewBox === 'string' ? fm.viewBox.trim().replace(/\s+/g, ' ') : undefined, colors: Object.values(palette), gradients: fm.gradients === true },
  94. prompt: list(fm.rules), examples: list(fm.examples).map(slash),
  95. };
  96. }
  97. /** The style the checks and the prompt hold: the one `style:` names in the settings, else the first base style. */
  98. export function iconStyle(root: string, s: Settings): IconStyle | null {
  99. if (s.style) return readIconStyle(root, s.style);
  100. for (const p of iconStylePages(root)) {
  101. const st = readIconStyle(root, p);
  102. if (st && st.role === 'base') return st;
  103. }
  104. return null;
  105. }
  106. /** Every installed icon style, the one the project holds first. */
  107. export function iconStyles(root: string, s: Settings): IconStyle[] {
  108. const all = iconStylePages(root).map((p) => readIconStyle(root, p)).filter((x): x is IconStyle => !!x);
  109. const d = iconStyle(root, s);
  110. return d ? [d, ...all.filter((x) => x.page !== d.page)] : all;
  111. }
  112. /** A page as the icon rules see it. */
  113. export type PageIcons = {
  114. id: string; // /work/tasks/x.md
  115. fm: Head;
  116. coll: string | null; // the collection the page is a record of
  117. tier: Tier;
  118. why: string; // where the tier comes from
  119. item: string; // the inherited (kind) icon, '' if none
  120. required: boolean;
  121. };
  122. export type CollIcons = { coll: string; tier: Tier; item: string; required: boolean; max: number; declared: boolean; fm: Head };
  123. export class Icons {
  124. readonly root: string;
  125. readonly s: Settings;
  126. private readonly proj: Project;
  127. private colls: Record<string, CollIcons> | null = null;
  128. constructor(root = process.cwd()) {
  129. this.proj = new Project(root);
  130. this.root = this.proj.root;
  131. this.s = settings(this.root);
  132. }
  133. collections(): Record<string, CollIcons> {
  134. if (this.colls) return this.colls;
  135. const out: Record<string, CollIcons> = {};
  136. for (const coll of ctx(this.proj).collections()) {
  137. const fm = fmOf(this.root, coll + '.md');
  138. const ic = fm.icons && typeof fm.icons === 'object' && !Array.isArray(fm.icons) ? (fm.icons as Head) : {};
  139. out[coll] = {
  140. coll, fm, declared: 'tier' in ic, tier: asTier(ic.tier, this.s.defaultTier),
  141. item: typeof ic.item === 'string' ? ic.item.trim() : '', required: ic.required === true,
  142. max: Number(ic.max) >= 0 && ic.max != null ? Number(ic.max) : this.s.max,
  143. };
  144. }
  145. return (this.colls = out);
  146. }
  147. /** Every page of the project with its tier. */
  148. pages(): PageIcons[] {
  149. const c = ctx(this.proj);
  150. const colls = this.collections();
  151. const inColl = new Map<string, string>();
  152. for (const coll of Object.keys(colls)) for (const r of c.records(coll)) inColl.set(r.id, coll);
  153. const out: PageIcons[] = [];
  154. for (const id of [...c.files()].sort()) {
  155. const fm = fmOf(this.root, id);
  156. out.push(this.classify(id, fm, inColl.get(id) ?? null));
  157. }
  158. return out;
  159. }
  160. classify(id: string, fm: Head, coll: string | null): PageIcons {
  161. const ci = coll ? this.collections()[coll] : null;
  162. const base = { id, fm, coll, item: ci?.item ?? '', required: ci?.required ?? false };
  163. if (this.s.heroes.includes(id)) return { ...base, tier: 'bespoke', why: `a hero page in ${SETTINGS_PAGE}` };
  164. if (fm.type === 'Collection') return { ...base, tier: this.s.collectionTier, why: 'a collection page (collectionTier)' };
  165. if (ci) return { ...base, tier: ci.tier, why: ci.declared ? `icons.tier of ${coll}.md` : `no icons.tier in ${coll}.md, defaultTier` };
  166. return { ...base, tier: this.s.looseTier, why: 'a page outside collections (looseTier)' };
  167. }
  168. /** The record of a collection by its page path, or a loose page. */
  169. page(id: string): PageIcons {
  170. const c = ctx(this.proj);
  171. const p = slash(id).replace(/(?<!\.md)$/, '.md');
  172. 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);
  173. return this.classify(p, fmOf(this.root, p), null);
  174. }
  175. /** A file path of an icon value as written on a page: root-absolute or relative to the page's folder. */
  176. resolve(page: string, v: string): string {
  177. const s = v.trim();
  178. return s.startsWith('/') ? posix.normalize(s) : posix.normalize(posix.join(posix.dirname(page), s));
  179. }
  180. inFolder = (path: string) => path.startsWith(this.s.folder + '/');
  181. inSet = (path: string) => path.startsWith(this.s.set + '/');
  182. }
  183. /** What a page's own `icon` and `art` are. */
  184. export function ownIcons(p: PageIcons): { icon: string; art: string } {
  185. const str = (v: unknown) => (typeof v === 'string' ? v.trim() : v == null ? '' : String(v));
  186. return { icon: str(p.fm.icon), art: str(p.fm.art) };
  187. }
  188. export { isGlyph, isSvgPath };
  189. // ---- the norm as the project holds it -------------------------------------------------
  190. export type Norm = { id: string; mode: string; active: boolean };
  191. export function norm(root: string, id: string, fallback = 'enforce'): Norm {
  192. const fm = fmOf(root, `/norms/rules/${PKG}/${id}.md`);
  193. if (!Object.keys(fm).length) return { id, mode: fallback, active: true };
  194. return { id, mode: String(fm.mode ?? fallback).trim(), active: String(fm.status ?? 'active').trim() === 'active' };
  195. }
  196. /** Prints the findings; only a norm in force in enforce mode fails. */
  197. export function finish(n: Norm, findings: string[]): void {
  198. if (!n.active) return void (process.exitCode = 0);
  199. const soft = n.mode !== 'enforce';
  200. if (findings.length) console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
  201. process.exitCode = findings.length && !soft ? 1 : 0;
  202. }