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