dsh-model-everything 0.5.1 → 0.5.2

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.
@@ -11,23 +11,34 @@
11
11
  * route, not picked by comparing the boxes' centres: a route between two rows arrives vertically, so the endpoint
12
12
  * is snapped onto the top or bottom perimeter in the direction the route approaches. Where along that side it sits
13
13
  * follows the symbol: a rectangle spreads its ports along the side, a cylinder's top port sits on its cap curve, and a
14
- * diamond or a circle has four legal points and no side to spread along at all.
14
+ * diamond or a circle has four legal points and no side to spread along at all. A side that carries one port is
15
+ * centred on it, and a side that carries several spreads them symmetrically about the middle; the bend budget comes
16
+ * first, so a port that is the end of a straight run or of a lane keeps the coordinate its route asked for.
15
17
  *
16
18
  * A symbol with discrete points gives each of its edges a point of its own: the point whose outward normal faces the
17
19
  * box at the other end is the one that edge takes, and an edge only shares a point when all four are spoken for. A
18
20
  * node with a run on its side keeps doing what it always did, because there the ports are places on the run and not
19
21
  * points at all. Sharing is the fallback, not the rule: two labelled branches of a decision leave by two vertices.
20
22
  *
21
- * An edge's name is drawn on the edge, not beside it: it is anchored at the midpoint of the edge's longest straight
22
- * run, over a rectangle in the page colour that masks the line behind the text, and it slides along that run when
23
- * something is in the way. Labels are placed after every edge is drawn, because what a label has to avoid is the
24
- * whole picture.
23
+ * An edge's name is drawn on the edge, not beside it: it is anchored at the midpoint of one of the edge's own straight
24
+ * runs, over a rectangle in the page colour that masks the line behind the text, and it slides along that run when
25
+ * something is in the way. It tries every run - the longest first - because on a dense drawing the longest one can be
26
+ * crowded for its whole length while a shorter run of the same edge is clear. A label that can clear nothing still
27
+ * stays on its edge, takes the place with the fewest collisions, and records what it could not avoid. Labels are
28
+ * placed after every edge is drawn, because what a label has to avoid is the whole picture.
29
+ *
30
+ * Every route is checked before it is drawn, and the assembled drawing is checked once more: a segment may touch no
31
+ * box except the two the edge terminates at. A route is a proposal - a channel run, a lane, a trunk branch, a wrapped
32
+ * column's sideways read - and any proposal that would cross a box is handed to the router instead. When even the
33
+ * router cannot clear a box, the failure is reported on the canvas rather than hidden: a drawing that says which edge
34
+ * could not be routed is worth more than one that quietly draws it through a box.
25
35
  *
26
36
  * Pure: a diagram in, shapes out, every decision assertable.
27
37
  */
28
38
  import { MARGIN, place, textOf } from './place.js';
29
39
  import { PORT_INSET } from './channels.js';
30
40
  import { anchor, approachSides, crossesBox, normalOf, ROUTE_STUB, routeEdge, simplify } from './route.js';
41
+ import { planTrunks } from './trunk.js';
31
42
  import { cylinderApex, cylinderCaps, hasDiscretePorts, hexagonCut, stadiumRadius } from './symbol.js';
32
43
  import { textWidth } from './text.js';
33
44
  import { palette, roleForVerdict } from './palette.js';
@@ -78,6 +89,23 @@ function packPorts(wanted, low, high) {
78
89
  }
79
90
  return placed;
80
91
  }
92
+ /**
93
+ * Centre a row of ports on the side it sits on.
94
+ *
95
+ * The row keeps its order, its gaps and its separation, and is translated as a whole so its outer two ports sit
96
+ * symmetrically about the middle of the span: two ports become the middle less and plus half their gap, and a longer
97
+ * row is the same run of places the routing asked for, moved to where the side has room for it. A row that cannot
98
+ * travel the whole way stops where its last port reaches the end of the span - the alternative is a port off the box.
99
+ */
100
+ function centreRun(placed, low, high) {
101
+ if (placed.length === 0)
102
+ return placed;
103
+ const first = placed[0];
104
+ const last = placed[placed.length - 1];
105
+ const middle = (low + high) / 2;
106
+ const shift = Math.min(high - last, Math.max(low - first, middle - (first + last) / 2));
107
+ return shift === 0 ? placed : placed.map((value) => value + shift);
108
+ }
81
109
  /** Which colour a box earns from its role. One mapping, used by every container. */
