ShtukbaseStandard
包文件→ .shtukbase/packages/ontology/actions/lib/render_layer_ontology.ts

actions/lib/render_layer_ontology.ts

614 行, 30.8 KB.

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

  1. // Static lens "Links of concepts": the concepts of all layers of the base and the links between them, one graph.
  2. //
  3. // What is read (paths from the base root):
  4. // <layer>/ontology.md the layer description (title only)
  5. // <layer>/ontology/concepts/*.md one file per concept (type Concept: id, kind, collection, contour, aka)
  6. // <layer>/*.md collections of the layer; fields `kind: relation` give the edges,
  7. // the label of an edge is the field name; `kind: phase, contour:` gives the contour
  8. // <layer>/contours/**/*.md contours: states are the pages listed in `phases`
  9. // A collection with `itemType` that has no concept file is drawn as a concept anyway and marked
  10. // "no concept file" (the layer was not split yet).
  11. //
  12. // What is drawn (the lens is built on the lens kit, template `canvas`):
  13. // - the concepts are records of window.SHTUKS (type Concept), the relation fields of their collections are record
  14. // fields `rel:<field>`; the kit draws the cards, the arrows by those fields, the legend, the side panel and the zoom;
  15. // - one region per layer, arrows between regions; concepts of other layers that are not in the base (bridges)
  16. // are a region "Outside the base";
  17. // - kinds of links: between concepts, provenance (sourceDocs, sourceMeetings; hidden by default);
  18. // - a counters row above the canvas, concept cards under it; a click opens the concept card in the side panel.
  19. // The kit (kit.css, kit.js, templates/canvas.js) is embedded as is: one file, no network, opens from disk.
  20. // Its version and sha256 are in <meta name="shtuk:kit">.
  21. //
  22. // Sources (`sources` in the header): the layer masks above plus the few files of other layers that were read
  23. // for grey nodes (collection page, concept file).
  24. import { createHash } from 'node:crypto';
  25. import { createRequire } from 'node:module';
  26. import { existsSync, readdirSync, statSync } from 'node:fs';
  27. import { dirname, join, relative, resolve } from 'node:path';
  28. import * as lenshead from './lenshead.ts';
  29. import * as lc from './lenscommon.ts';
  30. import { cmp, e, isObject, or, str, truthy } from './lenscommon.ts';
  31. type Meta = Record<string, any>;
  32. type Rel = { field: string; target: string };
  33. type Contour = { path: string; file: string; title: string; states: { title: string; category: string }[] };
  34. type Collection = { path: string; file: string; title: string; icon: string; itemType: string; description: string; relations: Rel[]; contour: string };
  35. type ConceptFile = { id: string; file: string; title: string; kind: string; collection: string; contour: string; aka: string[]; description: string; body: string };
  36. type LayerData = { id: string; title: string; icon: string; collections: Collection[]; concepts: ConceptFile[] };
  37. type Concept = {
  38. key: string; layer: string; title: string; kind: string; collection: string; contour: Contour | null; contourPath: string;
  39. aka: string[]; file: string; nofile: boolean; icon: string; body: string; description: string; relations: Rel[];
  40. };
  41. type Foreign = { key: string; layer: string; title: string; sub: string; link: string; present: boolean; layerTitle: string; icon?: string };
  42. type Edge = { a: string; b: string; fields: Rel[]; cross: boolean };
  43. type Region = Record<string, any>;
  44. const SKIP_LAYER_DIRS = new Set(['lab', 'deleted', 'assets', 'node_modules', '__pycache__', 'documents']);
  45. const W = '\\p{L}\\p{N}_';
  46. const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
  47. const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
  48. /** '/business/requirements.md' and 'business/requirements/' both become '/business/requirements'. */
  49. function normPath(p: unknown): string {
  50. let s = truthy(p) ? str(p).trim() : '';
  51. if (s.endsWith('.md')) s = s.slice(0, -3);
  52. s = s.replace(/^\/+|\/+$/g, '');
  53. return s ? `/${s}` : '';
  54. }
  55. // ---------------------------------------------------------------- reading
  56. /** The base on disk. Remembers which files were read (for `sources`) and what could not be parsed. */
  57. class Base {
  58. reads: string[] = [];
  59. problems: string[] = [];
  60. private cache = new Map<string, [Meta, string]>();
  61. constructor(readonly root: string) {}
  62. path = (rel: string) => join(this.root, rel);
  63. exists = (rel: string) => isFile(this.path(rel));
  64. /** (front matter, body) of a page; ({}, '') if the file is missing or the front matter does not parse. */
  65. page(rel: string, log = true): [Meta, string] {
  66. if (!this.cache.has(rel)) {
  67. this.cache.set(rel, this.exists(rel)
  68. ? lc.page(this.path(rel), (err) => this.problems.push(`${rel}: the header could not be read (${err})`)) : [{}, '']);
  69. }
  70. if (log && this.exists(rel) && !this.reads.includes(rel)) this.reads.push(rel);
  71. return this.cache.get(rel) as [Meta, string];
  72. }
  73. mdNames(relDir: string): string[] {
  74. const full = this.path(relDir);
  75. if (!isDir(full)) return [];
  76. return readdirSync(full).filter((f) => f.endsWith('.md') && isFile(join(full, f))).sort(cmp);
  77. }
  78. }
  79. function firstParagraph(body: string): string {
  80. const para: string[] = [];
  81. for (const line of body.split('\n')) {
  82. const s = line.trim();
  83. if (!s) {
  84. if (para.length) break;
  85. continue;
  86. }
  87. if (/^(#|\||>|```|<!--)/.test(s) || (/^[-*]\s/.test(s) && !para.length)) {
  88. if (para.length) break;
  89. continue;
  90. }
  91. para.push(s);
  92. }
  93. return para.join(' ').replace(/\[([^\]]+)\]\([^)\s]+\)/g, (_, text) => text).replace(/[`*]/g, '').trim();
  94. }
  95. /** Layers of the base: top-level folders with `ontology.md` or with at least one collection that has `itemType`. */
  96. function layerIds(base: Base): string[] {
  97. const out: string[] = [];
  98. for (const d of readdirSync(base.root).sort(cmp)) {
  99. if (/^[._]/.test(d) || SKIP_LAYER_DIRS.has(d) || !isDir(join(base.root, d))) continue;
  100. if (base.exists(`${d}/ontology.md`)) out.push(d);
  101. else if (base.mdNames(d).some((f) => truthy(base.page(`${d}/${f}`, false)[0].itemType))) out.push(d);
  102. }
  103. return out;
  104. }
  105. /** Layers in the order of the layers table of base/ontology.md; the rest alphabetically, `base` last. */
  106. function orderLayers(base: Base, ids: string[]): string[] {
  107. const ranked: string[] = [];
  108. if (base.exists('base/ontology.md')) {
  109. for (const line of base.page('base/ontology.md', false)[1].split('\n')) {
  110. if (!line.trim().startsWith('|')) continue;
  111. const links = [...line.matchAll(new RegExp(`\\]\\(/([${W}-]+)(?:/|\\.md)`, 'gu'))].map((m) => m[1]);
  112. const spans = [...line.matchAll(new RegExp(`\`([${W}-]+)\``, 'gu'))].map((m) => m[1]);
  113. for (const m of [...links, ...spans]) {
  114. if (ids.includes(m) && !ranked.includes(m)) {
  115. ranked.push(m);
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. const rest = ids.filter((i) => !ranked.includes(i) && i !== 'base').sort(cmp);
  122. const tail = ids.includes('base') && !ranked.includes('base') ? ['base'] : [];
  123. return [...ranked, ...rest, ...tail];
  124. }
  125. /** A contour by its path, or null if there is no such file. */
  126. function loadContour(base: Base, path: string): Contour | null {
  127. path = normPath(path);
  128. const rel = `${path.replace(/^\/+/, '')}.md`;
  129. if (!path || !base.exists(rel)) return null;
  130. const meta = base.page(rel)[0];
  131. const states = (Array.isArray(meta.phases) ? meta.phases : []).map((p: unknown) => {
  132. const prel = `${normPath(p).replace(/^\/+/, '')}.md`;
  133. const pm = base.exists(prel) ? base.page(prel)[0] : {};
  134. return { title: str(or(pm.title, normPath(p).split('/').pop())), category: str(or(pm.category, '')) };
  135. });
  136. return { path, file: rel, title: str(or(meta.title, path.split('/').pop())), states };
  137. }
  138. const layerTitleOf = (pageMeta: Meta, ontMeta: Meta, lid: string): string =>
  139. str(or(pageMeta.title, str(or(ontMeta.title, '')).replace(/\s+ontology$/i, ''), lid));
  140. /** All that the lens needs from one layer. */
  141. function loadLayer(base: Base, lid: string): LayerData {
  142. const pageMeta = base.exists(`${lid}.md`) ? base.page(`${lid}.md`)[0] : {};
  143. const ontMeta = base.exists(`${lid}/ontology.md`) ? base.page(`${lid}/ontology.md`)[0] : {};
  144. const layer: LayerData = { id: lid, title: layerTitleOf(pageMeta, ontMeta, lid), icon: str(or(pageMeta.icon, ontMeta.icon, '')),
  145. collections: [], concepts: [] };
  146. for (const f of base.mdNames(lid)) {
  147. const rel = `${lid}/${f}`;
  148. const [meta, body] = base.page(rel);
  149. if (meta.type !== 'Collection' || !truthy(meta.itemType)) continue;
  150. const relations: Rel[] = [];
  151. let contour = '';
  152. for (const [name, prop] of Object.entries(isObject(meta.properties) ? meta.properties : {})) {
  153. if (!isObject(prop)) continue;
  154. if (prop.kind === 'relation' && truthy(prop.collection)) relations.push({ field: name, target: normPath(prop.collection) });
  155. else if (prop.kind === 'phase' && truthy(prop.contour) && !contour) contour = normPath(prop.contour);
  156. }
  157. layer.collections.push({ path: `/${lid}/${f.slice(0, -3)}`, file: rel, title: str(or(meta.title, f.slice(0, -3))),
  158. icon: str(or(meta.icon, '')), itemType: str(meta.itemType),
  159. description: str(or(str(or(meta.description, '')), firstParagraph(body))), relations, contour });
  160. }
  161. const cdir = `${lid}/ontology/concepts`;
  162. for (const f of base.mdNames(cdir)) {
  163. const rel = `${cdir}/${f}`;
  164. const [meta, body] = base.page(rel);
  165. if (meta.type !== 'Concept') continue;
  166. layer.concepts.push({ id: str(or(meta.id, f.slice(0, -3))), file: rel, title: str(or(meta.title, f.slice(0, -3))),
  167. kind: str(or(meta.kind, '')), collection: normPath(meta.collection), contour: normPath(meta.contour),
  168. aka: Array.isArray(meta.aka) ? meta.aka.map(str) : [], description: firstParagraph(body), body: body.trim() });
  169. }
  170. return layer;
  171. }
  172. /** Concept records of a layer: files first, then the collections that have no concept file (nofile). */
  173. function makeConcepts(base: Base, layer: LayerData): Concept[] {
  174. const lid = layer.id;
  175. const byColl = new Map(layer.collections.map((c) => [c.path, c]));
  176. const out: Concept[] = [];
  177. const claimed = new Set<string>();
  178. for (const c of layer.concepts) {
  179. const coll = c.collection ? byColl.get(c.collection) : undefined;
  180. if (coll) claimed.add(coll.path);
  181. const contour = c.contour || coll?.contour || '';
  182. out.push({ key: `${lid}/${c.id}`, layer: lid, title: c.title, kind: c.kind, collection: c.collection,
  183. contour: contour ? loadContour(base, contour) : null, contourPath: contour, aka: c.aka, file: c.file, nofile: false,
  184. icon: coll?.icon ?? '', body: c.body, description: c.description || coll?.description || '', relations: coll?.relations ?? [] });
  185. }
  186. for (const coll of layer.collections) {
  187. if (claimed.has(coll.path)) continue;
  188. out.push({ key: `${lid}/${coll.itemType}`, layer: lid, title: coll.title, kind: '', collection: coll.path,
  189. contour: coll.contour ? loadContour(base, coll.contour) : null, contourPath: coll.contour, aka: [], file: coll.file,
  190. nofile: true, icon: coll.icon, body: '', description: coll.description, relations: coll.relations });
  191. }
  192. return out;
  193. }
  194. class Model {
  195. layers = new Map<string, LayerData>();
  196. concepts: Concept[] = []; // in layer order
  197. byColl = new Map<string, Concept>(); // collection path -> concept
  198. foreign = new Map<string, Foreign>();
  199. edges: Edge[] = [];
  200. constructor(readonly base: Base, readonly lids: string[]) {
  201. for (const lid of lids) {
  202. const layer = loadLayer(base, lid);
  203. this.layers.set(lid, layer);
  204. for (const c of makeConcepts(base, layer)) {
  205. this.concepts.push(c);
  206. if (c.collection && !this.byColl.has(c.collection)) this.byColl.set(c.collection, c);
  207. }
  208. }
  209. this.buildEdges();
  210. }
  211. /** Grey node for a collection that is not a concept of this lens. */
  212. foreignNode(target: string): Foreign {
  213. const key = `x:${target}`;
  214. const known = this.foreign.get(key);
  215. if (known) return known;
  216. const parts = target.replace(/^\/+|\/+$/g, '').split('/');
  217. const fl = parts[0];
  218. const name = parts.slice(1).join('/');
  219. const base = this.base;
  220. const node: Foreign = { key, layer: fl, title: name || fl, sub: target, link: '', present: false, layerTitle: fl };
  221. if (fl && isDir(base.path(fl))) {
  222. const lm = base.exists(`${fl}.md`) ? base.page(`${fl}.md`)[0] : {};
  223. const om = base.exists(`${fl}/ontology.md`) ? base.page(`${fl}/ontology.md`)[0] : {};
  224. node.layerTitle = layerTitleOf(lm, om, fl);
  225. node.link = base.exists(`${fl}/ontology.md`) ? `${fl}/ontology.md` : '';
  226. const crel = `${fl}/${name}.md`;
  227. if (name && base.exists(crel)) {
  228. const cm = base.page(crel)[0];
  229. node.title = str(or(cm.title, name));
  230. node.icon = str(or(cm.icon, ''));
  231. node.present = true;
  232. node.link = crel;
  233. node.sub = `layer "${node.layerTitle}"`;
  234. for (const cf of base.mdNames(`${fl}/ontology/concepts`)) {
  235. const crel2 = `${fl}/ontology/concepts/${cf}`;
  236. const m2 = base.page(crel2, false)[0];
  237. if (m2.type === 'Concept' && normPath(m2.collection) === target) {
  238. base.page(crel2);
  239. node.title = str(or(m2.title, node.title));
  240. node.link = crel2;
  241. break;
  242. }
  243. }
  244. } else if (name) node.sub = `layer "${node.layerTitle}": no such collection`;
  245. else node.sub = `layer "${node.layerTitle}"`;
  246. } else node.sub = fl ? `the base has no layer "${fl}"` : target;
  247. this.foreign.set(key, node);
  248. return node;
  249. }
  250. private buildEdges(): void {
  251. const merged = new Map<string, Edge>();
  252. for (const c of this.concepts) {
  253. for (const r of c.relations) {
  254. const tgt = this.byColl.get(r.target);
  255. const tkey = tgt ? tgt.key : this.foreignNode(r.target).key;
  256. const k = `${c.key}\0${tkey}`;
  257. if (!merged.has(k)) merged.set(k, { a: c.key, b: tkey, fields: [], cross: !tgt || tgt.layer !== c.layer });
  258. (merged.get(k) as Edge).fields.push(r);
  259. }
  260. }
  261. this.edges = [...merged.values()];
  262. }
  263. }
  264. // ---------------------------------------------------------------- layout
  265. /** Edges without the ones that close a cycle (depth-first search). */
  266. function breakCycles(keys: string[], pairs: [string, string][]): [string, string][] {
  267. const adj = new Map<string, string[]>(keys.map((k) => [k, []]));
  268. for (const [a, b] of pairs) if (a !== b && adj.has(a) && adj.has(b)) (adj.get(a) as string[]).push(b);
  269. const state = new Map<string, number>();
  270. const back = new Set<string>();
  271. const dfs = (u: string): void => {
  272. state.set(u, 1);
  273. for (const v of adj.get(u) as string[]) {
  274. if (state.get(v) === 1) back.add(`${u}\0${v}`);
  275. else if (!state.has(v)) dfs(v);
  276. }
  277. state.set(u, 2);
  278. };
  279. for (const k of keys) if (!state.has(k)) dfs(k);
  280. return pairs.filter(([a, b]) => a !== b && adj.has(a) && adj.has(b) && !back.has(`${a}\0${b}`));
  281. }
  282. /** Longest-path rank: a node stands to the right of every node that points to it. */
  283. function ranks(keys: string[], pairs: [string, string][]): Map<string, number> {
  284. const dag = breakCycles(keys, pairs);
  285. const rank = new Map<string, number>(keys.map((k) => [k, 0]));
  286. let changed = true;
  287. for (let pass = 0; pass <= keys.length && changed; pass++) {
  288. changed = false;
  289. for (const [a, b] of dag) {
  290. if ((rank.get(b) as number) < (rank.get(a) as number) + 1) {
  291. rank.set(b, (rank.get(a) as number) + 1);
  292. changed = true;
  293. }
  294. }
  295. }
  296. return rank;
  297. }
  298. /** Split layers (in order) into n stacks of about equal height: [(id, size)] -> [[id, ...], ...]. */
  299. function balance(sizes: [string, number][], n: number): string[][] {
  300. n = Math.max(1, Math.min(n, sizes.length));
  301. const total = sizes.reduce((s, [, size]) => s + size, 0) || 1;
  302. const stacks: string[][] = [];
  303. let cur: string[] = [];
  304. let acc = 0;
  305. let left = n;
  306. sizes.forEach(([lid, size], i) => {
  307. const rest = sizes.length - i;
  308. if (cur.length && left > 1 && (acc + size / 2 > (total / n) * (stacks.length + 1) || rest < left)) {
  309. stacks.push(cur);
  310. cur = [];
  311. left -= 1;
  312. }
  313. cur.push(lid);
  314. acc += size;
  315. });
  316. if (cur.length) stacks.push(cur);
  317. return stacks;
  318. }
  319. // ---------------------------------------------------------------- kit
  320. const KIT_FILES = ['kit/kit.css', 'kit/kit.js', 'kit/templates/canvas.js'];
  321. // Colours of layers: names from the kit palette (kit.css --c-*), no colours of our own. A layer page may set `color:`.
  322. const LAYER_COLORS = new Map(Object.entries({ business: 'green', deal: 'orange', product: 'blue', ops: 'teal', decisions: 'purple',
  323. questions: 'pink', research: 'brown', documents: 'gray', work: 'yellow', factory: 'red',
  324. design: 'pink', dev: 'blue', tech: 'teal', quality: 'green', norms: 'purple', risks: 'red',
  325. compilation: 'brown', base: 'gray' }));
  326. const PALETTE = ['blue', 'green', 'orange', 'purple', 'teal', 'pink', 'brown', 'yellow', 'red'];
  327. const KINDS = [{ name: 'entity', label: 'entity', color: 'blue' }, { name: 'value', label: 'value', color: 'teal' },
  328. { name: 'role', label: 'role', color: 'purple' }, { name: 'event', label: 'event', color: 'orange' }];
  329. type Kit = { version: string; hash: string; css: string; js: string; canvas: string };
  330. /**
  331. * The kit files, embedded into the lens. `dir` is the folder that holds `kit/kit.css` and the rest. Since lenses 0.3
  332. * kit/kit.css is only the lenses' own part: the style and the skins come from the package kit-style, and the kit's
  333. * build (src/build.js, kitStyle) puts them together for the project `root`, the same way as lib/kit.css.
  334. */
  335. function loadKit(dir: string, root: string): Kit {
  336. if (!KIT_FILES.every((f) => isFile(join(dir, f)))) throw new Error(`${dir} has no kit: needed ${KIT_FILES.join(', ')}`);
  337. const parts = new Map(KIT_FILES.map((f) => [f, lc.read(join(dir, f))]));
  338. const builder = join(dir, 'src', 'build.js');
  339. if (isFile(builder)) {
  340. const kitStyle = createRequire(import.meta.url)(builder).kitStyle as ((root: string) => { css: string; js: string }) | undefined;
  341. if (kitStyle) {
  342. const style = kitStyle(root);
  343. parts.set(KIT_FILES[0], style.css);
  344. parts.set(KIT_FILES[1], `${parts.get(KIT_FILES[1])}\n${style.js}\n`);
  345. }
  346. }
  347. for (const [f, text] of parts) {
  348. const tag = f.endsWith('.css') ? '</style' : '</script';
  349. if (text.toLowerCase().includes(tag)) throw new Error(`${f}: the kit file contains ${tag}, it cannot be embedded`);
  350. }
  351. const h = createHash('sha256');
  352. for (const f of KIT_FILES) {
  353. h.update(`${f}\n`);
  354. h.update(`${createHash('sha256').update(parts.get(f) as string).digest('hex')}\n`);
  355. }
  356. let version = '';
  357. const pj = join(dir, 'package.json');
  358. if (isFile(pj)) {
  359. try {
  360. const pkg = JSON.parse(lc.read(pj));
  361. version = isObject(pkg) ? str(or(pkg.version, '')) : '';
  362. } catch { version = ''; }
  363. }
  364. return { version, hash: h.digest('hex'), css: parts.get(KIT_FILES[0]) as string, js: parts.get(KIT_FILES[1]) as string,
  365. canvas: parts.get(KIT_FILES[2]) as string };
  366. }
  367. function layerColor(base: Base, lid: string, i = 0): string {
  368. const meta = base.exists(`${lid}.md`) ? base.page(`${lid}.md`, false)[0] : {};
  369. const c = str(or(meta.color, ''));
  370. if (PALETTE.includes(c) || c === 'gray') return c;
  371. return LAYER_COLORS.get(lid) || PALETTE[i % PALETTE.length];
  372. }
  373. /** Provenance links (documents, meetings): a kind of their own, hidden by default. [tentative: by field name] */
  374. const isSourceField = (name: string) => name.startsWith('source');
  375. /** JSON for a <script>, as Python writes it with sort_keys: keys in code point order, no spaces, no `<` at all
  376. * (so neither </script> nor <!-- can end the block). */
  377. function jsJson(v: unknown): string {
  378. const dump = (x: unknown): string => {
  379. if (Array.isArray(x)) return `[${x.map(dump).join(',')}]`;
  380. if (x !== null && typeof x === 'object') {
  381. const o = x as Record<string, unknown>;
  382. return `{${Object.keys(o).filter((k) => o[k] !== undefined).sort(cmp).map((k) => `${JSON.stringify(k)}:${dump(o[k])}`).join(',')}}`;
  383. }
  384. return JSON.stringify(x === undefined ? null : x);
  385. };
  386. return dump(v).split('<').join('\\u003c');
  387. }
  388. // ---------------------------------------------------------------- records and config
  389. /** [data for window.SHTUKS, config for Lens.run] of the lens. */
  390. function buildData(model: Model): [Region, Region] {
  391. const base = model.base;
  392. const own = model.concepts;
  393. const rid = new Map<string, string>();
  394. const used = new Set<string>();
  395. for (const c of own) {
  396. rid.set(c.key, `/${c.file}`);
  397. used.add(`/${c.file}`);
  398. }
  399. for (const k of [...model.foreign.keys()].sort(cmp)) {
  400. const f = model.foreign.get(k) as Foreign;
  401. const plainPath = `/${f.key.slice(2).replace(/^\/+|\/+$/g, '')}`;
  402. let cand = f.link && f.present ? `/${f.link}` : `${plainPath}.md`;
  403. if (used.has(cand)) cand = `${plainPath}.md`;
  404. let n = 2;
  405. while (used.has(cand)) cand = `${plainPath}~${n++}.md`;
  406. rid.set(k, cand);
  407. used.add(cand);
  408. }
  409. const mdLink = (title: string, path: string) => {
  410. const rel = path.replace(/^\/+/, '') + (path.endsWith('.md') ? '' : '.md');
  411. return base.exists(rel) ? `[${title.replaceAll(']', ')')}](/${rel})` : `\`${path}\``;
  412. };
  413. const fields: string[] = []; // relation field names, in order of first use
  414. const outEdges = new Map<string, Edge[]>();
  415. for (const ed of model.edges) {
  416. outEdges.set(ed.a, [...(outEdges.get(ed.a) ?? []), ed]);
  417. for (const f of ed.fields) if (!fields.includes(f.field)) fields.push(f.field);
  418. }
  419. const records: Record<string, any> = {};
  420. own.forEach((c, i) => {
  421. const props: Record<string, any> = { _order: i, description: c.description };
  422. if (c.kind) props.kind = c.kind;
  423. if (c.collection) {
  424. const coll = model.layers.get(c.layer)?.collections.find((x) => x.path === c.collection);
  425. props.collection = mdLink(coll ? coll.title : c.collection, c.collection);
  426. }
  427. if (c.contour) {
  428. props.contour = mdLink(c.contour.title, c.contour.path);
  429. if (c.contour.states.length) {
  430. props.states = c.contour.states.map((s) => s.title).join(' → ');
  431. props._contour = `⟳ ${c.contour.states.length} states`;
  432. }
  433. } else if (c.contourPath) props.contour = `\`${c.contourPath}\` - no file`;
  434. if (c.aka.length) props.aka = c.aka.join(', ');
  435. props.layer = (model.layers.get(c.layer) as LayerData).title;
  436. const loops: string[] = [];
  437. for (const ed of outEdges.get(c.key) ?? []) {
  438. for (const f of ed.fields) {
  439. const key = `rel:${f.field}`;
  440. const tgt = rid.get(ed.b);
  441. if (!tgt) continue;
  442. if (ed.b === c.key) loops.push(f.field);
  443. props[key] = key in props ? [...(Array.isArray(props[key]) ? props[key] : [props[key]]), tgt] : tgt;
  444. }
  445. }
  446. if (loops.length) props._loops = `↻ ${loops.join(', ')}`;
  447. if (c.nofile) props._warn = 'nofile';
  448. const body = c.nofile
  449. ? 'There is no concept file: the node is built from the collection schema. To describe the concept, put a file `<layer>/ontology/concepts/<id>.md` (type: Concept).\n\n' + c.description
  450. : c.body;
  451. records[rid.get(c.key) as string] = { id: rid.get(c.key), type: 'Concept', title: c.title, icon: c.icon || '', props, body };
  452. });
  453. for (const [k, f] of model.foreign) {
  454. const props: Record<string, any> = { description: f.sub, layer: f.layerTitle || f.layer };
  455. if (f.link) props.source = mdLink(f.title, `/${f.link}`);
  456. records[rid.get(k) as string] = { id: rid.get(k), type: 'Bridge', title: f.title, icon: f.icon || '', props, body: '' };
  457. }
  458. const kindOpts: Record<string, string>[] = KINDS.map((o) => ({ ...o }));
  459. for (const c of own) {
  460. if (c.kind && !kindOpts.some((o) => o.name === c.kind)) kindOpts.push({ name: c.kind, label: c.kind, color: 'gray' });
  461. }
  462. const cprops: Record<string, any> = { description: { kind: 'text', label: 'Description' },
  463. kind: { kind: 'select', label: 'Kind', options: kindOpts },
  464. collection: { kind: 'text', label: 'Collection' }, contour: { kind: 'text', label: 'Contour' },
  465. states: { kind: 'text', label: 'States' }, aka: { kind: 'text', label: 'Also called' }, layer: { kind: 'text', label: 'Layer' } };
  466. for (const f of fields) cprops[`rel:${f}`] = { kind: 'relation', label: f };
  467. cprops._warn = { kind: 'select', label: 'Remark', options: [{ name: 'nofile', label: 'no concept file', color: 'red' }] };
  468. const types = { Concept: { title: 'Concept', icon: '💡', properties: cprops },
  469. Bridge: { title: 'Concept of another layer', icon: '↗️',
  470. properties: { description: { kind: 'text', label: 'Where' }, layer: { kind: 'text', label: 'Layer' }, source: { kind: 'text', label: 'Open' } } } };
  471. const data = { base: base.root.split('/').pop(), records, types, phases: {}, stats: { types: {}, relations: [] }, lenses: [] };
  472. const card = { sub: 'description', chips: ['kind', '_contour', '_loops', '_warn'] };
  473. const relFields = fields.filter((f) => !isSourceField(f)).map((f) => `rel:${f}`);
  474. const srcFields = fields.filter(isSourceField).map((f) => `rel:${f}`);
  475. // counters count field links; provenance (sourceDocs, sourceMeetings) is a separate kind and not counted
  476. const linkFields = (ed: Edge) => ed.fields.filter((f) => !isSourceField(f.field)).length;
  477. const nedges = model.edges.reduce((n, ed) => n + linkFields(ed), 0);
  478. const ncross = model.edges.filter((ed) => ed.cross).reduce((n, ed) => n + linkFields(ed), 0);
  479. const ncontour = own.filter((c) => c.contour).length;
  480. const nnofile = own.filter((c) => c.nofile).length;
  481. const foreignOf = (k: string) => model.foreign.get(k) as Foreign;
  482. const fkeys = [...model.foreign.keys()].sort((x, y) => cmp(foreignOf(x).layerTitle || '', foreignOf(y).layerTitle || '')
  483. || cmp(foreignOf(x).title, foreignOf(y).title));
  484. const other: Region = { id: '~other', title: 'Outside the base', icon: '↗️', color: 'gray',
  485. hint: 'collections that are in no layer', ids: fkeys.map((k) => rid.get(k)), group: 'layer', card: { sub: 'description', chips: [] } };
  486. const edges: Region[] = [];
  487. const regions: Region[] = [];
  488. const sizes: [string, number][] = [];
  489. model.lids.forEach((lid, i) => {
  490. const cs = own.filter((c) => c.layer === lid);
  491. if (!cs.length) return;
  492. const L = model.layers.get(lid) as LayerData;
  493. const keys = new Set(cs.map((c) => c.key));
  494. const rk = ranks([...keys], model.edges.filter((ed) => keys.has(ed.a) && keys.has(ed.b)).map((ed) => [ed.a, ed.b]));
  495. cs.sort((x, y) => (rk.get(x.key) as number) - (rk.get(y.key) as number) || cmp(x.title, y.title));
  496. cs.forEach((c, j) => { records[rid.get(c.key) as string].props._order = j; });
  497. regions.push({ id: lid, title: L.title, icon: L.icon || null, color: layerColor(base, lid, i),
  498. ids: cs.map((c) => rid.get(c.key)), sort: '_order', card: { compact: true, chips: [] } });
  499. sizes.push([lid, 2 + cs.length]);
  500. if (relFields.length) {
  501. edges.push({ id: `from:${lid}`, fields: relFields, from: lid, label: `from layer "${L.title}"`, color: layerColor(base, lid, i), edgeLabel: true });
  502. }
  503. });
  504. if (fkeys.length) {
  505. regions.push(other);
  506. sizes.push(['~other', 2 + fkeys.length]);
  507. }
  508. if (srcFields.length) {
  509. edges.push({ id: 'source', fields: srcFields, label: 'Sources: documents and meetings', color: 'gray', dash: true, off: true, edgeLabel: true });
  510. }
  511. const stacks = balance(sizes, 4);
  512. const layout = { columns: `repeat(${stacks.length}, minmax(0, 1fr))`, stacks };
  513. const counters: [string, number][] = [['Layers', regions.filter((r) => r.id !== '~other').length], ['Concepts', own.length],
  514. ['Links', nedges], ['Between layers', ncross], ['With a contour', ncontour]];
  515. const groups = regions.filter((r) => r.id !== '~other').map((r) => ({ title: r.title, color: r.color, ids: r.ids }));
  516. if (nnofile) counters.push(['Without a concept file', nnofile]);
  517. const cfg: Region = { template: 'canvas', regions, layout, edges, show: 'areas', counters, fit: 'width',
  518. list: { title: 'Concepts', groups, card: { sub: 'description', chips: ['kind', '_contour', '_loops', '_warn'],
  519. mono: { fields: relFields } } } };
  520. return [data, cfg];
  521. }
  522. function problemsMd(model: Model): string {
  523. const notes = model.base.problems;
  524. return notes.length ? `\n\n**What could not be read**\n\n${notes.map((p) => `- ${p}`).join('\n')}` : '';
  525. }
  526. /** `sources` of the lens: masks of the layers (only the ones that find a file) and the foreign files that were read. */
  527. function sourceMasks(base: Base, lids: string[]): string[] {
  528. const masks: string[] = [];
  529. const own = new Set(lids);
  530. for (const lid of lids) {
  531. for (const m of [`${lid}.md`, `${lid}/*.md`, `${lid}/ontology/concepts/*.md`, `${lid}/contours`]) {
  532. if (lenshead.expand(base.root, [m]).length) masks.push(m);
  533. }
  534. }
  535. for (const rel of [...base.reads].sort(cmp)) {
  536. let head = rel.split('/')[0];
  537. if (head.endsWith('.md')) head = head.slice(0, -3);
  538. if (!own.has(head) && !masks.includes(rel)) masks.push(rel);
  539. }
  540. return masks;
  541. }
  542. /** Writes <root>/base/ontology/graph.html (or `outArg`) and returns its path. `kitDir` holds kit/kit.css and the rest. */
  543. export function main(root: string, kitDir: string, outArg?: string, generator = 'ontology graph'): string {
  544. root = resolve(root);
  545. const base = new Base(root);
  546. const lids = orderLayers(base, layerIds(base));
  547. if (!lids.length) throw new Error(`no layer found in ${root}`);
  548. const home = join(root, 'base', 'ontology', 'graph.html');
  549. const out = outArg ? resolve(outArg) : home;
  550. const kit = loadKit(resolve(kitDir), root);
  551. const model = new Model(base, lids);
  552. // where the lens stands in the base; a file written outside the base (an example) acts as if it stood in its place
  553. const place = relative(root, out).startsWith('..') ? home : out;
  554. const relRoot = `${(relative(dirname(place), root) || '.').split('\\').join('/').replace(/\/+$/, '')}/`;
  555. const [data, cfg] = buildData(model);
  556. const title = 'Links of the project concepts';
  557. const icon = '🧬';
  558. const desc = 'All concepts of all layers of the project, grouped by layer, and the links between them. Built from the collection schemas and the concept files.';
  559. const lead = 'Each layer is a region of its own. An arrow between regions shows how many link fields lead from one layer to another; '
  560. + 'hover a concept to see its links with the field names, click it to open the concept card.';
  561. const kitLabel = `shtukbase-html-lenses ${kit.version || '?'}`;
  562. const about = `${lead}${problemsMd(model)}\n\nBuilt by the generator from the markdown of the base, not edited by hand: \`${generator}\`. `
  563. + `Inside: kit ${kitLabel} (sha256 \`${kit.hash.slice(0, 12)}…\`).`;
  564. Object.assign(cfg, { id: 'graph', title, icon, description: desc, about, path: `/${relative(root, place).split('\\').join('/')}` });
  565. const slots: Record<string, string> = { title: e(title), kit_label: e(kitLabel), kit_hash: e(kit.hash), generator: e(generator),
  566. kit_css: kit.css, kit_js: kit.js, kit_canvas: kit.canvas, data: jsJson(data), config: jsJson(cfg), root: jsJson(relRoot) };
  567. const page = lc.template('layer-ontology').replace(/\{\{(\w+)\}\}/g, (m, k) => (Object.hasOwn(slots, k) ? slots[k] : m));
  568. const meta = { type: 'Lens', title, icon, description: desc, lensType: 'schema', render: 'static', generator, template: 'layer-ontology' };
  569. lc.build(root, out, meta, sourceMasks(base, lids), page);
  570. return out;
  571. }