@momoi-labs/kiso-react 0.24.0 → 0.26.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,1182 @@
1
+ /* Edge geometry for Diagram: routes as polylines, then crossings, paths and
2
+ labels. Pure functions over measured boxes, so the component only measures
3
+ and renders. */
4
+ export const RADIUS = 8;
5
+ /* Edges whose runs overlap in one channel sit this far apart. */
6
+ export const TRACK = 6;
7
+ /* The half width of a hop, and of a gap in a crossed line. */
8
+ const HOP = 5;
9
+ const GAP = 4;
10
+ /* Room the arrowhead takes at the end of an edge. */
11
+ const ARROW = 10;
12
+ /* A line runs this far past a crossing mark to its end, arrowhead
13
+ included, so the arrow sits on a straight line; without the room, the
14
+ mark is left out. A group's 24px entry room leaves enough for it. */
15
+ const SETTLE = 12;
16
+ /* How far a vertical run keeps from a node it passes, and two exits apart. */
17
+ const CLEAR = 12;
18
+ /* The run into a node's side, the turn included, so the arrow sits on a
19
+ straight line. The same room a group keeps where an edge comes in. */
20
+ const SIDE_RUN = 24;
21
+ export const look = (edge) => ({ line: edge.line, tone: edge.tone, series: edge.series, flow: edge.flow, shape: edge.shape, head: edge.head });
22
+ const dist = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
23
+ const towards = (a, b, d) => {
24
+ const n = dist(a, b) || 1;
25
+ return [a[0] + ((b[0] - a[0]) / n) * d, a[1] + ((b[1] - a[1]) / n) * d];
26
+ };
27
+ const isVertical = (a, b) => Math.abs(a[0] - b[0]) < 0.5;
28
+ /* Drops repeated points and points in the middle of a straight line, so every
29
+ inner point is a real turn. */
30
+ function clean(points) {
31
+ const out = [];
32
+ for (const point of points) {
33
+ if (out.length && dist(out[out.length - 1], point) < 0.5)
34
+ continue;
35
+ if (out.length >= 2) {
36
+ const a = out[out.length - 2];
37
+ const b = out[out.length - 1];
38
+ if ((isVertical(a, b) && isVertical(b, point)) || (Math.abs(a[1] - b[1]) < 0.5 && Math.abs(b[1] - point[1]) < 0.5))
39
+ out.pop();
40
+ }
41
+ out.push(point);
42
+ }
43
+ return out;
44
+ }
45
+ /* The corner radius at each point: 8px, or less when a segment is short. A
46
+ segment shared by two corners gives each half of its length. */
47
+ function radii(points) {
48
+ const last = points.length - 1;
49
+ return points.map((point, j) => {
50
+ if (j === 0 || j === last)
51
+ return 0;
52
+ const before = dist(points[j - 1], point) * (j - 1 === 0 ? 1 : 0.5);
53
+ const after = dist(point, points[j + 1]) * (j + 1 === last ? 1 : 0.5);
54
+ return Math.max(0, Math.min(RADIUS, before, after));
55
+ });
56
+ }
57
+ /* Assigns each run along a shared channel a track, so runs that overlap sit
58
+ apart and their dashes never paint over each other. Returns the offset of
59
+ each run from the channel's centre. */
60
+ function tracks(runs) {
61
+ const offsets = new Map();
62
+ for (const lane of new Set(runs.map((run) => run.lane))) {
63
+ const here = runs.filter((run) => run.lane === lane).sort((a, b) => a.left - b.left);
64
+ const ends = [];
65
+ const picked = here.map((run) => {
66
+ let track = ends.findIndex((end) => end < run.left - TRACK);
67
+ if (track < 0)
68
+ track = ends.push(run.right) - 1;
69
+ else
70
+ ends[track] = run.right;
71
+ return track;
72
+ });
73
+ here.forEach((run, index) => offsets.set(run.item, (picked[index] - (ends.length - 1) / 2) * TRACK));
74
+ }
75
+ return offsets;
76
+ }
77
+ const flip = (box) => ({
78
+ ...box, left: box.top, right: box.bottom, top: box.left, bottom: box.right,
79
+ width: box.height, height: box.width, x: box.y, y: box.x,
80
+ });
81
+ const turn = ([a, b]) => [b, a];
82
+ export function route(measured, nodes, flow, frames = []) {
83
+ if (flow !== "right")
84
+ return routeGrid(measured, nodes, frames, flow === "down", "up");
85
+ const turned = measured.map((item) => ({ ...item, target: flip(item.target), sources: item.sources.map(flip) }));
86
+ return routeGrid(turned, nodes.map(flip), frames.map(flip), true, "left").map((item) => ({
87
+ ...item, points: item.points.map(turn), dot: item.dot && turn(item.dot),
88
+ }));
89
+ }
90
+ function classify(source, target) {
91
+ const overlapY = source.top < target.bottom - 1 && target.top < source.bottom - 1;
92
+ const overlapX = source.left < target.right - 1 && target.left < source.right - 1;
93
+ if (overlapY && !overlapX)
94
+ return "side";
95
+ if (target.top >= source.bottom - 1)
96
+ return overlapX ? "down" : "drop";
97
+ return null;
98
+ }
99
+ const keyOf = (pair) => `${pair.edge.key}:${pair.up ? pair.target.id : pair.source.id}`;
100
+ /* Picks a point for each exit along a source's bottom: as close to an even
101
+ spread as it can, in the order of their targets, and clear of every node
102
+ its straight run passes, so a trunk never runs through a node. */
103
+ const holds = (frame, box) => frame.left <= box.left + 1 && frame.right >= box.right - 1 && frame.top <= box.top + 1 && frame.bottom >= box.bottom - 1;
104
+ function placeExits(source, ports, nodes, frames) {
105
+ const pad = Math.min(CLEAR, source.width / 4);
106
+ const placed = [];
107
+ ports.forEach((port, index) => {
108
+ let free = [[source.left + pad, source.right - pad]];
109
+ // Groups count as well, but only those that hold neither end.
110
+ const walls = [...nodes, ...frames.filter((frame) => !holds(frame, source) && !holds(frame, port.target))];
111
+ for (const node of walls) {
112
+ if (node.id === source.id || port.skip.has(node.id))
113
+ continue;
114
+ if (node.bottom <= source.bottom || node.top >= port.extent)
115
+ continue;
116
+ const lo = node.left - CLEAR;
117
+ const hi = node.right + CLEAR;
118
+ free = free.flatMap(([a, b]) => {
119
+ if (hi <= a || lo >= b)
120
+ return [[a, b]];
121
+ return [[a, lo], [hi, b]].filter(([x, y]) => y > x);
122
+ });
123
+ }
124
+ // A trunk that runs past its target into a side stays SIDE_RUN away from
125
+ // that side, so the run into it is long enough to read as an arrow.
126
+ if (port.straight) {
127
+ const { target } = port;
128
+ for (const [lo, hi] of [[target.left - SIDE_RUN, target.left + RADIUS], [target.right - RADIUS, target.right + SIDE_RUN]]) {
129
+ free = free.flatMap(([a, b]) => {
130
+ if (hi <= a || lo >= b)
131
+ return [[a, b]];
132
+ return [[a, lo], [hi, b]].filter(([x, y]) => y > x);
133
+ });
134
+ }
135
+ }
136
+ const ideal = source.left + (source.width * (index + 1)) / (ports.length + 1);
137
+ const floor = index ? placed[index - 1] + CLEAR : -Infinity;
138
+ let best = null;
139
+ for (const [a, b] of free) {
140
+ if (b < floor)
141
+ continue;
142
+ const x = Math.min(Math.max(ideal, a, floor), b);
143
+ if (best === null || Math.abs(x - ideal) < Math.abs(best - ideal))
144
+ best = x;
145
+ }
146
+ placed.push(best ?? Math.max(ideal, floor));
147
+ });
148
+ return placed;
149
+ }
150
+ /* In a stage layout, rows or columns, an edge to a later stage turns in
151
+ the channel under its source when no node stands in the way. Otherwise it
152
+ runs straight past the nodes between, as in a grid: a drop into the
153
+ target's side, or straight into its top. Plain edges from one source
154
+ share one trunk, as series edges do. */
155
+ function routeGrid(measured, nodes, frames, stages, backward) {
156
+ // A node between the two, across the span from lo to hi.
157
+ const between = (source, target, lo, hi) => nodes.some((node) => node.id !== source.id && node.id !== target.id
158
+ && node.top >= source.bottom - 1 && node.bottom <= target.top + 1 && node.right > lo && node.left < hi);
159
+ const pairs = [];
160
+ for (const { edge, target, sources } of measured) {
161
+ sources.forEach((start, index) => {
162
+ if (start.id === target.id)
163
+ return;
164
+ const up = edge.route !== "side" && !classify(start, target) && !!classify(target, start);
165
+ const [source, end] = up ? [target, start] : [start, target];
166
+ let kind = edge.route ?? classify(source, end);
167
+ let blocked = false;
168
+ if (stages && !edge.route && kind === "drop" && !between(source, end, Math.min(source.left, end.left), Math.max(source.right, end.right)))
169
+ kind = "down";
170
+ else if (stages && !edge.route && kind === "down")
171
+ blocked = between(source, end, Math.max(source.left, end.left), Math.min(source.right, end.right));
172
+ if (kind)
173
+ pairs.push({ edge, source, target: end, kind, labelled: index === 0, blocked, up });
174
+ else
175
+ warn(`${edge.key}:${backward}`, `Diagram: the edge ${start.id} -> ${target.id} goes ${backward}, so it is not drawn. Put the target ${backward === "up" ? "lower" : "further right"}.`);
176
+ });
177
+ }
178
+ // Edges down from one source with one series share an exit and a trunk.
179
+ const groups = new Map();
180
+ for (const pair of pairs.filter((item) => item.kind !== "side")) {
181
+ // An edge up keeps its own exit: it never shares a trunk.
182
+ const key = pair.up ? `^${keyOf(pair)}` : `${pair.source.id}\n${pair.edge.series ?? (stages ? "plain" : `#${pair.edge.key}`)}`;
183
+ groups.set(key, [...(groups.get(key) ?? []), pair]);
184
+ }
185
+ for (const list of groups.values())
186
+ list.sort((a, b) => a.target.top - b.target.top || a.target.y - b.target.y);
187
+ const exitOf = new Map();
188
+ for (const sourceId of new Set(pairs.map((pair) => pair.source.id))) {
189
+ const ports = [...groups.values()].filter((list) => list[0].source.id === sourceId);
190
+ const mean = (list) => list.reduce((sum, pair) => sum + pair.target.x, 0) / list.length;
191
+ ports.sort((a, b) => mean(a) - mean(b));
192
+ const source = ports[0]?.[0].source;
193
+ if (!source)
194
+ continue;
195
+ const xs = placeExits(source, ports.map((list) => {
196
+ const far = list[list.length - 1];
197
+ const straight = (!stages && list.length > 1) || far.kind === "drop" || list.some((pair) => pair.blocked);
198
+ return { extent: straight ? far.target.y : (source.bottom + far.target.top) / 2, skip: new Set([far.target.id]), x: mean(list), target: far.target, straight };
199
+ }), nodes, frames);
200
+ ports.forEach((list, index) => exitOf.set(list, xs[index]));
201
+ }
202
+ const joined = (plan) => stages && pairs.filter((pair) => pair.edge === plan.pair.edge && pair.target === plan.pair.target).length > 1;
203
+ const plans = [];
204
+ for (const [list, x] of exitOf) {
205
+ list.forEach((pair, index) => {
206
+ const far = index === list.length - 1;
207
+ const { target } = pair;
208
+ if (pair.kind === "down" && (!far || list.length === 1 || stages) && !pair.blocked) {
209
+ plans.push({ pair, x, enter: "top", near: !far && (!stages || list.length > 1) });
210
+ }
211
+ else if (pair.kind === "down" && x >= target.left + RADIUS && x <= target.right - RADIUS) {
212
+ plans.push({ pair, x, enter: "top", fixed: x });
213
+ }
214
+ else {
215
+ plans.push({ pair, x, enter: x < target.x ? "left" : "right", near: !far });
216
+ }
217
+ });
218
+ }
219
+ for (const pair of pairs.filter((item) => item.kind === "side")) {
220
+ plans.push({ pair, x: pair.source.x, enter: pair.source.x < pair.target.x ? "left" : "right" });
221
+ }
222
+ // Entries spread along each side they use. On the top, in the order of
223
+ // their exits. On a side, edges from above come first, the nearest on top,
224
+ // then edges from beside, so none of them crosses another.
225
+ const entry = new Map();
226
+ for (const id of new Set(plans.map((plan) => plan.pair.target.id))) {
227
+ const here = plans.filter((plan) => plan.pair.target.id === id);
228
+ const target = here[0].pair.target;
229
+ // In a stage layout the sources of one edge join and come in at one
230
+ // point, so a fan-in reads as one edge.
231
+ const slots = new Map();
232
+ for (const plan of here.filter((item) => item.enter === "top" && item.fixed === undefined)) {
233
+ const slot = joined(plan) ? plan.pair.edge : plan;
234
+ slots.set(slot, [...(slots.get(slot) ?? []), plan]);
235
+ }
236
+ const xOf = (list) => list.reduce((sum, plan) => sum + plan.x, 0) / list.length;
237
+ const top = [...slots.values()].sort((a, b) => xOf(a) - xOf(b));
238
+ top.forEach((list, index) => list.forEach((plan) => entry.set(plan, target.left + (target.width * (index + 1)) / (top.length + 1))));
239
+ // A single edge into the top whose exit already sits over the target
240
+ // comes straight down, with no step.
241
+ const only = top.length === 1 && top[0].length === 1 ? top[0][0] : undefined;
242
+ if (only && only.x >= target.left + RADIUS && only.x <= target.right - RADIUS)
243
+ entry.set(only, only.x);
244
+ for (const plan of here.filter((item) => item.fixed !== undefined))
245
+ entry.set(plan, plan.fixed);
246
+ for (const side of ["left", "right"]) {
247
+ const list = here.filter((plan) => plan.enter === side);
248
+ const fromAbove = list.filter((plan) => plan.pair.kind !== "side").sort((a, b) => side === "left" ? b.x - a.x : a.x - b.x);
249
+ const fromBeside = list.filter((plan) => plan.pair.kind === "side").sort((a, b) => a.pair.source.y - b.pair.source.y);
250
+ [...fromAbove, ...fromBeside].forEach((plan, index, all) => entry.set(plan, target.top + (target.height * (index + 1)) / (all.length + 1)));
251
+ }
252
+ }
253
+ // Lanes: a down route turns midway between its source and its target. In
254
+ // a stage layout a trunk's down routes share the channel under the source
255
+ // and one track in it, so they part at one fork.
256
+ const listOf = new Map();
257
+ for (const list of exitOf.keys())
258
+ for (const pair of list)
259
+ listOf.set(pair, list);
260
+ const downs = plans.filter((plan) => plan.enter === "top" && plan.fixed === undefined);
261
+ // A lane keeps out of the nodes and of the groups that hold neither of
262
+ // its ends, across the width it runs. When the middle is taken, it moves
263
+ // to the middle of the widest gap left.
264
+ const trackOf = (plan) => !stages ? plan : joined(plan) ? plan.pair.edge : listOf.get(plan.pair);
265
+ const lanes = new Map();
266
+ for (const key of new Set(downs.map(trackOf))) {
267
+ const here = downs.filter((plan) => trackOf(plan) === key);
268
+ const ends = here.flatMap((plan) => [plan.pair.source, plan.pair.target]);
269
+ const top = Math.max(...here.map((plan) => plan.pair.source.bottom));
270
+ const bottom = Math.min(...here.map((plan) => plan.pair.target.top));
271
+ const mid = (top + bottom) / 2;
272
+ const lo = Math.min(...here.flatMap((plan) => [plan.x, entry.get(plan)])) - CLEAR;
273
+ const hi = Math.max(...here.flatMap((plan) => [plan.x, entry.get(plan)])) + CLEAR;
274
+ const walls = [
275
+ ...nodes.filter((node) => !ends.some((end) => end.id === node.id)),
276
+ ...frames.filter((frame) => !ends.some((end) => holds(frame, end))),
277
+ ];
278
+ let free = [[top + RADIUS, bottom - RADIUS]];
279
+ for (const wall of walls) {
280
+ if (wall.right <= lo || wall.left >= hi)
281
+ continue;
282
+ const a = wall.top - TRACK;
283
+ const b = wall.bottom + TRACK;
284
+ free = free.flatMap(([x, y]) => b <= x || a >= y ? [[x, y]] : [[x, a], [b, y]].filter(([m, n]) => n > m));
285
+ }
286
+ const widest = [...free].sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]))[0];
287
+ const lane = free.some(([a, b]) => a <= mid && mid <= b) || !widest ? mid : (widest[0] + widest[1]) / 2;
288
+ for (const plan of here)
289
+ lanes.set(plan, lane);
290
+ }
291
+ const spans = new Map();
292
+ for (const plan of downs) {
293
+ const ex = entry.get(plan);
294
+ const lane = Math.round(lanes.get(plan) / 2);
295
+ const span = spans.get(trackOf(plan));
296
+ const left = Math.min(plan.x, ex, span?.left ?? Infinity);
297
+ const right = Math.max(plan.x, ex, span?.right ?? -Infinity);
298
+ spans.set(trackOf(plan), { lane, left, right });
299
+ }
300
+ const offsets = tracks([...spans].map(([item, span]) => ({ item, ...span })));
301
+ const routes = [];
302
+ const splits = new Map();
303
+ for (const plan of plans) {
304
+ const { pair } = plan;
305
+ const { edge, source, target } = pair;
306
+ const key = keyOf(pair);
307
+ const ends = pair.up ? [target.id, source.id] : [source.id, target.id];
308
+ let points;
309
+ const at = entry.get(plan);
310
+ if (pair.kind === "side") {
311
+ const tx = plan.enter === "left" ? target.left : target.right;
312
+ const sx = plan.enter === "left" ? source.right : source.left;
313
+ // A side edge steps only when it must. It runs level at the height
314
+ // nearest its spread entry that both nodes share and that keeps clear
315
+ // of the other edges on the two sides it uses: those entering the
316
+ // target's side, and those entering the source's side it leaves by.
317
+ let at = entry.get(plan);
318
+ const lo = Math.max(source.top, target.top) + RADIUS;
319
+ const hi = Math.min(source.bottom, target.bottom) - RADIUS;
320
+ const exitSide = plan.enter === "left" ? "right" : "left";
321
+ const taken = plans.filter((item) => item !== plan && ((item.pair.target.id === target.id && item.enter === plan.enter) ||
322
+ (item.pair.target.id === source.id && item.enter === exitSide))).map((item) => entry.get(item));
323
+ if (lo <= hi) {
324
+ const clamp = (y) => Math.min(Math.max(y, lo), hi);
325
+ const tries = [at, ...taken.flatMap((y) => [y - CLEAR, y + CLEAR])].map(clamp);
326
+ const level = tries.filter((y) => taken.every((other) => Math.abs(other - y) >= CLEAR))
327
+ .sort((a, b) => Math.abs(a - at) - Math.abs(b - at))[0];
328
+ if (level !== undefined)
329
+ at = level;
330
+ }
331
+ const inside = at >= source.top + RADIUS && at <= source.bottom - RADIUS;
332
+ const mx = (sx + tx) / 2;
333
+ points = clean(inside ? [[sx, at], [tx, at]] : [[sx, source.y], [mx, source.y], [mx, at], [tx, at]]);
334
+ routes.push({
335
+ key, points, arrow: true, look: look(edge), ends,
336
+ label: pair.labelled && edge.label ? { text: edge.label, run: points.length - 2, along: points.length === 2 ? 0.5 : 0, room: Math.abs(tx - sx) - ARROW } : undefined,
337
+ });
338
+ continue;
339
+ }
340
+ if (plan.enter === "top" && plan.fixed === undefined) {
341
+ const my = lanes.get(plan) + (offsets.get(trackOf(plan)) ?? 0);
342
+ points = clean([[plan.x, source.bottom], [plan.x, my], [at, my], [at, target.top]]);
343
+ }
344
+ else if (plan.enter === "top") {
345
+ points = [[plan.x, source.bottom], [plan.x, target.top]];
346
+ }
347
+ else {
348
+ points = clean([[plan.x, source.bottom], [plan.x, at], [plan.enter === "left" ? target.left : target.right, at]]);
349
+ }
350
+ let dot;
351
+ if (plan.near && points.length > 2) {
352
+ // A nearer edge leaves the shared trunk at a dot, just before its turn.
353
+ const turn = points[1];
354
+ dot = [plan.x, turn[1] - RADIUS];
355
+ points = [dot, ...points.slice(1)];
356
+ const list = [...exitOf.keys()].find((item) => item.includes(pair));
357
+ splits.set(list, Math.max(splits.get(list) ?? 0, dot[1] - source.bottom + RADIUS));
358
+ }
359
+ let run = longestVertical(points);
360
+ if (pair.up) {
361
+ points = points.reverse();
362
+ run = points.length - 2 - run;
363
+ }
364
+ routes.push({ key, points, arrow: true, look: look(edge), ends, dot, label: pair.labelled && edge.label ? { text: edge.label, run } : undefined });
365
+ }
366
+ // The far edge's label keeps clear of the stub above its splits.
367
+ for (const [list, from] of splits) {
368
+ const far = list[list.length - 1];
369
+ const route = routes.find((item) => item.key === keyOf(far));
370
+ if (route?.label && route.label.run === 0)
371
+ route.label.from = from + 4;
372
+ }
373
+ if (stages)
374
+ fork(routes, plans, listOf);
375
+ checkNodes(routes, nodes);
376
+ return routes;
377
+ }
378
+ /* The segment of a path that holds a point, or -1. */
379
+ function holding(points, at) {
380
+ return points.findIndex((a, j) => {
381
+ const b = points[j + 1];
382
+ return !!b && Math.min(a[0], b[0]) - 0.5 <= at[0] && at[0] <= Math.max(a[0], b[0]) + 0.5
383
+ && Math.min(a[1], b[1]) - 0.5 <= at[1] && at[1] <= Math.max(a[1], b[1]) + 0.5;
384
+ });
385
+ }
386
+ /* Sets a route's path. Its label moves to the longest run of the new path,
387
+ since the old index no longer points at the same run. */
388
+ function reshape(route, points) {
389
+ route.points = points;
390
+ if (route.label)
391
+ route.label = { text: route.label.text, run: longestVertical(points) };
392
+ }
393
+ /* In a stage layout a trunk parts in the channel. When its branches all
394
+ turn one way, they part where the nearest one turns into its target, and
395
+ each branch starts there; when they go both ways, they part at the fork.
396
+ A trunk whose edges differ in look is drawn plain up to where the last
397
+ branch leaves it, whatever way the branches go. */
398
+ function fork(routes, plans, listOf) {
399
+ for (const list of new Set(listOf.values())) {
400
+ if (list.length < 2)
401
+ continue;
402
+ const here = list.map((pair) => ({ pair, route: routes.find((item) => item.key === keyOf(pair)) })).filter((item) => item.route);
403
+ const farPair = list[list.length - 1];
404
+ const same = list.every(({ edge }) => edge.line === list[0].edge.line && edge.tone === list[0].edge.tone && edge.series === list[0].edge.series && edge.flow === list[0].edge.flow);
405
+ const lane = here.filter(({ pair }) => plans.find((plan) => plan.pair === pair)?.enter === "top");
406
+ if (lane.length !== here.length || lane.length < 2) {
407
+ // Branches that leave a straight trunk at their own dots: the far
408
+ // edge gives up the trunk above the last dot when the looks differ.
409
+ const far = here.find(({ pair }) => pair === farPair)?.route;
410
+ if (same || !far)
411
+ continue;
412
+ const start = far.points[0];
413
+ const dots = here.flatMap(({ route: item }) => item !== far && item.dot ? [item.dot] : []);
414
+ const split = dots.sort((a, b) => dist(start, b) - dist(start, a))[0];
415
+ const j = split ? holding(far.points, split) : -1;
416
+ if (!split || j < 0)
417
+ continue;
418
+ routes.push({ key: `${keyOf(list[0])}:trunk`, points: clean([...far.points.slice(0, j + 1), split]), arrow: false, look: {} });
419
+ reshape(far, clean([split, ...far.points.slice(j + 1)]));
420
+ continue;
421
+ }
422
+ // Every branch here runs down from the exit to the lane, along it, and
423
+ // down into its target: a start, a turn into the lane, a turn out.
424
+ const full = here.map(({ pair, route: item }) => ({
425
+ pair, item, points: pair === farPair ? item.points : [[item.points[0][0], pair.source.bottom], ...item.points.slice(1)],
426
+ }));
427
+ const exit = full[0].points[0];
428
+ const my = Math.min(...full.map(({ points }) => points[1][1]));
429
+ const sides = new Set(full.map(({ points }) => Math.sign(Math.round(points[points.length - 1][0] - exit[0]))));
430
+ let split;
431
+ if (sides.size > 1 || sides.has(0))
432
+ split = [exit[0], my - RADIUS];
433
+ else {
434
+ const dir = [...sides][0];
435
+ const nearest = full.reduce((a, b) => Math.abs(a.points[a.points.length - 1][0] - exit[0]) <= Math.abs(b.points[b.points.length - 1][0] - exit[0]) ? a : b);
436
+ split = [nearest.points[nearest.points.length - 1][0] - dir * RADIUS, my];
437
+ }
438
+ for (const { pair, item, points } of full) {
439
+ item.dot = undefined;
440
+ const j = holding(points, split);
441
+ if (!(pair === farPair && same) && j >= 0)
442
+ reshape(item, clean([split, ...points.slice(j + 1)]));
443
+ else if (points !== item.points)
444
+ reshape(item, points);
445
+ }
446
+ full.find(({ pair }) => pair === farPair).item.dot = split;
447
+ if (!same) {
448
+ const trunk = full.find(({ pair }) => pair === farPair).points;
449
+ const j = holding(trunk, split);
450
+ if (j >= 0)
451
+ routes.push({ key: `${keyOf(list[0])}:trunk`, points: clean([...trunk.slice(0, j + 1), split]), arrow: false, look: {} });
452
+ }
453
+ }
454
+ }
455
+ function longestVertical(points) {
456
+ let best = points.length - 2;
457
+ let length = -1;
458
+ for (let j = 0; j < points.length - 1; j++) {
459
+ const a = points[j];
460
+ const b = points[j + 1];
461
+ if (isVertical(a, b) && dist(a, b) > length) {
462
+ best = j;
463
+ length = dist(a, b);
464
+ }
465
+ }
466
+ return best;
467
+ }
468
+ const warned = new Set();
469
+ function warn(key, message) {
470
+ if (warned.has(key))
471
+ return;
472
+ warned.add(key);
473
+ console.warn(message);
474
+ }
475
+ /* Kiso does not route around nodes. A run through one says the layout needs
476
+ a change, so it is reported once. */
477
+ function checkNodes(routes, nodes) {
478
+ for (const route of routes) {
479
+ for (let j = 0; j < route.points.length - 1; j++) {
480
+ const [ax, ay] = route.points[j];
481
+ const [bx, by] = route.points[j + 1];
482
+ for (const node of nodes) {
483
+ if (route.ends?.includes(node.id))
484
+ continue;
485
+ const hit = Math.max(ax, bx) > node.left + 1 && Math.min(ax, bx) < node.right - 1
486
+ && Math.max(ay, by) > node.top + 1 && Math.min(ay, by) < node.bottom - 1;
487
+ if (hit)
488
+ warn(`${route.key}>${node.id}`, `Diagram: the edge ${route.key.split(":")[0]} runs through the node "${node.id}". Move the node, or set route on the edge.`);
489
+ }
490
+ }
491
+ }
492
+ }
493
+ const unit = (a, b) => {
494
+ const n = dist(a, b) || 1;
495
+ return [(b[0] - a[0]) / n, (b[1] - a[1]) / n];
496
+ };
497
+ function push(out, p) {
498
+ const last = out[out.length - 1];
499
+ out.push([p[0], p[1], last ? last[2] + Math.hypot(p[0] - last[0], p[1] - last[1]) : 0]);
500
+ }
501
+ /* The drawn line of an orthogonal route: its runs and rounded corners. */
502
+ function dense(points, rad, step = 4) {
503
+ const out = [];
504
+ for (let j = 0; j < points.length - 1; j++) {
505
+ const s = towards(points[j], points[j + 1], rad[j]);
506
+ const e = towards(points[j + 1], points[j], rad[j + 1]);
507
+ const n = Math.max(1, Math.ceil(dist(s, e) / step));
508
+ for (let k = 0; k <= n; k++)
509
+ push(out, [s[0] + ((e[0] - s[0]) * k) / n, s[1] + ((e[1] - s[1]) * k) / n]);
510
+ if (j + 1 < points.length - 1) {
511
+ const q = points[j + 1];
512
+ const m = towards(q, points[j + 2], rad[j + 1]);
513
+ for (let k = 1; k < 4; k++) {
514
+ const t = k / 4;
515
+ push(out, [(1 - t) ** 2 * e[0] + 2 * (1 - t) * t * q[0] + t * t * m[0], (1 - t) ** 2 * e[1] + 2 * (1 - t) * t * q[1] + t * t * m[1]]);
516
+ }
517
+ }
518
+ }
519
+ return out;
520
+ }
521
+ /* An orthogonal path with rounded corners and no marks. */
522
+ function orthogonal(points) {
523
+ const rad = radii(points);
524
+ let d = `M ${points[0][0]} ${points[0][1]}`;
525
+ for (let j = 0; j < points.length - 1; j++) {
526
+ const e = towards(points[j + 1], points[j], rad[j + 1]);
527
+ d += ` L ${e[0]} ${e[1]}`;
528
+ if (j + 1 < points.length - 1) {
529
+ const q = points[j + 1];
530
+ const n = towards(q, points[j + 2], rad[j + 1]);
531
+ d += ` Q ${q[0]} ${q[1]} ${n[0]} ${n[1]}`;
532
+ }
533
+ }
534
+ return d;
535
+ }
536
+ /* Where a route parts from the others: the farthest junction dot on it, or
537
+ the end of the stretch from its start that lies on another route. Before
538
+ that point the route is shared, so it stays orthogonal in every shape. */
539
+ function parting(routes, i) {
540
+ const points = routes[i].points;
541
+ const cum = [0];
542
+ for (let k = 1; k < points.length; k++)
543
+ cum.push(cum[k - 1] + dist(points[k - 1], points[k]));
544
+ const arcOf = (at) => {
545
+ const k = holding(points, at);
546
+ return k < 0 ? -1 : cum[k] + dist(points[k], at);
547
+ };
548
+ let at = 0;
549
+ for (const other of routes)
550
+ if (other.dot)
551
+ at = Math.max(at, arcOf(other.dot));
552
+ const spans = [];
553
+ routes.forEach((other, j) => {
554
+ if (j === i)
555
+ return;
556
+ for (let k = 0; k < points.length - 1; k++) {
557
+ const a = points[k];
558
+ const b = points[k + 1];
559
+ for (let m = 0; m < other.points.length - 1; m++) {
560
+ const c = other.points[m];
561
+ const d = other.points[m + 1];
562
+ const vertical = isVertical(a, b) && isVertical(c, d) && Math.abs(a[0] - c[0]) < 0.5;
563
+ const flat = !isVertical(a, b) && !isVertical(c, d) && Math.abs(a[1] - b[1]) < 0.5 && Math.abs(c[1] - d[1]) < 0.5 && Math.abs(a[1] - c[1]) < 0.5;
564
+ if (!vertical && !flat)
565
+ continue;
566
+ const axis = vertical ? 1 : 0;
567
+ const dir = Math.sign(b[axis] - a[axis]) || 1;
568
+ const lo = Math.max(Math.min(a[axis], b[axis]), Math.min(c[axis], d[axis]));
569
+ const hi = Math.min(Math.max(a[axis], b[axis]), Math.max(c[axis], d[axis]));
570
+ if (hi - lo < 0.5)
571
+ continue;
572
+ const t0 = cum[k] + (dir > 0 ? lo - a[axis] : a[axis] - hi);
573
+ spans.push([t0, t0 + hi - lo]);
574
+ }
575
+ }
576
+ });
577
+ let reach = 0;
578
+ for (const [lo, hi] of spans.sort((a, b) => a[0] - b[0]))
579
+ if (lo <= reach + 0.5)
580
+ reach = Math.max(reach, hi);
581
+ at = Math.max(at, reach);
582
+ let k = 0;
583
+ while (k < points.length - 2 && cum[k + 1] < at - 0.01)
584
+ k++;
585
+ const point = towards(points[k], points[k + 1], Math.min(at - cum[k], dist(points[k], points[k + 1])));
586
+ return { at, k, point, dir: unit(points[k], points[k + 1]) };
587
+ }
588
+ /* A curve or a straight line from where the route parts to its end. Null
589
+ when what is left is one straight run along an axis: that edge draws as
590
+ it does orthogonally. */
591
+ function shaped(routes, i, shape, boxes) {
592
+ const route = routes[i];
593
+ const { points } = route;
594
+ const { at, k, point: P, dir } = parting(routes, i);
595
+ const E = points[points.length - 1];
596
+ const dE = unit(points[points.length - 2], E);
597
+ if (dist(P, E) < 1)
598
+ return null;
599
+ const along = Math.abs(dir[0] * dE[0] + dir[1] * dE[1]) > 0.99;
600
+ const level = Math.abs(P[0] - E[0]) < 0.5 || Math.abs(P[1] - E[1]) < 0.5;
601
+ const ahead = (E[0] - P[0]) * dE[0] + (E[1] - P[1]) * dE[1] > 0;
602
+ if (along && level && ahead)
603
+ return null;
604
+ // The shared stretch, orthogonal.
605
+ const head = clean([...points.slice(0, k + 1), P]);
606
+ let d = head.length > 1 ? orthogonal(head) : `M ${P[0]} ${P[1]}`;
607
+ const samples = head.length > 1 ? dense(head, radii(head), 2) : [[P[0], P[1], 0]];
608
+ const from = samples[samples.length - 1][2];
609
+ const add = (p) => push(samples, p);
610
+ if (shape === "curve") {
611
+ // A cubic to a point SETTLE short of the end, then straight into the
612
+ // port, so the arrowhead sits on a straight line and points along it.
613
+ const settle = Math.min(SETTLE, dist(P, E) / 2);
614
+ const F = [E[0] - dE[0] * settle, E[1] - dE[1] * settle];
615
+ const delta = [F[0] - P[0], F[1] - P[1]];
616
+ const span = Math.hypot(delta[0], delta[1]);
617
+ const axial = (v) => Math.abs(delta[0] * v[0] + delta[1] * v[1]);
618
+ // Each handle is the larger of 60% of the distance along its port's axis
619
+ // and 30% of the span, so short links still arch.
620
+ let kS = Math.min(160, Math.max(32, 0.6 * axial(dir), 0.3 * span));
621
+ let kE = Math.min(160, Math.max(32, 0.6 * axial(dE), 0.3 * span));
622
+ // Ends that face the same way make an S; handles longer than the run
623
+ // would make it double back.
624
+ if (dir[0] * dE[0] + dir[1] * dE[1] > 0.9) {
625
+ kS = Math.min(kS, axial(dir));
626
+ kE = Math.min(kE, axial(dE));
627
+ }
628
+ const c1 = [P[0] + dir[0] * kS, P[1] + dir[1] * kS];
629
+ const c2 = [F[0] - dE[0] * kE, F[1] - dE[1] * kE];
630
+ d += ` C ${c1[0]} ${c1[1]} ${c2[0]} ${c2[1]} ${F[0]} ${F[1]} L ${E[0]} ${E[1]}`;
631
+ const n = Math.max(8, Math.ceil(span / 3));
632
+ for (let m = 1; m <= n; m++) {
633
+ const t = m / n;
634
+ const u = 1 - t;
635
+ add([
636
+ u ** 3 * P[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t ** 3 * F[0],
637
+ u ** 3 * P[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t ** 3 * F[1],
638
+ ]);
639
+ }
640
+ add(E);
641
+ return { d, samples, from };
642
+ }
643
+ // Straight. Ports are picked for elbows, so a steep line into a side comes
644
+ // in through the top or bottom instead, 20px clear of the corners, with a
645
+ // straight SETTLE run into it.
646
+ let end = E;
647
+ let stub = null;
648
+ const box = route.ends ? boxes?.get(route.ends[1]) : undefined;
649
+ if (box) {
650
+ const v = [E[0] - P[0], E[1] - P[1]];
651
+ const intoSide = Math.abs(dE[0]) > 0.5;
652
+ const clampTo = (value, lo, hi) => lo > hi ? (lo + hi) / 2 : Math.min(Math.max(value, lo), hi);
653
+ if (intoSide && Math.abs(v[1]) > 1.5 * Math.abs(v[0])) {
654
+ const x = clampTo(E[0], box.left + 20, box.right - 20);
655
+ const y = v[1] > 0 ? box.top : box.bottom;
656
+ const run = [x, y - Math.sign(v[1]) * SETTLE];
657
+ // Only when the new face still lies ahead, steeply: a target stacked
658
+ // close beside the source keeps its side.
659
+ if (Math.abs(run[1] - P[1]) > Math.abs(run[0] - P[0])) {
660
+ end = [x, y];
661
+ stub = run;
662
+ }
663
+ }
664
+ }
665
+ for (const p of stub ? [stub, end] : [end]) {
666
+ d += ` L ${p[0]} ${p[1]}`;
667
+ const last = samples[samples.length - 1];
668
+ const n = Math.max(1, Math.ceil(dist([last[0], last[1]], p) / 3));
669
+ for (let m = 1; m <= n; m++)
670
+ add([last[0] + ((p[0] - last[0]) * m) / n, last[1] + ((p[1] - last[1]) * m) / n]);
671
+ }
672
+ if (boxes) {
673
+ // Kiso does not route around nodes, and a straight line takes no detour.
674
+ const line = [P, ...(stub ? [stub] : []), end];
675
+ for (const node of boxes.values()) {
676
+ if (route.ends?.includes(node.id))
677
+ continue;
678
+ for (let m = 0; m < line.length - 1; m++) {
679
+ if (crosses(line[m], line[m + 1], node))
680
+ warn(`${route.key}>${node.id}`, `Diagram: the edge ${route.key.split(":")[0]} runs through the node "${node.id}". Move the node, or set route on the edge.`);
681
+ }
682
+ }
683
+ }
684
+ return { d, samples, from };
685
+ }
686
+ /* Whether a segment passes through the inside of a box. */
687
+ function crosses(a, b, box) {
688
+ let lo = 0;
689
+ let hi = 1;
690
+ const dx = b[0] - a[0];
691
+ const dy = b[1] - a[1];
692
+ for (const [p, q] of [[-dx, a[0] - (box.left + 1)], [dx, box.right - 1 - a[0]], [-dy, a[1] - (box.top + 1)], [dy, box.bottom - 1 - a[1]]]) {
693
+ if (Math.abs(p) < 1e-9) {
694
+ if (q < 0)
695
+ return false;
696
+ continue;
697
+ }
698
+ const r = q / p;
699
+ if (p < 0)
700
+ lo = Math.max(lo, r);
701
+ else
702
+ hi = Math.min(hi, r);
703
+ if (lo > hi)
704
+ return false;
705
+ }
706
+ return true;
707
+ }
708
+ /* Where two sampled lines cross, as distances along the first. */
709
+ function meets(a, b) {
710
+ const out = [];
711
+ const box = (list) => list.reduce((r, p) => [Math.min(r[0], p[0]), Math.min(r[1], p[1]), Math.max(r[2], p[0]), Math.max(r[3], p[1])], [Infinity, Infinity, -Infinity, -Infinity]);
712
+ const [bx0, by0, bx1, by1] = box(b);
713
+ for (let k = 1; k < a.length; k++) {
714
+ const p = a[k - 1];
715
+ const q = a[k];
716
+ if (Math.max(p[0], q[0]) < bx0 || Math.min(p[0], q[0]) > bx1 || Math.max(p[1], q[1]) < by0 || Math.min(p[1], q[1]) > by1)
717
+ continue;
718
+ for (let m = 1; m < b.length; m++) {
719
+ const c = b[m - 1];
720
+ const d = b[m];
721
+ const t = segmentsMeet(p, q, c, d);
722
+ if (t !== null)
723
+ out.push(p[2] + (q[2] - p[2]) * t);
724
+ }
725
+ }
726
+ return out;
727
+ }
728
+ function segmentsMeet(a, b, c, d) {
729
+ const rx = b[0] - a[0];
730
+ const ry = b[1] - a[1];
731
+ const sx = d[0] - c[0];
732
+ const sy = d[1] - c[1];
733
+ const den = rx * sy - ry * sx;
734
+ if (Math.abs(den) < 1e-9)
735
+ return null;
736
+ const t = ((c[0] - a[0]) * sy - (c[1] - a[1]) * sx) / den;
737
+ const u = ((c[0] - a[0]) * ry - (c[1] - a[1]) * rx) / den;
738
+ return t >= 0 && t <= 1 && u >= 0 && u <= 1 ? t : null;
739
+ }
740
+ /* Sketch: the orthogonal line, hand drawn. The wobble is a function of where
741
+ a point is, the coordinate along its run and the run's own line, so two
742
+ edges on one stem wobble alike. It fades out near every route's ends and
743
+ corners, every dot and every crossing mark, so dots, heads, hops and the
744
+ joins between edges sit on the line. Same drawing on every render. */
745
+ const WOBBLE = 1.4;
746
+ const STEP = 7;
747
+ function hash(n) {
748
+ let h = Math.imul(Math.round(n) ^ 0x9e3779b9, 0x85ebca6b);
749
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
750
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
751
+ }
752
+ function wobble(u, line) {
753
+ const a = hash(line) * 6.283;
754
+ const b = hash(line + 7919) * 6.283;
755
+ return WOBBLE * (0.9 * Math.sin(u / 23 + a) + 0.45 * Math.sin(u / 9.5 + b) + 0.35 * (hash(line * 31 + Math.round(u / STEP)) - 0.5));
756
+ }
757
+ function fade(p, anchors) {
758
+ let f = 1;
759
+ for (const [x, y, r] of anchors)
760
+ f = Math.min(f, Math.hypot(p[0] - x, p[1] - y) / r);
761
+ return Math.max(0, f);
762
+ }
763
+ function sketch(points, rad, hops, gaps, anchors) {
764
+ const parts = [[]];
765
+ const add = (p) => parts[parts.length - 1].push(p);
766
+ const moved = (p, vertical) => {
767
+ const w = wobble(vertical ? p[1] : p[0], vertical ? p[0] : p[1]) * fade(p, anchors);
768
+ return (vertical ? [p[0] + w, p[1]] : [p[0], p[1] + w]);
769
+ };
770
+ for (let j = 0; j < points.length - 1; j++) {
771
+ const p = points[j];
772
+ const q = points[j + 1];
773
+ const s = towards(p, q, rad[j]);
774
+ const e = towards(q, p, rad[j + 1]);
775
+ const vertical = isVertical(p, q);
776
+ const axis = vertical ? 1 : 0;
777
+ const dir = Math.sign(e[axis] - s[axis]) || 1;
778
+ const at = (v) => vertical ? [s[0], v] : [v, s[1]];
779
+ // Marks along the run: hops (a half circle, like the orthogonal line)
780
+ // and breaks (a gap left for a crossing edge).
781
+ const marks = [
782
+ ...(hops.get(j) ?? []).map((t) => ({ v: s[axis] + dir * t, hop: true })),
783
+ ...(gaps.get(j) ?? []).map((v) => ({ v, hop: false })),
784
+ ].sort((a, b) => (a.v - b.v) * dir);
785
+ let v = s[axis];
786
+ // Anchors on this run, such as a dot or where another edge joins it,
787
+ // are samples too, so the line passes through them exactly.
788
+ const pinned = anchors.filter(([x, y]) => Math.abs((vertical ? x : y) - s[1 - axis]) < 0.5).map((a) => a[axis]);
789
+ const run = (to) => {
790
+ // Samples on a grid shared by every edge, plus the pinned points, so
791
+ // shared runs match.
792
+ const marks = [];
793
+ for (let g = (dir > 0 ? Math.floor(v / STEP) + 1 : Math.ceil(v / STEP) - 1) * STEP; (g - to) * dir < 0; g += dir * STEP)
794
+ marks.push(g);
795
+ for (const a of pinned)
796
+ if ((a - v) * dir > 0.5 && (to - a) * dir > 0.5)
797
+ marks.push(a);
798
+ add(moved(at(v), vertical));
799
+ for (const m of marks.sort((a, b) => (a - b) * dir))
800
+ add(moved(at(m), vertical));
801
+ add(moved(at(to), vertical));
802
+ v = to;
803
+ };
804
+ for (const mark of marks) {
805
+ if (mark.hop) {
806
+ run(mark.v - dir * HOP);
807
+ // Vertical runs hop to the right, flat runs up, as the arc does.
808
+ const c = at(mark.v);
809
+ for (let m = 1; m <= 8; m++) {
810
+ const ang = (Math.PI * m) / 8;
811
+ const back = -HOP * Math.cos(ang) * dir;
812
+ const out = HOP * Math.sin(ang);
813
+ add(vertical ? [c[0] + out, c[1] + back] : [c[0] + back, c[1] - out]);
814
+ }
815
+ v = mark.v + dir * HOP;
816
+ }
817
+ else {
818
+ run(mark.v - dir * (GAP + 1));
819
+ parts.push([]);
820
+ v = mark.v + dir * (GAP + 1);
821
+ }
822
+ }
823
+ run(e[axis]);
824
+ if (j + 1 < points.length - 1) {
825
+ const n = towards(q, points[j + 2], rad[j + 1]);
826
+ for (let k = 1; k < 4; k++) {
827
+ const t = k / 4;
828
+ add([(1 - t) ** 2 * e[0] + 2 * (1 - t) * t * q[0] + t * t * n[0], (1 - t) ** 2 * e[1] + 2 * (1 - t) * t * q[1] + t * t * n[1]]);
829
+ }
830
+ }
831
+ }
832
+ return parts.map(spline).join(" ");
833
+ }
834
+ /* A smooth path through points: Catmull-Rom as cubics. */
835
+ function spline(raw) {
836
+ const pts = raw.filter((p, k) => k === 0 || dist(raw[k - 1], p) > 0.2);
837
+ if (!pts.length)
838
+ return "";
839
+ const f = (n) => Math.round(n * 100) / 100;
840
+ let d = `M ${f(pts[0][0])} ${f(pts[0][1])}`;
841
+ for (let k = 0; k < pts.length - 1; k++) {
842
+ const p0 = pts[Math.max(0, k - 1)];
843
+ const p1 = pts[k];
844
+ const p2 = pts[k + 1];
845
+ const p3 = pts[Math.min(pts.length - 1, k + 2)];
846
+ d += ` C ${f(p1[0] + (p2[0] - p0[0]) / 6)} ${f(p1[1] + (p2[1] - p0[1]) / 6)} ${f(p2[0] - (p3[0] - p1[0]) / 6)} ${f(p2[1] - (p3[1] - p1[1]) / 6)} ${f(p2[0])} ${f(p2[1])}`;
847
+ }
848
+ return d;
849
+ }
850
+ export function draw(routes, frames, crossings, labels, measure, style = {}) {
851
+ const shapes = routes.map((route) => ({ points: route.points, rad: radii(route.points) }));
852
+ // A trunk is the shared run of several edges: it keeps its right angles,
853
+ // unless the drawing is sketched.
854
+ const kinds = routes.map((route) => {
855
+ const shape = route.look.shape ?? style.shape ?? "orthogonal";
856
+ return !route.arrow && shape !== "sketch" ? "orthogonal" : shape;
857
+ });
858
+ const heads = routes.map((route, i) => route.look.head ?? style.arrow ?? (kinds[i] === "sketch" ? "sketch" : "triangle"));
859
+ const free = routes.map((_, i) => kinds[i] === "curve" || kinds[i] === "straight" ? shaped(routes, i, kinds[i], style.boxes) : null);
860
+ const straights = [];
861
+ shapes.forEach(({ points, rad }, i) => {
862
+ // Curves and straight lines have no runs; their crossings come below.
863
+ if (free[i])
864
+ return;
865
+ for (let j = 0; j < points.length - 1; j++) {
866
+ const s = towards(points[j], points[j + 1], rad[j]);
867
+ const e = towards(points[j + 1], points[j], rad[j + 1]);
868
+ const vertical = isVertical(points[j], points[j + 1]);
869
+ straights.push({
870
+ route: i, seg: j, vertical, at: vertical ? s[0] : s[1], a: vertical ? s[1] : s[0], b: vertical ? e[1] : e[0],
871
+ ending: routes[i].arrow && j === points.length - 2,
872
+ });
873
+ }
874
+ });
875
+ // Lines a run can cross: frame borders, and other edges' horizontal runs.
876
+ // A frame's rounded corners are left out, so nothing hops on a curve.
877
+ const across = frames.flatMap((f) => [
878
+ { at: f.top, lo: f.left + f.radius, hi: f.right - f.radius },
879
+ { at: f.bottom, lo: f.left + f.radius, hi: f.right - f.radius },
880
+ ]);
881
+ for (const s of straights)
882
+ if (!s.vertical)
883
+ across.push({ at: s.at, lo: Math.min(s.a, s.b), hi: Math.max(s.a, s.b), route: s.route, seg: s.seg });
884
+ const upright = frames.flatMap((f) => [
885
+ { at: f.left, lo: f.top + f.radius, hi: f.bottom - f.radius },
886
+ { at: f.right, lo: f.top + f.radius, hi: f.bottom - f.radius },
887
+ ]);
888
+ const found = new Map();
889
+ const gaps = new Map();
890
+ const plates = [];
891
+ if (crossings !== "none") {
892
+ for (const s of straights) {
893
+ const lines = s.vertical ? across : upright;
894
+ const dir = Math.sign(s.b - s.a) || 1;
895
+ const length = Math.abs(s.b - s.a);
896
+ const list = [];
897
+ for (const line of lines) {
898
+ if (line.route === s.route)
899
+ continue;
900
+ const margin = line.route === undefined ? 1 : HOP + 2;
901
+ if (s.at <= line.lo + margin || s.at >= line.hi - margin)
902
+ continue;
903
+ const t = (line.at - s.a) * dir;
904
+ // Hops stay away from corners and from the edge's ends.
905
+ if (t <= HOP + 4 || t >= length - (s.ending ? HOP + SETTLE : HOP + 4))
906
+ continue;
907
+ list.push({ t, at: line.at, line });
908
+ }
909
+ list.sort((a, b) => a.t - b.t);
910
+ const kept = list.filter((item, index) => index === 0 || item.t - list[index - 1].t >= 2 * HOP + 2);
911
+ if (!kept.length)
912
+ continue;
913
+ found.set(`${s.route}:${s.seg}`, kept);
914
+ if (crossings !== "gap")
915
+ continue;
916
+ // A gap breaks the crossed line: a frame under a plate in the card
917
+ // colour, an edge by leaving out that stretch of its path.
918
+ for (const item of kept) {
919
+ const x = s.vertical ? s.at : item.at;
920
+ const y = s.vertical ? item.at : s.at;
921
+ if (item.line.route === undefined) {
922
+ plates.push(s.vertical
923
+ ? { key: `${s.route}:${s.seg}:${x}:${y}`, x: x - GAP - 1, y: y - 2, width: 2 * GAP + 2, height: 4 }
924
+ : { key: `${s.route}:${s.seg}:${x}:${y}`, x: x - 2, y: y - GAP - 1, width: 4, height: 2 * GAP + 2 });
925
+ }
926
+ else {
927
+ const key = `${item.line.route}:${item.line.seg}`;
928
+ gaps.set(key, [...(gaps.get(key) ?? []), x]);
929
+ }
930
+ }
931
+ }
932
+ }
933
+ // Crossings that involve a curve or a straight line, found on the drawn
934
+ // lines. They are always gaps: a hop on a slanted line reads as a bump.
935
+ // The later edge crosses the earlier one, so the knockout under it breaks
936
+ // the earlier line. Edges on one stem only touch where they part, which
937
+ // the clearance at their start leaves out.
938
+ const knocks = new Map();
939
+ if (crossings !== "none" && free.some(Boolean)) {
940
+ const lines = routes.map((_, i) => free[i]?.samples ?? dense(shapes[i].points, shapes[i].rad));
941
+ routes.forEach((route, i) => {
942
+ const mine = lines[i];
943
+ const length = mine[mine.length - 1][2];
944
+ const list = [];
945
+ if (free[i]) {
946
+ for (const f of frames) {
947
+ const sides = [
948
+ [[f.left + f.radius, f.top], [f.right - f.radius, f.top], false],
949
+ [[f.left + f.radius, f.bottom], [f.right - f.radius, f.bottom], false],
950
+ [[f.left, f.top + f.radius], [f.left, f.bottom - f.radius], true],
951
+ [[f.right, f.top + f.radius], [f.right, f.bottom - f.radius], true],
952
+ ];
953
+ for (const [a, b, upright] of sides) {
954
+ for (const t of meets(mine, [[...a, 0], [...b, 0]])) {
955
+ const k = mine.findIndex((p) => p[2] >= t);
956
+ const p = mine[Math.max(0, k)];
957
+ const q = mine[Math.max(0, k - 1)];
958
+ // The break in the border widens as the line slants.
959
+ const slant = Math.max(0.3, upright ? Math.abs(unit([q[0], q[1]], [p[0], p[1]])[0]) : Math.abs(unit([q[0], q[1]], [p[0], p[1]])[1]));
960
+ const half = (GAP + 1) / slant;
961
+ list.push({ t, plate: upright
962
+ ? { key: `${i}:${t}`, x: a[0] - 2, y: p[1] - half, width: 4, height: 2 * half }
963
+ : { key: `${i}:${t}`, x: p[0] - half, y: a[1] - 2, width: 2 * half, height: 4 } });
964
+ }
965
+ }
966
+ }
967
+ }
968
+ for (let j = 0; j < i; j++) {
969
+ if (!free[i] && !free[j])
970
+ continue;
971
+ for (const t of meets(mine, lines[j]))
972
+ list.push({ t });
973
+ }
974
+ const start = (free[i]?.from ?? 0) + HOP + 4;
975
+ const end = length - (route.arrow ? HOP + SETTLE : HOP + 4);
976
+ const sorted = list.filter((item) => item.t > start && item.t < end).sort((a, b) => a.t - b.t);
977
+ const kept = sorted.filter((item, index) => index === 0 || item.t - sorted[index - 1].t >= 2 * HOP + 2);
978
+ const parts = [];
979
+ for (const item of kept) {
980
+ if (item.plate) {
981
+ plates.push(item.plate);
982
+ continue;
983
+ }
984
+ const near = mine.filter((p) => Math.abs(p[2] - item.t) <= GAP + 2);
985
+ if (near.length > 1)
986
+ parts.push(near.map((p, k) => `${k ? "L" : "M"} ${p[0]} ${p[1]}`).join(" "));
987
+ }
988
+ if (parts.length)
989
+ knocks.set(i, parts.join(" "));
990
+ });
991
+ }
992
+ // Sketched lines fade their wobble out near these points.
993
+ const anchors = [];
994
+ if (kinds.includes("sketch")) {
995
+ for (const route of routes) {
996
+ route.points.forEach((p, k) => anchors.push([p[0], p[1], k === 0 || k === route.points.length - 1 ? 18 : 12]));
997
+ if (route.dot)
998
+ anchors.push([route.dot[0], route.dot[1], 18]);
999
+ }
1000
+ shapes.forEach(({ points, rad }, i) => {
1001
+ for (let j = 0; j < points.length - 1; j++) {
1002
+ const s = towards(points[j], points[j + 1], rad[j]);
1003
+ const vertical = isVertical(points[j], points[j + 1]);
1004
+ const dir = Math.sign(vertical ? points[j + 1][1] - s[1] : points[j + 1][0] - s[0]) || 1;
1005
+ for (const item of found.get(`${i}:${j}`) ?? [])
1006
+ anchors.push(vertical ? [s[0], s[1] + dir * item.t, 12] : [s[0] + dir * item.t, s[1], 12]);
1007
+ for (const x of gaps.get(`${i}:${j}`) ?? [])
1008
+ anchors.push([x, s[1], 12]);
1009
+ }
1010
+ });
1011
+ }
1012
+ const drawn = { paths: [], labels: [], plates, dots: [] };
1013
+ routes.forEach((route, i) => {
1014
+ const { points, rad } = shapes[i];
1015
+ const shaped = free[i];
1016
+ if (shaped || kinds[i] === "sketch") {
1017
+ let d;
1018
+ if (shaped)
1019
+ d = shaped.d;
1020
+ else {
1021
+ const hops = new Map();
1022
+ const breaks = new Map();
1023
+ for (let j = 0; j < points.length - 1; j++) {
1024
+ if (crossings === "hop")
1025
+ hops.set(j, (found.get(`${i}:${j}`) ?? []).map((item) => item.t));
1026
+ if (!isVertical(points[j], points[j + 1]))
1027
+ breaks.set(j, gaps.get(`${i}:${j}`) ?? []);
1028
+ }
1029
+ d = sketch(points, rad, hops, breaks, anchors);
1030
+ }
1031
+ drawn.paths.push({ key: route.key, d, arrow: route.arrow, ...route.look, shape: kinds[i], head: heads[i], knock: knocks.get(i) });
1032
+ if (route.dot)
1033
+ drawn.dots.push({ key: route.key, x: route.dot[0], y: route.dot[1], ...route.look });
1034
+ if (route.label && shaped) {
1035
+ // A curve has no run to turn a label along: it sits flat, on a
1036
+ // plate, in the middle of the edge's own part.
1037
+ const list = shaped.samples;
1038
+ const total = list[list.length - 1][2];
1039
+ const mid = list.find((p) => p[2] >= shaped.from + (total - shaped.from) / 2) ?? list[list.length - 1];
1040
+ const size = measure(route.label.text);
1041
+ drawn.labels.push({
1042
+ key: route.key, x: mid[0], y: mid[1], lines: [route.label.text], middle: true,
1043
+ plate: { key: route.key, x: mid[0] - size.width / 2 - 3, y: mid[1] - size.height / 2, width: size.width + 6, height: size.height },
1044
+ });
1045
+ }
1046
+ else if (route.label) {
1047
+ const placed = place(route, found, i, labels, measure, frames);
1048
+ if (placed)
1049
+ drawn.labels.push(placed);
1050
+ }
1051
+ return;
1052
+ }
1053
+ let d = `M ${points[0][0]} ${points[0][1]}`;
1054
+ for (let j = 0; j < points.length - 1; j++) {
1055
+ const p = points[j];
1056
+ const q = points[j + 1];
1057
+ const s = towards(p, q, rad[j]);
1058
+ const e = towards(q, p, rad[j + 1]);
1059
+ const vertical = isVertical(p, q);
1060
+ const dir = Math.sign(vertical ? e[1] - s[1] : e[0] - s[0]) || 1;
1061
+ const along = (t) => vertical ? [s[0], s[1] + dir * t] : [s[0] + dir * t, s[1]];
1062
+ if (crossings === "hop") {
1063
+ for (const item of found.get(`${i}:${j}`) ?? []) {
1064
+ const [x1, y1] = along(item.t - HOP);
1065
+ const [x2, y2] = along(item.t + HOP);
1066
+ d += ` L ${x1} ${y1} A ${HOP} ${HOP} 0 0 ${dir > 0 ? 1 : 0} ${x2} ${y2}`;
1067
+ }
1068
+ }
1069
+ const breaks = gaps.get(`${i}:${j}`);
1070
+ if (breaks && !vertical) {
1071
+ for (const x of [...breaks].sort((a, b) => (a - b) * dir)) {
1072
+ d += ` L ${x - dir * (GAP + 1)} ${s[1]} M ${x + dir * (GAP + 1)} ${s[1]}`;
1073
+ }
1074
+ }
1075
+ d += ` L ${e[0]} ${e[1]}`;
1076
+ if (j + 1 < points.length - 1) {
1077
+ const n = towards(q, points[j + 2], rad[j + 1]);
1078
+ d += ` Q ${q[0]} ${q[1]} ${n[0]} ${n[1]}`;
1079
+ }
1080
+ }
1081
+ drawn.paths.push({ key: route.key, d, arrow: route.arrow, ...route.look, head: heads[i], knock: knocks.get(i) });
1082
+ if (route.dot)
1083
+ drawn.dots.push({ key: route.key, x: route.dot[0], y: route.dot[1], ...route.look });
1084
+ if (route.label) {
1085
+ const placed = place(route, found, i, labels, measure, frames);
1086
+ if (placed)
1087
+ drawn.labels.push(placed);
1088
+ }
1089
+ });
1090
+ return drawn;
1091
+ }
1092
+ function place(route, found, index, mode, measure, frames) {
1093
+ const label = route.label;
1094
+ const p = route.points[label.run];
1095
+ const q = route.points[label.run + 1];
1096
+ if (!p || !q)
1097
+ return null;
1098
+ const size = measure(label.text);
1099
+ if (!isVertical(p, q)) {
1100
+ // A flat label sits above its run. When it does not fit the room, it
1101
+ // breaks at its first space into two lines, both above the arrow.
1102
+ let x = p[0] + (q[0] - p[0]) * (label.along ?? 0.5);
1103
+ // Without a room of its own, a label may take its run, less the arrow.
1104
+ let room = label.room ?? Math.abs(q[0] - p[0]) - (route.arrow && label.run === route.points.length - 2 ? ARROW : 0);
1105
+ // A run that crosses frame sides, such as an edge out of one group
1106
+ // into another, takes its label in the gap between the frames: the
1107
+ // stretch inside the fewest frames, the widest of those. The label never
1108
+ // sits across a border.
1109
+ const lo = Math.min(p[0], q[0]);
1110
+ const hi = Math.max(p[0], q[0]);
1111
+ const cuts = frames.flatMap((f) => [f.left, f.right].filter((at) => at > lo + 1 && at < hi - 1 && p[1] > f.top && p[1] < f.bottom));
1112
+ if (cuts.length) {
1113
+ const marks = [lo, ...cuts.sort((a, b) => a - b), hi];
1114
+ const depth = (k) => {
1115
+ const mid = (marks[k] + marks[k + 1]) / 2;
1116
+ return frames.filter((f) => mid > f.left && mid < f.right && p[1] > f.top && p[1] < f.bottom).length;
1117
+ };
1118
+ const width = (k) => marks[k + 1] - marks[k];
1119
+ let best = 0;
1120
+ for (let k = 1; k < marks.length - 1; k++) {
1121
+ if (depth(k) < depth(best) || (depth(k) === depth(best) && width(k) > width(best)))
1122
+ best = k;
1123
+ }
1124
+ const ends = route.arrow && label.run === route.points.length - 2 && marks[best + 1] === (q[0] > p[0] ? hi : lo);
1125
+ x = (marks[best] + marks[best + 1]) / 2;
1126
+ room = marks[best + 1] - marks[best] - (ends ? ARROW : 0);
1127
+ }
1128
+ const space = label.text.indexOf(" ");
1129
+ const stack = room !== undefined && size.width > room && space > 0;
1130
+ const lines = stack ? [label.text.slice(0, space), label.text.slice(space + 1)] : [label.text];
1131
+ return { key: route.key, x, y: p[1] - RADIUS, lines };
1132
+ }
1133
+ const x = p[0];
1134
+ const dir = Math.sign(q[1] - p[1]) || 1;
1135
+ const length = Math.abs(q[1] - p[1]);
1136
+ const ending = route.arrow && label.run === route.points.length - 2;
1137
+ // Free stretches of the run: clear of its corners, the arrow, a split
1138
+ // above it and any crossing.
1139
+ const start = Math.max(RADIUS, label.from ?? 0);
1140
+ const end = length - RADIUS - (ending ? ARROW : 0);
1141
+ const blocked = (found.get(`${index}:${label.run}`) ?? []).map((item) => (item.at - p[1]) * dir);
1142
+ const free = [];
1143
+ let from = start;
1144
+ for (const t of blocked.sort((a, b) => a - b)) {
1145
+ if (t - HOP - 3 > from)
1146
+ free.push([from, Math.min(t - HOP - 3, end)]);
1147
+ from = Math.max(from, t + HOP + 3);
1148
+ }
1149
+ if (end > from)
1150
+ free.push([from, end]);
1151
+ const need = size.width + 8;
1152
+ const middle = (start + end) / 2;
1153
+ let centre = null;
1154
+ const holding = free.find(([a, b]) => a <= middle && middle <= b && b - a >= need);
1155
+ if (holding)
1156
+ centre = Math.min(Math.max(middle, holding[0] + need / 2), holding[1] - need / 2);
1157
+ else {
1158
+ const longest = free.filter(([a, b]) => b - a >= need).sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]))[0];
1159
+ if (longest)
1160
+ centre = (longest[0] + longest[1]) / 2;
1161
+ }
1162
+ const rotate = mode === "vertical" || (mode === "auto" && centre !== null);
1163
+ if (rotate) {
1164
+ // Turned to read along the run, centred on the line, on a plate in the
1165
+ // card colour that breaks the line around it.
1166
+ const y = p[1] + dir * (centre ?? middle);
1167
+ return {
1168
+ key: route.key, x, y, lines: [label.text], rotate: true,
1169
+ plate: { key: route.key, x: x - size.height / 2, y: y - size.width / 2 - 3, width: size.height, height: size.width + 6 },
1170
+ };
1171
+ }
1172
+ if (mode === "horizontal") {
1173
+ // Flat by choice: on the line, at the same free spot, on a plate.
1174
+ const y = p[1] + dir * (centre ?? middle);
1175
+ return {
1176
+ key: route.key, x, y, lines: [label.text], middle: true,
1177
+ plate: { key: route.key, x: x - size.width / 2 - 3, y: y - size.height / 2, width: size.width + 6, height: size.height },
1178
+ };
1179
+ }
1180
+ // Too short to turn: beside the run.
1181
+ return { key: route.key, x: x + TRACK, y: p[1] + (q[1] - p[1]) / 2 + 4, lines: [label.text], anchor: "start" };
1182
+ }