package file→ .shtukbase/packages/ontology/actions/lib/render_layer_ontology.ts
actions/lib/render_layer_ontology.ts
614 lines, 30.8 KB.
- // Static lens "Links of concepts": the concepts of all layers of the base and the links between them, one graph.
- //
- // What is read (paths from the base root):
- // <layer>/ontology.md the layer description (title only)
- // <layer>/ontology/concepts/*.md one file per concept (type Concept: id, kind, collection, contour, aka)
- // <layer>/*.md collections of the layer; fields `kind: relation` give the edges,
- // the label of an edge is the field name; `kind: phase, contour:` gives the contour
- // <layer>/contours/**/*.md contours: states are the pages listed in `phases`
- // A collection with `itemType` that has no concept file is drawn as a concept anyway and marked
- // "no concept file" (the layer was not split yet).
- //
- // What is drawn (the lens is built on the lens kit, template `canvas`):
- // - the concepts are records of window.SHTUKS (type Concept), the relation fields of their collections are record
- // fields `rel:<field>`; the kit draws the cards, the arrows by those fields, the legend, the side panel and the zoom;
- // - one region per layer, arrows between regions; concepts of other layers that are not in the base (bridges)
- // are a region "Outside the base";
- // - kinds of links: between concepts, provenance (sourceDocs, sourceMeetings; hidden by default);
- // - a counters row above the canvas, concept cards under it; a click opens the concept card in the side panel.
- // The kit (kit.css, kit.js, templates/canvas.js) is embedded as is: one file, no network, opens from disk.
- // Its version and sha256 are in <meta name="shtuk:kit">.
- //
- // Sources (`sources` in the header): the layer masks above plus the few files of other layers that were read
- // for grey nodes (collection page, concept file).
- import { createHash } from 'node:crypto';
- import { createRequire } from 'node:module';
- import { existsSync, readdirSync, statSync } from 'node:fs';
- import { dirname, join, relative, resolve } from 'node:path';
- import * as lenshead from './lenshead.ts';
- import * as lc from './lenscommon.ts';
- import { cmp, e, isObject, or, str, truthy } from './lenscommon.ts';
- type Meta = Record<string, any>;
- type Rel = { field: string; target: string };
- type Contour = { path: string; file: string; title: string; states: { title: string; category: string }[] };
- type Collection = { path: string; file: string; title: string; icon: string; itemType: string; description: string; relations: Rel[]; contour: string };
- type ConceptFile = { id: string; file: string; title: string; kind: string; collection: string; contour: string; aka: string[]; description: string; body: string };
- type LayerData = { id: string; title: string; icon: string; collections: Collection[]; concepts: ConceptFile[] };
- type Concept = {
- key: string; layer: string; title: string; kind: string; collection: string; contour: Contour | null; contourPath: string;
- aka: string[]; file: string; nofile: boolean; icon: string; body: string; description: string; relations: Rel[];
- };
- type Foreign = { key: string; layer: string; title: string; sub: string; link: string; present: boolean; layerTitle: string; icon?: string };
- type Edge = { a: string; b: string; fields: Rel[]; cross: boolean };
- type Region = Record<string, any>;
- const SKIP_LAYER_DIRS = new Set(['lab', 'deleted', 'assets', 'node_modules', '__pycache__', 'documents']);
- const W = '\\p{L}\\p{N}_';
- const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
- const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
- /** '/business/requirements.md' and 'business/requirements/' both become '/business/requirements'. */
- function normPath(p: unknown): string {
- let s = truthy(p) ? str(p).trim() : '';
- if (s.endsWith('.md')) s = s.slice(0, -3);
- s = s.replace(/^\/+|\/+$/g, '');
- return s ? `/${s}` : '';
- }
- // ---------------------------------------------------------------- reading
- /** The base on disk. Remembers which files were read (for `sources`) and what could not be parsed. */
- class Base {
- reads: string[] = [];
- problems: string[] = [];
- private cache = new Map<string, [Meta, string]>();
- constructor(readonly root: string) {}
- path = (rel: string) => join(this.root, rel);
- exists = (rel: string) => isFile(this.path(rel));
- /** (front matter, body) of a page; ({}, '') if the file is missing or the front matter does not parse. */
- page(rel: string, log = true): [Meta, string] {
- if (!this.cache.has(rel)) {
- this.cache.set(rel, this.exists(rel)
- ? lc.page(this.path(rel), (err) => this.problems.push(`${rel}: the header could not be read (${err})`)) : [{}, '']);
- }
- if (log && this.exists(rel) && !this.reads.includes(rel)) this.reads.push(rel);
- return this.cache.get(rel) as [Meta, string];
- }
- mdNames(relDir: string): string[] {
- const full = this.path(relDir);
- if (!isDir(full)) return [];
- return readdirSync(full).filter((f) => f.endsWith('.md') && isFile(join(full, f))).sort(cmp);
- }
- }
- function firstParagraph(body: string): string {
- const para: string[] = [];
- for (const line of body.split('\n')) {
- const s = line.trim();
- if (!s) {
- if (para.length) break;
- continue;
- }
- if (/^(#|\||>|```|<!--)/.test(s) || (/^[-*]\s/.test(s) && !para.length)) {
- if (para.length) break;
- continue;
- }
- para.push(s);
- }
- return para.join(' ').replace(/\[([^\]]+)\]\([^)\s]+\)/g, (_, text) => text).replace(/[`*]/g, '').trim();
- }
- /** Layers of the base: top-level folders with `ontology.md` or with at least one collection that has `itemType`. */
- function layerIds(base: Base): string[] {
- const out: string[] = [];
- for (const d of readdirSync(base.root).sort(cmp)) {
- if (/^[._]/.test(d) || SKIP_LAYER_DIRS.has(d) || !isDir(join(base.root, d))) continue;
- if (base.exists(`${d}/ontology.md`)) out.push(d);
- else if (base.mdNames(d).some((f) => truthy(base.page(`${d}/${f}`, false)[0].itemType))) out.push(d);
- }
- return out;
- }
- /** Layers in the order of the layers table of base/ontology.md; the rest alphabetically, `base` last. */
- function orderLayers(base: Base, ids: string[]): string[] {
- const ranked: string[] = [];
- if (base.exists('base/ontology.md')) {
- for (const line of base.page('base/ontology.md', false)[1].split('\n')) {
- if (!line.trim().startsWith('|')) continue;
- const links = [...line.matchAll(new RegExp(`\\]\\(/([${W}-]+)(?:/|\\.md)`, 'gu'))].map((m) => m[1]);
- const spans = [...line.matchAll(new RegExp(`\`([${W}-]+)\``, 'gu'))].map((m) => m[1]);
- for (const m of [...links, ...spans]) {
- if (ids.includes(m) && !ranked.includes(m)) {
- ranked.push(m);
- break;
- }
- }
- }
- }
- const rest = ids.filter((i) => !ranked.includes(i) && i !== 'base').sort(cmp);
- const tail = ids.includes('base') && !ranked.includes('base') ? ['base'] : [];
- return [...ranked, ...rest, ...tail];
- }
- /** A contour by its path, or null if there is no such file. */
- function loadContour(base: Base, path: string): Contour | null {
- path = normPath(path);
- const rel = `${path.replace(/^\/+/, '')}.md`;
- if (!path || !base.exists(rel)) return null;
- const meta = base.page(rel)[0];
- const states = (Array.isArray(meta.phases) ? meta.phases : []).map((p: unknown) => {
- const prel = `${normPath(p).replace(/^\/+/, '')}.md`;
- const pm = base.exists(prel) ? base.page(prel)[0] : {};
- return { title: str(or(pm.title, normPath(p).split('/').pop())), category: str(or(pm.category, '')) };
- });
- return { path, file: rel, title: str(or(meta.title, path.split('/').pop())), states };
- }
- const layerTitleOf = (pageMeta: Meta, ontMeta: Meta, lid: string): string =>
- str(or(pageMeta.title, str(or(ontMeta.title, '')).replace(/\s+ontology$/i, ''), lid));
- /** All that the lens needs from one layer. */
- function loadLayer(base: Base, lid: string): LayerData {
- const pageMeta = base.exists(`${lid}.md`) ? base.page(`${lid}.md`)[0] : {};
- const ontMeta = base.exists(`${lid}/ontology.md`) ? base.page(`${lid}/ontology.md`)[0] : {};
- const layer: LayerData = { id: lid, title: layerTitleOf(pageMeta, ontMeta, lid), icon: str(or(pageMeta.icon, ontMeta.icon, '')),
- collections: [], concepts: [] };
- for (const f of base.mdNames(lid)) {
- const rel = `${lid}/${f}`;
- const [meta, body] = base.page(rel);
- if (meta.type !== 'Collection' || !truthy(meta.itemType)) continue;
- const relations: Rel[] = [];
- let contour = '';
- for (const [name, prop] of Object.entries(isObject(meta.properties) ? meta.properties : {})) {
- if (!isObject(prop)) continue;
- if (prop.kind === 'relation' && truthy(prop.collection)) relations.push({ field: name, target: normPath(prop.collection) });
- else if (prop.kind === 'phase' && truthy(prop.contour) && !contour) contour = normPath(prop.contour);
- }
- layer.collections.push({ path: `/${lid}/${f.slice(0, -3)}`, file: rel, title: str(or(meta.title, f.slice(0, -3))),
- icon: str(or(meta.icon, '')), itemType: str(meta.itemType),
- description: str(or(str(or(meta.description, '')), firstParagraph(body))), relations, contour });
- }
- const cdir = `${lid}/ontology/concepts`;
- for (const f of base.mdNames(cdir)) {
- const rel = `${cdir}/${f}`;
- const [meta, body] = base.page(rel);
- if (meta.type !== 'Concept') continue;
- layer.concepts.push({ id: str(or(meta.id, f.slice(0, -3))), file: rel, title: str(or(meta.title, f.slice(0, -3))),
- kind: str(or(meta.kind, '')), collection: normPath(meta.collection), contour: normPath(meta.contour),
- aka: Array.isArray(meta.aka) ? meta.aka.map(str) : [], description: firstParagraph(body), body: body.trim() });
- }
- return layer;
- }
- /** Concept records of a layer: files first, then the collections that have no concept file (nofile). */
- function makeConcepts(base: Base, layer: LayerData): Concept[] {
- const lid = layer.id;
- const byColl = new Map(layer.collections.map((c) => [c.path, c]));
- const out: Concept[] = [];
- const claimed = new Set<string>();
- for (const c of layer.concepts) {
- const coll = c.collection ? byColl.get(c.collection) : undefined;
- if (coll) claimed.add(coll.path);
- const contour = c.contour || coll?.contour || '';
- out.push({ key: `${lid}/${c.id}`, layer: lid, title: c.title, kind: c.kind, collection: c.collection,
- contour: contour ? loadContour(base, contour) : null, contourPath: contour, aka: c.aka, file: c.file, nofile: false,
- icon: coll?.icon ?? '', body: c.body, description: c.description || coll?.description || '', relations: coll?.relations ?? [] });
- }
- for (const coll of layer.collections) {
- if (claimed.has(coll.path)) continue;
- out.push({ key: `${lid}/${coll.itemType}`, layer: lid, title: coll.title, kind: '', collection: coll.path,
- contour: coll.contour ? loadContour(base, coll.contour) : null, contourPath: coll.contour, aka: [], file: coll.file,
- nofile: true, icon: coll.icon, body: '', description: coll.description, relations: coll.relations });
- }
- return out;
- }
- class Model {
- layers = new Map<string, LayerData>();
- concepts: Concept[] = []; // in layer order
- byColl = new Map<string, Concept>(); // collection path -> concept
- foreign = new Map<string, Foreign>();
- edges: Edge[] = [];
- constructor(readonly base: Base, readonly lids: string[]) {
- for (const lid of lids) {
- const layer = loadLayer(base, lid);
- this.layers.set(lid, layer);
- for (const c of makeConcepts(base, layer)) {
- this.concepts.push(c);
- if (c.collection && !this.byColl.has(c.collection)) this.byColl.set(c.collection, c);
- }
- }
- this.buildEdges();
- }
- /** Grey node for a collection that is not a concept of this lens. */
- foreignNode(target: string): Foreign {
- const key = `x:${target}`;
- const known = this.foreign.get(key);
- if (known) return known;
- const parts = target.replace(/^\/+|\/+$/g, '').split('/');
- const fl = parts[0];
- const name = parts.slice(1).join('/');
- const base = this.base;
- const node: Foreign = { key, layer: fl, title: name || fl, sub: target, link: '', present: false, layerTitle: fl };
- if (fl && isDir(base.path(fl))) {
- const lm = base.exists(`${fl}.md`) ? base.page(`${fl}.md`)[0] : {};
- const om = base.exists(`${fl}/ontology.md`) ? base.page(`${fl}/ontology.md`)[0] : {};
- node.layerTitle = layerTitleOf(lm, om, fl);
- node.link = base.exists(`${fl}/ontology.md`) ? `${fl}/ontology.md` : '';
- const crel = `${fl}/${name}.md`;
- if (name && base.exists(crel)) {
- const cm = base.page(crel)[0];
- node.title = str(or(cm.title, name));
- node.icon = str(or(cm.icon, ''));
- node.present = true;
- node.link = crel;
- node.sub = `layer "${node.layerTitle}"`;
- for (const cf of base.mdNames(`${fl}/ontology/concepts`)) {
- const crel2 = `${fl}/ontology/concepts/${cf}`;
- const m2 = base.page(crel2, false)[0];
- if (m2.type === 'Concept' && normPath(m2.collection) === target) {
- base.page(crel2);
- node.title = str(or(m2.title, node.title));
- node.link = crel2;
- break;
- }
- }
- } else if (name) node.sub = `layer "${node.layerTitle}": no such collection`;
- else node.sub = `layer "${node.layerTitle}"`;
- } else node.sub = fl ? `the base has no layer "${fl}"` : target;
- this.foreign.set(key, node);
- return node;
- }
- private buildEdges(): void {
- const merged = new Map<string, Edge>();
- for (const c of this.concepts) {
- for (const r of c.relations) {
- const tgt = this.byColl.get(r.target);
- const tkey = tgt ? tgt.key : this.foreignNode(r.target).key;
- const k = `${c.key}\0${tkey}`;
- if (!merged.has(k)) merged.set(k, { a: c.key, b: tkey, fields: [], cross: !tgt || tgt.layer !== c.layer });
- (merged.get(k) as Edge).fields.push(r);
- }
- }
- this.edges = [...merged.values()];
- }
- }
- // ---------------------------------------------------------------- layout
- /** Edges without the ones that close a cycle (depth-first search). */
- function breakCycles(keys: string[], pairs: [string, string][]): [string, string][] {
- const adj = new Map<string, string[]>(keys.map((k) => [k, []]));
- for (const [a, b] of pairs) if (a !== b && adj.has(a) && adj.has(b)) (adj.get(a) as string[]).push(b);
- const state = new Map<string, number>();
- const back = new Set<string>();
- const dfs = (u: string): void => {
- state.set(u, 1);
- for (const v of adj.get(u) as string[]) {
- if (state.get(v) === 1) back.add(`${u}\0${v}`);
- else if (!state.has(v)) dfs(v);
- }
- state.set(u, 2);
- };
- for (const k of keys) if (!state.has(k)) dfs(k);
- return pairs.filter(([a, b]) => a !== b && adj.has(a) && adj.has(b) && !back.has(`${a}\0${b}`));
- }
- /** Longest-path rank: a node stands to the right of every node that points to it. */
- function ranks(keys: string[], pairs: [string, string][]): Map<string, number> {
- const dag = breakCycles(keys, pairs);
- const rank = new Map<string, number>(keys.map((k) => [k, 0]));
- let changed = true;
- for (let pass = 0; pass <= keys.length && changed; pass++) {
- changed = false;
- for (const [a, b] of dag) {
- if ((rank.get(b) as number) < (rank.get(a) as number) + 1) {
- rank.set(b, (rank.get(a) as number) + 1);
- changed = true;
- }
- }
- }
- return rank;
- }
- /** Split layers (in order) into n stacks of about equal height: [(id, size)] -> [[id, ...], ...]. */
- function balance(sizes: [string, number][], n: number): string[][] {
- n = Math.max(1, Math.min(n, sizes.length));
- const total = sizes.reduce((s, [, size]) => s + size, 0) || 1;
- const stacks: string[][] = [];
- let cur: string[] = [];
- let acc = 0;
- let left = n;
- sizes.forEach(([lid, size], i) => {
- const rest = sizes.length - i;
- if (cur.length && left > 1 && (acc + size / 2 > (total / n) * (stacks.length + 1) || rest < left)) {
- stacks.push(cur);
- cur = [];
- left -= 1;
- }
- cur.push(lid);
- acc += size;
- });
- if (cur.length) stacks.push(cur);
- return stacks;
- }
- // ---------------------------------------------------------------- kit
- const KIT_FILES = ['kit/kit.css', 'kit/kit.js', 'kit/templates/canvas.js'];
- // Colours of layers: names from the kit palette (kit.css --c-*), no colours of our own. A layer page may set `color:`.
- const LAYER_COLORS = new Map(Object.entries({ business: 'green', deal: 'orange', product: 'blue', ops: 'teal', decisions: 'purple',
- questions: 'pink', research: 'brown', documents: 'gray', work: 'yellow', factory: 'red',
- design: 'pink', dev: 'blue', tech: 'teal', quality: 'green', norms: 'purple', risks: 'red',
- compilation: 'brown', base: 'gray' }));
- const PALETTE = ['blue', 'green', 'orange', 'purple', 'teal', 'pink', 'brown', 'yellow', 'red'];
- const KINDS = [{ name: 'entity', label: 'entity', color: 'blue' }, { name: 'value', label: 'value', color: 'teal' },
- { name: 'role', label: 'role', color: 'purple' }, { name: 'event', label: 'event', color: 'orange' }];
- type Kit = { version: string; hash: string; css: string; js: string; canvas: string };
- /**
- * The kit files, embedded into the lens. `dir` is the folder that holds `kit/kit.css` and the rest. Since lenses 0.3
- * kit/kit.css is only the lenses' own part: the style and the skins come from the package kit-style, and the kit's
- * build (src/build.js, kitStyle) puts them together for the project `root`, the same way as lib/kit.css.
- */
- function loadKit(dir: string, root: string): Kit {
- if (!KIT_FILES.every((f) => isFile(join(dir, f)))) throw new Error(`${dir} has no kit: needed ${KIT_FILES.join(', ')}`);
- const parts = new Map(KIT_FILES.map((f) => [f, lc.read(join(dir, f))]));
- const builder = join(dir, 'src', 'build.js');
- if (isFile(builder)) {
- const kitStyle = createRequire(import.meta.url)(builder).kitStyle as ((root: string) => { css: string; js: string }) | undefined;
- if (kitStyle) {
- const style = kitStyle(root);
- parts.set(KIT_FILES[0], style.css);
- parts.set(KIT_FILES[1], `${parts.get(KIT_FILES[1])}\n${style.js}\n`);
- }
- }
- for (const [f, text] of parts) {
- const tag = f.endsWith('.css') ? '</style' : '</script';
- if (text.toLowerCase().includes(tag)) throw new Error(`${f}: the kit file contains ${tag}, it cannot be embedded`);
- }
- const h = createHash('sha256');
- for (const f of KIT_FILES) {
- h.update(`${f}\n`);
- h.update(`${createHash('sha256').update(parts.get(f) as string).digest('hex')}\n`);
- }
- let version = '';
- const pj = join(dir, 'package.json');
- if (isFile(pj)) {
- try {
- const pkg = JSON.parse(lc.read(pj));
- version = isObject(pkg) ? str(or(pkg.version, '')) : '';
- } catch { version = ''; }
- }
- return { version, hash: h.digest('hex'), css: parts.get(KIT_FILES[0]) as string, js: parts.get(KIT_FILES[1]) as string,
- canvas: parts.get(KIT_FILES[2]) as string };
- }
- function layerColor(base: Base, lid: string, i = 0): string {
- const meta = base.exists(`${lid}.md`) ? base.page(`${lid}.md`, false)[0] : {};
- const c = str(or(meta.color, ''));
- if (PALETTE.includes(c) || c === 'gray') return c;
- return LAYER_COLORS.get(lid) || PALETTE[i % PALETTE.length];
- }
- /** Provenance links (documents, meetings): a kind of their own, hidden by default. [tentative: by field name] */
- const isSourceField = (name: string) => name.startsWith('source');
- /** JSON for a <script>, as Python writes it with sort_keys: keys in code point order, no spaces, no `<` at all
- * (so neither </script> nor <!-- can end the block). */
- function jsJson(v: unknown): string {
- const dump = (x: unknown): string => {
- if (Array.isArray(x)) return `[${x.map(dump).join(',')}]`;
- if (x !== null && typeof x === 'object') {
- const o = x as Record<string, unknown>;
- return `{${Object.keys(o).filter((k) => o[k] !== undefined).sort(cmp).map((k) => `${JSON.stringify(k)}:${dump(o[k])}`).join(',')}}`;
- }
- return JSON.stringify(x === undefined ? null : x);
- };
- return dump(v).split('<').join('\\u003c');
- }
- // ---------------------------------------------------------------- records and config
- /** [data for window.SHTUKS, config for Lens.run] of the lens. */
- function buildData(model: Model): [Region, Region] {
- const base = model.base;
- const own = model.concepts;
- const rid = new Map<string, string>();
- const used = new Set<string>();
- for (const c of own) {
- rid.set(c.key, `/${c.file}`);
- used.add(`/${c.file}`);
- }
- for (const k of [...model.foreign.keys()].sort(cmp)) {
- const f = model.foreign.get(k) as Foreign;
- const plainPath = `/${f.key.slice(2).replace(/^\/+|\/+$/g, '')}`;
- let cand = f.link && f.present ? `/${f.link}` : `${plainPath}.md`;
- if (used.has(cand)) cand = `${plainPath}.md`;
- let n = 2;
- while (used.has(cand)) cand = `${plainPath}~${n++}.md`;
- rid.set(k, cand);
- used.add(cand);
- }
- const mdLink = (title: string, path: string) => {
- const rel = path.replace(/^\/+/, '') + (path.endsWith('.md') ? '' : '.md');
- return base.exists(rel) ? `[${title.replaceAll(']', ')')}](/${rel})` : `\`${path}\``;
- };
- const fields: string[] = []; // relation field names, in order of first use
- const outEdges = new Map<string, Edge[]>();
- for (const ed of model.edges) {
- outEdges.set(ed.a, [...(outEdges.get(ed.a) ?? []), ed]);
- for (const f of ed.fields) if (!fields.includes(f.field)) fields.push(f.field);
- }
- const records: Record<string, any> = {};
- own.forEach((c, i) => {
- const props: Record<string, any> = { _order: i, description: c.description };
- if (c.kind) props.kind = c.kind;
- if (c.collection) {
- const coll = model.layers.get(c.layer)?.collections.find((x) => x.path === c.collection);
- props.collection = mdLink(coll ? coll.title : c.collection, c.collection);
- }
- if (c.contour) {
- props.contour = mdLink(c.contour.title, c.contour.path);
- if (c.contour.states.length) {
- props.states = c.contour.states.map((s) => s.title).join(' → ');
- props._contour = `⟳ ${c.contour.states.length} states`;
- }
- } else if (c.contourPath) props.contour = `\`${c.contourPath}\` - no file`;
- if (c.aka.length) props.aka = c.aka.join(', ');
- props.layer = (model.layers.get(c.layer) as LayerData).title;
- const loops: string[] = [];
- for (const ed of outEdges.get(c.key) ?? []) {
- for (const f of ed.fields) {
- const key = `rel:${f.field}`;
- const tgt = rid.get(ed.b);
- if (!tgt) continue;
- if (ed.b === c.key) loops.push(f.field);
- props[key] = key in props ? [...(Array.isArray(props[key]) ? props[key] : [props[key]]), tgt] : tgt;
- }
- }
- if (loops.length) props._loops = `↻ ${loops.join(', ')}`;
- if (c.nofile) props._warn = 'nofile';
- const body = c.nofile
- ? '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
- : c.body;
- records[rid.get(c.key) as string] = { id: rid.get(c.key), type: 'Concept', title: c.title, icon: c.icon || '', props, body };
- });
- for (const [k, f] of model.foreign) {
- const props: Record<string, any> = { description: f.sub, layer: f.layerTitle || f.layer };
- if (f.link) props.source = mdLink(f.title, `/${f.link}`);
- records[rid.get(k) as string] = { id: rid.get(k), type: 'Bridge', title: f.title, icon: f.icon || '', props, body: '' };
- }
- const kindOpts: Record<string, string>[] = KINDS.map((o) => ({ ...o }));
- for (const c of own) {
- if (c.kind && !kindOpts.some((o) => o.name === c.kind)) kindOpts.push({ name: c.kind, label: c.kind, color: 'gray' });
- }
- const cprops: Record<string, any> = { description: { kind: 'text', label: 'Description' },
- kind: { kind: 'select', label: 'Kind', options: kindOpts },
- collection: { kind: 'text', label: 'Collection' }, contour: { kind: 'text', label: 'Contour' },
- states: { kind: 'text', label: 'States' }, aka: { kind: 'text', label: 'Also called' }, layer: { kind: 'text', label: 'Layer' } };
- for (const f of fields) cprops[`rel:${f}`] = { kind: 'relation', label: f };
- cprops._warn = { kind: 'select', label: 'Remark', options: [{ name: 'nofile', label: 'no concept file', color: 'red' }] };
- const types = { Concept: { title: 'Concept', icon: '💡', properties: cprops },
- Bridge: { title: 'Concept of another layer', icon: '↗️',
- properties: { description: { kind: 'text', label: 'Where' }, layer: { kind: 'text', label: 'Layer' }, source: { kind: 'text', label: 'Open' } } } };
- const data = { base: base.root.split('/').pop(), records, types, phases: {}, stats: { types: {}, relations: [] }, lenses: [] };
- const card = { sub: 'description', chips: ['kind', '_contour', '_loops', '_warn'] };
- const relFields = fields.filter((f) => !isSourceField(f)).map((f) => `rel:${f}`);
- const srcFields = fields.filter(isSourceField).map((f) => `rel:${f}`);
- // counters count field links; provenance (sourceDocs, sourceMeetings) is a separate kind and not counted
- const linkFields = (ed: Edge) => ed.fields.filter((f) => !isSourceField(f.field)).length;
- const nedges = model.edges.reduce((n, ed) => n + linkFields(ed), 0);
- const ncross = model.edges.filter((ed) => ed.cross).reduce((n, ed) => n + linkFields(ed), 0);
- const ncontour = own.filter((c) => c.contour).length;
- const nnofile = own.filter((c) => c.nofile).length;
- const foreignOf = (k: string) => model.foreign.get(k) as Foreign;
- const fkeys = [...model.foreign.keys()].sort((x, y) => cmp(foreignOf(x).layerTitle || '', foreignOf(y).layerTitle || '')
- || cmp(foreignOf(x).title, foreignOf(y).title));
- const other: Region = { id: '~other', title: 'Outside the base', icon: '↗️', color: 'gray',
- hint: 'collections that are in no layer', ids: fkeys.map((k) => rid.get(k)), group: 'layer', card: { sub: 'description', chips: [] } };
- const edges: Region[] = [];
- const regions: Region[] = [];
- const sizes: [string, number][] = [];
- model.lids.forEach((lid, i) => {
- const cs = own.filter((c) => c.layer === lid);
- if (!cs.length) return;
- const L = model.layers.get(lid) as LayerData;
- const keys = new Set(cs.map((c) => c.key));
- const rk = ranks([...keys], model.edges.filter((ed) => keys.has(ed.a) && keys.has(ed.b)).map((ed) => [ed.a, ed.b]));
- cs.sort((x, y) => (rk.get(x.key) as number) - (rk.get(y.key) as number) || cmp(x.title, y.title));
- cs.forEach((c, j) => { records[rid.get(c.key) as string].props._order = j; });
- regions.push({ id: lid, title: L.title, icon: L.icon || null, color: layerColor(base, lid, i),
- ids: cs.map((c) => rid.get(c.key)), sort: '_order', card: { compact: true, chips: [] } });
- sizes.push([lid, 2 + cs.length]);
- if (relFields.length) {
- edges.push({ id: `from:${lid}`, fields: relFields, from: lid, label: `from layer "${L.title}"`, color: layerColor(base, lid, i), edgeLabel: true });
- }
- });
- if (fkeys.length) {
- regions.push(other);
- sizes.push(['~other', 2 + fkeys.length]);
- }
- if (srcFields.length) {
- edges.push({ id: 'source', fields: srcFields, label: 'Sources: documents and meetings', color: 'gray', dash: true, off: true, edgeLabel: true });
- }
- const stacks = balance(sizes, 4);
- const layout = { columns: `repeat(${stacks.length}, minmax(0, 1fr))`, stacks };
- const counters: [string, number][] = [['Layers', regions.filter((r) => r.id !== '~other').length], ['Concepts', own.length],
- ['Links', nedges], ['Between layers', ncross], ['With a contour', ncontour]];
- const groups = regions.filter((r) => r.id !== '~other').map((r) => ({ title: r.title, color: r.color, ids: r.ids }));
- if (nnofile) counters.push(['Without a concept file', nnofile]);
- const cfg: Region = { template: 'canvas', regions, layout, edges, show: 'areas', counters, fit: 'width',
- list: { title: 'Concepts', groups, card: { sub: 'description', chips: ['kind', '_contour', '_loops', '_warn'],
- mono: { fields: relFields } } } };
- return [data, cfg];
- }
- function problemsMd(model: Model): string {
- const notes = model.base.problems;
- return notes.length ? `\n\n**What could not be read**\n\n${notes.map((p) => `- ${p}`).join('\n')}` : '';
- }
- /** `sources` of the lens: masks of the layers (only the ones that find a file) and the foreign files that were read. */
- function sourceMasks(base: Base, lids: string[]): string[] {
- const masks: string[] = [];
- const own = new Set(lids);
- for (const lid of lids) {
- for (const m of [`${lid}.md`, `${lid}/*.md`, `${lid}/ontology/concepts/*.md`, `${lid}/contours`]) {
- if (lenshead.expand(base.root, [m]).length) masks.push(m);
- }
- }
- for (const rel of [...base.reads].sort(cmp)) {
- let head = rel.split('/')[0];
- if (head.endsWith('.md')) head = head.slice(0, -3);
- if (!own.has(head) && !masks.includes(rel)) masks.push(rel);
- }
- return masks;
- }
- /** Writes <root>/base/ontology/graph.html (or `outArg`) and returns its path. `kitDir` holds kit/kit.css and the rest. */
- export function main(root: string, kitDir: string, outArg?: string, generator = 'ontology graph'): string {
- root = resolve(root);
- const base = new Base(root);
- const lids = orderLayers(base, layerIds(base));
- if (!lids.length) throw new Error(`no layer found in ${root}`);
- const home = join(root, 'base', 'ontology', 'graph.html');
- const out = outArg ? resolve(outArg) : home;
- const kit = loadKit(resolve(kitDir), root);
- const model = new Model(base, lids);
- // where the lens stands in the base; a file written outside the base (an example) acts as if it stood in its place
- const place = relative(root, out).startsWith('..') ? home : out;
- const relRoot = `${(relative(dirname(place), root) || '.').split('\\').join('/').replace(/\/+$/, '')}/`;
- const [data, cfg] = buildData(model);
- const title = 'Links of the project concepts';
- const icon = '🧬';
- 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.';
- 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; '
- + 'hover a concept to see its links with the field names, click it to open the concept card.';
- const kitLabel = `shtukbase-html-lenses ${kit.version || '?'}`;
- const about = `${lead}${problemsMd(model)}\n\nBuilt by the generator from the markdown of the base, not edited by hand: \`${generator}\`. `
- + `Inside: kit ${kitLabel} (sha256 \`${kit.hash.slice(0, 12)}…\`).`;
- Object.assign(cfg, { id: 'graph', title, icon, description: desc, about, path: `/${relative(root, place).split('\\').join('/')}` });
- const slots: Record<string, string> = { title: e(title), kit_label: e(kitLabel), kit_hash: e(kit.hash), generator: e(generator),
- kit_css: kit.css, kit_js: kit.js, kit_canvas: kit.canvas, data: jsJson(data), config: jsJson(cfg), root: jsJson(relRoot) };
- const page = lc.template('layer-ontology').replace(/\{\{(\w+)\}\}/g, (m, k) => (Object.hasOwn(slots, k) ? slots[k] : m));
- const meta = { type: 'Lens', title, icon, description: desc, lensType: 'schema', render: 'static', generator, template: 'layer-ontology' };
- lc.build(root, out, meta, sourceMasks(base, lids), page);
- return out;
- }