182 lines
8.4 KiB
JavaScript
182 lines
8.4 KiB
JavaScript
// The Doctrine diagram's geometry, without the DOM (node --test ide/ui/js/doctrine-layout.test.mjs): the graph of the
|
|
// entities (relations, inheritance, embedded classes, enums), a layered layout (each connected group in columns, the
|
|
// order inside a column by the neighbours' places), the neighbours of a focused entity, the filter.
|
|
|
|
const short = (c) => String(c || '').split('\\').pop();
|
|
|
|
/** The graph of a mapping: nodes {id, kind, entity, rows} and edges {from, to, kind, label, ...}. */
|
|
export function graph(mapping, { fields = true, enums = true } = {}) {
|
|
const nodes = [];
|
|
const edges = [];
|
|
const ids = new Set();
|
|
for (const e of mapping.entities || []) {
|
|
ids.add(e.class);
|
|
const rows = fields ? e.fields.length + e.relations.length + e.embedded.length : 0;
|
|
nodes.push({ id: e.class, kind: e.kind, entity: e, rows });
|
|
}
|
|
if (enums) {
|
|
for (const en of mapping.enums || []) {
|
|
const used = (mapping.entities || []).some((e) => e.fields.some((f) => f.enumType === en.class));
|
|
if (!used) continue;
|
|
ids.add(en.class);
|
|
nodes.push({ id: en.class, kind: 'enum', enum: en, rows: fields ? en.cases.length : 0 });
|
|
}
|
|
}
|
|
const pair = new Set();
|
|
for (const e of mapping.entities || []) {
|
|
for (const r of e.relations) {
|
|
if (r.inherited || !r.target || !ids.has(r.target)) continue;
|
|
// one edge per bidirectional relation, drawn from its owning side
|
|
const other = r.mappedBy || r.inversedBy;
|
|
const key = [e.class, r.name, r.target, other].join('|');
|
|
const back = [r.target, other, e.class, r.name].join('|');
|
|
if (other && pair.has(back)) continue;
|
|
pair.add(key);
|
|
const owning = r.owning;
|
|
edges.push({ from: owning ? e.class : r.target, to: owning ? r.target : e.class, kind: 'relation', relation: owning ? r.kind : invert(r.kind),
|
|
fromField: owning ? r.name : other, toField: owning ? other : r.name, bidirectional: !!other, cascade: r.cascade, orphanRemoval: r.orphanRemoval,
|
|
joinTable: r.joinTable?.name || null });
|
|
}
|
|
if (e.parent && ids.has(e.parent)) edges.push({ from: e.class, to: e.parent, kind: 'inheritance', label: e.inheritance?.type || (e.kind === 'entity' ? '' : 'mapped superclass') });
|
|
for (const em of e.embedded) if (ids.has(em.class)) edges.push({ from: e.class, to: em.class, kind: 'embedded', fromField: em.name });
|
|
if (enums) for (const f of e.fields) if (f.enumType && ids.has(f.enumType) && !f.inherited) edges.push({ from: e.class, to: f.enumType, kind: 'enum', fromField: f.name });
|
|
}
|
|
return { nodes, edges };
|
|
}
|
|
|
|
/** ManyToOne seen from the other side: OneToMany (and the reverse) */
|
|
export function invert(kind) {
|
|
return { ManyToOne: 'OneToMany', OneToMany: 'ManyToOne', OneToOne: 'OneToOne', ManyToMany: 'ManyToMany' }[kind] || kind;
|
|
}
|
|
|
|
/** the two ends of a relation as UML multiplicities: [at its owner, at its target] */
|
|
export function ends(kind) {
|
|
return { ManyToOne: ['*', '1'], OneToMany: ['1', '*'], OneToOne: ['1', '1'], ManyToMany: ['*', '*'] }[kind] || ['', ''];
|
|
}
|
|
|
|
/** The size of a box: its title and its rows. */
|
|
export function boxSize(node, { rowHeight = 18, head = 40, width = 230 } = {}) {
|
|
return { w: width, h: head + Math.max(node.rows, 0) * rowHeight + (node.rows ? 8 : 0) };
|
|
}
|
|
|
|
/**
|
|
* Positions {id: {x, y}} of boxes {id, w, h} linked by edges {from, to}: each connected group in layers (a breadth-first walk
|
|
* from its most linked node), the layers side by side, the order inside a layer by the mean place of the neighbours (a few
|
|
* sweeps), the groups one after the other on rows no wider than maxWidth. Deterministic: the same graph, the same picture.
|
|
*/
|
|
export function layout(nodes, edges, { gapX = 80, gapY = 30, maxWidth = 2600 } = {}) {
|
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
const adj = new Map(nodes.map((n) => [n.id, new Set()]));
|
|
for (const e of edges) {
|
|
if (!byId.has(e.from) || !byId.has(e.to) || e.from === e.to) continue;
|
|
adj.get(e.from).add(e.to);
|
|
adj.get(e.to).add(e.from);
|
|
}
|
|
const sorted = [...nodes].sort((a, b) => adj.get(b.id).size - adj.get(a.id).size || String(a.id).localeCompare(String(b.id)));
|
|
const seen = new Set();
|
|
const groups = [];
|
|
for (const start of sorted) {
|
|
if (seen.has(start.id)) continue;
|
|
const layers = [];
|
|
const layerOf = new Map([[start.id, 0]]);
|
|
seen.add(start.id);
|
|
const queue = [start.id];
|
|
while (queue.length) {
|
|
const id = queue.shift();
|
|
const l = layerOf.get(id);
|
|
(layers[l] ||= []).push(id);
|
|
for (const n of [...adj.get(id)].sort()) {
|
|
if (seen.has(n)) continue;
|
|
seen.add(n);
|
|
layerOf.set(n, l + 1);
|
|
queue.push(n);
|
|
}
|
|
}
|
|
// a wide first layer is split so that a star does not make one very high column
|
|
for (let sweep = 0; sweep < 4; sweep++) {
|
|
for (let l = 1; l < layers.length; l++) {
|
|
const prev = new Map(layers[l - 1].map((id, i) => [id, i]));
|
|
const score = (id) => { const p = [...adj.get(id)].filter((n) => prev.has(n)).map((n) => prev.get(n)); return p.length ? p.reduce((a, b) => a + b, 0) / p.length : 0; };
|
|
layers[l].sort((a, b) => score(a) - score(b) || String(a).localeCompare(String(b)));
|
|
}
|
|
}
|
|
groups.push(layers);
|
|
}
|
|
const pos = {};
|
|
let x0 = 0;
|
|
let y0 = 0;
|
|
let rowHeight = 0;
|
|
for (const layers of groups) {
|
|
// the group's own size
|
|
const widths = layers.map((ids) => Math.max(...ids.map((id) => byId.get(id).w)));
|
|
const heights = layers.map((ids) => ids.reduce((s, id) => s + byId.get(id).h, 0) + gapY * (ids.length - 1));
|
|
const gw = widths.reduce((a, b) => a + b, 0) + gapX * (layers.length - 1);
|
|
const gh = Math.max(...heights);
|
|
if (x0 > 0 && x0 + gw > maxWidth) { x0 = 0; y0 += rowHeight + gapY * 2; rowHeight = 0; }
|
|
let x = x0;
|
|
layers.forEach((ids, l) => {
|
|
let y = y0 + (gh - heights[l]) / 2;
|
|
for (const id of ids) { pos[id] = { x: Math.round(x), y: Math.round(y) }; y += byId.get(id).h + gapY; }
|
|
x += widths[l] + gapX;
|
|
});
|
|
x0 += gw + gapX * 1.5;
|
|
rowHeight = Math.max(rowHeight, gh);
|
|
}
|
|
return pos;
|
|
}
|
|
|
|
/** whether two placed boxes overlap */
|
|
export function overlaps(a, b) {
|
|
return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
|
}
|
|
|
|
/** the ids at most `depth` links away from `id` (itself included) */
|
|
export function neighbours(edges, id, depth = 1) {
|
|
const out = new Set([id]);
|
|
let frontier = [id];
|
|
for (let d = 0; d < depth && frontier.length; d++) {
|
|
const next = [];
|
|
for (const e of edges) {
|
|
for (const [a, b] of [[e.from, e.to], [e.to, e.from]]) {
|
|
if (frontier.includes(a) && !out.has(b)) { out.add(b); next.push(b); }
|
|
}
|
|
}
|
|
frontier = next;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** the nodes a filter keeps: a word of the class, table, a field or relation name ("is:api", "is:embeddable" too) */
|
|
export function matches(node, filter) {
|
|
const words = String(filter || '').toLowerCase().split(/\s+/).filter(Boolean);
|
|
if (!words.length) return true;
|
|
const e = node.entity;
|
|
const hay = [node.id, short(node.id), e?.table, ...(e ? [...e.fields, ...e.relations, ...e.embedded].map((x) => x.name) : (node.enum?.cases || []).map((c) => c.name))]
|
|
.filter(Boolean).join(' ').toLowerCase();
|
|
return words.every((w) => {
|
|
if (w === 'is:api') return !!e?.api;
|
|
if (w.startsWith('is:')) return node.kind.toLowerCase() === w.slice(3).toLowerCase() || (w === 'is:inheritance' && !!e?.inheritance);
|
|
return hay.includes(w);
|
|
});
|
|
}
|
|
|
|
/** the anchor points of an edge between two boxes: the sides that face each other */
|
|
export function anchors(a, b) {
|
|
const ac = { x: a.x + a.w / 2, y: a.y + a.h / 2 };
|
|
const bc = { x: b.x + b.w / 2, y: b.y + b.h / 2 };
|
|
if (Math.abs(ac.x - bc.x) * 0.6 > Math.abs(ac.y - bc.y) || Math.abs(ac.x - bc.x) > (a.w + b.w) / 2) {
|
|
const left = ac.x < bc.x;
|
|
return [{ x: left ? a.x + a.w : a.x, y: ac.y, side: left ? 'r' : 'l' }, { x: left ? b.x : b.x + b.w, y: bc.y, side: left ? 'l' : 'r' }];
|
|
}
|
|
const up = ac.y < bc.y;
|
|
return [{ x: ac.x, y: up ? a.y + a.h : a.y, side: up ? 'b' : 't' }, { x: bc.x, y: up ? b.y : b.y + b.h, side: up ? 't' : 'b' }];
|
|
}
|
|
|
|
/** an SVG path between two anchors (a soft curve) */
|
|
export function curve(p, q) {
|
|
const d = Math.max(30, Math.hypot(q.x - p.x, q.y - p.y) / 3);
|
|
const off = (s) => ({ r: [d, 0], l: [-d, 0], b: [0, d], t: [0, -d] }[s] || [0, 0]);
|
|
const [ax, ay] = off(p.side);
|
|
const [bx, by] = off(q.side);
|
|
return `M${p.x},${p.y} C${p.x + ax},${p.y + ay} ${q.x + bx},${q.y + by} ${q.x},${q.y}`;
|
|
}
|