82
110
  export function roleOfNode(node) {
83
111
  if (node.role === 'error')
@@ -127,19 +155,42 @@ export const LABEL_HEIGHT = 12;
127
155
  const LABEL_PAD = 2;
128
156
  /** How far a label steps along its own run while it looks for a clear place to sit. */
129
157
  const LABEL_STEP = 3;
130
- /** The point an edge's label is drawn at.
158
+ /** The runs of one edge, longest first. A label prefers the run with the most room. */
159
+ function runsOf(points) {
160
+ const runs = [];
161
+ for (let index = 0; index + 1 < points.length; index += 1) {
162
+ const from = points[index];
163
+ const to = points[index + 1];
164
+ const length = Math.abs(to.x - from.x) + Math.abs(to.y - from.y);
165
+ if (length < 1)
166
+ continue;
167
+ runs.push({ from, to, length, index });
168
+ }
169
+ return runs.sort((left, right) => right.length - left.length || left.index - right.index);
170
+ }
171
+ /**
172
+ * The point an edge's label is drawn at.
131
173
  *
132
- * A label is not furniture parked beside the line: it names the transition, so it sits on the line - anchored at
133
- * the middle of the longest straight run of its own edge - and the writer masks the stretch of line it covers.
134
- * Text beside a line can be read as belonging to whatever it happens to sit next to; text that interrupts its own
135
- * line reads as part of it.
174
+ * A label is not furniture parked beside the line: it names the transition, so it sits on the line - anchored on one
175
+ * of its own straight runs - and the writer masks the stretch of line it covers. Text beside a line can be read as
176
+ * belonging to whatever it happens to sit next to; text that interrupts its own line reads as part of it.
136
177
  *
137
- * The anchor then has to be earned. A mask over a box hides a border, over another label it makes both
138
- * unreadable, and over a third edge's line it hides that line. So the label walks along its own run in small
139
- * steps, in both directions and bounded so its rectangle stays on that run, and takes the first place that is
140
- * clear. It never leaves the run: a label moved onto a neighbouring edge is a label that names the wrong thing.
178
+ * The anchor then has to be earned. A mask over a box hides a border, over another label it makes both unreadable,
179
+ * and over a third edge's line it hides that line. So the label walks along a run in small steps, in both directions
180
+ * and bounded so its rectangle stays on that run, and takes the first place that is clear. It tries the longest run
181
+ * first and then the shorter ones: on a dense drawing the longest run can be crowded for its whole length while a
182
+ * shorter run of the same edge is empty, and a label that gives up after one run leaves the drawing with a collision
183
+ * it did not have to accept.
184
+ *
185
+ * When no run offers a clear place, the label takes the place with the fewest collisions - boxes and other labels
186
+ * first, because text over a border hides the border and text over text is unreadable, then other edges, which a mask
187
+ * merely interrupts. It never leaves its own edge: a label moved onto a neighbouring edge is a label that names the
188
+ * wrong thing. The choice is returned with the label, so a crowded drawing can be told from a placement bug.
189
+ *
190
+ * Exported because the choice is pure and worth asserting without a layout: a test can hand it one polyline, one box
191
+ * and one other route, and read which run it took and what it could not clear.
141
192
  */
142
- function placeLabel(label, from, to, boxes, placed, segments) {
193
+ export function placeLabel(label, points, boxes, placed, otherRoutes) {
143
194
  const width = textWidth(label);
144
195
  const height = LABEL_HEIGHT;
145
196
  const spotAt = (x, y) => ({ x, y, width, height });
@@ -157,51 +208,63 @@ function placeLabel(label, from, to, boxes, placed, segments) {
157
208
  spot.x - spot.width / 2 < Math.max(segment.x1, segment.x2) + LABEL_PAD &&
158
209
  spot.y + spot.height / 2 > Math.min(segment.y1, segment.y2) - LABEL_PAD &&
159
210
  spot.y - spot.height / 2 < Math.max(segment.y1, segment.y2) + LABEL_PAD;
160
- const clearOfBoxes = (spot) => {
211
+ /** Everything one candidate place overlaps, counted by the thing it covers rather than by the segment that draws it. */
212
+ const collisionsAt = (spot, run) => {
213
+ let boxHits = 0;
214
+ let labelHits = 0;
215
+ let edgeHits = 0;
161
216
  for (const box of boxes)
162
217
  if (hitsBox(spot, box))
163
- return false;
218
+ boxHits += 1;
164
219
  for (const earlier of placed)
165
220
  if (hitsSpot(spot, earlier))
166
- return false;
167
- return true;
168
- };
169
- const clearOfEdges = (spot) => {
170
- for (const segment of segments)
171
- if (hitsSegment(spot, segment))
172
- return false;
173
- return true;
221
+ labelHits += 1;
222
+ for (const route of otherRoutes) {
223
+ for (const segment of route) {
224
+ if (!hitsSegment(spot, segment))
225
+ continue;
226
+ edgeHits += 1;
227
+ break;
228
+ }
229
+ }
230
+ return { run, collisions: boxHits + labelHits + edgeHits, boxes: boxHits, labels: labelHits, edges: edgeHits };
174
231
  };
175
- const middle = { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2 };
176
- // The run is axis-aligned, so its Manhattan length is its length.
177
- const dx = to.x - from.x;
178
- const dy = to.y - from.y;
179
- const length = Math.abs(dx) + Math.abs(dy);
180
- const ux = dx / length;
181
- const uy = dy / length;
182
- // The walk is bounded so the label's own rectangle stays on the run that names it: a mask that hangs off the
183
- // end of its segment would be half over the next thing and would not read as sitting on this edge.
184
- const along = (Math.abs(ux) * width) / 2 + (Math.abs(uy) * height) / 2;
185
- const bound = Math.max(0, length / 2 - along);
186
- const walk = [0];
187
- for (let step = LABEL_STEP; step <= bound + 0.001; step += LABEL_STEP)
188
- walk.push(step, -step);
189
- const at = (offset) => spotAt(middle.x + ux * offset, middle.y + uy * offset);
190
- for (const offset of walk) {
191
- const spot = at(offset);
192
- if (clearOfBoxes(spot) && clearOfEdges(spot))
193
- return spot;
232
+ const runs = runsOf(points);
233
+ if (runs.length === 0) {
234
+ // A route with no straight piece has no line to sit on: keep the label at the route's own point rather than move
235
+ // it into the air. Only a degenerate route reaches this, and the writer still draws its mask.
236
+ const point = points[0] ?? { x: 0, y: 0 };
237
+ return { ...spotAt(point.x, point.y), run: -1, collisions: 0, boxes: 0, labels: 0, edges: 0 };
194
238
  }
195
- // Nothing on the run is clear of every other edge - two runs may lie side by side for their whole length, and
196
- // then no place on one is clear of the other. Covering a neighbour's line is the least of the three: text over
197
- // a line still reads, while text over a box hides the box and text over text is unreadable. The label stays
198
- // on its own edge, which is the one thing it may not give up.
199
- for (const offset of walk) {
200
- const spot = at(offset);
201
- if (clearOfBoxes(spot))
202
- return spot;
239
+ let best;
240
+ for (const [runIndex, run] of runs.entries()) {
241
+ const dx = run.to.x - run.from.x;
242
+ const dy = run.to.y - run.from.y;
243
+ const ux = dx / run.length;
244
+ const uy = dy / run.length;
245
+ const middle = { x: (run.from.x + run.to.x) / 2, y: (run.from.y + run.to.y) / 2 };
246
+ // The walk is bounded so the label's own rectangle stays on the run that names it: a mask that hangs off the
247
+ // end of its segment would be half over the next thing and would not read as sitting on this edge.
248
+ const along = (Math.abs(ux) * width) / 2 + (Math.abs(uy) * height) / 2;
249
+ const bound = Math.max(0, run.length / 2 - along);
250
+ const walk = [0];
251
+ for (let step = LABEL_STEP; step <= bound + 0.001; step += LABEL_STEP)
252
+ walk.push(step, -step);
253
+ for (const offset of walk) {
254
+ const spot = spotAt(middle.x + ux * offset, middle.y + uy * offset);
255
+ const placement = collisionsAt(spot, runIndex);
256
+ // A clear place is the answer, and the first one is the preferred one: the search order is already the
257
+ // drawing's preference - longest run, own midpoint, then either side.
258
+ if (placement.collisions === 0)
259
+ return { ...spot, ...placement };
260
+ if (best === undefined ||
261
+ placement.collisions < best.collisions ||
262
+ (placement.collisions === best.collisions && placement.boxes + placement.labels < best.boxes + best.labels)) {
263
+ best = { ...spot, ...placement };
264
+ }
265
+ }
203
266
  }
204
- return at(0);
267
+ return best;
205
268
  }
206
269
  /** The furthest right and bottom point any shape reaches. */
207
270
  function drawnExtent(shapes) {
@@ -235,10 +298,35 @@ function drawnExtent(shapes) {
235
298
  case 'title':
236
299
  consider(textWidth(shape.lines?.[0] ?? '') + shape.x, shape.y + 12);
237
300
  break;
301
+ case 'junction':
302
+ // A dot sits on a line that already reaches further than it does: counting it would never widen the canvas.
303
+ break;
238
304
  }
239
305
  }
240
306
  return { width, height };
241
307
  }
308
+ /**
309
+ * The boxes a polyline passes through other than the two it terminates at.
310
+ *
311
+ * This is the drawing's one clearance rule, and it is deliberately written once: a channel run, a lane, a trunk
312
+ * branch, a wrapped column's sideways step and the router's fallback all have to obey the same test. A box is skipped
313
+ * only when it is one of the edge's own two ends, so a port that sits inside its own symbol (a cylinder's cap apex)
314
+ * is allowed and a segment that ends inside somebody else's box is not.
315
+ */
316
+ export function boxesCrossedBy(points, from, to, boxes) {
317
+ const crossed = [];
318
+ for (let index = 0; index + 1 < points.length; index += 1) {
319
+ const a = points[index];
320
+ const b = points[index + 1];
321
+ for (const box of boxes) {
322
+ if (box === from || box === to)
323
+ continue;
324
+ if (crossesBox(a.x, a.y, b.x, b.y, box))
325
+ crossed.push(box);
326
+ }
327
+ }
328
+ return crossed;
329
+ }
242
330
  export function paintWith(diagram, overrides = {}, options = {}) {
243
331
  const colours = palette(overrides, options);
244
332
  const shapes = [];
@@ -335,45 +423,238 @@ export function paintWith(diagram, overrides = {}, options = {}) {
335
423
  endsAt.set(edge.from, (endsAt.get(edge.from) ?? 0) + 1);
336
424
  endsAt.set(edge.to, (endsAt.get(edge.to) ?? 0) + 1);
337
425
  }
426
+ /**
427
+ * Where a port may sit on one side of one node, as the interval its coordinate may take.
428
+ *
429
+ * This is the per-symbol rule, and it is why the rule lives here: a port slot is chosen in this module, so this is
430
+ * where the symbol has to be known. A rectangle spreads a port along the side, and a subroutine does the same. A
431
+ * diamond's side meets its outline at exactly one point - the vertex - so its interval is that point, and a circle's
432
+ * is its cardinal point; a point is all that side has to give, so two edges on one side share it rather than take
433
+ * two points in the air. A hexagon's top and bottom are the flat run between the cut corners, and its left and right
434
+ * are the vertices. A stadium's flat run stops at the end caps, and a cylinder's flat sides are the two vertical
435
+ * runs, never the caps.
436
+ *
437
+ * A zero-width interval is not a failure: the packer keeps every port on it, so a symbol that offers one point on a
438
+ * side hands that point to every edge that wants it. Which is why a symbol with four points is given one edge per
439
+ * side first - the point is only shared when the four are taken.
440
+ */
441
+ const spanOf = (boxId, side, corner) => {
442
+ const box = endBox(boxId);
443
+ const vertical = side === 'top' || side === 'bottom';
444
+ const middle = vertical ? box.x + box.width / 2 : box.y + box.height / 2;
445
+ const within = (low, high) => ({ low, high: Math.max(low, high) });
446
+ switch (shapeOf(boxId)) {
447
+ // The four vertices of a diamond, and the four cardinal points of an ellipse, are the middles of its sides.
448
+ case 'diamond':
449
+ case 'circle':
450
+ return within(middle, middle);
451
+ case 'hexagon':
452
+ return vertical ? within(box.x + hexagonCut(box.width), box.x + box.width - hexagonCut(box.width)) : within(middle, middle);
453
+ case 'stadium': {
454
+ const radius = stadiumRadius(box);
455
+ return vertical ? within(box.x + radius, box.x + box.width - radius) : within(middle, middle);
456
+ }
457
+ case 'cylinder': {
458
+ if (vertical)
459
+ return within(middle, middle);
460
+ const cap = cylinderCaps(box).cap;
461
+ return within(box.y + cap, box.y + box.height - cap);
462
+ }
463
+ default: {
464
+ // A rectangle, and a subroutine's doubled side, keep the margins they have always had; `corner` relaxes them
465
+ // because a side that is crowded uses its corners.
466
+ const inset = corner ? 2 : vertical ? PORT_INSET : 8;
467
+ return vertical ? within(box.x + inset, box.x + box.width - inset) : within(box.y + inset, box.y + box.height - inset);
468
+ }
469
+ }
470
+ };
471
+ const clampTo = (boxId, side, value, corner) => {
472
+ const span = spanOf(boxId, side, corner);
473
+ return Math.min(span.high, Math.max(span.low, value));
474
+ };
475
+ /**
476
+ * The boundary point a coordinate along one side takes.
477
+ *
478
+ * The box's rectangle is the point for every symbol whose side is the box's side. A cylinder's top and bottom are
479
+ * arcs, so a port there sits on the cap curve's apex - `cap / 4` inside the box, not on the box's own edge.
480
+ */
481
+ const pointOn = (boxId, side, along) => {
482
+ const box = endBox(boxId);
483
+ if (side === 'left')
484
+ return { x: box.x, y: along };
485
+ if (side === 'right')
486
+ return { x: box.x + box.width, y: along };
487
+ if (side === 'top')
488
+ return { x: along, y: shapeOf(boxId) === 'cylinder' ? cylinderApex(box, 'top').y : box.y };
489
+ return { x: along, y: shapeOf(boxId) === 'cylinder' ? cylinderApex(box, 'bottom').y : box.y + box.height };
490
+ };
338
491
  /** The side each edge end's port is on, where the port is a point rather than a place along a run. */
339
492
  const claimed = new Map();
340
493
  const claimedAt = new Map();
341
494
  const claim = (id, index, end, side) => {
342
495
  claimed.set(endKey(index, end), side);
343
- claimedAt.set(id, [...(claimedAt.get(id) ?? []), side]);
496
+ claimedAt.set(id, [...(claimedAt.get(id) ?? []), { index, side }]);
497
+ };
498
+ /** The sides of one node another edge already holds. An edge is not crowded by its own other end. */
499
+ const takenSides = (id, except) => (claimedAt.get(id) ?? []).filter((entry) => entry.index !== except).map((entry) => entry.side);
500
+ /** The middle of one side: the coordinate that side's point sits at when nothing has moved it. */
501
+ const sideMiddle = (box, side) => (isVerticalSide(side) ? box.x + box.width / 2 : box.y + box.height / 2);
502
+ /** The point a side offers at its middle: a symbol's own point, or the middle of the run it spreads along. */
503
+ const sidePoint = (boxId, side) => pointOn(boxId, side, sideMiddle(endBox(boxId), side));
504
+ /** Does this side face away from the box at the other end? A route leaving it has to come back round its own box. */
505
+ const facesAway = (box, other, side) => {
506
+ const out = normalOf(side);
507
+ const dx = other.x + other.width / 2 - (box.x + box.width / 2);
508
+ const dy = other.y + other.height / 2 - (box.y + box.height / 2);
509
+ return out.x * dx + out.y * dy < 0;
510
+ };
511
+ /** The coordinate a free side takes when the other end is pinned: the pinned port's stub, read on the free axis. */
512
+ const stubAlong = (pinnedId, pinnedSide, freeSide) => {
513
+ const point = sidePoint(pinnedId, pinnedSide);
514
+ const out = normalOf(pinnedSide);
515
+ return isVerticalSide(freeSide) ? point.x + out.x * ROUTE_STUB : point.y + out.y * ROUTE_STUB;
516
+ };
517
+ /** Can this side put a port at `value`? A point-side offers exactly one coordinate; a run offers an interval. */
518
+ const offers = (boxId, side, value) => {
519
+ const span = spanOf(boxId, side, true);
520
+ return value >= span.low - 0.01 && value <= span.high + 0.01;
344
521
  };
345
522
  /**
346
- * The side a discrete port takes: the one whose outward normal points most nearly at the other box.
523
+ * The bend budget a candidate (exit side, entry side) pair spends on the orthogonal route it implies, before a lane
524
+ * or a router is consulted. The numbers, and what each one is:
525
+ *
526
+ * 0 the two stubs share a line: both on vertical sides whose x can be the same, or both on horizontal sides
527
+ * whose y can be the same, with each stub pointing the way the edge travels. One straight run, no corner.
528
+ * 1 an L: the two sides are perpendicular and the one that can still move can be placed exactly where the pinned
529
+ * side's stub ends, so the route turns once. It is the rung between the straight run and the Z: an L never
530
+ * beats a run that shares a line, and always beats a Z.
531
+ * 2 a Z: the stubs are perpendicular but cannot meet at one corner, or they are parallel and offset. Out, across,
532
+ * in: two corners.
533
+ * 4 a U: a side faces away from the box at the other end, so the route has to wrap a box - out, round, back
534
+ * in. The canonical U has both sides facing away; one is already enough to force the wrap, and a pair that
535
+ * has to come back the way it went is never worth a pair that does not.
347
536
  *
348
- * The score is the cosine of the angle between the normal and the direction to the other box, so 1 is dead ahead
349
- * and the four sides of a diamond rank by how much of the way to the target each one faces. Equal scores are broken
350
- * by the point nearest the other box - the port the route has least ground to cover from - and then by the order the
351
- * sides are drawn in. That last tie-break is what "the earlier edge keeps the earlier point" means in practice: the
352
- * edges are walked in source order, and each one takes the best side still free.
537
+ * "Can be the same" is the symbol's own answer (`spanOf`): a rectangle offers its whole side, a diamond one point, a
538
+ * cylinder's top the apex of its cap. Two rectangles facing each other therefore share a line wherever they sit; two
539
+ * diamonds only when their vertices line up. This is a budget, not the final polyline: the router still adds the
540
+ * length an obstacle demands, and the channel stage still decides which lanes exist.
541
+ *
542
+ * A side another edge already holds is charged for the L it costs: the packer has to move this pair's port at least
543
+ * a port separation along the side, which turns the one corner the pair counted on into a jog. A Z is not charged -
544
+ * it was already off the line, and a port that moves along its side does not add a corner to it.
353
545
  */
354
- const bestSide = (id, other) => {
546
+ const bendBudget = (fromId, toId, exit, entry, index) => {
547
+ const from = endBox(fromId);
548
+ const to = endBox(toId);
549
+ if (facesAway(from, to, exit) || facesAway(to, from, entry))
550
+ return 4;
551
+ if (isVerticalSide(exit) === isVerticalSide(entry)) {
552
+ // Parallel: a straight run only when the two stubs travel the same way and the sides can meet on one line.
553
+ const out = normalOf(exit);
554
+ const into = normalOf(entry);
555
+ const sameWay = out.x === -into.x && out.y === -into.y;
556
+ const fromSpan = spanOf(fromId, exit, true);
557
+ const toSpan = spanOf(toId, entry, true);
558
+ const meet = fromSpan.low <= toSpan.high + 0.01 && toSpan.low <= fromSpan.high + 0.01;
559
+ return sameWay && meet ? 0 : 2;
560
+ }
561
+ // Perpendicular: one corner when the vertical side can be placed at the horizontal side's stub end.
562
+ const horizontalId = isVerticalSide(exit) ? toId : fromId;
563
+ const horizontalSide = isVerticalSide(exit) ? entry : exit;
564
+ const verticalId = isVerticalSide(exit) ? fromId : toId;
565
+ const verticalSide = isVerticalSide(exit) ? exit : entry;
566
+ if (!offers(verticalId, verticalSide, stubAlong(horizontalId, horizontalSide, verticalSide)))
567
+ return 2;
568
+ const crowded = takenSides(fromId, index).includes(exit) || takenSides(toId, index).includes(entry);
569
+ return crowded ? 2 : 1;
570
+ };
571
+ /**
572
+ * The side a discrete port takes: the point whose pair with the edge's other end bends least.
573
+ *
574
+ * `partner` is the side the other end holds - the side it was claimed, or, until it is claimed, the side the route
575
+ * approaches by. The bend budget comes first. Equal budgets fall back to the rule that was here before: the cosine
576
+ * of the outward normal against the direction to the other box, then the point nearest that box, then the ground
577
+ * between the two points - the small length term. So a case that already read well does not move, and a point that
578
+ * costs an extra corner loses even when it faces the target more squarely.
579
+ */
580
+ const bestSide = (id, otherId, end, partner, index) => {
355
581
  const box = endBox(id);
582
+ const other = endBox(otherId);
356
583
  const centre = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
357
584
  const toward = { x: other.x + other.width / 2 - centre.x, y: other.y + other.height / 2 - centre.y };
358
585
  const reach = Math.hypot(toward.x, toward.y);
359
- const taken = claimedAt.get(id) ?? [];
586
+ const taken = takenSides(id, index);
360
587
  let best;
361
588
  for (const side of PORT_SIDES) {
362
589
  if (taken.includes(side))
363
590
  continue;
591
+ const bends = end === 'exit' ? bendBudget(id, otherId, side, partner, index) : bendBudget(otherId, id, partner, side, index);
364
592
  const normal = normalOf(side);
365
593
  const score = reach === 0 ? 0 : (normal.x * toward.x + normal.y * toward.y) / reach;
366
594
  // How far the point is from the other box's rectangle: the nearest port is the one the edge reaches first.
367
595
  const point = anchor(box, side);
368
596
  const near = Math.hypot(Math.max(other.x - point.x, 0, point.x - (other.x + other.width)), Math.max(other.y - point.y, 0, point.y - (other.y + other.height)));
597
+ const partnerPoint = anchor(other, partner);
598
+ const ground = Math.abs(point.x - partnerPoint.x) + Math.abs(point.y - partnerPoint.y);
369
599
  const better = best === undefined ||
370
- score > best.score + 1e-9 ||
371
- (Math.abs(score - best.score) <= 1e-9 && near < best.near - 1e-9);
600
+ bends < best.bends ||
601
+ (bends === best.bends &&
602
+ (score > best.score + 1e-9 ||
603
+ (Math.abs(score - best.score) <= 1e-9 &&
604
+ (near < best.near - 1e-9 || (Math.abs(near - best.near) <= 1e-9 && ground < best.ground - 1e-9)))));
372
605
  if (better)
373
- best = { side, score, near };
606
+ best = { side, bends, score, near, ground };
374
607
  }
375
608
  return best?.side;
376
609
  };
610
+ /**
611
+ * The sides an edge leaves and enters by when no claimed point decides either end: the pair the budget likes best.
612
+ *
613
+ * Only the two same-kind pairs are offered. Both ends here spread their ports along a side, so the choice is which
614
+ * side of the box the edge travels on; a pair that turns the corner one side further is the case `bestEnd` decides,
615
+ * where a claimed point has already fixed the near end. A pair strictly cheaper than the one the route approaches by
616
+ * wins; an equal pair keeps the approach, which leaves a drawing that was already right exactly as it was.
617
+ */
618
+ const bestPair = (fromId, toId, index) => {
619
+ const approach = approachSides(endBox(fromId), endBox(toId));
620
+ const pairs = [
621
+ { exit: 'bottom', entry: 'top' },
622
+ { exit: 'top', entry: 'bottom' },
623
+ { exit: 'right', entry: 'left' },
624
+ { exit: 'left', entry: 'right' },
625
+ ];
626
+ let best = approach;
627
+ let bestBends = bendBudget(fromId, toId, approach.exit, approach.entry, index);
628
+ for (const pair of pairs) {
629
+ const bends = bendBudget(fromId, toId, pair.exit, pair.entry, index);
630
+ if (bends >= bestBends)
631
+ continue;
632
+ best = pair;
633
+ bestBends = bends;
634
+ }
635
+ return best;
636
+ };
637
+ /**
638
+ * The side one end takes when the other end has already been decided: the cheapest of the four.
639
+ *
640
+ * The side the route approaches by wins a tie, for the same reason as `bestPair` - a drawing that already read well
641
+ * does not move for a pair the budget cannot tell apart.
642
+ */
643
+ const bestEnd = (id, otherId, end, partner, index) => {
644
+ const approach = end === 'exit'
645
+ ? approachSides(endBox(id), endBox(otherId)).exit
646
+ : approachSides(endBox(otherId), endBox(id)).entry;
647
+ let best = approach;
648
+ let bestBends = end === 'exit' ? bendBudget(id, otherId, approach, partner, index) : bendBudget(otherId, id, partner, approach, index);
649
+ for (const side of PORT_SIDES) {
650
+ const bends = end === 'exit' ? bendBudget(id, otherId, side, partner, index) : bendBudget(otherId, id, partner, side, index);
651
+ if (bends >= bestBends)
652
+ continue;
653
+ best = side;
654
+ bestBends = bends;
655
+ }
656
+ return best;
657
+ };
377
658
  // A side the drawing has already decided is claimed first, because a point there would point the route away from
378
659
  // the corridor it has to run in: a long edge leaves by the side its lane starts from, and an edge read across two
379
660
  // wrapped columns leaves and arrives on the sides the reading order turns at.
@@ -415,7 +696,11 @@ export function paintWith(diagram, overrides = {}, options = {}) {
415
696
  continue;
416
697
  if (!hasDiscretePorts(shapeOf(id)))
417
698
  continue;
418
- const side = bestSide(id, end === 'exit' ? target : source);
699
+ // The side the other end holds, or will hold if nothing claims it first.
700
+ const approached = approachSides(source, target);
701
+ const partner = claimed.get(endKey(index, end === 'exit' ? 'entry' : 'exit')) ??
702
+ (end === 'exit' ? approached.entry : approached.exit);
703
+ const side = bestSide(id, end === 'exit' ? edge.to : edge.from, end, partner, index);
419
704
  if (side === undefined)
420
705
  continue;
421
706
  claim(id, index, end, side);
@@ -428,23 +713,29 @@ export function paintWith(diagram, overrides = {}, options = {}) {
428
713
  return undefined;
429
714
  // A wrapped drawing is read in columns: the edge from one column to the next leaves and arrives at the side,
430
715
  // which is the direction that reading order travels. A column is always to the right of the one before it.
431
- const sides = placement.across.has(index)
432
- ? { exit: 'right', entry: 'left' }
433
- : approachSides(source, target);
716
+ if (placement.across.has(index))
717
+ return { exit: 'right', entry: 'left' };
434
718
  const lane = placement.lanes.get(index);
435
- if (lane === undefined || lane.points.length === 0) {
719
+ // A lane runs down the page, so its ends face the rows above and below wherever the box centres are.
720
+ const down = target.y > source.y;
721
+ if (lane !== undefined && lane.points.length > 0) {
436
722
  return {
437
- exit: claimed.get(endKey(index, 'exit')) ?? sides.exit,
438
- entry: claimed.get(endKey(index, 'entry')) ?? sides.entry,
723
+ exit: claimed.get(endKey(index, 'exit')) ?? (down ? 'bottom' : 'top'),
724
+ entry: claimed.get(endKey(index, 'entry')) ?? (down ? 'top' : 'bottom'),
725
+ at: lane.points[0].x,
439
726
  };
440
727
  }
441
- // A lane runs down the page, so its ends face the rows above and below wherever the box centres are.
442
- const down = target.y > source.y;
443
- return {
444
- exit: claimed.get(endKey(index, 'exit')) ?? (down ? 'bottom' : 'top'),
445
- entry: claimed.get(endKey(index, 'entry')) ?? (down ? 'top' : 'bottom'),
446
- at: lane.points[0].x,
447
- };
728
+ // No claimed point and no lane: an end that was claimed keeps its point, the other one takes the side the budget
729
+ // likes best against it; with neither claimed, the pair is chosen together.
730
+ const exit = claimed.get(endKey(index, 'exit'));
731
+ const entry = claimed.get(endKey(index, 'entry'));
732
+ if (exit !== undefined && entry !== undefined)
733
+ return { exit, entry };
734
+ if (exit !== undefined)
735
+ return { exit, entry: bestEnd(edge.to, edge.from, 'entry', exit, index) };
736
+ if (entry !== undefined)
737
+ return { exit: bestEnd(edge.from, edge.to, 'exit', entry, index), entry };
738
+ return bestPair(edge.from, edge.to, index);
448
739
  });
449
740
  // A long edge's lane is where the whole edge runs, so a fan moves the lane instead of bending the edge twice at its
450
741
  // ends. It tries the place that keeps the set evenly spaced first, then its own place moved by the same offset; a
@@ -493,71 +784,6 @@ export function paintWith(diagram, overrides = {}, options = {}) {
493
784
  }
494
785
  const wanted = new Map();
495
786
  const slotKey = (boxId, side, index) => boxId + ':' + side + ':' + String(index);
496
- /**
497
- * Where a port may sit on one side of one node, as the interval its coordinate may take.
498
- *
499
- * This is the per-symbol rule, and it is why the rule lives here: a port slot is chosen in this module, so this is
500
- * where the symbol has to be known. A rectangle spreads a port along the side, and a subroutine does the same. A
501
- * diamond's side meets its outline at exactly one point - the vertex - so its interval is that point, and a circle's
502
- * is its cardinal point; a point is all that side has to give, so two edges on one side share it rather than take
503
- * two points in the air. A hexagon's top and bottom are the flat run between the cut corners, and its left and right
504
- * are the vertices. A stadium's flat run stops at the end caps, and a cylinder's flat sides are the two vertical
505
- * runs, never the caps.
506
- *
507
- * A zero-width interval is not a failure: the packer keeps every port on it, so a symbol that offers one point on a
508
- * side hands that point to every edge that wants it. Which is why a symbol with four points is given one edge per
509
- * side first - the point is only shared when the four are taken.
510
- */
511
- const spanOf = (boxId, side, corner) => {
512
- const box = endBox(boxId);
513
- const vertical = side === 'top' || side === 'bottom';
514
- const middle = vertical ? box.x + box.width / 2 : box.y + box.height / 2;
515
- const within = (low, high) => ({ low, high: Math.max(low, high) });
516
- switch (shapeOf(boxId)) {
517
- // The four vertices of a diamond, and the four cardinal points of an ellipse, are the middles of its sides.
518
- case 'diamond':
519
- case 'circle':
520
- return within(middle, middle);
521
- case 'hexagon':
522
- return vertical ? within(box.x + hexagonCut(box.width), box.x + box.width - hexagonCut(box.width)) : within(middle, middle);
523
- case 'stadium': {
524
- const radius = stadiumRadius(box);
525
- return vertical ? within(box.x + radius, box.x + box.width - radius) : within(middle, middle);
526
- }
527
- case 'cylinder': {
528
- if (vertical)
529
- return within(middle, middle);
530
- const cap = cylinderCaps(box).cap;
531
- return within(box.y + cap, box.y + box.height - cap);
532
- }
533
- default: {
534
- // A rectangle, and a subroutine's doubled side, keep the margins they have always had; `corner` relaxes them
535
- // because a side that is crowded uses its corners.
536
- const inset = corner ? 2 : vertical ? PORT_INSET : 8;
537
- return vertical ? within(box.x + inset, box.x + box.width - inset) : within(box.y + inset, box.y + box.height - inset);
538
- }
539
- }
540
- };
541
- const clampTo = (boxId, side, value, corner) => {
542
- const span = spanOf(boxId, side, corner);
543
- return Math.min(span.high, Math.max(span.low, value));
544
- };
545
- /**
546
- * The boundary point a coordinate along one side takes.
547
- *
548
- * The box's rectangle is the point for every symbol whose side is the box's side. A cylinder's top and bottom are
549
- * arcs, so a port there sits on the cap curve's apex - `cap / 4` inside the box, not on the box's own edge.
550
- */
551
- const pointOn = (boxId, side, along) => {
552
- const box = endBox(boxId);
553
- if (side === 'left')
554
- return { x: box.x, y: along };
555
- if (side === 'right')
556
- return { x: box.x + box.width, y: along };
557
- if (side === 'top')
558
- return { x: along, y: shapeOf(boxId) === 'cylinder' ? cylinderApex(box, 'top').y : box.y };
559
- return { x: along, y: shapeOf(boxId) === 'cylinder' ? cylinderApex(box, 'bottom').y : box.y + box.height };
560
- };
561
787
  for (const [index, entry] of facing.entries()) {
562
788
  if (entry === undefined)
563
789
  continue;
@@ -592,16 +818,16 @@ export function paintWith(diagram, overrides = {}, options = {}) {
592
818
  entryWanted = clampTo(edge.to, entry.entry, chosen, corner);
593
819
  }
594
820
  else {
595
- // The two ports sit on sides of different kinds, which only a discrete point causes. The end that is fixed on
596
- // its symbol's point keeps that point's coordinate; the other one sits where the route actually arrives - one
597
- // step out of the fixed port along its own normal - so the two legs of the route meet in a straight drop
598
- // instead of jogging sideways to reach a middle that the route never passes.
821
+ // The two ports sit on sides of different kinds, which a discrete point causes. The end that is fixed on its
822
+ // symbol's point keeps that point's coordinate; the other one sits where the route actually arrives - one step
823
+ // out of the fixed port along that port's own normal, read on the free side's axis - so the two legs of the
824
+ // route meet in one corner instead of jogging sideways to reach a middle the route never passes.
599
825
  exitWanted = hasDiscretePorts(shapeOf(edge.from))
600
826
  ? fromMiddle
601
- : clampTo(edge.from, entry.exit, anchor(to, entry.entry).x + normalOf(entry.entry).x * ROUTE_STUB, false) + offset;
827
+ : clampTo(edge.from, entry.exit, stubAlong(edge.to, entry.entry, entry.exit), false) + offset;
602
828
  entryWanted = hasDiscretePorts(shapeOf(edge.to))
603
829
  ? toMiddle
604
- : clampTo(edge.to, entry.entry, anchor(from, entry.exit).x + normalOf(entry.exit).x * ROUTE_STUB, false) + offset;
830
+ : clampTo(edge.to, entry.entry, stubAlong(edge.from, entry.exit, entry.entry), false) + offset;
605
831
  }
606
832
  wanted.set(slotKey(edge.from, entry.exit, index), exitWanted);
607
833
  wanted.set(slotKey(edge.to, entry.entry, index), entryWanted);
@@ -656,6 +882,167 @@ export function paintWith(diagram, overrides = {}, options = {}) {
656
882
  if (!moved)
657
883
  break;
658
884
  }
885
+ /**
886
+ * A batch of arrows into one box from one side is one bundle, not a comb: which ends may merge is the planner's
887
+ * answer (`trunk.ts` carries the rules), and this module supplies what only it knows - which edges have a run of
888
+ * their own, and where each port landed.
889
+ *
890
+ * The plan is made twice. The first pass, from the ports the packing gave, says which ends merge; the centring rule
891
+ * below reads it, because a merged branch is drawn into the bundle's one port and that - not its own entry port -
892
+ * is the coordinate its exit either shares a line with or does not. The second pass is made from the centred ports
893
+ * and is the plan the drawing uses: the run it lays out is the run of the ports that are actually drawn.
894
+ */
895
+ const trunkEnds = [];
896
+ diagram.edges.forEach((edge, index) => {
897
+ const entry = facing[index];
898
+ if (entry === undefined)
899
+ return;
900
+ const runY = placement.runs.get(index);
901
+ trunkEnds.push({
902
+ index,
903
+ from: edge.from,
904
+ to: edge.to,
905
+ exit: entry.exit,
906
+ entry: entry.entry,
907
+ ...(edge.arrow === undefined ? {} : { arrow: edge.arrow }),
908
+ ...(runY === undefined ? {} : { runY }),
909
+ });
910
+ });
911
+ const planFor = (exitPortOf) => planTrunks({
912
+ ends: trunkEnds,
913
+ // Only a node's own box is a trunk target: an arrow into a boundary points past it, not at it.
914
+ boxOf: (id) => boxes.get(id),
915
+ boxes: boxList,
916
+ exitPortOf,
917
+ });
918
+ /** Where an edge's exit port sits before the centring rule has had its say. */
919
+ const packedExit = (index) => {
920
+ const entry = facing[index];
921
+ if (entry === undefined)
922
+ return undefined;
923
+ const edge = diagram.edges[index];
924
+ const coordinate = placedPort.get(slotKey(edge.from, entry.exit, index));
925
+ return coordinate === undefined ? undefined : pointOn(edge.from, entry.exit, coordinate);
926
+ };
927
+ const planned = planFor(packedExit);
928
+ /**
929
+ * Does the channel stage's lane pin this port to its own coordinate? A port off its lane is a jog added to the run.
930
+ * A merged branch has a lane the painter never follows - the branch is drawn from its exit to the trunk - so it is
931
+ * not pinned by it.
932
+ */
933
+ const onLane = (index, coordinate) => {
934
+ if (planned.groupOf.has(index))
935
+ return false;
936
+ const lane = placement.lanes.get(index);
937
+ if (lane === undefined || lane.points.length === 0)
938
+ return false;
939
+ return Math.abs(lane.points[0].x - coordinate) <= 0.5;
940
+ };
941
+ const rows = [];
942
+ const rowOf = new Map();
943
+ for (const [key, list] of sides) {
944
+ const [boxId, side] = key.split(':');
945
+ const span = spanOf(boxId, side, true);
946
+ const slots = [...list]
947
+ .map((entry) => ({ index: entry.index, at: placedPort.get(slotKey(boxId, side, entry.index)) }))
948
+ .sort((left, right) => left.at - right.at || left.index - right.index);
949
+ const centred = centreRun(slots.map((slot) => slot.at), span.low, span.high);
950
+ const first = slots[0];
951
+ const row = {
952
+ boxId,
953
+ side,
954
+ indexes: slots.map((slot) => slot.index),
955
+ at: slots.map((slot) => slot.at),
956
+ position: new Map(slots.map((slot, at) => [slot.index, at])),
957
+ shift: centred[0] - first.at,
958
+ allowed: true,
959
+ };
960
+ rows.push(row);
961
+ rowOf.set(key, row);
962
+ }
963
+ /** Where a port of a row will sit once the rows that may move have moved. */
964
+ const movedAt = (row, at) => row.at[at] + (row.allowed ? row.shift : 0);
965
+ /**
966
+ * The coordinate the port at the other end of this edge sits at, and the row that port belongs to.
967
+ *
968
+ * Three ends are not a drawn port of a row: the entry of a merged branch (the bundle has one port), the shared
969
+ * entry itself (the planner's `entryAlong`), and a partner on a side of the other kind (a discrete symbol's point,
970
+ * on a different axis). Each is a fixed coordinate or nothing, which is all the pin test needs.
971
+ */
972
+ const partnerOf = (boxId, side, index) => {
973
+ const entry = facing[index];
974
+ if (entry === undefined)
975
+ return undefined;
976
+ const edge = diagram.edges[index];
977
+ const isExit = edge.from === boxId && entry.exit === side;
978
+ const groupId = planned.groupOf.get(index);
979
+ if (groupId !== undefined) {
980
+ // A merged branch ends at the bundle's one port, so its own entry port is not drawn and pins nothing. Its exit
981
+ // is drawn, and the line it may share is the one to that shared port.
982
+ if (!isExit)
983
+ return undefined;
984
+ const group = planned.groups[groupId];
985
+ if (isVerticalSide(side) !== isVerticalSide(group.side))
986
+ return undefined;
987
+ return { coordinate: group.entryAlong };
988
+ }
989
+ const partnerId = isExit ? edge.to : edge.from;
990
+ const partnerSide = isExit ? entry.entry : entry.exit;
991
+ if (isVerticalSide(side) !== isVerticalSide(partnerSide))
992
+ return undefined;
993
+ const coordinate = placedPort.get(slotKey(partnerId, partnerSide, index));
994
+ if (coordinate === undefined)
995
+ return undefined;
996
+ const row = rowOf.get(partnerId + ':' + partnerSide);
997
+ return { coordinate, ...(row === undefined ? {} : { row, at: row.position.get(index) }) };
998
+ };
999
+ /**
1000
+ * A side that carries one port is centred on it; a side that carries several keeps its spread, translated as a
1001
+ * whole so its outer ports sit symmetrically about the middle.
1002
+ *
1003
+ * A port is put where the route wants it, and a side that carries one relation has no spread to fit: the only
1004
+ * reason its port is not in the middle is that the route asked for a coordinate near one end - the far end of the
1005
+ * span, the point a lane runs at. That request is real, and the bend budget decides whether it may be overruled.
1006
+ * A port that shares a line with the port at the other end of its edge is the middle of a straight run, and a port
1007
+ * on a lane is the end of a channel: moving either adds two corners. Every other port moves to where its side has
1008
+ * room, which costs nothing.
1009
+ *
1010
+ * So the bend budget is a fixpoint over rows, not a test per port: a row may move unless that breaks a line it
1011
+ * shares with a port that is staying. Two ends of one straight line may both move when they move by the same
1012
+ * amount - which is what centring both sides of one pair does - so the rows are resolved together, and a row that
1013
+ * is refused takes the lines it shares with it.
1014
+ */
1015
+ for (let pass = 0; pass < rows.length; pass += 1) {
1016
+ let refused = false;
1017
+ for (const row of rows) {
1018
+ if (!row.allowed || row.shift === 0)
1019
+ continue;
1020
+ const pinned = row.indexes.some((index, at) => {
1021
+ if (onLane(index, row.at[at]))
1022
+ return true;
1023
+ const partner = partnerOf(row.boxId, row.side, index);
1024
+ if (partner === undefined)
1025
+ return false;
1026
+ // Only a line that exists now can be broken: two ports that already differ are a Z, and moving one end of a Z
1027
+ // along its own side changes where its corners are, not how many.
1028
+ if (Math.abs(row.at[at] - partner.coordinate) > 0.5)
1029
+ return false;
1030
+ const partnerAt = partner.row === undefined ? partner.coordinate : movedAt(partner.row, partner.at);
1031
+ return Math.abs(movedAt(row, at) - partnerAt) > 0.5;
1032
+ });
1033
+ if (!pinned)
1034
+ continue;
1035
+ row.allowed = false;
1036
+ refused = true;
1037
+ }
1038
+ if (!refused)
1039
+ break;
1040
+ }
1041
+ for (const row of rows) {
1042
+ if (!row.allowed || row.shift === 0)
1043
+ continue;
1044
+ row.indexes.forEach((index, at) => placedPort.set(slotKey(row.boxId, row.side, index), movedAt(row, at)));
1045
+ }
659
1046
  const portOf = (boxId, side, edgeIndex) => {
660
1047
  const coordinate = placedPort.get(slotKey(boxId, side, edgeIndex));
661
1048
  return pointOn(boxId, side, coordinate);
@@ -672,18 +1059,13 @@ export function paintWith(diagram, overrides = {}, options = {}) {
672
1059
  entrySide: entry.entry,
673
1060
  });
674
1061
  }
675
- /** The longest straight run of a polyline: where a label has the most room. */
676
- const longestRun = (points) => {
677
- let best = { from: points[0], to: points[points.length - 1], length: -1 };
678
- for (let index = 0; index + 1 < points.length; index += 1) {
679
- const from = points[index];
680
- const to = points[index + 1];
681
- const length = Math.abs(to.x - from.x) + Math.abs(to.y - from.y);
682
- if (length > best.length)
683
- best = { from, to, length };
684
- }
685
- return best;
686
- };
1062
+ const trunks = planFor((index) => anchorsFor.get(index)?.exit);
1063
+ // The one port each accepted bundle enters by: the middle of the target's side, which is the port the planner
1064
+ // centred on `entryAlong`. A merged entry is one port, so the rule for a side with one port applies to it, and the
1065
+ // target carries one relation's worth of ports however many arrows point at it.
1066
+ const sharedEntry = new Map();
1067
+ for (const group of trunks.groups)
1068
+ sharedEntry.set(group.id, pointOn(group.target, group.side, group.entryAlong));
687
1069
  /** The points a drawn edge passes through, whichever of the two shapes carries it. */
688
1070
  const pointsOfRoute = (shape) => shape.kind === 'path' ? shape.points : [{ x: shape.x1, y: shape.y1 }, { x: shape.x2, y: shape.y2 }];
689
1071
  /** The straight pieces an edge draws, so a label can tell its own line from every other one. */
@@ -698,7 +1080,7 @@ export function paintWith(diagram, overrides = {}, options = {}) {
698
1080
  return out;
699
1081
  };
700
1082
  /** Paint one edge as a polyline. Its label is placed once every edge is drawn; see the pass after the loop. */
701
- const paintPath = (edge, points, colour) => {
1083
+ const paintPath = (edgeIndex, edge, points, colour) => {
702
1084
  const shape = {
703
1085
  kind: 'path',
704
1086
  points,
@@ -710,12 +1092,12 @@ export function paintWith(diagram, overrides = {}, options = {}) {
710
1092
  ...(edge.arrow === undefined ? {} : { arrow: edge.arrow }),
711
1093
  };
712
1094
  shapes.push(shape);
713
- routes.push(shape);
1095
+ routes.push({ shape, edge: edgeIndex, fixed: false });
714
1096
  };
715
1097
  /** Two points are a line and more of them are a polyline; both are an edge carrying a label. */
716
- const paintRoute = (edge, points, colour) => {
1098
+ const paintRoute = (edgeIndex, edge, points, colour) => {
717
1099
  if (points.length > 2) {
718
- paintPath(edge, points, colour);
1100
+ paintPath(edgeIndex, edge, points, colour);
719
1101
  return;
720
1102
  }
721
1103
  const exit = points[0];
@@ -734,8 +1116,16 @@ export function paintWith(diagram, overrides = {}, options = {}) {
734
1116
  ...(edge.arrow === undefined ? {} : { arrow: edge.arrow }),
735
1117
  };
736
1118
  shapes.push(shape);
737
- routes.push(shape);
1119
+ routes.push({ shape, edge: edgeIndex, fixed: false });
738
1120
  };
1121
+ /**
1122
+ * Is this route clear of every box it does not terminate at?
1123
+ *
1124
+ * One test, used by every stage. A run, a lane and a trunk branch are proposals made from the layout; when the
1125
+ * proposal meets a box - which happens when the layout reserved a run between two boundaries while the painter
1126
+ * draws the boxes inside them - the proposal is refused and the router gets the edge.
1127
+ */
1128
+ const clearOfBoxes = (points, from, to) => boxesCrossedBy(points, from, to, boxList).length === 0;
739
1129
  /**
740
1130
  * The polyline through a run: out of one port, across the strip between two rows, and into the other, square to
741
1131
  * whatever side each port belongs to.
@@ -748,12 +1138,18 @@ export function paintWith(diagram, overrides = {}, options = {}) {
748
1138
  const runRoute = (ports, runY) => {
749
1139
  const out = isVerticalSide(ports.exitSide) ? 0 : normalOf(ports.exitSide).x * ROUTE_STUB;
750
1140
  const into = isVerticalSide(ports.entrySide) ? 0 : normalOf(ports.entrySide).x * ROUTE_STUB;
1141
+ // A sideways port and a vertical one meet where the other port already is, if that is the way the stub points: the
1142
+ // stub is the straight run out of the port, and it is worth more than a stub to avoid the point-wide jog that
1143
+ // meeting at the nominal length leaves behind - a jog the edge would be charged a bend for and a reader for
1144
+ // nothing. Only when the other port is on the far side does the stub have to overshoot.
1145
+ const exitRun = out !== 0 && into === 0 && Math.sign(ports.entry.x - ports.exit.x) === Math.sign(out) ? ports.entry.x : ports.exit.x + out;
1146
+ const entryRun = into !== 0 && out === 0 && Math.sign(ports.exit.x - ports.entry.x) === Math.sign(into) ? ports.exit.x : ports.entry.x + into;
751
1147
  const points = [ports.exit];
752
1148
  if (out !== 0)
753
- points.push({ x: ports.exit.x + out, y: ports.exit.y });
754
- points.push({ x: ports.exit.x + out, y: runY }, { x: ports.entry.x + into, y: runY });
1149
+ points.push({ x: exitRun, y: ports.exit.y });
1150
+ points.push({ x: exitRun, y: runY }, { x: entryRun, y: runY });
755
1151
  if (into !== 0)
756
- points.push({ x: ports.entry.x + into, y: ports.entry.y });
1152
+ points.push({ x: entryRun, y: ports.entry.y });
757
1153
  points.push(ports.entry);
758
1154
  return simplify(points);
759
1155
  };
@@ -776,20 +1172,8 @@ export function paintWith(diagram, overrides = {}, options = {}) {
776
1172
  }
777
1173
  return true;
778
1174
  };
779
- /** Does the route pass through a box it does not attach to? A run is an empty strip; a step out of a side may not be. */
780
- const clearsBoxes = (points, from, to) => {
781
- for (let at = 0; at + 1 < points.length; at += 1) {
782
- const a = points[at];
783
- const b = points[at + 1];
784
- for (const box of boxList) {
785
- if (box === from || box === to)
786
- continue;
787
- if (crossesBox(a.x, a.y, b.x, b.y, box))
788
- return false;
789
- }
790
- }
791
- return true;
792
- };
1175
+ /** Where a branch meets its trunk, one per merged edge. They are drawn after every line, so no line covers one. */
1176
+ const junctions = [];
793
1177
  for (const [edgeIndex, edge] of diagram.edges.entries()) {
794
1178
  const source = endBox(edge.from);
795
1179
  const target = endBox(edge.to);
@@ -799,7 +1183,7 @@ export function paintWith(diagram, overrides = {}, options = {}) {
799
1183
  if (edge.from === edge.to) {
800
1184
  const x = source.x + source.width;
801
1185
  const y = source.y + source.height / 2;
802
- shapes.push({
1186
+ const shape = {
803
1187
  kind: 'path',
804
1188
  points: [
805
1189
  { x, y: y - 9 },
@@ -815,10 +1199,35 @@ export function paintWith(diagram, overrides = {}, options = {}) {
815
1199
  colour,
816
1200
  ...(edge.dashed === undefined ? {} : { dashed: edge.dashed }),
817
1201
  ...(edge.arrow === undefined ? {} : { arrow: edge.arrow }),
818
- });
1202
+ };
1203
+ shapes.push(shape);
1204
+ routes.push({ shape, edge: edgeIndex, fixed: true });
819
1205
  continue;
820
1206
  }
821
1207
  const anchors = anchorsFor.get(edgeIndex);
1208
+ // A branch of an accepted bundle: out of its own port, square onto the trunk, along the trunk to the bundle's one
1209
+ // port, and in. The last leg is shared with every other branch of the group, so the target is entered once; the
1210
+ // branch still draws its own head and its own label. The junction is recorded where the branch meets the trunk,
1211
+ // because a reader who is not shown the join reads the two lines as one line that was broken. A branch that would
1212
+ // cross a box is refused here as well: the planner checked it, but the painter is the last stage that knows every
1213
+ // box the drawing actually carries.
1214
+ const groupId = trunks.groupOf.get(edgeIndex);
1215
+ if (groupId !== undefined && anchors !== undefined) {
1216
+ const group = trunks.groups[groupId];
1217
+ const entry = sharedEntry.get(groupId);
1218
+ const branch = isVerticalSide(group.side)
1219
+ ? [anchors.exit, { x: anchors.exit.x, y: group.at }, { x: entry.x, y: group.at }, entry]
1220
+ : [anchors.exit, { x: group.at, y: anchors.exit.y }, { x: group.at, y: entry.y }, entry];
1221
+ const points = simplify(branch);
1222
+ if (clearOfBoxes(points, source, target)) {
1223
+ paintRoute(edgeIndex, edge, points, colour);
1224
+ // The join itself, read off the two ports rather than off the emitted points: a branch that drops straight
1225
+ // into the shared port is drawn as one segment, and its junction is still where the trunk crosses it.
1226
+ const meet = isVerticalSide(group.side) ? { x: anchors.exit.x, y: group.at } : { x: group.at, y: anchors.exit.y };
1227
+ junctions.push({ kind: 'junction', x: meet.x, y: meet.y, colour, trunk: group.id });
1228
+ continue;
1229
+ }
1230
+ }
822
1231
  // A long edge follows the lane the channel stage gave it: down the exit stub, across to the lane's x on the run
823
1232
  // the gap was assigned, down the lane, and across to the entry stub. The spine carries one point per gap, so the
824
1233
  // two runs are the places where a port and the lane disagree, and everything between them is one straight drop.
@@ -838,38 +1247,87 @@ export function paintWith(diagram, overrides = {}, options = {}) {
838
1247
  if (Math.abs(previous.x - anchors.entry.x) > 0.5 && Math.abs(previous.y - anchors.entry.y) > 0.5)
839
1248
  points.push({ x: anchors.entry.x, y: previous.y });
840
1249
  points.push(anchors.entry);
841
- paintPath(edge, simplify(points), colour);
842
- continue;
1250
+ const simplified = simplify(points);
1251
+ if (clearOfBoxes(simplified, source, target)) {
1252
+ paintPath(edgeIndex, edge, simplified, colour);
1253
+ continue;
1254
+ }
843
1255
  }
844
- // Two rows with nothing between them: the edge is the two-bend run the channel stage stacked. A run sits in the
845
- // empty strip between its own two rows and inside its own component's column, so it cannot meet a box - unless a
846
- // port on a side steps out of it, and then the step is checked and a route that would meet a box is the router's.
1256
+ // Two rows with nothing between them: the edge is the two-bend run the channel stage stacked. The run's height is
1257
+ // an empty strip only when the two rows it was measured between are the boxes actually drawn: a run reserved
1258
+ // between two boundaries is a strip outside them, while the painter's ports belong to boxes inside them. So the
1259
+ // proposal is checked, not trusted, and an edge whose legs would cross a box is the router's.
847
1260
  const runY = placement.runs.get(edgeIndex);
848
1261
  if (runY !== undefined && anchors !== undefined && runFits(anchors, runY)) {
849
1262
  const points = runRoute(anchors, runY);
850
- const mixed = isVerticalSide(anchors.exitSide) !== isVerticalSide(anchors.entrySide);
851
- if (!mixed || clearsBoxes(points, source, target)) {
852
- paintRoute(edge, points, colour);
1263
+ if (clearOfBoxes(points, source, target)) {
1264
+ paintRoute(edgeIndex, edge, points, colour);
853
1265
  continue;
854
1266
  }
855
1267
  }
856
- paintRoute(edge, routeEdge(source, target, boxList, anchors).points, colour);
1268
+ // The router is the last stage. Its own straight-line shortcut is already refused when a box is in the way; a
1269
+ // search that cannot finish still returns a line, and the final pass over the assembled drawing reports it.
1270
+ paintRoute(edgeIndex, edge, routeEdge(source, target, boxList, anchors).points, colour);
1271
+ }
1272
+ // The dots last of the lines: a dot marks a join, so no line of the drawing may be drawn over it.
1273
+ for (const dot of junctions)
1274
+ shapes.push(dot);
1275
+ // The assembled drawing, checked once: every segment of every drawn edge against every box it does not terminate
1276
+ // at. Each candidate route was checked before it was emitted, so this pass is the assertion that no stage slipped a
1277
+ // segment through a box - and the place a router that found no way round is reported rather than hidden.
1278
+ const boxEntries = Array.from(boxes.entries());
1279
+ const routingFailures = [];
1280
+ for (const { shape, edge } of routes) {
1281
+ const diagramEdge = diagram.edges[edge];
1282
+ const source = endBox(diagramEdge.from);
1283
+ const target = endBox(diagramEdge.to);
1284
+ if (source === undefined || target === undefined)
1285
+ continue;
1286
+ for (const segment of segmentsOfRoute(shape)) {
1287
+ for (const [id, box] of boxEntries) {
1288
+ if (box === source || box === target)
1289
+ continue;
1290
+ if (!crossesBox(segment.x1, segment.y1, segment.x2, segment.y2, box))
1291
+ continue;
1292
+ routingFailures.push({
1293
+ edge,
1294
+ from: diagramEdge.from,
1295
+ to: diagramEdge.to,
1296
+ box: id,
1297
+ x1: segment.x1,
1298
+ y1: segment.y1,
1299
+ x2: segment.x2,
1300
+ y2: segment.y2,
1301
+ });
1302
+ }
1303
+ }
857
1304
  }
858
1305
  // Labels last. A label has to clear every other edge, and until the last edge is drawn the painter does not know
859
1306
  // where those are: this is why the whole pass exists rather than a decision made edge by edge.
860
- const routeSegments = routes.map((shape) => segmentsOfRoute(shape));
1307
+ const routeSegments = routes.map(({ shape }) => segmentsOfRoute(shape));
861
1308
  const placedLabels = [];
862
- routes.forEach((shape, index) => {
863
- const run = longestRun(pointsOfRoute(shape));
864
- // The middle of the longest run is where the label belongs; a label with nothing to avoid stays exactly there.
865
- let spot = { x: (run.from.x + run.to.x) / 2, y: (run.from.y + run.to.y) / 2, width: textWidth(shape.label), height: LABEL_HEIGHT };
866
- if (shape.label !== '') {
867
- spot = placeLabel(shape.label, run.from, run.to, boxList, placedLabels, routeSegments.flatMap((list, at) => (at === index ? [] : list)));
868
- placedLabels.push(spot);
869
- }
870
- shape.labelX = spot.x;
871
- shape.labelY = spot.y;
1309
+ routes.forEach(({ shape, fixed }, at) => {
1310
+ if (fixed) {
1311
+ if (shape.label !== '') {
1312
+ placedLabels.push({ x: shape.labelX, y: shape.labelY, width: textWidth(shape.label), height: LABEL_HEIGHT });
1313
+ }
1314
+ return;
1315
+ }
1316
+ if (shape.label === '')
1317
+ return;
1318
+ const placement = placeLabel(shape.label, pointsOfRoute(shape), boxList, placedLabels, routeSegments.filter((_, other) => other !== at));
1319
+ shape.labelX = placement.x;
1320
+ shape.labelY = placement.y;
1321
+ shape.labelPlacement = {
1322
+ run: placement.run,
1323
+ collisions: placement.collisions,
1324
+ boxes: placement.boxes,
1325
+ labels: placement.labels,
1326
+ edges: placement.edges,
1327
+ };
1328
+ placedLabels.push({ x: placement.x, y: placement.y, width: placement.width, height: placement.height });
872
1329
  });
1330
+ const labelCollisions = routes.reduce((total, { shape }) => total + ((shape.labelPlacement?.collisions ?? 0) > 0 ? 1 : 0), 0);
873
1331
  shapes.push({ kind: 'title', x: MARGIN, y: MARGIN + 12, text: diagram.title, colour: 'text' });
874
1332
  const contentRight = Math.max(MARGIN, ...Array.from(boxes.values(), (box) => box.x + box.width), ...Array.from(groupRects.values(), (rect) => rect.x + rect.width));
875
1333
  const captionLines = wrap(diagram.caption, CAPTION_CHARS);
@@ -884,7 +1342,10 @@ export function paintWith(diagram, overrides = {}, options = {}) {
884
1342
  const extent = drawnExtent(shapes);
885
1343
  const canvasWidth = Math.max(width, extent.width + MARGIN);
886
1344
  const canvasHeight = Math.max(height, extent.height + MARGIN);
887
- return { canvas: { width: Math.round(canvasWidth), height: Math.round(canvasHeight), shapes }, colours };
1345
+ return {
1346
+ canvas: { width: Math.round(canvasWidth), height: Math.round(canvasHeight), shapes, routingFailures, labelCollisions },
1347
+ colours,
1348
+ };
888
1349
  }
889
1350
  export function paint(diagram, overrides = {}) {
890
1351
  return paintWith(diagram, overrides).canvas;