@grethel-labs/excaliplant 0.1.0

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.
@@ -0,0 +1,160 @@
1
+ // Container/box sizing.
2
+ //
3
+ // Boxes size themselves from their text content and from the number of
4
+ // connections that need to attach. Subplanes and planes then size
5
+ // themselves from their children AND from the number of internal-routing
6
+ // lanes the lane allocator (step2b) requested on each side. All children
7
+ // of a container share the same content width so titles align.
8
+
9
+ import { Box, Plane, Subplane } from "../model/diagram.mjs";
10
+ import { FONT, measureLine, measureWrapped } from "../style/text.mjs";
11
+
12
+ export const SIZING = {
13
+ boxPaddingX: 14,
14
+ boxPaddingY: 12,
15
+ boxTitleGap: 4,
16
+ boxMinHeight: 56,
17
+ boxConnectionSlot: 18, // height per connection on a side
18
+
19
+ subplanePaddingX: 16,
20
+ subplanePaddingY: 18,
21
+ subplaneChildGap: 16,
22
+ subplaneTitleHeight: 26,
23
+
24
+ planePaddingX: 22,
25
+ planePaddingY: 28,
26
+ planeChildGap: 22,
27
+ planeTitleHeight: 38,
28
+
29
+ // Pixels per internal-routing lane on each side of a container.
30
+ laneWidth: 18,
31
+
32
+ // Content width is computed from the widest box title/description so
33
+ // that every box label fits without truncation. The constants below
34
+ // clamp the result.
35
+ contentMinWidth: 220,
36
+ contentMaxWidth: 360,
37
+ };
38
+
39
+ export function sizeDiagram(diagram) {
40
+ for (const plane of diagram.planes) sizePlane(plane);
41
+ }
42
+
43
+ function sizePlane(plane) {
44
+ const planeLanes = laneSpace(plane);
45
+ const baseInner = computePlaneContentWidth(plane);
46
+ const innerWidth = baseInner; // every child gets exactly this width
47
+ for (const child of plane.children) {
48
+ if (child instanceof Subplane) sizeSubplane(child, innerWidth);
49
+ else sizeBox(child, innerWidth);
50
+ }
51
+ let h = SIZING.planePaddingY + SIZING.planeTitleHeight;
52
+ for (let i = 0; i < plane.children.length; i++) {
53
+ if (i > 0) h += SIZING.planeChildGap;
54
+ h += plane.children[i].height;
55
+ }
56
+ h += SIZING.planePaddingY;
57
+ plane.width = innerWidth + SIZING.planePaddingX * 2 + planeLanes;
58
+ plane.height = Math.max(120, h);
59
+ }
60
+
61
+ function sizeSubplane(sub, planeContentWidth) {
62
+ const subLanes = laneSpace(sub);
63
+ // Subplane occupies the full plane content width (so titles align).
64
+ sub.width = planeContentWidth;
65
+ // Boxes inside the subplane get the remaining space minus padding and
66
+ // the lane allowance.
67
+ const innerBoxWidth = Math.max(40,
68
+ planeContentWidth - SIZING.subplanePaddingX * 2 - subLanes);
69
+ for (const box of sub.boxes) sizeBox(box, innerBoxWidth);
70
+ let h = SIZING.subplanePaddingY + SIZING.subplaneTitleHeight;
71
+ for (let i = 0; i < sub.boxes.length; i++) {
72
+ if (i > 0) h += SIZING.subplaneChildGap;
73
+ h += sub.boxes[i].height;
74
+ }
75
+ h += SIZING.subplanePaddingY;
76
+ sub.height = Math.max(80, h);
77
+ }
78
+
79
+ function sizeBox(box, width) {
80
+ box.width = width;
81
+ const innerWidth = Math.max(20, width - SIZING.boxPaddingX * 2);
82
+ // Title can be multi-line via "\n".
83
+ const titleLines = String(box.title || "").split("\n");
84
+ const titleHeight = titleLines.length * FONT.sizeTitle * FONT.lineHeight;
85
+ const description = box.description ? measureWrapped(box.description, FONT.sizeDescription, innerWidth) : { height: 0 };
86
+ let textHeight = SIZING.boxPaddingY + titleHeight;
87
+ if (box.stereotype) textHeight += FONT.sizeDescription * FONT.lineHeight;
88
+ if (description.height) textHeight += SIZING.boxTitleGap + description.height;
89
+ textHeight += SIZING.boxPaddingY;
90
+
91
+ const connectionsHeight = box.connections.length * SIZING.boxConnectionSlot + SIZING.boxPaddingY * 2;
92
+
93
+ // Shape-specific minimum heights.
94
+ let shapeMin = SIZING.boxMinHeight;
95
+ switch (box.shape) {
96
+ case "actor":
97
+ // Stickman ~ headD + body + legs + label
98
+ shapeMin = Math.max(shapeMin, 110 + titleHeight);
99
+ break;
100
+ case "interface":
101
+ shapeMin = Math.max(shapeMin, 70 + titleHeight);
102
+ break;
103
+ case "usecase":
104
+ shapeMin = Math.max(shapeMin, 70);
105
+ break;
106
+ case "database":
107
+ shapeMin = Math.max(shapeMin, 90);
108
+ break;
109
+ case "cloud":
110
+ shapeMin = Math.max(shapeMin, 80);
111
+ break;
112
+ case "node":
113
+ // 3-D shadow uses extra ~8px on top.
114
+ shapeMin = Math.max(shapeMin, textHeight + 8);
115
+ break;
116
+ case "class":
117
+ if (box.members && box.members.length) {
118
+ shapeMin = Math.max(shapeMin,
119
+ textHeight + box.members.length * FONT.sizeDescription * FONT.lineHeight + 12);
120
+ }
121
+ break;
122
+ case "note":
123
+ shapeMin = Math.max(shapeMin, 50);
124
+ break;
125
+ }
126
+
127
+ box.height = Math.max(shapeMin, textHeight, connectionsHeight);
128
+ }
129
+
130
+ function computePlaneContentWidth(plane) {
131
+ let widest = SIZING.contentMinWidth;
132
+ for (const box of plane.allBoxes) {
133
+ const titleSize = measureLine(box.title, FONT.sizeTitle);
134
+ widest = Math.max(widest, titleSize.width + SIZING.boxPaddingX * 2);
135
+ }
136
+ // Subplanes need extra room for their padding and their internal lanes.
137
+ for (const sub of plane.subplanes) {
138
+ const need = widest + SIZING.subplanePaddingX * 2 + laneSpace(sub);
139
+ widest = Math.max(widest, need);
140
+ }
141
+ // Plane title also wants to fit (excluding plane-level lanes — those
142
+ // sit outside the title area at the children row).
143
+ const planeTitle = measureLine(plane.title, FONT.sizePlaneTitle);
144
+ widest = Math.max(widest, planeTitle.width + SIZING.planePaddingX * 2);
145
+ // Clamp to contentMaxWidth, but never below what we just computed for
146
+ // box / subplane needs (those constraints are hard).
147
+ const hardMin = widest;
148
+ const clamped = Math.min(SIZING.contentMaxWidth, Math.max(SIZING.contentMinWidth, Math.ceil(widest)));
149
+ return Math.max(clamped, hardMin);
150
+ }
151
+
152
+ function laneSpace(container) {
153
+ // ELK-based layout does not use the legacy lane allocator. Boxes /
154
+ // subplanes are sized purely from their content; ELK injects port
155
+ // spacing on the fly via its own port-side options.
156
+ return 0;
157
+ }
158
+
159
+ // Re-export classes for test convenience.
160
+ export { Box, Plane, Subplane };
@@ -0,0 +1,207 @@
1
+ /**
2
+ * @module model
3
+ *
4
+ * Input-agnostic diagram model. Two top-level kinds:
5
+ *
6
+ * - **`Diagram`** — component / deployment / use-case style
7
+ * (planes, subplanes, boxes, connections).
8
+ * - **`SequenceDiagram`** — lifelines + messages + notes.
9
+ *
10
+ * Layout and renderer dispatch on the model class. Anything that
11
+ * can be expressed as one of these two shapes flows through the
12
+ * pipeline; the parser is just one possible source. Callers can
13
+ * also build a `Diagram` programmatically and feed it to
14
+ * `renderDiagram()`.
15
+ */
16
+
17
+ // Generic, input-agnostic diagram model.
18
+ //
19
+ // Two top-level model kinds are supported:
20
+ // - Diagram → component / deployment / use-case style
21
+ // (planes, subplanes, boxes, connections)
22
+ // - SequenceDiagram → lifelines + messages
23
+ //
24
+ // Layout and renderer dispatch on the model class.
25
+
26
+ export const SIDES = ["top", "right", "bottom", "left"];
27
+
28
+ // Logical box shapes the parser may attach to a Box. The renderer turns
29
+ // them into the corresponding Excalidraw primitives.
30
+ export const SHAPES = [
31
+ "rectangle", "component",
32
+ "actor", "usecase", "database", "node", "cloud",
33
+ "interface", "entity", "class", "note",
34
+ ];
35
+
36
+ export class Box {
37
+ constructor({
38
+ id, title, description = "",
39
+ shape = "rectangle", stereotype = "", members = [],
40
+ }) {
41
+ this.id = id;
42
+ this.title = title;
43
+ this.description = description;
44
+ this.shape = shape;
45
+ this.stereotype = stereotype; // <<service>>, <<entity>>, …
46
+ this.members = members; // class members (string[])
47
+ this.parent = null; // Plane or Subplane
48
+ this.connections = []; // Connection[] referencing this box on either end
49
+ this.ports = { top: [], right: [], bottom: [], left: [] };
50
+ this.x = 0; this.y = 0;
51
+ this.width = 0; this.height = 0;
52
+ }
53
+ get plane() {
54
+ return this.parent instanceof Plane ? this.parent : this.parent?.parent || null;
55
+ }
56
+ centre() { return { x: this.x + this.width / 2, y: this.y + this.height / 2 }; }
57
+ }
58
+
59
+ export class Subplane {
60
+ constructor({ id, title, kind = "subplane" }) {
61
+ this.id = id;
62
+ this.title = title;
63
+ this.kind = kind; // subplane | frame | folder | rectangle | together
64
+ this.parent = null;
65
+ this.boxes = [];
66
+ this.x = 0; this.y = 0;
67
+ this.width = 0; this.height = 0;
68
+ }
69
+ addBox(box) { box.parent = this; this.boxes.push(box); return box; }
70
+ }
71
+
72
+ export class Plane {
73
+ constructor({ id, title, color = null, kind = "package" }) {
74
+ this.id = id;
75
+ this.title = title;
76
+ this.kind = kind; // package | frame | folder | rectangle | node | together
77
+ this.color = color;
78
+ this.children = [];
79
+ this.x = 0; this.y = 0;
80
+ this.width = 0; this.height = 0;
81
+ this.gridRow = 0; this.gridCol = 0;
82
+ }
83
+ addSubplane(subplane) { subplane.parent = this; this.children.push(subplane); return subplane; }
84
+ addBox(box) { box.parent = this; this.children.push(box); return box; }
85
+ get subplanes() { return this.children.filter((c) => c instanceof Subplane); }
86
+ get directBoxes() { return this.children.filter((c) => c instanceof Box); }
87
+ get allBoxes() {
88
+ const out = [];
89
+ for (const c of this.children) {
90
+ if (c instanceof Box) out.push(c);
91
+ else if (c instanceof Subplane) out.push(...c.boxes);
92
+ }
93
+ return out;
94
+ }
95
+ }
96
+
97
+ // Arrowhead values map directly onto Excalidraw's start/end arrowhead
98
+ // strings: arrow | triangle | triangle_outline | diamond |
99
+ // diamond_outline | dot | bar | circle | circle_outline | null.
100
+ export class Connection {
101
+ constructor({
102
+ id, from, to, label = "", kind = "default", dashed = false,
103
+ startArrowhead = null, endArrowhead = "arrow",
104
+ directionHint = null,
105
+ }) {
106
+ this.id = id;
107
+ this.from = from;
108
+ this.to = to;
109
+ this.label = label;
110
+ this.kind = kind; // default | inheritance | composition | aggregation | realization | dependency
111
+ this.dashed = dashed;
112
+ this.startArrowhead = startArrowhead;
113
+ this.endArrowhead = endArrowhead;
114
+ this.directionHint = directionHint; // up|down|left|right|null
115
+ this.fromSide = null;
116
+ this.toSide = null;
117
+ this.path = [];
118
+ }
119
+ get internal() {
120
+ return this.from.plane && this.from.plane === this.to.plane;
121
+ }
122
+ }
123
+
124
+ export class Diagram {
125
+ constructor() {
126
+ this.title = "";
127
+ this.planes = [];
128
+ this.connections = [];
129
+ }
130
+ addPlane(plane) { this.planes.push(plane); return plane; }
131
+ addConnection(connection) {
132
+ this.connections.push(connection);
133
+ connection.from.connections.push(connection);
134
+ connection.to.connections.push(connection);
135
+ return connection;
136
+ }
137
+ allBoxes() { return this.planes.flatMap((p) => p.allBoxes); }
138
+ boxById(id) {
139
+ for (const p of this.planes) for (const b of p.allBoxes) if (b.id === id) return b;
140
+ return null;
141
+ }
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Sequence diagrams
146
+ // ---------------------------------------------------------------------------
147
+
148
+ export class Participant {
149
+ constructor({ id, title, shape = "participant", stereotype = "" }) {
150
+ this.id = id;
151
+ this.title = title;
152
+ this.shape = shape; // participant | actor | boundary | control | entity | database | collections | queue
153
+ this.stereotype = stereotype;
154
+ this.x = 0; // centre x of the head
155
+ this.headY = 0;
156
+ this.headWidth = 0;
157
+ this.headHeight = 0;
158
+ this.lifelineTop = 0;
159
+ this.lifelineBottom = 0;
160
+ }
161
+ }
162
+
163
+ export class Message {
164
+ constructor({
165
+ id, from, to, label = "",
166
+ dashed = false, kind = "sync",
167
+ startArrowhead = null, endArrowhead = "arrow",
168
+ }) {
169
+ this.id = id;
170
+ this.from = from;
171
+ this.to = to;
172
+ this.label = label;
173
+ this.dashed = dashed;
174
+ this.kind = kind; // sync | async | reply | self
175
+ this.startArrowhead = startArrowhead;
176
+ this.endArrowhead = endArrowhead;
177
+ this.y = 0;
178
+ }
179
+ get isSelf() { return this.from === this.to; }
180
+ }
181
+
182
+ export class SequenceNote {
183
+ constructor({ id, text, side, target, target2 = null }) {
184
+ this.id = id;
185
+ this.text = text;
186
+ this.side = side; // left | right | over
187
+ this.target = target; // Participant
188
+ this.target2 = target2; // Participant or null (for "over A,B")
189
+ this.x = 0; this.y = 0;
190
+ this.width = 0; this.height = 0;
191
+ }
192
+ }
193
+
194
+ export class SequenceDiagram {
195
+ constructor() {
196
+ this.title = "";
197
+ this.participants = [];
198
+ this.messages = [];
199
+ this.notes = [];
200
+ this.width = 0;
201
+ this.height = 0;
202
+ }
203
+ addParticipant(p) { this.participants.push(p); return p; }
204
+ addMessage(m) { this.messages.push(m); return m; }
205
+ addNote(n) { this.notes.push(n); return n; }
206
+ participantById(id) { return this.participants.find((p) => p.id === id) || null; }
207
+ }
@@ -0,0 +1,129 @@
1
+ // Mutable parsing context for component-style diagrams.
2
+ //
3
+ // All component plugins receive an instance of this and use its
4
+ // helpers; this keeps plugins free of cross-cutting state management.
5
+
6
+ import { Box, Connection, Diagram, Plane, Subplane } from "../model/diagram.mjs";
7
+ import { planeColor, subplaneColor } from "../style/colors.mjs";
8
+
9
+ export function createComponentContext() {
10
+ const diagram = new Diagram();
11
+ /** @type {Array<{kind:'plane'|'subplane', plane?:Plane, subplane?:Subplane, id:string}>} */
12
+ const stack = [];
13
+ const planes = new Map();
14
+ const subplanes = new Map();
15
+ const boxes = new Map();
16
+ const pendingConnections = [];
17
+ const pendingNotes = [];
18
+ let floatingPlane = null;
19
+
20
+ const ensureFloatingPlane = () => {
21
+ if (floatingPlane) return floatingPlane;
22
+ floatingPlane = new Plane({
23
+ id: "__floating__",
24
+ title: "",
25
+ color: planeColor("__floating__"),
26
+ kind: "package",
27
+ });
28
+ diagram.addPlane(floatingPlane);
29
+ planes.set("__floating__", floatingPlane);
30
+ return floatingPlane;
31
+ };
32
+
33
+ const findPlane = () => {
34
+ for (let i = stack.length - 1; i >= 0; i--) {
35
+ if (stack[i].kind === "plane") return stack[i].plane;
36
+ }
37
+ return null;
38
+ };
39
+
40
+ const ctx = {
41
+ get result() { return diagram; },
42
+ diagram,
43
+ boxes,
44
+
45
+ setTitle(t) { diagram.title = t; },
46
+
47
+ openContainer({ id, title, kind }) {
48
+ if (stack.length === 0) {
49
+ const plane = new Plane({ id, title, color: planeColor(id), kind });
50
+ diagram.addPlane(plane);
51
+ planes.set(id, plane);
52
+ stack.push({ kind: "plane", plane, id });
53
+ } else {
54
+ const parentPlane = findPlane();
55
+ const sub = new Subplane({ id, title, kind });
56
+ if (parentPlane?.color) sub.color = subplaneColor(parentPlane.color);
57
+ parentPlane.addSubplane(sub);
58
+ subplanes.set(id, sub);
59
+ stack.push({ kind: "subplane", subplane: sub, id });
60
+ }
61
+ },
62
+
63
+ closeContainer() { stack.pop(); },
64
+
65
+ addBox({ id, title, description = "", shape = "rectangle", stereotype = "", members = [] }) {
66
+ if (boxes.has(id)) return boxes.get(id);
67
+ const box = new Box({ id, title, description, shape, stereotype, members });
68
+ boxes.set(id, box);
69
+ if (stack.length === 0) {
70
+ ensureFloatingPlane().addBox(box);
71
+ return box;
72
+ }
73
+ const top = stack[stack.length - 1];
74
+ if (top.kind === "subplane") top.subplane.addBox(box);
75
+ else top.plane.addBox(box);
76
+ return box;
77
+ },
78
+
79
+ queueConnection(spec) { pendingConnections.push(spec); },
80
+ queueNote(spec) { pendingNotes.push(spec); },
81
+
82
+ finalize() {
83
+ // Resolve connections.
84
+ for (const c of pendingConnections) {
85
+ const fromBox = boxes.get(c.fromId);
86
+ const toBox = boxes.get(c.toId);
87
+ if (!fromBox || !toBox || fromBox === toBox) continue;
88
+ const [from, to] = c.reversed ? [toBox, fromBox] : [fromBox, toBox];
89
+ const [startAh, endAh] = c.reversed
90
+ ? [c.endArrowhead, c.startArrowhead]
91
+ : [c.startArrowhead, c.endArrowhead];
92
+ diagram.addConnection(new Connection({
93
+ id: `${c.fromId}->${c.toId}#${diagram.connections.length}`,
94
+ from, to,
95
+ label: c.label,
96
+ kind: c.kind,
97
+ dashed: c.dashed,
98
+ startArrowhead: startAh,
99
+ endArrowhead: endAh,
100
+ directionHint: c.directionHint,
101
+ }));
102
+ }
103
+ // Resolve notes.
104
+ for (const n of pendingNotes) {
105
+ const target = boxes.get(n.targetId);
106
+ if (!target) continue;
107
+ const noteBox = new Box({
108
+ id: n.id, title: "note", description: n.text,
109
+ shape: "note",
110
+ });
111
+ boxes.set(n.id, noteBox);
112
+ const container = target.parent;
113
+ if (container instanceof Plane) container.addBox(noteBox);
114
+ else if (container instanceof Subplane) container.addBox(noteBox);
115
+ else continue;
116
+ diagram.addConnection(new Connection({
117
+ id: `${n.id}~${target.id}#${diagram.connections.length}`,
118
+ from: noteBox, to: target,
119
+ label: "",
120
+ kind: "note",
121
+ dashed: true,
122
+ startArrowhead: null,
123
+ endArrowhead: null,
124
+ }));
125
+ }
126
+ },
127
+ };
128
+ return ctx;
129
+ }
@@ -0,0 +1,87 @@
1
+ // Tiny line-driven parsing engine.
2
+ //
3
+ // The engine walks PlantUML lines and offers each line to a list of
4
+ // plugins in declared order. Plugins decide whether to consume the line.
5
+
6
+ /**
7
+ * @module parser/engine
8
+ *
9
+ * A ~50-line line-walker. The engine itself knows nothing about
10
+ * PlantUML syntax; that lives entirely in plugins. Block plugins
11
+ * (multi-line notes, class bodies) take exclusive ownership of
12
+ * subsequent lines until they release.
13
+ *
14
+ * Plugin contract:
15
+ * ```js
16
+ * {
17
+ * name,
18
+ * tryStart?(line, ctx): null | { onLine, tryEnd },
19
+ * tryLine?(line, ctx): boolean,
20
+ * }
21
+ * ```
22
+ */
23
+ //
24
+ // Plugin contract:
25
+ //
26
+ // {
27
+ // name: string,
28
+ // // OPTIONAL — declare a multi-line block. If `tryStart` returns a
29
+ // // block handler, the engine routes subsequent raw-trimmed lines
30
+ // // into the handler until `block.tryEnd(line)` returns true.
31
+ // // Inside a block no other plugin sees the line.
32
+ // tryStart?(line, ctx): null | {
33
+ // onLine(line, ctx): void,
34
+ // tryEnd(line, ctx): boolean,
35
+ // },
36
+ // // OPTIONAL — single-line handler. Return true if consumed.
37
+ // tryLine?(line, ctx): boolean,
38
+ // }
39
+ //
40
+ // Adding support for a new PlantUML construct = drop a new plugin file
41
+ // and add it to the registry; no engine change required.
42
+
43
+ import { stripComment, ALWAYS_SKIP } from "./utils.mjs";
44
+
45
+ /**
46
+ * Walk `lines` once and dispatch each line to a list of plugins.
47
+ *
48
+ * @param {object} args
49
+ * @param {string[]} args.lines Raw PlantUML lines (already split).
50
+ * @param {Array<object>} args.plugins
51
+ * Plugins in priority order. Each plugin must implement `tryStart`
52
+ * (block plugins) or `tryLine` (line plugins) — see the module-level
53
+ * doc block for the plugin contract.
54
+ * @param {object} args.ctx Mutable context object. Plugins
55
+ * attach state here; the engine never
56
+ * reads it directly.
57
+ * @returns {object} The same `ctx` object the caller
58
+ * passed in (for chaining).
59
+ */
60
+ export function runEngine({ lines, plugins, ctx }) {
61
+ let block = null;
62
+ for (const raw of lines) {
63
+ const line = stripComment(raw).trim();
64
+
65
+ if (block) {
66
+ if (block.tryEnd(line, ctx)) { block = null; continue; }
67
+ block.onLine(line, ctx);
68
+ continue;
69
+ }
70
+
71
+ if (!line) continue;
72
+ if (ALWAYS_SKIP.some((re) => re.test(line))) continue;
73
+
74
+ let consumed = false;
75
+ for (const p of plugins) {
76
+ if (p.tryStart) {
77
+ const b = p.tryStart(line, ctx);
78
+ if (b) { block = b; consumed = true; break; }
79
+ }
80
+ if (p.tryLine && p.tryLine(line, ctx)) { consumed = true; break; }
81
+ }
82
+ // Unknown lines are silently ignored — same tolerance as before.
83
+ void consumed;
84
+ }
85
+ ctx.finalize?.();
86
+ return ctx.result;
87
+ }