@momoi-labs/kiso-react 0.26.0 → 0.27.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.
@@ -2,7 +2,7 @@
2
2
  labels. Pure functions over measured boxes, so the component only measures
3
3
  and renders. */
4
4
  export const RADIUS = 8;
5
- /* Edges whose runs overlap in one channel sit this far apart. */
5
+ /* A label beside a run sits this far from it. */
6
6
  export const TRACK = 6;
7
7
  /* The half width of a hop, and of a gap in a crossed line. */
8
8
  const HOP = 5;
@@ -13,11 +13,6 @@ const ARROW = 10;
13
13
  included, so the arrow sits on a straight line; without the room, the
14
14
  mark is left out. A group's 24px entry room leaves enough for it. */
15
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
16
  export const look = (edge) => ({ line: edge.line, tone: edge.tone, series: edge.series, flow: edge.flow, shape: edge.shape, head: edge.head });
22
17
  const dist = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
23
18
  const towards = (a, b, d) => {
@@ -54,326 +49,600 @@ function radii(points) {
54
49
  return Math.max(0, Math.min(RADIUS, before, after));
55
50
  });
56
51
  }
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;
52
+ /* How far a run keeps from a card it passes. */
53
+ const PAD = 10;
54
+ /* Two runs side by side sit this far apart. */
55
+ const LANE = 12;
56
+ /* The straight run out of a node, and the run into one: the run in holds the
57
+ arrowhead and the turn before it. */
58
+ const OUT = 12;
59
+ const IN = 20;
60
+ /* The price of a turn, in pixels of length. */
61
+ const BEND = 40;
62
+ /* Running within LANE of another edge costs this many times its length. */
63
+ const NEAR = 3;
64
+ /* Running on an edge of the same kind and end costs half: they share it. */
65
+ const JOIN = 0.5;
66
+ /* The price of crossing another edge. */
67
+ const CROSS = 16;
68
+ /* The price of an anchor already taken the other way. */
69
+ const TAKEN = 400;
70
+ /* How far a search looks past the box around its two nodes, before it
71
+ tries the whole drawing. */
72
+ const REACH = 160;
73
+ const SIDES = ["top", "right", "bottom", "left"];
74
+ const NORMAL = { top: [0, -1], right: [1, 0], bottom: [0, 1], left: [-1, 0] };
75
+ /* Directions a path moves in: right, down, left, up. */
76
+ const DIRS = [[1, 0], [0, 1], [-1, 0], [0, -1]];
77
+ const dirOf = (v) => DIRS.findIndex((d) => d[0] === v[0] && d[1] === v[1]);
78
+ const SWAP = { top: "left", left: "top", bottom: "right", right: "bottom" };
79
+ export function anchorOf(box, side) {
80
+ if (side === "top")
81
+ return [box.x, box.top];
82
+ if (side === "bottom")
83
+ return [box.x, box.bottom];
84
+ return [side === "left" ? box.left : box.right, box.y];
76
85
  }
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,
86
+ const grow = (box, by) => ({
87
+ ...box, left: box.left - by, right: box.right + by, top: box.top - by, bottom: box.bottom + by,
88
+ width: box.width + 2 * by, height: box.height + 2 * by,
80
89
  });
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),
90
+ const holds = (frame, box) => frame.left <= box.left + 1 && frame.right >= box.right - 1 && frame.top <= box.top + 1 && frame.bottom >= box.bottom - 1;
91
+ const inside = (box, [x, y]) => x > box.left + 0.01 && x < box.right - 0.01 && y > box.top + 0.01 && y < box.bottom - 0.01;
92
+ /* Whether an axis-aligned segment passes through the inside of a box. */
93
+ const through = (a, b, box) => Math.max(a[0], b[0]) > box.left + 0.01 && Math.min(a[0], b[0]) < box.right - 0.01
94
+ && Math.max(a[1], b[1]) > box.top + 0.01 && Math.min(a[1], b[1]) < box.bottom - 0.01;
95
+ /* `route` names a path relative to the flow; it becomes the sides it uses.
96
+ Left to right the names hold with the axes swapped. */
97
+ function forced(edge, source, target, flow) {
98
+ if (!edge.route)
99
+ return null;
100
+ const turned = flow === "right";
101
+ const along = (box) => turned ? box.x : box.y;
102
+ const across = (box) => turned ? box.y : box.x;
103
+ const ahead = along(target) >= along(source);
104
+ const toward = across(target) >= across(source) ? "right" : "left";
105
+ const away = toward === "right" ? "left" : "right";
106
+ const pair = edge.route === "side" ? [toward, away]
107
+ : edge.route === "down" ? [ahead ? "bottom" : "top", ahead ? "top" : "bottom"]
108
+ : [ahead ? "bottom" : "top", away];
109
+ return turned ? [SWAP[pair[0]], SWAP[pair[1]]] : pair;
110
+ }
111
+ /* The side of a box an anchor sits on. */
112
+ function sideAt(box, [x, y]) {
113
+ return SIDES.find((side) => {
114
+ const a = anchorOf(box, side);
115
+ return Math.abs(a[0] - x) < 0.5 && Math.abs(a[1] - y) < 0.5;
116
+ }) ?? null;
117
+ }
118
+ const kindOf = (edge) => `${edge.series ?? ""}|${edge.line ?? ""}|${edge.tone ?? ""}|${edge.flow ?? ""}`;
119
+ export function route(measured, nodes, flow, frames = [], titles = []) {
120
+ const pairs = [];
121
+ for (const { edge, target, sources } of measured) {
122
+ sources.forEach((source, index) => {
123
+ if (source.id === target.id)
124
+ return;
125
+ const pick = forced(edge, source, target, flow);
126
+ pairs.push({
127
+ edge, source, target, labelled: index === 0,
128
+ from: edge.fromSide ? [edge.fromSide] : pick ? [pick[0]] : SIDES,
129
+ to: edge.toSide ? [edge.toSide] : pick ? [pick[1]] : SIDES,
130
+ });
131
+ });
132
+ }
133
+ // Short edges go first, so they keep the straight lines.
134
+ const span = (pair) => Math.abs(pair.source.x - pair.target.x) + Math.abs(pair.source.y - pair.target.y);
135
+ const order = pairs.map((_, index) => index).sort((a, b) => span(pairs[a]) - span(pairs[b]) || a - b);
136
+ const forward = flow === "right" ? ["right", "left"] : ["bottom", "top"];
137
+ // Group borders count as runs too, so no edge runs along one.
138
+ const runs = frames.flatMap((frame) => {
139
+ const corners = [[frame.left, frame.top], [frame.right, frame.top], [frame.right, frame.bottom], [frame.left, frame.bottom]];
140
+ return corners.map((a, k) => ({ a, b: corners[(k + 1) % 4], kind: "", source: "", target: "", border: true }));
141
+ });
142
+ // An anchor an edge comes into is not one an edge leaves by, and the
143
+ // other way round, so an arrow never points at a line going out.
144
+ const used = new Map();
145
+ const found = [];
146
+ for (const index of order) {
147
+ const pair = pairs[index];
148
+ const points = search(pair, nodes, frames, titles, runs, forward, used);
149
+ found[index] = points;
150
+ const kind = kindOf(pair.edge);
151
+ for (let j = 0; j < points.length - 1; j++)
152
+ runs.push({ a: points[j], b: points[j + 1], kind, source: pair.source.id, target: pair.target.id });
153
+ const out = sideAt(pair.source, points[0]);
154
+ const into = sideAt(pair.target, points[points.length - 1]);
155
+ if (out)
156
+ used.set(`${pair.source.id}:${out}`, "out");
157
+ if (into)
158
+ used.set(`${pair.target.id}:${into}`, "in");
159
+ }
160
+ const routes = pairs.map((pair, index) => ({
161
+ key: `${pair.edge.key}:${pair.source.id}`, points: found[index], arrow: true, look: look(pair.edge),
162
+ ends: [pair.source.id, pair.target.id], ...(pair.edge.toSide ? { pinned: true } : {}),
88
163
  }));
164
+ trunks(routes, pairs);
165
+ pairs.forEach((pair, index) => {
166
+ const item = routes[index];
167
+ if (!pair.labelled || !pair.edge.label)
168
+ return;
169
+ const run = longest(item.points);
170
+ const flat = item.points.length === 2 && !isVertical(item.points[0], item.points[1]);
171
+ item.label = { text: pair.edge.label, run, ...(flat ? { along: 0.5, room: dist(item.points[0], item.points[1]) - ARROW } : {}) };
172
+ });
173
+ return routes;
89
174
  }
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;
175
+ function longest(points) {
176
+ let best = 0;
177
+ for (let j = 1; j < points.length - 1; j++)
178
+ if (dist(points[j], points[j + 1]) > dist(points[best], points[best + 1]) + 0.5)
179
+ best = j;
180
+ return best;
98
181
  }
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))
182
+ /* Coordinates of a search grid, each one exact: no rounding, so no run
183
+ slants. The anchors and their stubs stay as they are; any other
184
+ coordinate closer than 3px to one already kept is left out. */
185
+ function axis(keys, rest) {
186
+ const kept = [...new Set(keys)];
187
+ for (const value of rest)
188
+ if (Number.isFinite(value) && kept.every((other) => Math.abs(other - value) >= 3))
189
+ kept.push(value);
190
+ kept.sort((a, b) => a - b);
191
+ const mids = [];
192
+ for (let k = 0; k < kept.length - 1; k++)
193
+ if (kept[k + 1] - kept[k] >= 2 * LANE)
194
+ mids.push((kept[k] + kept[k + 1]) / 2);
195
+ return [...kept, ...mids].sort((a, b) => a - b);
196
+ }
197
+ function lowerBound(list, value) {
198
+ let lo = 0;
199
+ let hi = list.length;
200
+ while (lo < hi) {
201
+ const mid = (lo + hi) >> 1;
202
+ if (list[mid] < value)
203
+ lo = mid + 1;
204
+ else
205
+ hi = mid;
206
+ }
207
+ return lo;
208
+ }
209
+ /* The cheapest path for one edge. It looks near the two nodes first, then
210
+ across the whole drawing, then through the groups that hold neither end.
211
+ With no clear path at all it takes an elbow and says so once. */
212
+ function search(pair, nodes, frames, titles, runs, forward, used) {
213
+ const { source, target } = pair;
214
+ const area = {
215
+ left: Math.min(source.left, target.left) - REACH, right: Math.max(source.right, target.right) + REACH,
216
+ top: Math.min(source.top, target.top) - REACH, bottom: Math.max(source.bottom, target.bottom) + REACH,
217
+ };
218
+ const walls = (strict) => [
219
+ ...nodes.map((node) => grow(node, PAD)),
220
+ ...titles.map((title) => grow(title, 4)),
221
+ ...(strict ? frames.filter((frame) => !holds(frame, source) && !holds(frame, target)).map((frame) => grow(frame, 4)) : []),
222
+ ];
223
+ for (const [strict, near] of [[true, true], [true, false], [false, false]]) {
224
+ for (const into of [IN, OUT]) {
225
+ const points = cheapest(pair, walls(strict), runs, forward, used, near ? area : null, into);
226
+ if (points)
227
+ return points;
228
+ }
229
+ }
230
+ warn(`${pair.edge.key}:${source.id}`, `Diagram: the edge ${source.id} -> ${target.id} finds no clear path, so it runs through what is in the way. Move a node, or set fromSide and toSide on the edge.`);
231
+ const a = anchorOf(source, forward[0]);
232
+ const b = anchorOf(target, forward[1]);
233
+ return clean([a, [a[0], (a[1] + b[1]) / 2], [b[0], (a[1] + b[1]) / 2], b]);
234
+ }
235
+ function cheapest(pair, walls, runs, forward, used, area, into) {
236
+ const { source, target } = pair;
237
+ const kind = kindOf(pair.edge);
238
+ const own = [grow(source, PAD), grow(target, PAD)];
239
+ const others = walls.filter((wall) => !own.some((item) => item.left === wall.left && item.top === wall.top && item.right === wall.right && item.bottom === wall.bottom));
240
+ const clear = (a, b) => !others.some((wall) => through(a, b, wall));
241
+ // A side along the flow costs a little less; an anchor taken the other
242
+ // way costs as much as a long detour.
243
+ const prefer = (box, side, best, way) => {
244
+ const taken = used.get(`${box.id}:${side}`);
245
+ return (side === best ? 0 : 2) + (taken && taken !== way ? TAKEN : 0);
246
+ };
247
+ const starts = pair.from.flatMap((side) => {
248
+ const a = anchorOf(source, side);
249
+ const n = NORMAL[side];
250
+ const p = [a[0] + n[0] * OUT, a[1] + n[1] * OUT];
251
+ return clear(a, p) && !inside(own[1], p) ? [{ side, a, p, dir: dirOf(n), cost: prefer(source, side, forward[0], "out") }] : [];
252
+ });
253
+ const ends = pair.to.flatMap((side) => {
254
+ const a = anchorOf(target, side);
255
+ const n = NORMAL[side];
256
+ const p = [a[0] + n[0] * into, a[1] + n[1] * into];
257
+ return clear(p, a) && !inside(own[0], p) ? [{ side, a, p, dir: dirOf([-n[0], -n[1]]), cost: prefer(target, side, forward[1], "in") }] : [];
258
+ });
259
+ // Two anchors that face each other on one line join straight.
260
+ let direct = null;
261
+ for (const start of pair.from) {
262
+ for (const end of pair.to) {
263
+ const a = anchorOf(source, start);
264
+ const b = anchorOf(target, end);
265
+ const n = NORMAL[start];
266
+ const m = NORMAL[end];
267
+ if (n[0] !== -m[0] || n[1] !== -m[1])
113
268
  continue;
114
- if (node.bottom <= source.bottom || node.top >= port.extent)
269
+ const ahead = (b[0] - a[0]) * n[0] + (b[1] - a[1]) * n[1];
270
+ if (ahead < ARROW + 2 || Math.abs((b[0] - a[0]) * n[1] - (b[1] - a[1]) * n[0]) > 0.5)
115
271
  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
- });
272
+ if (!clear(a, b))
273
+ continue;
274
+ const cost = ahead + prefer(source, start, forward[0], "out") + prefer(target, end, forward[1], "in") + crossings(a, b, runs);
275
+ if (!direct || cost < direct.cost)
276
+ direct = { cost, points: [a, b] };
123
277
  }
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
- });
278
+ }
279
+ if (!starts.length || !ends.length)
280
+ return direct?.points ?? null;
281
+ const inArea = (value, lo, hi) => value >= lo && value <= hi;
282
+ const pick = (values, lo, hi) => area ? values.filter((value) => inArea(value, lo, hi)) : values;
283
+ const keyX = [...starts.flatMap((item) => [item.p[0], item.a[0]]), ...ends.flatMap((item) => [item.p[0], item.a[0]])];
284
+ const keyY = [...starts.flatMap((item) => [item.p[1], item.a[1]]), ...ends.flatMap((item) => [item.p[1], item.a[1]])];
285
+ const lanesX = runs.flatMap((run) => isVertical(run.a, run.b) ? [run.a[0], run.a[0] - LANE, run.a[0] + LANE] : []);
286
+ const lanesY = runs.flatMap((run) => isVertical(run.a, run.b) ? [] : [run.a[1], run.a[1] - LANE, run.a[1] + LANE]);
287
+ const boundsX = walls.flatMap((wall) => [wall.left, wall.right]);
288
+ const boundsY = walls.flatMap((wall) => [wall.top, wall.bottom]);
289
+ const lo = area ?? { left: Math.min(...boundsX, ...keyX) - 2 * LANE, right: Math.max(...boundsX, ...keyX) + 2 * LANE, top: Math.min(...boundsY, ...keyY) - 2 * LANE, bottom: Math.max(...boundsY, ...keyY) + 2 * LANE };
290
+ const xs = axis(keyX, [...pick(boundsX, lo.left, lo.right), ...pick(lanesX, lo.left, lo.right), lo.left, lo.right]);
291
+ const ys = axis(keyY, [...pick(boundsY, lo.top, lo.bottom), ...pick(lanesY, lo.top, lo.bottom), lo.top, lo.bottom]);
292
+ const nx = xs.length;
293
+ const ny = ys.length;
294
+ const at = (i, j) => j * nx + i;
295
+ // Runs between neighbouring grid points: blocked, beside another edge,
296
+ // on one of its own kind, or across one.
297
+ const blockH = new Uint8Array(nx * ny);
298
+ const blockV = new Uint8Array(nx * ny);
299
+ const nearH = new Uint8Array(nx * ny);
300
+ const nearV = new Uint8Array(nx * ny);
301
+ const joinH = new Uint8Array(nx * ny);
302
+ const joinV = new Uint8Array(nx * ny);
303
+ const crossH = new Float64Array(nx * ny);
304
+ const crossV = new Float64Array(nx * ny);
305
+ for (const wall of walls) {
306
+ const i0 = Math.max(0, lowerBound(xs, wall.left) - 1);
307
+ const i1 = lowerBound(xs, wall.right);
308
+ const j0 = Math.max(0, lowerBound(ys, wall.top) - 1);
309
+ const j1 = lowerBound(ys, wall.bottom);
310
+ for (let j = j0; j <= j1 && j < ny; j++) {
311
+ for (let i = i0; i <= i1 && i < nx; i++) {
312
+ if (i + 1 < nx && through([xs[i], ys[j]], [xs[i + 1], ys[j]], wall))
313
+ blockH[at(i, j)] = 1;
314
+ if (j + 1 < ny && through([xs[i], ys[j]], [xs[i], ys[j + 1]], wall))
315
+ blockV[at(i, j)] = 1;
134
316
  }
135
317
  }
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;
318
+ }
319
+ for (const run of runs) {
320
+ const friend = run.kind === kind && (run.source === source.id || run.target === target.id);
321
+ const x0 = Math.min(run.a[0], run.b[0]);
322
+ const x1 = Math.max(run.a[0], run.b[0]);
323
+ const y0 = Math.min(run.a[1], run.b[1]);
324
+ const y1 = Math.max(run.a[1], run.b[1]);
325
+ if (isVertical(run.a, run.b)) {
326
+ const x = run.a[0];
327
+ for (let i = lowerBound(xs, x - LANE + 0.5); i < nx && xs[i] < x + LANE - 0.5; i++) {
328
+ const on = Math.abs(xs[i] - x) < 0.5;
329
+ for (let j = lowerBound(ys, y0); j + 1 < ny && ys[j] < y1 - 0.5; j++) {
330
+ if (on && friend)
331
+ joinV[at(i, j)] = 1;
332
+ else
333
+ nearV[at(i, j)] = 1;
334
+ }
335
+ }
336
+ // Flat runs across this one.
337
+ const i = lowerBound(xs, x) - 1;
338
+ if (!run.border && i >= 0 && i + 1 < nx)
339
+ for (let j = lowerBound(ys, y0 + 0.5); j < ny && ys[j] < y1 - 0.5; j++)
340
+ crossH[at(i, j)] += CROSS;
341
+ }
342
+ else {
343
+ const y = run.a[1];
344
+ for (let j = lowerBound(ys, y - LANE + 0.5); j < ny && ys[j] < y + LANE - 0.5; j++) {
345
+ const on = Math.abs(ys[j] - y) < 0.5;
346
+ for (let i = lowerBound(xs, x0); i + 1 < nx && xs[i] < x1 - 0.5; i++) {
347
+ if (on && friend)
348
+ joinH[at(i, j)] = 1;
349
+ else
350
+ nearH[at(i, j)] = 1;
351
+ }
352
+ }
353
+ const j = lowerBound(ys, y) - 1;
354
+ if (!run.border && j >= 0 && j + 1 < ny)
355
+ for (let i = lowerBound(xs, x0 + 0.5); i < nx && xs[i] < x1 - 0.5; i++)
356
+ crossV[at(i, j)] += CROSS;
145
357
  }
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
358
  }
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]);
359
+ // Dijkstra over grid points and the direction each was reached in. The
360
+ // last state is the sink every end leads to.
361
+ const count = nx * ny * 4;
362
+ const sink = count;
363
+ const cost = new Float64Array(count + 1).fill(Infinity);
364
+ const prev = new Int32Array(count + 1).fill(-1);
365
+ const heap = new Heap();
366
+ const endAt = new Map();
367
+ const startAt = new Map();
368
+ const indexOf = ([x, y]) => {
369
+ const i = lowerBound(xs, x - 0.01);
370
+ const j = lowerBound(ys, y - 0.01);
371
+ return i < nx && j < ny && Math.abs(xs[i] - x) < 0.01 && Math.abs(ys[j] - y) < 0.01 ? at(i, j) : -1;
372
+ };
373
+ for (const end of ends) {
374
+ const k = indexOf(end.p);
375
+ if (k >= 0)
376
+ endAt.set(k, [...(endAt.get(k) ?? []), end]);
184
377
  }
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)
378
+ for (const start of starts) {
379
+ const k = indexOf(start.p);
380
+ if (k < 0)
194
381
  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]));
