@tjakoen/grain 0.1.35 → 0.1.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/molecules/stat-tile/stat-tile.css +2 -0
- package/components/molecules/stat-tile/stat-tile.md +4 -1
- package/components/organisms/diagram/diagram.css +39 -0
- package/components/organisms/diagram/diagram.md +33 -0
- package/components/organisms/diagram/diagram.test.ts +125 -0
- package/components/organisms/diagram/diagram.ts +541 -0
- package/package.json +1 -1
|
@@ -20,8 +20,10 @@
|
|
|
20
20
|
/* ---- tone (attribute) — ink-level + border weight, NOT hue ----
|
|
21
21
|
default : the calm baseline (a healthy/positive count needs no shouting).
|
|
22
22
|
ok : same calm baseline — an explicit "good" that reads identical, by design.
|
|
23
|
+
warn : worth a look, not yet wrong — the value firms to semibold, the border stays calm.
|
|
23
24
|
bad : draws the eye monochromatically — a solid-ink border + full-ink value.
|
|
24
25
|
muted : a context/secondary count (skipped, pending, a total) recedes to faint. */
|
|
26
|
+
.stat[data-tone="warn"] .stat__value { font-weight: var(--font-weight-semibold); }
|
|
25
27
|
.stat[data-tone="bad"] { border-color: var(--ink); }
|
|
26
28
|
.stat[data-tone="muted"] .stat__value { color: var(--ink-muted); }
|
|
27
29
|
.stat[data-tone="muted"] .stat__label { color: var(--ink-muted); }
|
|
@@ -32,11 +32,14 @@ state.
|
|
|
32
32
|
```
|
|
33
33
|
|
|
34
34
|
## Tones
|
|
35
|
-
`data-tone` shifts ink-level, not hue. `
|
|
35
|
+
`data-tone` shifts ink-level, not hue. `warn` marks a count worth a look that is not yet wrong
|
|
36
|
+
(items waiting, checks due) by setting the value in semibold while the border stays calm; `bad`
|
|
37
|
+
draws the eye with a solid-ink border; `muted` is a
|
|
36
38
|
secondary/context count that recedes to faint; `ok` and the default read identically on purpose
|
|
37
39
|
(a healthy count needs no shouting).
|
|
38
40
|
```html
|
|
39
41
|
<div class="stat" data-tone="ok"><span class="stat__value">14</span><span class="stat__label">passed</span></div>
|
|
42
|
+
<div class="stat" data-tone="warn"><span class="stat__value">4</span><span class="stat__label">due</span></div>
|
|
40
43
|
<div class="stat" data-tone="bad"><span class="stat__value">2</span><span class="stat__label">failed</span></div>
|
|
41
44
|
<div class="stat" data-tone="muted"><span class="stat__value">3</span><span class="stat__label">skipped</span></div>
|
|
42
45
|
```
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/* organisms/diagram: planning diagrams as inline SVG (diagram.ts draws them on the server).
|
|
2
|
+
The palette is closed: every stroke and fill is a semantic token, so state is shown by line
|
|
3
|
+
weight, dashes and words, and the diagram follows both theme axes without being redrawn. */
|
|
4
|
+
.diagram { margin: 0 0 var(--space-4); border: 1px solid var(--color-line); border-radius: var(--radius-md); background: var(--color-surface); overflow: hidden; }
|
|
5
|
+
.diagram__bar { display: flex; flex-wrap: wrap; gap: var(--space-2); align-items: center; padding: var(--space-2); border-bottom: 1px solid var(--color-line); }
|
|
6
|
+
.diagram__bar button { font: inherit; min-width: 2rem; padding: 0.15rem 0.5rem; border: 1px solid var(--color-line); border-radius: var(--radius-sm); background: var(--color-surface); color: var(--color-fg); cursor: pointer; }
|
|
7
|
+
.diagram__bar button:focus-visible { outline: 2px solid var(--color-fg); outline-offset: 1px; }
|
|
8
|
+
.diagram__hint { font-size: var(--text-xs); color: var(--color-muted); }
|
|
9
|
+
.diagram__svg { display: block; width: 100%; height: auto; max-height: 75vh; min-height: 18rem; cursor: grab; touch-action: none; user-select: none; font-family: var(--font-mono); font-size: 12px; }
|
|
10
|
+
.diagram__svg.is-panning { cursor: grabbing; }
|
|
11
|
+
.diagram__svg a, .diagram__svg text { text-decoration: none; }
|
|
12
|
+
.diagram__svg a { cursor: pointer; }
|
|
13
|
+
.diagram__svg text { fill: var(--color-fg); }
|
|
14
|
+
.diagram__svg .dg-box { fill: var(--color-surface); stroke: var(--color-fg); stroke-width: 1.4; }
|
|
15
|
+
.diagram__svg .dg-fill { fill: var(--color-surface); stroke: none; }
|
|
16
|
+
.diagram__svg .dg-rule { fill: none; stroke: var(--color-fg); stroke-width: 1.4; }
|
|
17
|
+
.diagram__svg .dg-shadow { fill: var(--color-fg); opacity: 0.18; }
|
|
18
|
+
.diagram__svg .dg-heavy { stroke-width: 2.6; }
|
|
19
|
+
.diagram__svg .dg-dashed, .diagram__svg .dg-stub .dg-box { stroke-dasharray: 5 4; }
|
|
20
|
+
.diagram__svg .dg-title { font-weight: var(--font-weight-semibold); font-family: var(--type-font); font-size: 13px; }
|
|
21
|
+
.diagram__svg .dg-sub, .diagram__svg .dg-key, .diagram__svg .dg-tag { fill: var(--color-muted); font-size: 11px; }
|
|
22
|
+
.diagram__svg .dg-pk { font-weight: var(--font-weight-bold); text-decoration: underline; }
|
|
23
|
+
.diagram__svg .dg-line, .diagram__svg .dg-card { fill: none; stroke: var(--color-fg); stroke-width: 1.3; }
|
|
24
|
+
.diagram__svg .dg-ring { fill: var(--color-surface); }
|
|
25
|
+
.diagram__svg .dg-optional { stroke-dasharray: 6 4; }
|
|
26
|
+
.diagram__svg .dg-arrowhead { fill: var(--color-fg); }
|
|
27
|
+
.diagram__svg .dg-hit { fill: none; stroke: transparent; stroke-width: 14; }
|
|
28
|
+
.diagram__svg .dg-elabel rect { fill: var(--color-surface); stroke: var(--color-line); }
|
|
29
|
+
.diagram__svg .dg-elabel text { font-size: 11px; font-family: var(--type-font); }
|
|
30
|
+
/* An emphasised flow (one crossing a region, say) is heavier and dashed, and says why in its title. */
|
|
31
|
+
.diagram__svg .dg-emphasis .dg-line { stroke-width: 2.6; stroke-dasharray: 8 5; }
|
|
32
|
+
.diagram__svg .dg-boundary rect { fill: none; stroke: var(--color-muted); stroke-width: 1.2; stroke-dasharray: 10 6; }
|
|
33
|
+
.diagram__svg .is-selected .dg-box, .diagram__svg .is-selected .dg-line { stroke-width: 3; }
|
|
34
|
+
.diagram__svg .dg-nodes a:hover .dg-box, .diagram__svg .dg-nodes a:focus-visible .dg-box { stroke-width: 2.6; }
|
|
35
|
+
.diagram__svg .dg-node, .diagram__svg .dg-edge { transition: opacity 0.12s; }
|
|
36
|
+
.diagram__svg.is-tracing .dg-node:not(.is-lit), .diagram__svg.is-tracing .dg-edge:not(.is-lit) { opacity: 0.18; }
|
|
37
|
+
.diagram__svg.is-tracing .dg-edge.is-lit .dg-line { stroke-width: 2.6; }
|
|
38
|
+
.diagram[data-diagram="flow"] .diagram__svg { min-height: 34rem; }
|
|
39
|
+
@media (prefers-reduced-motion: reduce) { .diagram__svg .dg-node, .diagram__svg .dg-edge { transition: none; } }
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Diagram
|
|
2
|
+
|
|
3
|
+
Planning diagrams drawn as inline SVG on the server, each in its method's own notation:
|
|
4
|
+
crow's-foot for an entity relationship diagram, Gane and Sarson for a data flow diagram with
|
|
5
|
+
trust boundaries, C4 for context and container views, and a flowchart for a user flow. Every
|
|
6
|
+
node and edge can be a link, and the frame gives pan, zoom and hover tracing with no library.
|
|
7
|
+
|
|
8
|
+
The palette is closed. Colour comes from the semantic tokens, so state is shown by line weight,
|
|
9
|
+
dashes and words: a heavy outline marks the system in scope or a flow's end, a dashed outline
|
|
10
|
+
marks something outside the scope, and an emphasised flow says why in its title.
|
|
11
|
+
|
|
12
|
+
diagram.ts has three layers, and a consumer can stop at any of them. The geometry (textWidth,
|
|
13
|
+
edgePoint, layers, orderByConnection, LabelPlacer) places things. The notation shapes (crowsFoot,
|
|
14
|
+
ganeSarson, c4, flowchart, boundary, arrow) each return one symbol. The renderers (erdDiagram,
|
|
15
|
+
dfdDiagram, layeredDiagram) take plain data and return a whole diagram inside diagramFrame. A page
|
|
16
|
+
that shows a diagram includes DIAGRAM_SCRIPT once.
|
|
17
|
+
|
|
18
|
+
The DFD keeps each trust boundary contiguous, then orders the boundaries so that no flow passes
|
|
19
|
+
through a boundary it does not touch, puts each external entity on the outer edge nearer to what
|
|
20
|
+
it talks to, and orders every column by connection.
|
|
21
|
+
|
|
22
|
+
## A small flow
|
|
23
|
+
```html
|
|
24
|
+
<figure class="diagram" data-diagram="flow">
|
|
25
|
+
<svg class="diagram__svg" viewBox="0 0 260 150" role="img" aria-label="A two-step flow">
|
|
26
|
+
<g class="dg-edges"><g class="dg-edge" data-edge="a-b" data-ends="a b"><path class="dg-line" d="M130,58 L130,92"></path></g></g>
|
|
27
|
+
<g class="dg-nodes">
|
|
28
|
+
<g class="dg-node" data-node="a"><rect class="dg-box" x="40" y="10" width="180" height="48" rx="24"></rect><text class="dg-title" x="130" y="39" text-anchor="middle">Open the link</text></g>
|
|
29
|
+
<g class="dg-node" data-node="b"><rect class="dg-box dg-heavy" x="40" y="92" width="180" height="48" rx="24"></rect><text class="dg-title" x="130" y="121" text-anchor="middle">See the page</text></g>
|
|
30
|
+
</g>
|
|
31
|
+
</svg>
|
|
32
|
+
</figure>
|
|
33
|
+
```
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// grain/components/organisms/diagram/diagram.test.ts: the diagram organism's geometry and renderers.
|
|
2
|
+
import { test, expect, describe } from "bun:test";
|
|
3
|
+
import {
|
|
4
|
+
edgePoint, layers, orderByConnection, LabelPlacer, overlaps, dfdColumns,
|
|
5
|
+
erdDiagram, dfdDiagram, layeredDiagram, crowsFoot, type DfdInput, type Box,
|
|
6
|
+
} from "./diagram.ts";
|
|
7
|
+
|
|
8
|
+
const xOf = (svg: string, id: string) => Number(svg.match(new RegExp(`data-node="${id}"[^>]*>(?:<title>[^<]*</title>)?<rect[^>]* x="([\\d.]+)"`))?.[1]);
|
|
9
|
+
|
|
10
|
+
describe("geometry", () => {
|
|
11
|
+
test("a line leaves a box at its edge, and a diamond at its slanted side", () => {
|
|
12
|
+
const b: Box = { id: "b", x: 0, y: 0, w: 100, h: 40 };
|
|
13
|
+
expect(edgePoint(b, 200, 20)).toEqual([100, 20]);
|
|
14
|
+
expect(edgePoint(b, 50, 100)).toEqual([50, 40]);
|
|
15
|
+
const [x, y] = edgePoint(b, 100, 40, "diamond");
|
|
16
|
+
expect(x / 50 + y / 20).toBeCloseTo(3, 5);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("layers follow the longest path and a cycle stays bounded", () => {
|
|
20
|
+
expect(layers(["a", "b", "c"], [["a", "b"], ["b", "c"], ["a", "c"]])).toEqual([["a"], ["b"], ["c"]]);
|
|
21
|
+
expect(layers(["a", "b"], [["a", "b"], ["b", "a"]]).flat().sort()).toEqual(["a", "b"]);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("ordering by connection uncrosses two parallel edges", () => {
|
|
25
|
+
const out = orderByConnection([["a", "b"], ["y", "x"]], [["a", "x"], ["b", "y"]]);
|
|
26
|
+
expect(out[1]).toEqual(["x", "y"]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("a label steps away from one already placed", () => {
|
|
30
|
+
const p = new LabelPlacer();
|
|
31
|
+
const one = p.place(50, 50, "first label")!, two = p.place(50, 50, "second label")!;
|
|
32
|
+
expect(overlaps(one, two)).toBe(false);
|
|
33
|
+
expect(p.svg()).toContain("second label");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("text is escaped", () => {
|
|
37
|
+
const p = new LabelPlacer();
|
|
38
|
+
p.place(0, 0, "<a & b>");
|
|
39
|
+
expect(p.svg()).toContain("<a & b>");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("crow's-foot ends draw the shape the cardinality names", () => {
|
|
43
|
+
expect(crowsFoot.many(0, 0, 1)).toContain("<path");
|
|
44
|
+
expect(crowsFoot.exactlyOne(0, 0, 1).match(/<line/g)).toHaveLength(2);
|
|
45
|
+
expect(crowsFoot.zeroOrOne(0, 0, -1)).toContain("<circle");
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// The case that motivated ordering by connection: a visitor posts to a function in the second
|
|
50
|
+
// boundary, and the first boundary sat between them.
|
|
51
|
+
const avero: DfdInput = {
|
|
52
|
+
nodes: [
|
|
53
|
+
{ id: "visitor", kind: "external", label: "Website visitor" },
|
|
54
|
+
{ id: "staff", kind: "external", label: "Staff" },
|
|
55
|
+
{ id: "client", kind: "external", label: "Client member" },
|
|
56
|
+
{ id: "book", kind: "process", label: "Book function", boundary: "supabase" },
|
|
57
|
+
{ id: "portal", kind: "process", label: "Client page", boundary: "browser" },
|
|
58
|
+
{ id: "bookings", kind: "store", label: "Bookings table", boundary: "supabase" },
|
|
59
|
+
{ id: "clients", kind: "store", label: "Client tables", boundary: "supabase" },
|
|
60
|
+
],
|
|
61
|
+
boundaries: [{ id: "browser", label: "The user's browser" }, { id: "supabase", label: "Supabase project" }],
|
|
62
|
+
flows: [
|
|
63
|
+
{ id: "f1", from: "visitor", to: "book", label: "Visitor sends a request" },
|
|
64
|
+
{ id: "f2", from: "book", to: "bookings" },
|
|
65
|
+
{ id: "f3", from: "clients", to: "portal" },
|
|
66
|
+
{ id: "f4", from: "staff", to: "clients" },
|
|
67
|
+
{ id: "f5", from: "client", to: "portal" },
|
|
68
|
+
],
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
describe("DFD layout", () => {
|
|
72
|
+
test("no flow passes through a boundary it does not touch", () => {
|
|
73
|
+
const { slots, side } = dfdColumns(avero);
|
|
74
|
+
expect(side.get("visitor")).toBe("right");
|
|
75
|
+
expect(side.get("client")).toBe("left");
|
|
76
|
+
const order = slots.map((s) => s.boundary?.id ?? s.side);
|
|
77
|
+
expect(order).toEqual(["left", "browser", "supabase", "right"]);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("the visitor sits beyond the Book function, not across the browser", () => {
|
|
81
|
+
const svg = dfdDiagram(avero);
|
|
82
|
+
expect(xOf(svg, "visitor")).toBeGreaterThan(xOf(svg, "book"));
|
|
83
|
+
expect(xOf(svg, "portal")).toBeLessThan(xOf(svg, "book"));
|
|
84
|
+
expect(svg).toContain('data-ends="visitor book"');
|
|
85
|
+
expect(svg).toContain("P1");
|
|
86
|
+
expect(svg).toContain("D1");
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("renderers", () => {
|
|
91
|
+
test("the ERD puts a referenced table left of its child and draws its notation", () => {
|
|
92
|
+
const svg = erdDiagram({
|
|
93
|
+
entities: [
|
|
94
|
+
{ id: "child", columns: [{ name: "id", pk: true }, { name: "parent_id", fk: true, nullable: true }], href: "/t/child" },
|
|
95
|
+
{ id: "parent", columns: [{ name: "id", pk: true }], tag: "RLS" },
|
|
96
|
+
],
|
|
97
|
+
relations: [{ id: "r1", from: "child", to: "parent", fromColumn: "parent_id", toColumn: "id", optional: true, toEnd: "zero-or-one" }],
|
|
98
|
+
selected: "child",
|
|
99
|
+
});
|
|
100
|
+
expect(xOf(svg, "parent")).toBeLessThan(xOf(svg, "child"));
|
|
101
|
+
expect(svg).toContain('href="/t/child"');
|
|
102
|
+
expect(svg).toContain("dg-optional");
|
|
103
|
+
expect(svg).toContain("<circle");
|
|
104
|
+
expect(svg).toContain(">RLS<");
|
|
105
|
+
expect(svg).toContain("is-selected");
|
|
106
|
+
expect(svg).toContain('class="diagram"');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("a layered diagram draws each kind's shape and the group scope", () => {
|
|
110
|
+
const svg = layeredDiagram({
|
|
111
|
+
kind: "c4-containers", label: "C4", group: { label: "Avero", members: ["web"] },
|
|
112
|
+
nodes: [
|
|
113
|
+
{ id: "u", kind: "person", label: "User" },
|
|
114
|
+
{ id: "web", kind: "container", label: "Web", sub: "[Bun]" },
|
|
115
|
+
{ id: "ok", kind: "decision", label: "Ok?" },
|
|
116
|
+
],
|
|
117
|
+
edges: [{ from: "u", to: "web", label: "Uses" }, { from: "web", to: "ok" }],
|
|
118
|
+
});
|
|
119
|
+
expect(svg).toContain("dg-k-person");
|
|
120
|
+
expect(svg).toContain("<circle");
|
|
121
|
+
expect(svg).toContain("dg-boundary");
|
|
122
|
+
expect(svg).toContain("[Bun]");
|
|
123
|
+
expect(svg).toContain(">Uses<");
|
|
124
|
+
});
|
|
125
|
+
});
|
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
// grain/components/organisms/diagram/diagram.ts: planning diagrams drawn as inline SVG on the server.
|
|
2
|
+
//
|
|
3
|
+
// Four notations, each in its method's own shapes: crow's-foot for an ERD, Gane and Sarson for a
|
|
4
|
+
// DFD with trust boundaries, C4 for context and container views, and a flowchart for user flows.
|
|
5
|
+
// The module has three layers, and a consumer can stop at any of them:
|
|
6
|
+
//
|
|
7
|
+
// 1. geometry: text widths, where a line leaves a box, longest-path layering, crossing reduction,
|
|
8
|
+
// and a label placer that steps a label away until it overlaps nothing already drawn;
|
|
9
|
+
// 2. notation shapes: one function per symbol (crow's-foot ends, process, store, external,
|
|
10
|
+
// person, system, container, start, action, decision, end), each returning an SVG fragment;
|
|
11
|
+
// 3. renderers: erdDiagram, dfdDiagram and layeredDiagram take plain neutral data and return a
|
|
12
|
+
// whole diagram inside diagramFrame, which DIAGRAM_SCRIPT gives pan, zoom and hover tracing.
|
|
13
|
+
//
|
|
14
|
+
// The palette is closed. Colour comes from the semantic tokens in diagram.css, so state is shown by
|
|
15
|
+
// line weight, dashes and words, never by a new hue. Every node and edge carries data-node or
|
|
16
|
+
// data-edge, and an edge names its two ends in data-ends, which is all the tracing script reads.
|
|
17
|
+
|
|
18
|
+
// ── geometry ───────────────────────────────────────────────────────────────────────────────────
|
|
19
|
+
|
|
20
|
+
export interface Box { id: string; x: number; y: number; w: number; h: number }
|
|
21
|
+
export type Point = [number, number];
|
|
22
|
+
|
|
23
|
+
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
24
|
+
export { esc as escapeDiagramText };
|
|
25
|
+
|
|
26
|
+
/** The approximate width of one 12px character, which every box size is derived from. */
|
|
27
|
+
export const CHAR_W = 6.8;
|
|
28
|
+
/** A box wide enough for the text plus padding, never narrower than min. */
|
|
29
|
+
export const textWidth = (s: string, min = 0) => Math.max(min, Math.ceil(s.length * CHAR_W) + 24);
|
|
30
|
+
|
|
31
|
+
export const centre = (b: Box): Point => [b.x + b.w / 2, b.y + b.h / 2];
|
|
32
|
+
export const overlaps = (a: Box, b: Box) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
|
33
|
+
|
|
34
|
+
/** The point where a line from the box's centre toward (tx, ty) leaves the box. */
|
|
35
|
+
export function edgePoint(b: Box, tx: number, ty: number, shape: "rect" | "diamond" = "rect"): Point {
|
|
36
|
+
const [cx, cy] = centre(b);
|
|
37
|
+
const dx = tx - cx, dy = ty - cy;
|
|
38
|
+
if (!dx && !dy) return [cx, cy];
|
|
39
|
+
const hw = b.w / 2, hh = b.h / 2;
|
|
40
|
+
const t = shape === "diamond"
|
|
41
|
+
? 1 / (Math.abs(dx) / hw + Math.abs(dy) / hh)
|
|
42
|
+
: Math.min(dx ? hw / Math.abs(dx) : Infinity, dy ? hh / Math.abs(dy) : Infinity);
|
|
43
|
+
return [cx + dx * t, cy + dy * t];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Longest-path layering over a directed graph; a cycle cannot push a node past the last layer. */
|
|
47
|
+
export function layers(ids: string[], edges: [string, string][]): string[][] {
|
|
48
|
+
const rank = new Map<string, number>(ids.map((id) => [id, 0]));
|
|
49
|
+
for (let pass = 0; pass < ids.length; pass++) {
|
|
50
|
+
let moved = false;
|
|
51
|
+
for (const [a, b] of edges) {
|
|
52
|
+
if (a === b || !rank.has(a) || !rank.has(b)) continue;
|
|
53
|
+
const want = rank.get(a)! + 1;
|
|
54
|
+
if (want > rank.get(b)! && want < ids.length) { rank.set(b, want); moved = true; }
|
|
55
|
+
}
|
|
56
|
+
if (!moved) break;
|
|
57
|
+
}
|
|
58
|
+
const out: string[][] = [];
|
|
59
|
+
for (const id of ids) (out[rank.get(id)!] ??= []).push(id);
|
|
60
|
+
return out.filter(Boolean);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Reorders each layer so a node sits near the mean position of its neighbours in the layers either
|
|
65
|
+
* side (the barycenter heuristic), sweeping down and up a few times. It changes order only, never
|
|
66
|
+
* membership, and a node with no neighbours keeps its place, so an unconnected graph is unchanged.
|
|
67
|
+
*/
|
|
68
|
+
export function orderByConnection(rows: string[][], edges: [string, string][], sweeps = 4): string[][] {
|
|
69
|
+
const out = rows.map((r) => [...r]);
|
|
70
|
+
const nbrs = new Map<string, string[]>();
|
|
71
|
+
for (const [a, b] of edges) {
|
|
72
|
+
if (a === b) continue;
|
|
73
|
+
(nbrs.get(a) ?? nbrs.set(a, []).get(a)!).push(b);
|
|
74
|
+
(nbrs.get(b) ?? nbrs.set(b, []).get(b)!).push(a);
|
|
75
|
+
}
|
|
76
|
+
const pass = (i: number, ref: number[]) => {
|
|
77
|
+
const pos = new Map<string, number>();
|
|
78
|
+
for (const j of ref) out[j]?.forEach((id, k) => pos.set(id, k / Math.max(1, out[j]!.length - 1)));
|
|
79
|
+
const row = out[i]!;
|
|
80
|
+
const key = new Map(row.map((id, k) => {
|
|
81
|
+
const ps = (nbrs.get(id) ?? []).map((n) => pos.get(n)).filter((p): p is number => p !== undefined);
|
|
82
|
+
return [id, ps.length ? ps.reduce((s, p) => s + p, 0) / ps.length : k / Math.max(1, row.length - 1)];
|
|
83
|
+
}));
|
|
84
|
+
row.sort((a, b) => key.get(a)! - key.get(b)!);
|
|
85
|
+
};
|
|
86
|
+
for (let s = 0; s < sweeps; s++) {
|
|
87
|
+
for (let i = 1; i < out.length; i++) pass(i, [i - 1]);
|
|
88
|
+
for (let i = out.length - 2; i >= 0; i--) pass(i, [i + 1]);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Collects the labels of one diagram. A label is offered at a point, steps up and down until its
|
|
95
|
+
* box overlaps nothing already placed (nodes count, once added with avoid), and is drawn last, so a
|
|
96
|
+
* node never hides one.
|
|
97
|
+
*/
|
|
98
|
+
export class LabelPlacer {
|
|
99
|
+
private placed: Box[] = [];
|
|
100
|
+
private out: string[] = [];
|
|
101
|
+
avoid(...boxes: Box[]) { this.placed.push(...boxes); }
|
|
102
|
+
place(x: number, y: number, text: string): Box | undefined {
|
|
103
|
+
if (!text) return undefined;
|
|
104
|
+
const w = textWidth(text) - 12;
|
|
105
|
+
let box: Box = { id: "", x: x - w / 2, y: y - 9, w, h: 18 };
|
|
106
|
+
for (let i = 1; i < 12 && this.placed.some((p) => overlaps(p, box)); i++) {
|
|
107
|
+
const step = Math.ceil(i / 2) * 22 * (i % 2 ? 1 : -1);
|
|
108
|
+
box = { ...box, y: y - 9 + step };
|
|
109
|
+
}
|
|
110
|
+
this.placed.push(box);
|
|
111
|
+
this.out.push(`<g class="dg-elabel"><rect x="${box.x}" y="${box.y}" width="${w}" height="18" rx="3"/><text x="${x}" y="${box.y + 13}" text-anchor="middle">${esc(text)}</text></g>`);
|
|
112
|
+
return box;
|
|
113
|
+
}
|
|
114
|
+
svg() { return `<g class="dg-labels">${this.out.join("")}</g>`; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ── frame ──────────────────────────────────────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
const DEFS = `<defs><marker id="dg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead"/></marker></defs>`;
|
|
120
|
+
|
|
121
|
+
export interface FrameOptions { kind: string; width: number; height: number; label: string; hint?: string }
|
|
122
|
+
|
|
123
|
+
/** Wraps SVG content in the figure, toolbar and viewport that DIAGRAM_SCRIPT drives. */
|
|
124
|
+
export function diagramFrame(o: FrameOptions, inner: string): string {
|
|
125
|
+
const W = Math.ceil(o.width), H = Math.ceil(o.height);
|
|
126
|
+
const hint = o.hint ?? "Scroll or pinch to zoom, drag to pan, hover to trace, click to open.";
|
|
127
|
+
return `<figure class="diagram" data-diagram="${esc(o.kind)}">
|
|
128
|
+
<div class="diagram__bar" role="toolbar" aria-label="Diagram controls">
|
|
129
|
+
<button type="button" data-zoom="in" aria-label="Zoom in">+</button>
|
|
130
|
+
<button type="button" data-zoom="out" aria-label="Zoom out">−</button>
|
|
131
|
+
<button type="button" data-zoom="reset">Fit</button>
|
|
132
|
+
<span class="diagram__hint">${esc(hint)}</span>
|
|
133
|
+
</div>
|
|
134
|
+
<svg class="diagram__svg" viewBox="0 0 ${W} ${H}" data-w="${W}" data-h="${H}" role="img" aria-label="${esc(o.label)}" xmlns="http://www.w3.org/2000/svg">${DEFS}${inner}</svg>
|
|
135
|
+
</figure>`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A node or edge wrapper: a link when it has an href, a group otherwise, with a native tooltip. */
|
|
139
|
+
function wrap(attrs: { cls: string; node?: string; edge?: string; ends?: [string, string]; href?: string; title: string }, inner: string): string {
|
|
140
|
+
const tag = attrs.href ? "a" : "g";
|
|
141
|
+
const data = (attrs.node !== undefined ? ` data-node="${esc(attrs.node)}"` : "")
|
|
142
|
+
+ (attrs.edge !== undefined ? ` data-edge="${esc(attrs.edge)}"` : "")
|
|
143
|
+
+ (attrs.ends ? ` data-ends="${esc(attrs.ends[0])} ${esc(attrs.ends[1])}"` : "")
|
|
144
|
+
+ (attrs.href ? ` href="${esc(attrs.href)}"` : "");
|
|
145
|
+
return `<${tag} class="${attrs.cls}"${data}><title>${esc(attrs.title)}</title>${inner}</${tag}>`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ── notation shapes ────────────────────────────────────────────────────────────────────────────
|
|
149
|
+
|
|
150
|
+
const title = (x: number, y: number, s: string, anchor = "middle") => `<text class="dg-title" x="${x}" y="${y}" text-anchor="${anchor}">${esc(s)}</text>`;
|
|
151
|
+
const sub = (x: number, y: number, s: string) => `<text class="dg-sub" x="${x}" y="${y}" text-anchor="middle">${esc(s)}</text>`;
|
|
152
|
+
const tag = (x: number, y: number, s: string, anchor = "middle") => `<text class="dg-tag" x="${x}" y="${y}" text-anchor="${anchor}">${esc(s)}</text>`;
|
|
153
|
+
const bar = (x: number, y: number) => `<line class="dg-card" x1="${x}" y1="${y - 7}" x2="${x}" y2="${y + 7}"/>`;
|
|
154
|
+
|
|
155
|
+
/** Crow's-foot cardinality ends. The end sits at (x, y) and the shape grows in direction dir (1 right, -1 left). */
|
|
156
|
+
export const crowsFoot = {
|
|
157
|
+
/** Many: a foot spreading onto the box, with a bar behind it (one or more). */
|
|
158
|
+
many: (x: number, y: number, dir: 1 | -1) => `<path class="dg-card" d="M${x},${y - 7} L${x + dir * 14},${y} L${x},${y + 7}"/>${bar(x + dir * 18, y)}`,
|
|
159
|
+
/** One: a single bar. */
|
|
160
|
+
one: (x: number, y: number, dir: 1 | -1) => bar(x + dir * 10, y),
|
|
161
|
+
/** Exactly one: two bars. */
|
|
162
|
+
exactlyOne: (x: number, y: number, dir: 1 | -1) => bar(x + dir * 9, y) + bar(x + dir * 15, y),
|
|
163
|
+
/** Zero or one: a ring and a bar. */
|
|
164
|
+
zeroOrOne: (x: number, y: number, dir: 1 | -1) => `<circle class="dg-card dg-ring" cx="${x + dir * 20}" cy="${y}" r="5"/>${bar(x + dir * 9, y)}`,
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
/** Gane and Sarson symbols. tagText is the P1 or D1 identifier the notation prints in the strip. */
|
|
168
|
+
export const ganeSarson = {
|
|
169
|
+
/** A process: a rounded rectangle with an identifier strip across the top. */
|
|
170
|
+
process: (b: Box, label: string, tagText: string) =>
|
|
171
|
+
`<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="12"/><path class="dg-rule" d="M${b.x},${b.y + 20} h${b.w}"/>${tag(b.x + b.w / 2, b.y + 14, tagText)}${title(b.x + b.w / 2, b.y + b.h / 2 + 10, label)}`,
|
|
172
|
+
/** A data store: an open-ended rectangle with an identifier compartment. */
|
|
173
|
+
store: (b: Box, label: string, tagText: string) =>
|
|
174
|
+
`<rect class="dg-fill" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}"/><path class="dg-rule" d="M${b.x + b.w},${b.y} H${b.x} V${b.y + b.h} H${b.x + b.w}"/><path class="dg-rule" d="M${b.x + 32},${b.y} V${b.y + b.h}"/>${tag(b.x + 16, b.y + b.h / 2 + 4, tagText)}${title(b.x + 32 + (b.w - 32) / 2, b.y + b.h / 2 + 5, label)}`,
|
|
175
|
+
/** An external entity: a square with a heavier shadow edge. */
|
|
176
|
+
external: (b: Box, label: string) =>
|
|
177
|
+
`<rect class="dg-shadow" x="${b.x + 4}" y="${b.y + 4}" width="${b.w}" height="${b.h}"/><rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}"/>${title(b.x + b.w / 2, b.y + b.h / 2 + 5, label)}`,
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
/** Text for a box: a bold label and an optional second line, centred around ty. */
|
|
181
|
+
function boxText(b: Box, label: string, second: string | undefined, ty = b.y + b.h / 2 + (second ? -2 : 5)): string {
|
|
182
|
+
const cx = b.x + b.w / 2;
|
|
183
|
+
return title(cx, ty, label) + (second ? sub(cx, ty + 16, second) : "");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** C4 symbols. second is the bracketed line under the name, such as [Container: Bun]. */
|
|
187
|
+
export const c4 = {
|
|
188
|
+
/** A person: a head over a rounded body. Needs a box about 84 high. */
|
|
189
|
+
person: (b: Box, label: string, second?: string) => {
|
|
190
|
+
const cx = b.x + b.w / 2;
|
|
191
|
+
return `<circle class="dg-box" cx="${cx}" cy="${b.y + 14}" r="14"/><rect class="dg-box" x="${b.x}" y="${b.y + 30}" width="${b.w}" height="${b.h - 30}" rx="16"/>${boxText(b, label, second, b.y + 30 + (b.h - 30) / 2 + (second ? -2 : 5))}`;
|
|
192
|
+
},
|
|
193
|
+
/** The system in scope: a heavy outline, the weight standing in for the notation's fill colour. */
|
|
194
|
+
system: (b: Box, label: string, second?: string) => `<rect class="dg-box dg-heavy" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6"/>${boxText(b, label, second)}`,
|
|
195
|
+
/** A container inside the system boundary. */
|
|
196
|
+
container: (b: Box, label: string, second?: string) => `<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6"/>${boxText(b, label, second)}`,
|
|
197
|
+
/** A system outside the scope: dashed, the dashes standing in for the notation's grey. */
|
|
198
|
+
external: (b: Box, label: string, second?: string) => `<rect class="dg-box dg-dashed" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6"/>${boxText(b, label, second)}`,
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
/** Flowchart symbols. */
|
|
202
|
+
export const flowchart = {
|
|
203
|
+
/** Start: a stadium. */
|
|
204
|
+
start: (b: Box, label: string, second?: string) => `<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="${b.h / 2}"/>${boxText(b, label, second)}`,
|
|
205
|
+
/** End: a stadium with a heavy outline, so it reads as terminal without a second colour. */
|
|
206
|
+
end: (b: Box, label: string, second?: string) => `<rect class="dg-box dg-heavy" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="${b.h / 2}"/>${boxText(b, label, second)}`,
|
|
207
|
+
/** Action: a rounded rectangle. */
|
|
208
|
+
action: (b: Box, label: string, second?: string) => `<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6"/>${boxText(b, label, second)}`,
|
|
209
|
+
/** Decision: a diamond. Edges leave it through edgePoint with shape "diamond". */
|
|
210
|
+
decision: (b: Box, label: string, second?: string) => {
|
|
211
|
+
const cx = b.x + b.w / 2;
|
|
212
|
+
return `<path class="dg-box" d="M${cx},${b.y} L${b.x + b.w},${b.y + b.h / 2} L${cx},${b.y + b.h} L${b.x},${b.y + b.h / 2} z"/>${boxText(b, label, second)}`;
|
|
213
|
+
},
|
|
214
|
+
/** System step: the predefined-process box, a rectangle with a double rule at each side. */
|
|
215
|
+
system: (b: Box, label: string, second?: string) => `<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}"/><path class="dg-rule" d="M${b.x + 10},${b.y} V${b.y + b.h} M${b.x + b.w - 10},${b.y} V${b.y + b.h}"/>${boxText(b, label, second)}`,
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
/** A dashed boundary with its label in the top-left corner: a trust boundary or a C4 system scope. */
|
|
219
|
+
export function boundary(b: Box, label: string, titleText = label): string {
|
|
220
|
+
return `<g class="dg-boundary" data-node="${esc(b.id)}"><title>${esc(titleText)}</title><rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="14"/>${tag(b.x + 14, b.y + 20, label, "start")}</g>`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A straight connector with an arrow, plus a wide invisible stroke so it is easy to hover. */
|
|
224
|
+
export function arrow(p1: Point, p2: Point): string {
|
|
225
|
+
const d = `M${p1[0]},${p1[1]} L${p2[0]},${p2[1]}`;
|
|
226
|
+
return `<path class="dg-line" d="${d}" marker-end="url(#dg-arrow)"/><path class="dg-hit" d="${d}"/>`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ── renderer: ERD ──────────────────────────────────────────────────────────────────────────────
|
|
230
|
+
|
|
231
|
+
export interface ErdColumnIn { name: string; type?: string; pk?: boolean; fk?: boolean; nullable?: boolean }
|
|
232
|
+
export interface ErdEntityIn { id: string; columns: ErdColumnIn[]; tag?: string; stub?: boolean; href?: string; title?: string }
|
|
233
|
+
export type ErdEnd = "many" | "one" | "exactly-one" | "zero-or-one";
|
|
234
|
+
export interface ErdRelationIn {
|
|
235
|
+
id: string; from: string; to: string; fromColumn?: string; toColumn?: string;
|
|
236
|
+
/** The end at the referencing table, many by default. */
|
|
237
|
+
fromEnd?: ErdEnd;
|
|
238
|
+
/** The end at the referenced table, exactly one by default. */
|
|
239
|
+
toEnd?: ErdEnd;
|
|
240
|
+
optional?: boolean; href?: string; title?: string;
|
|
241
|
+
}
|
|
242
|
+
export interface ErdInput { entities: ErdEntityIn[]; relations: ErdRelationIn[]; selected?: string; label?: string }
|
|
243
|
+
|
|
244
|
+
const ROW = 20, HEAD = 30, ERD_W = 230;
|
|
245
|
+
const endShape = (end: ErdEnd, x: number, y: number, dir: 1 | -1) =>
|
|
246
|
+
end === "many" ? crowsFoot.many(x, y, dir) : end === "one" ? crowsFoot.one(x, y, dir) : end === "zero-or-one" ? crowsFoot.zeroOrOne(x, y, dir) : crowsFoot.exactlyOne(x, y, dir);
|
|
247
|
+
|
|
248
|
+
/** A crow's-foot ERD. Referenced tables sit to the left of the tables that point at them. */
|
|
249
|
+
export function erdDiagram(input: ErdInput): string {
|
|
250
|
+
const ents = new Map(input.entities.map((x) => [x.id, x]));
|
|
251
|
+
const rels = input.relations.filter((r) => ents.has(r.from) && ents.has(r.to));
|
|
252
|
+
const parentEdges: [string, string][] = rels.filter((r) => r.from !== r.to).map((r) => [r.to, r.from]);
|
|
253
|
+
const cols = orderByConnection(layers([...ents.keys()], parentEdges), parentEdges);
|
|
254
|
+
const GAPX = 120, GAPY = 36, PAD = 24;
|
|
255
|
+
const boxes = new Map<string, Box>();
|
|
256
|
+
let H = 0;
|
|
257
|
+
cols.forEach((col, ci) => {
|
|
258
|
+
let y = PAD;
|
|
259
|
+
for (const id of col) {
|
|
260
|
+
const h = HEAD + ents.get(id)!.columns.length * ROW + 8;
|
|
261
|
+
boxes.set(id, { id, x: PAD + ci * (ERD_W + GAPX), y, w: ERD_W, h });
|
|
262
|
+
y += h + GAPY;
|
|
263
|
+
}
|
|
264
|
+
H = Math.max(H, y);
|
|
265
|
+
});
|
|
266
|
+
const W = PAD * 2 + cols.length * ERD_W + (cols.length - 1) * GAPX;
|
|
267
|
+
const rowY = (id: string, col = "") => {
|
|
268
|
+
const b = boxes.get(id)!, i = ents.get(id)!.columns.findIndex((c) => c.name === col);
|
|
269
|
+
return b.y + HEAD + (i < 0 ? 0 : i) * ROW + ROW / 2 + 2;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const edges = rels.map((r) => {
|
|
273
|
+
const a = boxes.get(r.from)!, b = boxes.get(r.to)!;
|
|
274
|
+
const y1 = rowY(r.from, r.fromColumn), y2 = rowY(r.to, r.toColumn);
|
|
275
|
+
const leftward = b.x + b.w <= a.x;
|
|
276
|
+
const x1 = leftward ? a.x : a.x + a.w, x2 = leftward ? b.x + b.w : b.x;
|
|
277
|
+
const dir: 1 | -1 = leftward ? -1 : 1;
|
|
278
|
+
const bend = Math.max(40, Math.abs(x2 - x1) / 2);
|
|
279
|
+
const d = `M${x1},${y1} C${x1 + dir * bend},${y1} ${x2 - dir * bend},${y2} ${x2},${y2}`;
|
|
280
|
+
const inner = `<path class="dg-line${r.optional ? " dg-optional" : ""}" d="${d}"/><path class="dg-hit" d="${d}"/>${endShape(r.fromEnd ?? "many", x1, y1, dir)}${endShape(r.toEnd ?? "exactly-one", x2, y2, dir === 1 ? -1 : 1)}`;
|
|
281
|
+
return wrap({ cls: `dg-edge${r.id === input.selected ? " is-selected" : ""}`, edge: r.id, ends: [r.from, r.to], href: r.href, title: r.title ?? r.id }, inner);
|
|
282
|
+
}).join("");
|
|
283
|
+
|
|
284
|
+
const nodes = [...boxes.values()].map((b) => {
|
|
285
|
+
const ent = ents.get(b.id)!;
|
|
286
|
+
const rows = ent.columns.map((c, i) => {
|
|
287
|
+
const y = b.y + HEAD + i * ROW + ROW / 2 + 6;
|
|
288
|
+
const key = c.pk ? "PK" : c.fk ? "FK" : "";
|
|
289
|
+
return `<text class="dg-key" x="${b.x + 10}" y="${y}">${key}</text><text class="dg-col${c.pk ? " dg-pk" : ""}" x="${b.x + 38}" y="${y}">${esc(c.name)}</text><text class="dg-sub" x="${b.x + b.w - 10}" y="${y}" text-anchor="end">${esc((c.type ?? "") + (c.nullable ? "?" : ""))}</text>`;
|
|
290
|
+
}).join("");
|
|
291
|
+
const inner = `<rect class="dg-box" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6"/><path class="dg-rule" d="M${b.x},${b.y + HEAD} h${b.w}"/>${title(b.x + 10, b.y + 20, b.id, "start")}${ent.tag ? tag(b.x + b.w - 10, b.y + 20, ent.tag, "end") : ""}${rows}`;
|
|
292
|
+
const cls = `dg-node${ent.stub ? " dg-stub" : ""}${b.id === input.selected ? " is-selected" : ""}`;
|
|
293
|
+
return wrap({ cls, node: b.id, href: ent.href, title: ent.title ?? b.id }, inner);
|
|
294
|
+
}).join("");
|
|
295
|
+
return diagramFrame({ kind: "erd", width: W, height: H, label: input.label ?? `Entity relationship diagram with ${input.entities.length} tables` },
|
|
296
|
+
`<g class="dg-edges">${edges}</g><g class="dg-nodes">${nodes}</g>`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ── renderer: DFD ──────────────────────────────────────────────────────────────────────────────
|
|
300
|
+
|
|
301
|
+
export type DfdKind = "process" | "store" | "external";
|
|
302
|
+
export interface DfdNodeIn { id: string; kind: DfdKind; label: string; boundary?: string; href?: string; title?: string }
|
|
303
|
+
export interface DfdBoundaryIn { id: string; label: string; title?: string }
|
|
304
|
+
export interface DfdFlowIn { id: string; from: string; to: string; label?: string; emphasis?: boolean; href?: string; title?: string }
|
|
305
|
+
export interface DfdInput { nodes: DfdNodeIn[]; boundaries: DfdBoundaryIn[]; flows: DfdFlowIn[]; selected?: string; label?: string }
|
|
306
|
+
|
|
307
|
+
/** A column slot in the DFD: a trust boundary, or loose nodes on the left or right edge. */
|
|
308
|
+
type Slot = { boundary?: DfdBoundaryIn; side?: "left" | "right" };
|
|
309
|
+
|
|
310
|
+
function permutations<T>(xs: T[]): T[][] {
|
|
311
|
+
if (xs.length <= 1) return [xs];
|
|
312
|
+
return xs.flatMap((x, i) => permutations([...xs.slice(0, i), ...xs.slice(i + 1)]).map((p) => [x, ...p]));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Where each DFD column goes. Boundaries stay contiguous, and their order is the one that keeps
|
|
317
|
+
* flows short and, above all, keeps a flow from passing through a boundary it does not touch. Each
|
|
318
|
+
* loose node (an external entity, mostly) then sits on whichever outer edge is nearer to what it
|
|
319
|
+
* connects to. Up to six boundaries are tried exhaustively; past that, the given order stands.
|
|
320
|
+
*/
|
|
321
|
+
export function dfdColumns(input: DfdInput): { slots: Slot[]; side: Map<string, "left" | "right"> } {
|
|
322
|
+
const known = new Set(input.boundaries.map((b) => b.id));
|
|
323
|
+
const groupOf = (id: string) => { const n = input.nodes.find((x) => x.id === id); return n?.boundary && known.has(n.boundary) ? n.boundary : undefined; };
|
|
324
|
+
const loose = input.nodes.filter((n) => !groupOf(n.id)).map((n) => n.id);
|
|
325
|
+
const tries = input.boundaries.length <= 6 ? permutations(input.boundaries) : [input.boundaries];
|
|
326
|
+
let best = { cost: Infinity, order: input.boundaries, side: new Map<string, "left" | "right">() };
|
|
327
|
+
for (const order of tries) {
|
|
328
|
+
const pos = new Map(order.map((b, i) => [b.id, i + 1]));
|
|
329
|
+
const last = order.length + 1;
|
|
330
|
+
const side = new Map<string, "left" | "right">();
|
|
331
|
+
for (const id of loose) {
|
|
332
|
+
const touches = input.flows.flatMap((f) => (f.from === id ? [f.to] : f.to === id ? [f.from] : [])).map((o) => pos.get(groupOf(o) ?? "")).filter((p): p is number => p !== undefined);
|
|
333
|
+
const mean = touches.length ? touches.reduce((s, p) => s + p, 0) / touches.length : 0;
|
|
334
|
+
side.set(id, touches.length && mean > last / 2 ? "right" : "left");
|
|
335
|
+
}
|
|
336
|
+
const at = (id: string) => pos.get(groupOf(id) ?? "") ?? (side.get(id) === "right" ? last : 0);
|
|
337
|
+
let cost = 0;
|
|
338
|
+
for (const f of input.flows) {
|
|
339
|
+
const span = Math.abs(at(f.from) - at(f.to));
|
|
340
|
+
cost += Math.max(0, span - 1) * 100 + span;
|
|
341
|
+
}
|
|
342
|
+
if (cost < best.cost) best = { cost, order, side };
|
|
343
|
+
}
|
|
344
|
+
const slots: Slot[] = [];
|
|
345
|
+
if ([...best.side.values()].includes("left")) slots.push({ side: "left" });
|
|
346
|
+
for (const b of best.order) slots.push({ boundary: b });
|
|
347
|
+
if ([...best.side.values()].includes("right")) slots.push({ side: "right" });
|
|
348
|
+
return { slots, side: best.side };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** A Gane and Sarson DFD, with each trust boundary drawn as a dashed region around its members. */
|
|
352
|
+
export function dfdDiagram(input: DfdInput): string {
|
|
353
|
+
const PAD = 28, GAPX = 150, GAPY = 30, NH = 54, BPAD = 22, BHEAD = 30, INNER = 90;
|
|
354
|
+
const labels = new LabelPlacer();
|
|
355
|
+
const widthOf = (n: DfdNodeIn) => textWidth(n.label, 150) + (n.kind === "store" ? 36 : 0);
|
|
356
|
+
const { slots, side } = dfdColumns(input);
|
|
357
|
+
const byId = new Map(input.nodes.map((n) => [n.id, n]));
|
|
358
|
+
// Inside a boundary, processes and the rest form two columns, the processes facing the side
|
|
359
|
+
// where more of their outside flows go, so a flow in from an external never crosses the stores.
|
|
360
|
+
const columns: { slot: Slot; cols: string[][] }[] = slots.map((slot, si) => {
|
|
361
|
+
if (!slot.boundary) return { slot, cols: [input.nodes.filter((n) => side.get(n.id) === slot.side).map((n) => n.id)] };
|
|
362
|
+
const members = input.nodes.filter((n) => n.boundary === slot.boundary!.id);
|
|
363
|
+
const procs = members.filter((n) => n.kind === "process").map((n) => n.id), rest = members.filter((n) => n.kind !== "process").map((n) => n.id);
|
|
364
|
+
const slotOf = (id: string) => { const n = byId.get(id); const i = slots.findIndex((s) => (n?.boundary && s.boundary?.id === n.boundary) || (!s.boundary && side.get(id) === s.side)); return i; };
|
|
365
|
+
let pull = 0;
|
|
366
|
+
for (const f of input.flows) for (const [a, b] of [[f.from, f.to], [f.to, f.from]] as const) if (procs.includes(a)) { const o = slotOf(b); if (o !== si && o >= 0) pull += Math.sign(o - si); }
|
|
367
|
+
const pair = pull > 0 ? [rest, procs] : [procs, rest];
|
|
368
|
+
return { slot, cols: pair.filter((c) => c.length) };
|
|
369
|
+
});
|
|
370
|
+
// Vertical order within every column follows connection, across all columns left to right.
|
|
371
|
+
const flat = columns.flatMap((c) => c.cols);
|
|
372
|
+
const ordered = orderByConnection(flat, input.flows.map((f) => [f.from, f.to]));
|
|
373
|
+
let k = 0;
|
|
374
|
+
for (const c of columns) c.cols = c.cols.map(() => ordered[k++]!);
|
|
375
|
+
|
|
376
|
+
const boxes = new Map<string, Box>();
|
|
377
|
+
const regions: string[] = [];
|
|
378
|
+
let x = PAD, H = 0;
|
|
379
|
+
for (const group of columns) {
|
|
380
|
+
const top = PAD + (group.slot.boundary ? BHEAD : 0);
|
|
381
|
+
const startX = x + (group.slot.boundary ? BPAD : 0);
|
|
382
|
+
let cx = startX, bottom = top;
|
|
383
|
+
for (const col of group.cols) {
|
|
384
|
+
const w = Math.max(...col.map((id) => widthOf(byId.get(id)!)));
|
|
385
|
+
let y = top + (group.slot.boundary ? 6 : 0);
|
|
386
|
+
for (const id of col) { const nw = widthOf(byId.get(id)!); boxes.set(id, { id, x: cx + (w - nw) / 2, y, w: nw, h: NH }); y += NH + GAPY; }
|
|
387
|
+
bottom = Math.max(bottom, y - GAPY);
|
|
388
|
+
cx += w + INNER;
|
|
389
|
+
}
|
|
390
|
+
const innerW = cx - INNER - startX;
|
|
391
|
+
if (group.slot.boundary) {
|
|
392
|
+
const b = group.slot.boundary, bw = innerW + BPAD * 2, bh = bottom - PAD + BPAD;
|
|
393
|
+
regions.push(boundary({ id: b.id, x, y: PAD, w: bw, h: bh }, b.label, b.title ?? `Trust boundary: ${b.label}`));
|
|
394
|
+
x += bw + GAPX; H = Math.max(H, PAD + bh);
|
|
395
|
+
} else { x += innerW + GAPX; H = Math.max(H, bottom); }
|
|
396
|
+
}
|
|
397
|
+
const W = x - GAPX + PAD;
|
|
398
|
+
labels.avoid(...boxes.values());
|
|
399
|
+
const counter = { process: 0, store: 0, external: 0 };
|
|
400
|
+
const nodes = input.nodes.filter((n) => boxes.has(n.id)).map((n) => {
|
|
401
|
+
const b = boxes.get(n.id)!, i = ++counter[n.kind];
|
|
402
|
+
const shape = n.kind === "process" ? ganeSarson.process(b, n.label, `P${i}`) : n.kind === "store" ? ganeSarson.store(b, n.label, `D${i}`) : ganeSarson.external(b, n.label);
|
|
403
|
+
return wrap({ cls: `dg-node dg-dfd-${n.kind}${n.id === input.selected ? " is-selected" : ""}`, node: n.id, href: n.href, title: n.title ?? `${n.label} (${n.kind})` }, shape);
|
|
404
|
+
}).join("");
|
|
405
|
+
// Two flows between the same pair are spread apart so their labels do not sit on each other.
|
|
406
|
+
const pairCount = new Map<string, number>();
|
|
407
|
+
const flows = input.flows.filter((f) => boxes.has(f.from) && boxes.has(f.to)).map((f) => {
|
|
408
|
+
const a = boxes.get(f.from)!, b = boxes.get(f.to)!;
|
|
409
|
+
const key = [f.from, f.to].sort().join("|");
|
|
410
|
+
const n = pairCount.get(key) ?? 0; pairCount.set(key, n + 1);
|
|
411
|
+
const off = n * 16;
|
|
412
|
+
const [ax, ay] = centre(a), [bx, by] = centre(b);
|
|
413
|
+
const [x1, y1] = edgePoint(a, bx, by + off), [x2, y2] = edgePoint(b, ax, ay + off);
|
|
414
|
+
labels.place((x1 + x2) / 2, (y1 + y2) / 2 + off, f.label ?? f.id);
|
|
415
|
+
const cls = `dg-edge${f.emphasis ? " dg-emphasis" : ""}${f.id === input.selected ? " is-selected" : ""}`;
|
|
416
|
+
return wrap({ cls, edge: f.id, ends: [f.from, f.to], href: f.href, title: f.title ?? f.label ?? f.id }, arrow([x1, y1 + off], [x2, y2 + off]));
|
|
417
|
+
}).join("");
|
|
418
|
+
return diagramFrame({ kind: "dfd", width: W, height: H + PAD, label: input.label ?? `Data flow diagram with ${input.flows.length} flows` },
|
|
419
|
+
`<g class="dg-regions">${regions.join("")}</g><g class="dg-edges">${flows}</g><g class="dg-nodes">${nodes}</g>${labels.svg()}`);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ── renderer: layered box diagrams (C4 and flowcharts) ─────────────────────────────────────────
|
|
423
|
+
|
|
424
|
+
export type LayeredKind =
|
|
425
|
+
| "person" | "system" | "container" | "external"
|
|
426
|
+
| "start" | "action" | "decision" | "flow-system" | "end";
|
|
427
|
+
export interface LayeredNodeIn { id: string; kind: LayeredKind; label: string; sub?: string; href?: string; title?: string; selected?: boolean }
|
|
428
|
+
export interface LayeredEdgeIn { from: string; to: string; label?: string; id?: string; href?: string; title?: string }
|
|
429
|
+
export interface LayeredInput {
|
|
430
|
+
kind: string; nodes: LayeredNodeIn[]; edges: LayeredEdgeIn[]; label: string;
|
|
431
|
+
/** A dashed scope drawn around some nodes, such as the system boundary on a C4 container view. */
|
|
432
|
+
group?: { label: string; members: string[] };
|
|
433
|
+
/** The narrowest a node may be. */
|
|
434
|
+
minWidth?: number;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const SHAPES: Record<LayeredKind, (b: Box, label: string, second?: string) => string> = {
|
|
438
|
+
person: c4.person, system: c4.system, container: c4.container, external: c4.external,
|
|
439
|
+
start: flowchart.start, action: flowchart.action, decision: flowchart.decision, "flow-system": flowchart.system, end: flowchart.end,
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
/** A top-down layered diagram: rows by longest path, order within a row by connection. */
|
|
443
|
+
export function layeredDiagram(input: LayeredInput): string {
|
|
444
|
+
const PAD = 30, GAPX = 60, GAPY = 96;
|
|
445
|
+
const labels = new LabelPlacer();
|
|
446
|
+
const byId = new Map(input.nodes.map((n) => [n.id, n]));
|
|
447
|
+
const sizeOf = (n: LayeredNodeIn) => {
|
|
448
|
+
const w = Math.max(textWidth(n.label, input.minWidth ?? 180), n.sub ? textWidth(n.sub) - 10 : 0);
|
|
449
|
+
if (n.kind === "decision") return { w: w + 40, h: 76 };
|
|
450
|
+
if (n.kind === "person") return { w, h: 84 };
|
|
451
|
+
return { w, h: n.sub ? 62 : 48 };
|
|
452
|
+
};
|
|
453
|
+
const pairs: [string, string][] = input.edges.map((x) => [x.from, x.to]);
|
|
454
|
+
const rows = orderByConnection(layers(input.nodes.map((n) => n.id), pairs), pairs);
|
|
455
|
+
const rowW = rows.map((r) => r.reduce((s, id) => s + sizeOf(byId.get(id)!).w, 0) + (r.length - 1) * GAPX);
|
|
456
|
+
const W = Math.max(...rowW) + PAD * 2 + (input.group ? 40 : 0);
|
|
457
|
+
const boxes = new Map<string, Box>();
|
|
458
|
+
let y = PAD + (input.group ? 30 : 0);
|
|
459
|
+
rows.forEach((r, i) => {
|
|
460
|
+
let x = (W - rowW[i]!) / 2;
|
|
461
|
+
const h = Math.max(...r.map((id) => sizeOf(byId.get(id)!).h));
|
|
462
|
+
for (const id of r) { const s = sizeOf(byId.get(id)!); boxes.set(id, { id, x, y: y + (h - s.h) / 2, w: s.w, h: s.h }); x += s.w + GAPX; }
|
|
463
|
+
y += h + GAPY;
|
|
464
|
+
});
|
|
465
|
+
const H = y - GAPY + PAD;
|
|
466
|
+
let scope = "";
|
|
467
|
+
if (input.group) {
|
|
468
|
+
const mem = input.group.members.map((id) => boxes.get(id)).filter((b): b is Box => !!b);
|
|
469
|
+
if (mem.length) {
|
|
470
|
+
const x0 = Math.min(...mem.map((b) => b.x)) - 24, y0 = Math.min(...mem.map((b) => b.y)) - 34;
|
|
471
|
+
const x1 = Math.max(...mem.map((b) => b.x + b.w)) + 24, y1 = Math.max(...mem.map((b) => b.y + b.h)) + 20;
|
|
472
|
+
scope = boundary({ id: "scope", x: x0, y: y0, w: x1 - x0, h: y1 - y0 }, input.group.label);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
labels.avoid(...boxes.values());
|
|
476
|
+
const edgeEls = input.edges.filter((x) => boxes.has(x.from) && boxes.has(x.to)).map((x) => {
|
|
477
|
+
const a = boxes.get(x.from)!, b = boxes.get(x.to)!;
|
|
478
|
+
const [ax, ay] = centre(a), [bx, by] = centre(b);
|
|
479
|
+
const sa = byId.get(x.from)!.kind === "decision" ? "diamond" : "rect", sb = byId.get(x.to)!.kind === "decision" ? "diamond" : "rect";
|
|
480
|
+
const p1 = edgePoint(a, bx, by, sa), p2 = edgePoint(b, ax, ay, sb);
|
|
481
|
+
labels.place((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2, x.label ?? "");
|
|
482
|
+
const id = x.id ?? `${x.from}-${x.to}`;
|
|
483
|
+
return wrap({ cls: "dg-edge", edge: id, ends: [x.from, x.to], href: x.href, title: x.title ?? x.label ?? id }, arrow(p1, p2));
|
|
484
|
+
}).join("");
|
|
485
|
+
const nodeEls = input.nodes.map((n) => {
|
|
486
|
+
const b = boxes.get(n.id)!;
|
|
487
|
+
return wrap({ cls: `dg-node dg-k-${n.kind}${n.selected ? " is-selected" : ""}`, node: n.id, href: n.href, title: n.title ?? n.label }, SHAPES[n.kind](b, n.label, n.sub));
|
|
488
|
+
}).join("");
|
|
489
|
+
return diagramFrame({ kind: input.kind, width: W, height: H, label: input.label }, `${scope}<g class="dg-edges">${edgeEls}</g><g class="dg-nodes">${nodeEls}</g>${labels.svg()}`);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// ── behaviour: pan, zoom and hover tracing ─────────────────────────────────────────────────────
|
|
493
|
+
|
|
494
|
+
/** The browser half, as a script tag a page includes once. It wires every .diagram on the page. */
|
|
495
|
+
export const DIAGRAM_SCRIPT = `<script>
|
|
496
|
+
(() => {
|
|
497
|
+
for (const fig of document.querySelectorAll(".diagram")) {
|
|
498
|
+
const svg = fig.querySelector("svg.diagram__svg"); if (!svg || svg.dataset.wired) continue;
|
|
499
|
+
svg.dataset.wired = "1";
|
|
500
|
+
const W = +svg.dataset.w, H = +svg.dataset.h;
|
|
501
|
+
let vb = [0, 0, W, H];
|
|
502
|
+
const set = () => svg.setAttribute("viewBox", vb.map((n) => n.toFixed(1)).join(" "));
|
|
503
|
+
const zoom = (k, cx = vb[0] + vb[2] / 2, cy = vb[1] + vb[3] / 2) => {
|
|
504
|
+
const w = Math.min(W * 4, Math.max(W / 8, vb[2] * k)), h = w * (vb[3] / vb[2]);
|
|
505
|
+
vb = [cx - (cx - vb[0]) * (w / vb[2]), cy - (cy - vb[1]) * (h / vb[3]), w, h]; set();
|
|
506
|
+
};
|
|
507
|
+
const pt = (ev) => { const r = svg.getBoundingClientRect(); return [vb[0] + (ev.clientX - r.left) / r.width * vb[2], vb[1] + (ev.clientY - r.top) / r.height * vb[3]]; };
|
|
508
|
+
fig.querySelectorAll("[data-zoom]").forEach((b) => b.addEventListener("click", () => {
|
|
509
|
+
const z = b.dataset.zoom; if (z === "reset") { vb = [0, 0, W, H]; set(); } else zoom(z === "in" ? 0.8 : 1.25);
|
|
510
|
+
}));
|
|
511
|
+
svg.addEventListener("wheel", (ev) => { ev.preventDefault(); const [x, y] = pt(ev); zoom(ev.deltaY < 0 ? 0.88 : 1.14, x, y); }, { passive: false });
|
|
512
|
+
let drag = null, moved = false;
|
|
513
|
+
svg.addEventListener("pointerdown", (ev) => { drag = [ev.clientX, ev.clientY, vb[0], vb[1]]; moved = false; });
|
|
514
|
+
addEventListener("pointermove", (ev) => {
|
|
515
|
+
if (!drag) return;
|
|
516
|
+
const r = svg.getBoundingClientRect(), dx = ev.clientX - drag[0], dy = ev.clientY - drag[1];
|
|
517
|
+
if (Math.abs(dx) + Math.abs(dy) > 4) { moved = true; svg.classList.add("is-panning"); }
|
|
518
|
+
if (moved) { vb[0] = drag[2] - dx / r.width * vb[2]; vb[1] = drag[3] - dy / r.height * vb[3]; set(); }
|
|
519
|
+
});
|
|
520
|
+
addEventListener("pointerup", () => { drag = null; svg.classList.remove("is-panning"); });
|
|
521
|
+
svg.addEventListener("click", (ev) => { if (moved) { ev.preventDefault(); ev.stopPropagation(); moved = false; } }, true);
|
|
522
|
+
// Hover a node to trace everything it touches; hover an edge to trace its two ends.
|
|
523
|
+
const edges = [...svg.querySelectorAll("[data-edge]")];
|
|
524
|
+
const ends = (x) => x.dataset.ends.split(" ");
|
|
525
|
+
const trace = (nodeIds, lit) => {
|
|
526
|
+
svg.classList.add("is-tracing");
|
|
527
|
+
svg.querySelectorAll("[data-node]").forEach((n) => n.classList.toggle("is-lit", nodeIds.has(n.dataset.node)));
|
|
528
|
+
edges.forEach((x) => x.classList.toggle("is-lit", lit.includes(x)));
|
|
529
|
+
};
|
|
530
|
+
const clear = () => { svg.classList.remove("is-tracing"); svg.querySelectorAll(".is-lit").forEach((n) => n.classList.remove("is-lit")); };
|
|
531
|
+
svg.querySelectorAll(".dg-nodes [data-node]").forEach((n) => {
|
|
532
|
+
n.addEventListener("mouseenter", () => {
|
|
533
|
+
const id = n.dataset.node, touching = edges.filter((x) => ends(x).includes(id));
|
|
534
|
+
trace(new Set([id, ...touching.flatMap(ends)]), touching);
|
|
535
|
+
});
|
|
536
|
+
n.addEventListener("mouseleave", clear);
|
|
537
|
+
});
|
|
538
|
+
edges.forEach((x) => { x.addEventListener("mouseenter", () => trace(new Set(ends(x)), [x])); x.addEventListener("mouseleave", clear); });
|
|
539
|
+
}
|
|
540
|
+
})();
|
|
541
|
+
</script>`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tjakoen/grain",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.37",
|
|
4
4
|
"description": "GRAIN — an AI-interaction design system where every surface is operable by both a human and an AI through one shared vocabulary.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|