382
+ const state = k * 4 + start.dir;
383
+ if (start.cost + OUT < cost[state]) {
384
+ cost[state] = start.cost + OUT;
385
+ startAt.set(state, start);
386
+ heap.push(state, cost[state]);
387
+ }
201
388
  }
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) });
389
+ const closing = new Map();
390
+ while (heap.size) {
391
+ const [state, value] = heap.pop();
392
+ if (value > cost[state])
393
+ continue;
394
+ if (state === sink)
395
+ break;
396
+ const k = state >> 2;
397
+ const d = state & 3;
398
+ const i = k % nx;
399
+ const j = (k - i) / nx;
400
+ for (const end of endAt.get(k) ?? []) {
401
+ if (d === (end.dir + 2) % 4)
402
+ continue;
403
+ const total = value + (d === end.dir ? 0 : BEND) + into + end.cost;
404
+ if (total < cost[sink]) {
405
+ cost[sink] = total;
406
+ prev[sink] = state;
407
+ closing.set(state, end);
408
+ heap.push(sink, total);
210
409
  }
211
- else if (pair.kind === "down" && x >= target.left + RADIUS && x <= target.right - RADIUS) {
212
- plans.push({ pair, x, enter: "top", fixed: x });
410
+ }
411
+ for (let nd = 0; nd < 4; nd++) {
412
+ if (nd === (d + 2) % 4)
413
+ continue;
414
+ let ni = i;
415
+ let nj = j;
416
+ let step = 0;
417
+ let extra = 0;
418
+ let near = 0;
419
+ let join = 0;
420
+ if (nd === 0) {
421
+ if (i + 1 >= nx || blockH[k])
422
+ continue;
423
+ ni = i + 1;
424
+ step = xs[ni] - xs[i];
425
+ extra = crossH[k];
426
+ near = nearH[k];
427
+ join = joinH[k];
428
+ }
429
+ else if (nd === 2) {
430
+ if (i === 0 || blockH[k - 1])
431
+ continue;
432
+ ni = i - 1;
433
+ step = xs[i] - xs[ni];
434
+ extra = crossH[k - 1];
435
+ near = nearH[k - 1];
436
+ join = joinH[k - 1];
437
+ }
438
+ else if (nd === 1) {
439
+ if (j + 1 >= ny || blockV[k])
440
+ continue;
441
+ nj = j + 1;
442
+ step = ys[nj] - ys[j];
443
+ extra = crossV[k];
444
+ near = nearV[k];
445
+ join = joinV[k];
213
446
  }
214
447
  else {
215
- plans.push({ pair, x, enter: x < target.x ? "left" : "right", near: !far });
448
+ if (j === 0 || blockV[k - nx])
449
+ continue;
450
+ nj = j - 1;
451
+ step = ys[j] - ys[nj];
452
+ extra = crossV[k - nx];
453
+ near = nearV[k - nx];
454
+ join = joinV[k - nx];
216
455
  }
217
- });
456
+ const next = at(ni, nj) * 4 + nd;
457
+ const total = value + step * (near ? NEAR : join ? JOIN : 1) + extra + (nd === d ? 0 : BEND);
458
+ if (total < cost[next]) {
459
+ cost[next] = total;
460
+ prev[next] = state;
461
+ heap.push(next, total);
462
+ }
463
+ }
218
464
  }
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" });
465
+ if (cost[sink] === Infinity)
466
+ return direct?.points ?? null;
467
+ if (direct && direct.cost <= cost[sink])
468
+ return direct.points;
469
+ const last = prev[sink];
470
+ const end = closing.get(last);
471
+ const grid = [];
472
+ let state = last;
473
+ let first = last;
474
+ while (state >= 0) {
475
+ const k = state >> 2;
476
+ grid.push([xs[k % nx], ys[Math.floor(k / nx)]]);
477
+ first = state;
478
+ state = prev[state];
221
479
  }
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
- }
480
+ grid.reverse();
481
+ return clean([startAt.get(first).a, ...grid, end.a]);
482
+ }
483
+ /* The price of a straight run across the edges already drawn. */
484
+ function crossings(a, b, runs) {
485
+ let total = 0;
486
+ for (const run of runs) {
487
+ if (run.border || isVertical(a, b) === isVertical(run.a, run.b))
488
+ continue;
489
+ const [v, h] = isVertical(a, b) ? [[a, b], [run.a, run.b]] : [[run.a, run.b], [a, b]];
490
+ const x = v[0][0];
491
+ const y = h[0][1];
492
+ if (x > Math.min(h[0][0], h[1][0]) + 0.5 && x < Math.max(h[0][0], h[1][0]) - 0.5 && y > Math.min(v[0][1], v[1][1]) + 0.5 && y < Math.max(v[0][1], v[1][1]) - 0.5)
493
+ total += CROSS;
252
494
  }
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);
495
+ return total;
496
+ }
497
+ /* A binary heap of states by cost. */
498
+ class Heap {
499
+ items = [];
500
+ costs = [];
501
+ get size() {
502
+ return this.items.length;
290
503
  }
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 });
504
+ push(item, value) {
505
+ const items = this.items;
506
+ const costs = this.costs;
507
+ let k = items.length;
508
+ items.push(item);
509
+ costs.push(value);
510
+ while (k > 0) {
511
+ const up = (k - 1) >> 1;
512
+ if (costs[up] <= value)
513
+ break;
514
+ items[k] = items[up];
515
+ costs[k] = costs[up];
516
+ k = up;
517
+ }
518
+ items[k] = item;
519
+ costs[k] = value;
299
520
  }
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;
521
+ pop() {
522
+ const items = this.items;
523
+ const costs = this.costs;
524
+ const top = [items[0], costs[0]];
525
+ const item = items.pop();
526
+ const value = costs.pop();
527
+ if (items.length) {
528
+ let k = 0;
529
+ for (;;) {
530
+ const l = 2 * k + 1;
531
+ const r = l + 1;
532
+ let m = k;
533
+ let best = value;
534
+ if (l < items.length && costs[l] < best) {
535
+ m = l;
536
+ best = costs[l];
537
+ }
538
+ if (r < items.length && costs[r] < best)
539
+ m = r;
540
+ if (m === k)
541
+ break;
542
+ items[k] = items[m];
543
+ costs[k] = costs[m];
544
+ k = m;
330
545
  }
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]]);
546
+ items[k] = item;
547
+ costs[k] = value;
343
548
  }
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;
549
+ return top;
550
+ }
551
+ }
552
+ /* Where two paths from one point part: the length they share and the point
553
+ they part at. */
554
+ function shared(a, b) {
555
+ if (dist(a[0], b[0]) > 0.5)
556
+ return { length: 0, at: a[0], j: 0 };
557
+ let length = 0;
558
+ let at = a[0];
559
+ let j = 0;
560
+ let k = 0;
561
+ while (j < a.length - 1 && k < b.length - 1) {
562
+ const da = unit(at, a[j + 1]);
563
+ const db = unit(at, b[k + 1]);
564
+ if (Math.abs(da[0] - db[0]) > 0.01 || Math.abs(da[1] - db[1]) > 0.01)
565
+ break;
566
+ const step = Math.min(dist(at, a[j + 1]), dist(at, b[k + 1]));
567
+ at = towards(at, a[j + 1], step);
568
+ length += step;
569
+ if (dist(at, a[j + 1]) < 0.5) {
570
+ at = a[j + 1];
571
+ j++;
363
572
  }
364
- routes.push({ key, points, arrow: true, look: look(edge), ends, dot, label: pair.labelled && edge.label ? { text: edge.label, run } : undefined });
573
+ if (dist(at, b[k + 1]) < 0.5)
574
+ k++;
365
575
  }
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;
576
+ return { length, at, j };
577
+ }
578
+ const total = (points) => points.reduce((sum, p, k) => k ? sum + dist(points[k - 1], p) : 0, 0);
579
+ /* Edges of one kind out of one anchor share a trunk: the longest keeps it,
580
+ and each other leaves it at a dot, RADIUS before it turns away. Edges of
581
+ one kind into one anchor join the same way, at a dot where they meet. */
582
+ function trunks(routes, pairs) {
583
+ const groups = new Map();
584
+ routes.forEach((item, index) => {
585
+ const start = item.points[0];
586
+ const key = `${pairs[index].source.id}|${start[0]}|${start[1]}|${kindOf(pairs[index].edge)}`;
587
+ groups.set(key, [...(groups.get(key) ?? []), index]);
588
+ });
589
+ for (const list of groups.values()) {
590
+ if (list.length < 2)
591
+ continue;
592
+ const sorted = [...list].sort((a, b) => total(routes[b].points) - total(routes[a].points));
593
+ const full = sorted.map((index) => routes[index].points);
594
+ sorted.forEach((index, n) => {
595
+ if (!n)
596
+ return;
597
+ const mine = full[n];
598
+ let best = { length: 0, at: mine[0], j: 0 };
599
+ for (let m = 0; m < n; m++) {
600
+ const found = shared(mine, full[m]);
601
+ if (found.length > best.length)
602
+ best = found;
603
+ }
604
+ if (best.length < 1)
605
+ return;
606
+ const back = Math.min(RADIUS, best.length);
607
+ const before = best.j < mine.length - 1 && dist(best.at, mine[best.j]) > 0.5 ? mine[best.j] : mine[Math.max(0, best.j - 1)];
608
+ const dot = towards(best.at, before, back);
609
+ const rest = mine.slice(best.j + 1);
610
+ routes[index].points = clean([dot, best.at, ...rest]);
611
+ routes[index].dot = dot;
612
+ });
613
+ }
614
+ const joins = new Map();
615
+ routes.forEach((item, index) => {
616
+ if (item.dot)
617
+ return;
618
+ const end = item.points[item.points.length - 1];
619
+ const key = `${pairs[index].target.id}|${end[0]}|${end[1]}|${kindOf(pairs[index].edge)}`;
620
+ joins.set(key, [...(joins.get(key) ?? []), index]);
621
+ });
622
+ for (const list of joins.values()) {
623
+ if (list.length < 2)
624
+ continue;
625
+ const sorted = [...list].sort((a, b) => total(routes[b].points) - total(routes[a].points));
626
+ const full = sorted.map((index) => [...routes[index].points].reverse());
627
+ sorted.forEach((index, n) => {
628
+ if (!n)
629
+ return;
630
+ const mine = full[n];
631
+ let best = { length: 0, at: mine[0], j: 0 };
632
+ for (let m = 0; m < n; m++) {
633
+ const found = shared(mine, full[m]);
634
+ if (found.length > best.length)
635
+ best = found;
636
+ }
637
+ if (best.length < ARROW + RADIUS)
638
+ return;
639
+ const before = best.j < mine.length - 1 && dist(best.at, mine[best.j]) > 0.5 ? mine[best.j] : mine[Math.max(0, best.j - 1)];
640
+ const dot = towards(best.at, before, Math.min(RADIUS, best.length));
641
+ routes[index].points = clean([dot, best.at, ...mine.slice(best.j + 1)].reverse());
642
+ routes[index].dot = dot;
643
+ routes[index].arrow = false;
644
+ });
372
645
  }
373
- if (stages)
374
- fork(routes, plans, listOf);
375
- checkNodes(routes, nodes);
376
- return routes;
377
646
  }
378
647
  /* The segment of a path that holds a point, or -1. */
379
648
  function holding(points, at) {
@@ -383,88 +652,6 @@ function holding(points, at) {
383
652
  && Math.min(a[1], b[1]) - 0.5 <= at[1] && at[1] <= Math.max(a[1], b[1]) + 0.5;
384
653
  });
385
654
  }
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
655
  const warned = new Set();
469
656
  function warn(key, message) {
470
657
  if (warned.has(key))
@@ -472,24 +659,6 @@ function warn(key, message) {
472
659
  warned.add(key);
473
660
  console.warn(message);
474
661
  }
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
662
  const unit = (a, b) => {
494
663
  const n = dist(a, b) || 1;
495
664
  return [(b[0] - a[0]) / n, (b[1] - a[1]) / n];
@@ -640,18 +809,17 @@ function shaped(routes, i, shape, boxes) {
640
809
  add(E);
641
810
  return { d, samples, from };
642
811
  }
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.
812
+ // Straight. Anchors are picked for elbows, so a steep line into a side
813
+ // comes in through the anchor on the top or bottom instead, with a
814
+ // straight SETTLE run into it, unless the edge set its side.
646
815
  let end = E;
647
816
  let stub = null;
648
- const box = route.ends ? boxes?.get(route.ends[1]) : undefined;
817
+ const box = route.ends && !route.pinned ? boxes?.get(route.ends[1]) : undefined;
649
818
  if (box) {
650
819
  const v = [E[0] - P[0], E[1] - P[1]];
651
820
  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
821
  if (intoSide && Math.abs(v[1]) > 1.5 * Math.abs(v[0])) {
654
- const x = clampTo(E[0], box.left + 20, box.right - 20);
822
+ const x = box.x;
655
823
  const y = v[1] > 0 ? box.top : box.bottom;
656
824
  const run = [x, y - Math.sign(v[1]) * SETTLE];
657
825
  // Only when the new face still lies ahead, steeply: a target stacked
@@ -1010,6 +1178,61 @@ export function draw(routes, frames, crossings, labels, measure, style = {}) {
1010
1178
  });
1011
1179
  }
1012
1180
  const drawn = { paths: [], labels: [], plates, dots: [] };
1181
+ // A label tries its own run first, then the others, longest first, at a
1182
+ // few spots along each, and takes the first that runs into nothing.
1183
+ const walls = [...(style.boxes?.values() ?? []), ...(style.blocks ?? [])];
1184
+ const taken = [];
1185
+ const settle = (route, i) => {
1186
+ const label = route.label;
1187
+ const length = (j) => dist(route.points[j], route.points[j + 1]);
1188
+ const others = route.points.slice(0, -1).map((_, j) => j).filter((j) => j !== label.run).sort((a, b) => length(b) - length(a));
1189
+ let best = null;
1190
+ let score = Infinity;
1191
+ search: for (const run of [label.run, ...others]) {
1192
+ for (const along of [run === label.run ? label.along : 0.5, 0.3, 0.7, 0.15, 0.85]) {
1193
+ const tried = place({ ...route, label: run === label.run ? { ...label, along } : { text: label.text, run, along } }, found, i, labels, measure, frames);
1194
+ if (!tried)
1195
+ continue;
1196
+ const count = hits(boxOf(tried, measure), i, routes, walls, taken, frames);
1197
+ if (count < score) {
1198
+ best = tried;
1199
+ score = count;
1200
+ }
1201
+ if (!count)
1202
+ break search;
1203
+ }
1204
+ }
1205
+ // Nothing on the line is clear, such as a long label between two cards
1206
+ // close together: it sits flat on a plate at the nearest clear spot
1207
+ // around the middle of its run, above or below, left or right.
1208
+ if (score) {
1209
+ const p = route.points[label.run];
1210
+ const q = route.points[label.run + 1];
1211
+ const mid = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
1212
+ const size = measure(label.text);
1213
+ const near = (x, y) => ({
1214
+ key: route.key, x, y, lines: [label.text], middle: true,
1215
+ plate: { key: route.key, x: x - size.width / 2 - 3, y: y - size.height / 2, width: size.width + 6, height: size.height },
1216
+ });
1217
+ // Past every card, label, run and frame, a spot is always clear, so
1218
+ // the search reaches that far.
1219
+ const xs = [...walls.flatMap((box) => [box.left, box.right]), ...taken.flatMap((rect) => [rect.x, rect.x + rect.width]), ...routes.flatMap((item) => item.points.map((pt) => pt[0])), ...frames.flatMap((frame) => [frame.left, frame.right])];
1220
+ const ys = [...walls.flatMap((box) => [box.top, box.bottom]), ...taken.flatMap((rect) => [rect.y, rect.y + rect.height]), ...routes.flatMap((item) => item.points.map((pt) => pt[1])), ...frames.flatMap((frame) => [frame.top, frame.bottom])];
1221
+ const reach = Math.max(...xs.map((x) => Math.abs(x - mid[0])), ...ys.map((y) => Math.abs(y - mid[1]))) + size.width + size.height + 8;
1222
+ clear: for (let step = 4; step <= reach + 4; step += 4) {
1223
+ for (const [dx, dy] of [[0, -1], [0, 1], [-1, 0], [1, 0]]) {
1224
+ const tried = near(mid[0] + dx * step, mid[1] + dy * step);
1225
+ if (!hits(boxOf(tried, measure), i, routes, walls, taken, frames)) {
1226
+ best = tried;
1227
+ break clear;
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+ if (best)
1233
+ taken.push(boxOf(best, measure));
1234
+ return best;
1235
+ };
1013
1236
  routes.forEach((route, i) => {
1014
1237
  const { points, rad } = shapes[i];
1015
1238
  const shaped = free[i];
@@ -1042,9 +1265,10 @@ export function draw(routes, frames, crossings, labels, measure, style = {}) {
1042
1265
  key: route.key, x: mid[0], y: mid[1], lines: [route.label.text], middle: true,
1043
1266
  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
1267
  });
1268
+ taken.push(drawn.labels[drawn.labels.length - 1].plate);
1045
1269
  }
1046
1270
  else if (route.label) {
1047
- const placed = place(route, found, i, labels, measure, frames);
1271
+ const placed = settle(route, i);
1048
1272
  if (placed)
1049
1273
  drawn.labels.push(placed);
1050
1274
  }
@@ -1082,13 +1306,53 @@ export function draw(routes, frames, crossings, labels, measure, style = {}) {
1082
1306
  if (route.dot)
1083
1307
  drawn.dots.push({ key: route.key, x: route.dot[0], y: route.dot[1], ...route.look });
1084
1308
  if (route.label) {
1085
- const placed = place(route, found, i, labels, measure, frames);
1309
+ const placed = settle(route, i);
1086
1310
  if (placed)
1087
1311
  drawn.labels.push(placed);
1088
1312
  }
1089
1313
  });
1090
1314
  return drawn;
1091
1315
  }
1316
+ /* A label's box: its plate, or the room its text takes about its baseline. */
1317
+ function boxOf(item, measure) {
1318
+ if (item.plate)
1319
+ return item.plate;
1320
+ const sizes = item.lines.map(measure);
1321
+ const width = Math.max(...sizes.map((size) => size.width));
1322
+ const height = sizes[0].height;
1323
+ const above = height * 0.75 + (item.lines.length - 1) * height * 1.2;
1324
+ const left = item.anchor === "start" ? item.x : item.x - width / 2;
1325
+ return { key: item.key, x: left, y: item.y - above, width, height: above + height * 0.25 };
1326
+ }
1327
+ /* What a label's box runs into: a card or a group title counts four, as
1328
+ does a label already placed, a group border two, and each run of another
1329
+ edge one. */
1330
+ function hits(rect, index, routes, walls, taken, frames) {
1331
+ const area = { left: rect.x, right: rect.x + rect.width, top: rect.y, bottom: rect.y + rect.height };
1332
+ const meets = (box) => box.left < area.right && box.right > area.left && box.top < area.bottom && box.bottom > area.top;
1333
+ let count = 0;
1334
+ for (const wall of walls)
1335
+ if (meets(wall))
1336
+ count += 4;
1337
+ for (const other of taken)
1338
+ if (meets({ left: other.x, right: other.x + other.width, top: other.y, bottom: other.y + other.height }))
1339
+ count += 4;
1340
+ routes.forEach((route, j) => {
1341
+ if (j === index)
1342
+ return;
1343
+ for (let k = 0; k < route.points.length - 1; k++)
1344
+ if (through(route.points[k], route.points[k + 1], area))
1345
+ count++;
1346
+ });
1347
+ for (const frame of frames) {
1348
+ const corners = [[frame.left, frame.top], [frame.right, frame.top], [frame.right, frame.bottom], [frame.left, frame.bottom]];
1349
+ corners.forEach((a, k) => {
1350
+ if (through(a, corners[(k + 1) % 4], area))
1351
+ count += 2;
1352
+ });
1353
+ }
1354
+ return count;
1355
+ }
1092
1356
  function place(route, found, index, mode, measure, frames) {
1093
1357
  const label = route.label;
1094
1358
  const p = route.points[label.run];
@@ -1149,7 +1413,7 @@ function place(route, found, index, mode, measure, frames) {
1149
1413
  if (end > from)
1150
1414
  free.push([from, end]);
1151
1415
  const need = size.width + 8;
1152
- const middle = (start + end) / 2;
1416
+ const middle = start + (end - start) * (label.along ?? 0.5);
1153
1417
  let centre = null;
1154
1418
  const holding = free.find(([a, b]) => a <= middle && middle <= b && b - a >= need);
1155
1419
  if (holding)