@sentropic/diagram-canvas 0.3.1 → 0.4.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.
Files changed (53) hide show
  1. package/README.md +23 -2
  2. package/dist/camera.d.ts +28 -9
  3. package/dist/camera.js +34 -13
  4. package/dist/index.d.ts +4 -0
  5. package/dist/index.js +4 -0
  6. package/dist/layout/cache.js +12 -2
  7. package/dist/layout/channels.d.ts +10 -0
  8. package/dist/layout/channels.js +13 -0
  9. package/dist/layout/conventions.d.ts +117 -0
  10. package/dist/layout/conventions.js +185 -0
  11. package/dist/layout/dock.d.ts +2 -0
  12. package/dist/layout/dock.js +5 -1
  13. package/dist/layout/fingerprint.d.ts +4 -2
  14. package/dist/layout/fingerprint.js +26 -2
  15. package/dist/layout/hints.d.ts +1 -1
  16. package/dist/layout/hints.js +10 -3
  17. package/dist/layout/index.d.ts +5 -3
  18. package/dist/layout/index.js +5 -3
  19. package/dist/layout/labels.d.ts +2 -0
  20. package/dist/layout/labels.js +2 -0
  21. package/dist/layout/measure.d.ts +6 -0
  22. package/dist/layout/measure.js +28 -0
  23. package/dist/layout/measured.js +1051 -100
  24. package/dist/layout/route.d.ts +27 -1
  25. package/dist/layout/route.js +640 -32
  26. package/dist/layout/routeSpacing.d.ts +84 -0
  27. package/dist/layout/routeSpacing.js +472 -0
  28. package/dist/layout/spacing.generated.d.ts +10 -1
  29. package/dist/layout/spacing.generated.js +10 -1
  30. package/dist/layout/types.d.ts +33 -2
  31. package/dist/layout/types.js +2 -0
  32. package/dist/presentation/connectorPath.d.ts +32 -0
  33. package/dist/presentation/connectorPath.js +213 -0
  34. package/dist/presentation/connectorStyle.d.ts +70 -0
  35. package/dist/presentation/connectorStyle.js +99 -0
  36. package/dist/presentation/diagramCardModel.d.ts +1 -1
  37. package/dist/presentation/diagramCardModel.js +1 -1
  38. package/dist/presentation/diagramSceneModel.d.ts +58 -7
  39. package/dist/presentation/diagramSceneModel.js +225 -35
  40. package/dist/presentation/diagramSceneTypes.d.ts +9 -0
  41. package/dist/presentation/index.d.ts +4 -0
  42. package/dist/presentation/index.js +4 -0
  43. package/dist/presentation/linkLegend.d.ts +132 -0
  44. package/dist/presentation/linkLegend.js +231 -0
  45. package/dist/presentation/renderSceneSvg.d.ts +3 -1
  46. package/dist/presentation/renderSceneSvg.js +81 -11
  47. package/dist/presentation/sceneLabelClearance.d.ts +1 -1
  48. package/dist/presentation/sceneLabelClearance.js +19 -3
  49. package/dist/r7Mode.d.ts +13 -0
  50. package/dist/r7Mode.js +67 -0
  51. package/dist/visibility.d.ts +1 -1
  52. package/dist/visibility.js +3 -2
  53. package/package.json +2 -2
@@ -3,7 +3,8 @@ import { validateFlows } from "@sentropic/diagram-core";
3
3
  import { relationVerdict } from "../visibility.js";
4
4
  import { DEFAULT_FLOW_TOKENS, planFlows, placeFlowMarks } from "./flows.js";
5
5
  import { layoutErd } from "./erd.js";
6
- import { DEFAULT_MIN_READABLE_SCALE } from "../camera.js";
6
+ import { DEFAULT_EDGE_LABEL_SIZE } from "../camera.js";
7
+ import { diagramAnatomyOf, isR7ConnectorPresentation } from "../r7Mode.js";
7
8
  /**
8
9
  * Measured diagram layout (M3 §4.6–§4.8, layout half of §5.6; placement by
9
10
  * SPEC_EVOL_DC2A §3–§4).
@@ -30,18 +31,20 @@ import { DEFAULT_MIN_READABLE_SCALE } from "../camera.js";
30
31
  * with one `docking-overflow` per occurrence. No slot is ever truncated,
31
32
  * clipped or ellipsised.
32
33
  */
33
- import { collapsedOf, createTypeResolver, foldGroupId, GENERIC_PROFILE_ID, hasErrors, isPresentationContractV2Pin, localIdOf, occurrenceRef, parentOccurrenceOf, projectView, validateDocument, validateView, viewRef, } from "@sentropic/diagram-core";
34
- import { dockEdges } from "./dock.js";
34
+ import { collapsedOf, createTypeResolver, foldGroupId, GENERIC_PROFILE_ID, hasErrors, isArrowheadKind, isLinkEmphasis, isPresentationContractV2Pin, isStrokeStyle, localIdOf, occurrenceRef, parentOccurrenceOf, projectView, resolveArrowhead, resolveDashPattern, resolveLinkEmphasis, validateDocument, validateView, viewRef, } from "@sentropic/diagram-core";
35
+ import { dockEdges, sideToward } from "./dock.js";
35
36
  import { isAncestor } from "./graph.js";
36
37
  import { effectiveStretch, groupLeaves, isLayoutGroup, resolveGaps, resolveOrder, resolveRowGaps, validateHints, } from "./hints.js";
37
38
  import { measureSceneBox } from "./sceneMeasure.js";
38
39
  import { anatomyCardGeometry, anatomyZoneGeometry, ZONE_GEOMETRY, zoneDepthSurface } from "../presentation/diagramCardModel.js";
39
- import { placePackedLabel } from "./labels.js";
40
- import { CONTENT_INSET, DEFAULT_ALLOCATED_LINES, FIXED_CARD_HEIGHT, FIXED_CARD_WIDTH, headerAvailableWidth, headerOverflows, innerWidthOf, LEGEND_KEY_HEIGHT, measureHeader, SWATCH_ALLOCATION, TOGGLE_ALLOCATION, UNWRAPPED_PROBE_WIDTH, } from "./measure.js";
40
+ import { LABEL_CLEARANCE_REFERENCE_SCALE, placePackedLabel } from "./labels.js";
41
+ import { CONTENT_INSET, DEFAULT_ALLOCATED_LINES, FIXED_CARD_HEIGHT, FIXED_CARD_WIDTH, headerAvailableWidth, headerOverflows, innerWidthOf, LEGEND_KEY_HEIGHT, measureHeader, scaleEdgeLabelMeasurer, SWATCH_ALLOCATION, TOGGLE_ALLOCATION, UNWRAPPED_PROBE_WIDTH, } from "./measure.js";
41
42
  import { measureBundleLabel } from "./bundleLabel.js";
42
- import { channelGap, channelMetrics } from "./channels.js";
43
+ import { channelCapacity, channelGap, channelMetrics } from "./channels.js";
43
44
  import { chooseOrientation, packColumns, packRows, seatShelves } from "./pack.js";
44
45
  import { labelDetour, routeEdges, routesConflict } from "./route.js";
46
+ import { checkRouteSpacing, DEFAULT_ROUTE_BORDER_CLEARANCE, DEFAULT_ROUTE_SPACING, segmentToPassableBorderDistance, segmentToRectDistance, } from "./routeSpacing.js";
47
+ import { lintDiagramConventions } from "./conventions.js";
45
48
  import { rectsIntersect } from "../geometry.js";
46
49
  import { evaluateVisibility } from "../visibility.js";
47
50
  import { DEFAULT_LAYOUT_METRICS, MIN_ZOOM, PHONE_MAX_WIDTH, resolveRowPack, ROOT_LEVEL_KEY, validateRowPack, } from "./types.js";
@@ -77,7 +80,154 @@ function persistableDiagramPresentation(presentation) {
77
80
  }
78
81
  entities[key] = cleanEntry;
79
82
  }
80
- return { ...presentation, entities };
83
+ const { relations: _transientRelations, ...base } = presentation;
84
+ void _transientRelations;
85
+ return { ...base, entities };
86
+ }
87
+ function relationPresentationFor(relations, occurrence, relation) {
88
+ if (relations === undefined)
89
+ return undefined;
90
+ return relations[occurrence] ?? relations[relation];
91
+ }
92
+ const ALLOWED_RELATION_OCCURRENCE_FIELDS = new Set([
93
+ "id",
94
+ "relation",
95
+ "endpoints",
96
+ "waypoints",
97
+ "strokeStyle",
98
+ "arrowhead",
99
+ "emphasis",
100
+ ]);
101
+ function validateRelationPresentations(relations, contractPin, sourceView) {
102
+ const refusals = [];
103
+ const isV2 = contractPin !== undefined && isPresentationContractV2Pin(contractPin);
104
+ const isFrozenV1 = contractPin !== undefined && !isV2;
105
+ if (relations !== undefined && (relations === null || typeof relations !== "object" || Array.isArray(relations))) {
106
+ refusals.push({ code: "document-invalid", path: "presentation.relations", message: "connector styles must be keyed by relation" });
107
+ }
108
+ else if (relations !== undefined) {
109
+ const keys = Object.keys(relations).sort(byString);
110
+ if (isFrozenV1 && keys.length > 0) {
111
+ for (const key of keys) {
112
+ refusals.push({
113
+ code: "document-invalid",
114
+ path: `presentation.relations.${key}`,
115
+ message: "presentation.relations requires diagram-presentation@2; frozen diagram-presentation@1 cannot persist DE-2 connector styles",
116
+ });
117
+ }
118
+ }
119
+ for (const key of keys) {
120
+ const entry = relations[key];
121
+ if (entry === undefined)
122
+ continue;
123
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
124
+ refusals.push({ code: "document-invalid", path: `presentation.relations.${key}`, message: "connector style must be a record" });
125
+ continue;
126
+ }
127
+ for (const field of Object.keys(entry).sort(byString)) {
128
+ if (field !== "strokeStyle" && field !== "arrowhead" && field !== "emphasis") {
129
+ refusals.push({
130
+ code: "document-invalid",
131
+ path: `presentation.relations.${key}.${field}`,
132
+ message: `unknown connector presentation field ${field}; select connectors by closed registry words only`,
133
+ });
134
+ }
135
+ }
136
+ if (entry["strokeStyle"] !== undefined && !isStrokeStyle(entry["strokeStyle"])) {
137
+ refusals.push({
138
+ code: "document-invalid",
139
+ path: `presentation.relations.${key}.strokeStyle`,
140
+ message: `strokeStyle ${String(entry["strokeStyle"])} is not a closed dash-pattern registry word`,
141
+ });
142
+ }
143
+ if (entry["arrowhead"] !== undefined && !isArrowheadKind(entry["arrowhead"])) {
144
+ refusals.push({
145
+ code: "document-invalid",
146
+ path: `presentation.relations.${key}.arrowhead`,
147
+ message: `arrowhead ${String(entry["arrowhead"])} is not a closed arrowhead registry word`,
148
+ });
149
+ }
150
+ if (entry["emphasis"] !== undefined && !isLinkEmphasis(entry["emphasis"])) {
151
+ refusals.push({
152
+ code: "document-invalid",
153
+ path: `presentation.relations.${key}.emphasis`,
154
+ message: `emphasis ${String(entry["emphasis"])} is not a closed link-emphasis registry word`,
155
+ });
156
+ }
157
+ }
158
+ }
159
+ if (sourceView !== undefined) {
160
+ for (const key of Object.keys(sourceView.relationOccurrences).sort(byString)) {
161
+ const occurrence = sourceView.relationOccurrences[key];
162
+ if (occurrence === undefined)
163
+ continue;
164
+ if (occurrence === null || typeof occurrence !== "object" || Array.isArray(occurrence)) {
165
+ refusals.push({ code: "document-invalid", path: `sourceView.relationOccurrences.${key}`, message: "relation occurrence must be a record" });
166
+ continue;
167
+ }
168
+ for (const field of Object.keys(occurrence).sort(byString)) {
169
+ if (!ALLOWED_RELATION_OCCURRENCE_FIELDS.has(field)) {
170
+ refusals.push({
171
+ code: "document-invalid",
172
+ path: `sourceView.relationOccurrences.${key}.${field}`,
173
+ message: `unknown connector occurrence field ${field}; select connectors by closed registry words only`,
174
+ });
175
+ }
176
+ }
177
+ const strokeStyle = occurrence["strokeStyle"];
178
+ if (strokeStyle !== undefined) {
179
+ if (!isStrokeStyle(strokeStyle)) {
180
+ refusals.push({
181
+ code: "document-invalid",
182
+ path: `sourceView.relationOccurrences.${key}.strokeStyle`,
183
+ message: `strokeStyle ${String(strokeStyle)} is not a closed dash-pattern registry word`,
184
+ });
185
+ }
186
+ else if (isFrozenV1 && strokeStyle === "dotted") {
187
+ refusals.push({
188
+ code: "document-invalid",
189
+ path: `sourceView.relationOccurrences.${key}.strokeStyle`,
190
+ message: "strokeStyle dotted requires diagram-presentation@2 under view validation",
191
+ });
192
+ }
193
+ }
194
+ const arrowhead = occurrence["arrowhead"];
195
+ if (arrowhead !== undefined) {
196
+ if (!isArrowheadKind(arrowhead)) {
197
+ refusals.push({
198
+ code: "document-invalid",
199
+ path: `sourceView.relationOccurrences.${key}.arrowhead`,
200
+ message: `arrowhead ${String(arrowhead)} is not a closed arrowhead registry word`,
201
+ });
202
+ }
203
+ else if (isFrozenV1) {
204
+ refusals.push({
205
+ code: "document-invalid",
206
+ path: `sourceView.relationOccurrences.${key}.arrowhead`,
207
+ message: "arrowhead requires diagram-presentation@2 under view validation",
208
+ });
209
+ }
210
+ }
211
+ const emphasis = occurrence["emphasis"];
212
+ if (emphasis !== undefined) {
213
+ if (!isLinkEmphasis(emphasis)) {
214
+ refusals.push({
215
+ code: "document-invalid",
216
+ path: `sourceView.relationOccurrences.${key}.emphasis`,
217
+ message: `emphasis ${String(emphasis)} is not a closed link-emphasis registry word`,
218
+ });
219
+ }
220
+ else if (isFrozenV1) {
221
+ refusals.push({
222
+ code: "document-invalid",
223
+ path: `sourceView.relationOccurrences.${key}.emphasis`,
224
+ message: "emphasis requires diagram-presentation@2 under view validation",
225
+ });
226
+ }
227
+ }
228
+ }
229
+ }
230
+ return refusals;
81
231
  }
82
232
  /** Slot text for one occurrence: typed presentation slots, else the semantic name as title. */
83
233
  function slotTexts(document, presentation, occurrence, entity) {
@@ -165,6 +315,10 @@ const OUTER_LANES = 6;
165
315
  /** MAJ-1: at most one widening round after pass 1 (BF-6); afterwards the set only shrinks. */
166
316
  const WIDEN_ROUNDS = 1;
167
317
  export function layoutMeasured(document, options, sourceView) {
318
+ const relationStyleRefusals = validateRelationPresentations(options.presentation?.relations, options.presentation?.contractPin ?? sourceView?.presentation.diagram?.contractPin, sourceView);
319
+ if (relationStyleRefusals.length > 0) {
320
+ return { status: "refused", refusals: relationStyleRefusals, diagnostics: [] };
321
+ }
168
322
  if (document.profileRefs.length === 1 && document.profileRefs[0] === "erd@1")
169
323
  return layoutErd(document, options, sourceView);
170
324
  const first = layoutMeasuredPass(document, options, sourceView, new Set());
@@ -212,8 +366,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
212
366
  * absent everywhere means `"v1"` so existing views keep the frozen `460 × 200`
213
367
  * footprint by construction.
214
368
  */
215
- const viewAnatomy = sourceView?.presentation?.anatomy;
216
- const occurrenceAnatomy = (occurrence) => presentation.entities[occurrence]?.anatomy ?? viewAnatomy ?? "v1";
369
+ const occurrenceAnatomy = (occurrence) => diagramAnatomyOf(presentation, sourceView, occurrence);
217
370
  const cardWidthOf = (occurrence) => anatomyCardGeometry(occurrenceAnatomy(occurrence)).width;
218
371
  if (options.measureLines === undefined) {
219
372
  return {
@@ -235,8 +388,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
235
388
  let box = sceneBoxCache.get(key);
236
389
  if (box === undefined) {
237
390
  const rawEntry = presentation.entities[id];
238
- const entry = rawEntry === undefined ? undefined
239
- : rawEntry.anatomy === undefined && viewAnatomy !== undefined ? { ...rawEntry, anatomy: viewAnatomy } : rawEntry;
391
+ const entry = rawEntry === undefined ? undefined : { ...rawEntry, anatomy: occurrenceAnatomy(id) };
240
392
  const kind = kinds.get(projected.entityOccurrences[id]?.entity);
241
393
  const expanded = kind === "container-expanded" || kind === "legend-expanded";
242
394
  box = measureSceneBox(expanded && entry?.form === "card" ? { ...entry, form: "container" } : entry, id, width, collapsed, measure, metrics.containerPadding);
@@ -257,7 +409,21 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
257
409
  if ("refusals" in read)
258
410
  return { status: "refused", refusals: read.refusals, diagnostics: [] };
259
411
  const graph = read.graph;
260
- const metrics = { ...DEFAULT_LAYOUT_METRICS, ...options.metrics, slotSpacing: options.metrics?.slotSpacing ?? options.metrics?.trackSpacing ?? channelMetrics({}, true).trackSpacing };
412
+ const r7Routing = isR7ConnectorPresentation(presentation, sourceView, document);
413
+ const routeSpacing = r7Routing ? (options.metrics?.routeSpacing ?? DEFAULT_ROUTE_SPACING) : 0;
414
+ const borderClearance = r7Routing
415
+ ? (options.metrics?.routeBorderClearance ?? DEFAULT_ROUTE_BORDER_CLEARANCE)
416
+ : (options.metrics?.clearance ?? DEFAULT_LAYOUT_METRICS.clearance);
417
+ const dockCornerInset = routeSpacing > 0 ? Math.ceil(routeSpacing / Math.SQRT2) : 0;
418
+ const baseSlotSpacing = options.metrics?.trackSpacing ?? channelMetrics({}, true).trackSpacing;
419
+ const metrics = {
420
+ ...DEFAULT_LAYOUT_METRICS,
421
+ ...options.metrics,
422
+ routeSpacing,
423
+ routeBorderClearance: borderClearance,
424
+ slotSpacing: options.metrics?.slotSpacing ??
425
+ (r7Routing ? Math.max(routeSpacing, baseSlotSpacing) : baseSlotSpacing),
426
+ };
261
427
  const hints = options.hints ?? {};
262
428
  const gaps = resolveGaps(options.hints, metrics);
263
429
  const globalStretch = hints.stretch ?? false;
@@ -266,6 +432,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
266
432
  const rowPack = resolveRowPack(options.rowPack);
267
433
  const contentInset = metrics.containerPadding;
268
434
  const rowGaps = resolveRowGaps(hints, metrics);
435
+ const zoneGutter = resolveRowGaps(hints, metrics, r7Routing).zoneX;
269
436
  {
270
437
  const refusals = [...validateRowPack(rowPack)];
271
438
  // §3.7: a sibling-gap override above the axis cap refuses; it is never silently capped.
@@ -279,9 +446,9 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
279
446
  });
280
447
  };
281
448
  refuseGap("hints.cardGapX", "cardGapX", rowGaps.cardX, rowGaps.maxX);
282
- refuseGap("hints.zoneGapX", "zoneGapX", rowGaps.zoneX, rowGaps.maxX);
449
+ refuseGap("hints.zoneGapX", "zoneGapX", hints.zoneGapX ?? rowGaps.zoneX, rowGaps.maxX);
283
450
  refuseGap("hints.cardGapY", "cardGapY", rowGaps.cardY, rowGaps.maxY);
284
- refuseGap("hints.zoneGapY", "zoneGapY", rowGaps.zoneY, rowGaps.maxY);
451
+ refuseGap("hints.zoneGapY", "zoneGapY", hints.zoneGapY ?? rowGaps.zoneY, rowGaps.maxY);
285
452
  // A group's `gapAfter` lands on whichever axis its level packs along: it is held to both caps.
286
453
  const visitGap = (group, path) => {
287
454
  if (group.gapAfter !== undefined) {
@@ -367,6 +534,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
367
534
  const targetOccurrence = edge.target.port === undefined
368
535
  ? occurrenceOf(edge.target.entity)
369
536
  : occurrenceRef(`p.s.${coded(localIdOf(edge.target.port))}`);
537
+ const style = relationPresentationFor(presentation.relations, occurrence, edge.id);
370
538
  relationOccurrences[occurrence] = {
371
539
  id: occurrence,
372
540
  relation: edge.id,
@@ -374,6 +542,9 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
374
542
  { role: "source", occurrence: sourceOccurrence },
375
543
  { role: "target", occurrence: targetOccurrence },
376
544
  ],
545
+ ...(style?.strokeStyle === undefined ? {} : { strokeStyle: style.strokeStyle }),
546
+ ...(style?.arrowhead === undefined ? {} : { arrowhead: style.arrowhead }),
547
+ ...(style?.emphasis === undefined ? {} : { emphasis: style.emphasis }),
377
548
  };
378
549
  }
379
550
  return {
@@ -444,10 +615,19 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
444
615
  const list = entityToOccurrences.get(entity) ?? [];
445
616
  return (list.find((occurrence) => visibleOccurrences.has(occurrence)) ?? list[0] ?? occurrenceOf(entity));
446
617
  };
618
+ const anatomyOverrides = Object.fromEntries(Object.keys(projected.entityOccurrences).flatMap((id) => {
619
+ const anatomy = presentation.entities[id]?.anatomy ?? sourceView?.presentation.entityAnatomy?.[id];
620
+ return anatomy === undefined || anatomy === (projected.presentation.anatomy ?? "v1") ? [] : [[id, anatomy]];
621
+ }));
622
+ const { entityAnatomy: _previousAnatomy, ...projectedPresentation } = projected.presentation;
447
623
  const foldMetadata = {
448
624
  groups: projected.groups,
449
625
  filters: [...projected.filters],
450
- presentationState: { ...projected.presentation, diagram: persistableDiagramPresentation(presentation) },
626
+ presentationState: {
627
+ ...projectedPresentation,
628
+ ...(Object.keys(anatomyOverrides).length === 0 ? {} : { entityAnatomy: anatomyOverrides }),
629
+ diagram: persistableDiagramPresentation(presentation),
630
+ },
451
631
  summaryLabels: projected.summaryLabels,
452
632
  projected,
453
633
  representativeOf,
@@ -587,7 +767,9 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
587
767
  : { run: buildGroupRun(part.group, `${key}#${part.group.id}`, globalStretch), gapAfter: part.group.gapAfter });
588
768
  return { key, mode: "auto", items, stretch: false };
589
769
  };
590
- const runHasZone = (run) => run.items.some((item) => ("entity" in item ? kinds.get(item.entity) !== "leaf" : runHasZone(item.run)));
770
+ const itemHasZone = (item) => "entity" in item ? kinds.get(item.entity) !== "leaf" : runHasZone(item.run);
771
+ const runHasZone = (run) => run.items.some(itemHasZone);
772
+ const shelfHasZone = (run, shelf) => shelf.some((slot) => itemHasZone(run.items[slot]));
591
773
  // Drawn edges: the link occurrences the projected view draws. Internal
592
774
  // edges under a collapse are excluded by the same visibility; every
593
775
  // surviving edge carries its projected representative endpoints, and
@@ -633,7 +815,21 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
633
815
  const projectedEdge = projected.relationOccurrences[edge.occurrence];
634
816
  if (!projectedEdge.endpoints.some(end => end.sourceOccurrence !== undefined))
635
817
  continue;
636
- const key = JSON.stringify([edge.source.entity, edge.target.entity]);
818
+ let key;
819
+ if (r7Routing) {
820
+ // Keep lifted cross-zone edges with distinct connector styles apart so
821
+ // bundling never silently drops a strokeStyle, arrowhead, or emphasis from
822
+ // the scene or its automatic link legend (REQ-R7-05 / REQ-R7-11 / REQ-R7-12).
823
+ const relStyle = relationPresentationFor(presentation.relations, projectedEdge.id, projectedEdge.relation);
824
+ const strokeStyle = resolveDashPattern(projectedEdge.strokeStyle ?? relStyle?.strokeStyle)?.style ?? "solid";
825
+ const arrowhead = resolveArrowhead(projectedEdge.arrowhead ?? relStyle?.arrowhead)?.canonicalKind ?? "arrow";
826
+ const emphasis = resolveLinkEmphasis(projectedEdge.emphasis ?? relStyle?.emphasis)?.emphasis ?? "default";
827
+ key = JSON.stringify([edge.source.entity, edge.target.entity, strokeStyle, arrowhead, emphasis]);
828
+ }
829
+ else {
830
+ // Legacy @1 path preserves main endpoint-pair bundling regardless of strokeStyle (REQ-R7-28).
831
+ key = JSON.stringify([edge.source.entity, edge.target.entity]);
832
+ }
637
833
  const pair = liftedPairs.get(key) ?? [];
638
834
  pair.push(edge);
639
835
  liftedPairs.set(key, pair);
@@ -683,6 +879,8 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
683
879
  })),
684
880
  };
685
881
  // Edge labels, measured once: keyed by the projected relation occurrence id.
882
+ // Scale measured boxes when `metrics.edgeLabelSize` overrides the default 18 px token.
883
+ const edgeLabelMeasure = scaleEdgeLabelMeasurer(measure, r7Routing ? metrics.edgeLabelSize : undefined, DEFAULT_EDGE_LABEL_SIZE);
686
884
  const labelSizes = new Map();
687
885
  const edgeLayouts = new Map();
688
886
  for (const edge of drawnEdges) {
@@ -692,8 +890,8 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
692
890
  if (label === undefined)
693
891
  continue;
694
892
  const bundle = edgeBundles[edge.occurrence];
695
- const chip = bundle?.relations === undefined ? undefined : measureBundleLabel(bundle.relations, measure, metrics.bundleLabelMaxWidth, bundle.members.length);
696
- const layout = chip === undefined ? measure({
893
+ const chip = bundle?.relations === undefined ? undefined : measureBundleLabel(bundle.relations, edgeLabelMeasure, metrics.bundleLabelMaxWidth, bundle.members.length);
894
+ const layout = chip === undefined ? edgeLabelMeasure({
697
895
  text: label,
698
896
  role: "edge-label",
699
897
  availableWidth: EDGE_LABEL_WIDTH,
@@ -751,7 +949,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
751
949
  * and orientations chosen. With a plan, shelves and orientations are the
752
950
  * frozen ones of pass 1 and the listed gutters take their asked gap.
753
951
  */
754
- const runPass = (plan) => {
952
+ const runPass = (plan, orientationOverrides) => {
755
953
  const warnings = [];
756
954
  const overflows = [];
757
955
  const warnOverflow = (overflow, zone) => {
@@ -824,8 +1022,9 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
824
1022
  });
825
1023
  }
826
1024
  const zone = runHasZone(run);
827
- const baseX = zone ? rowGaps.zoneX : rowGaps.cardX;
828
- const baseY = zone ? rowGaps.zoneY : rowGaps.cardY;
1025
+ const hasSiblingZones = r7Routing && run.items.filter(itemHasZone).length > 1;
1026
+ const baseX = hasSiblingZones ? zoneGutter : zone ? rowGaps.zoneX : rowGaps.cardX;
1027
+ const baseY = hasSiblingZones ? zoneGutter : zone ? rowGaps.zoneY : rowGaps.cardY;
829
1028
  const packOptions = {
830
1029
  targetAspect: rowPack.targetAspect,
831
1030
  gapX: baseX,
@@ -838,7 +1037,12 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
838
1037
  const frozen = plan?.frozen.get(run.key);
839
1038
  let orientation;
840
1039
  let shelves;
841
- if (frozen !== undefined && frozen.shelves.reduce((count, shelf) => count + shelf.length, 0) === boxes.length) {
1040
+ const forcedOrientation = run.mode === "auto" ? orientationOverrides?.get(run.key) : undefined;
1041
+ if (forcedOrientation !== undefined) {
1042
+ orientation = forcedOrientation;
1043
+ shelves = (forcedOrientation === "rows" ? packRows : packColumns)(boxes, packOptions).rows;
1044
+ }
1045
+ else if (frozen !== undefined && frozen.shelves.reduce((count, shelf) => count + shelf.length, 0) === boxes.length) {
842
1046
  orientation = frozen.orientation;
843
1047
  shelves = frozen.shelves;
844
1048
  }
@@ -864,15 +1068,40 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
864
1068
  const rows = orientation === "rows";
865
1069
  const alongBase = rows ? baseX : baseY;
866
1070
  const acrossBase = rows ? baseY : baseX;
1071
+ const cardAlongBase = rows ? rowGaps.cardX : rowGaps.cardY;
1072
+ const cardAcrossBase = rows ? rowGaps.cardY : rowGaps.cardX;
1073
+ const zoneAlongBase = rows ? rowGaps.zoneX : rowGaps.zoneY;
1074
+ const zoneAcrossBase = rows ? rowGaps.zoneY : rowGaps.zoneX;
867
1075
  // §3.5: a gutter keeps its base gap (or the authored `gapAfter` of the
868
1076
  // group before it) unless the plan widens it for a label. One along gap
869
1077
  // per slot index on every shelf: the grid keeps its column starts.
1078
+ // REQ-R7-14: only gutters between two zones use the fixed zone token.
870
1079
  const gapAfterOf = (slot) => {
871
1080
  const item = run.items[slot];
872
1081
  return "run" in item ? item.gapAfter : undefined;
873
1082
  };
874
- const seated = seatShelves(boxes, shelves, orientation, (shelf, slot) => Math.max(gapAfterOf(shelves[shelf][slot]) ?? alongBase, plan?.widen.get(`${run.key}|along|${String(slot)}`) ?? 0, plan?.widen.get(`${run.key}|along|${String(slot)}|${String(shelf)}`) ?? 0), (shelf) => {
1083
+ const seated = seatShelves(boxes, shelves, orientation, (shelf, slot) => {
1084
+ const leftSlot = shelves[shelf][slot];
1085
+ const rightSlot = shelves[shelf][slot + 1];
1086
+ if (r7Routing) {
1087
+ const leftZone = itemHasZone(run.items[leftSlot]);
1088
+ const rightZone = itemHasZone(run.items[rightSlot]);
1089
+ if (leftZone && rightZone)
1090
+ return zoneGutter;
1091
+ return Math.max(gapAfterOf(leftSlot) ?? (leftZone || rightZone ? zoneAlongBase : cardAlongBase), plan?.widen.get(`${run.key}|along|${String(slot)}`) ?? 0, plan?.widen.get(`${run.key}|along|${String(slot)}|${String(shelf)}`) ?? 0);
1092
+ }
1093
+ return Math.max(gapAfterOf(leftSlot) ?? alongBase, plan?.widen.get(`${run.key}|along|${String(slot)}`) ?? 0, plan?.widen.get(`${run.key}|along|${String(slot)}|${String(shelf)}`) ?? 0);
1094
+ }, (shelf) => {
875
1095
  const last = shelves[shelf][shelves[shelf].length - 1];
1096
+ if (r7Routing) {
1097
+ const nextShelf = shelves[shelf + 1];
1098
+ const currentZone = shelfHasZone(run, shelves[shelf]);
1099
+ const nextZone = shelfHasZone(run, nextShelf);
1100
+ if (currentZone && nextZone)
1101
+ return zoneGutter;
1102
+ const base = currentZone || nextZone ? zoneAcrossBase : cardAcrossBase;
1103
+ return Math.max(gapAfterOf(last) ?? base, plan?.widen.get(`${run.key}|across|${String(shelf)}`) ?? 0);
1104
+ }
876
1105
  return Math.max(gapAfterOf(last) ?? acrossBase, plan?.widen.get(`${run.key}|across|${String(shelf)}`) ?? 0);
877
1106
  });
878
1107
  packedRuns.set(run.key, { run, rows, shelves, boxes, positions: seated.positions, alongBase, acrossBase });
@@ -1070,7 +1299,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1070
1299
  const zoneGeo = anatomyZoneGeometry(occurrenceAnatomy(representativeOf(id)));
1071
1300
  const inner = innerWidthOf(size.width);
1072
1301
  rects.set(id, { x, y, width: size.width, height: size.height });
1073
- const ruleClearance = (zoneGeo.ruleHeight / 2 + 1) / DEFAULT_MIN_READABLE_SCALE;
1302
+ const ruleClearance = (zoneGeo.ruleHeight / 2 + 1) / LABEL_CLEARANCE_REFERENCE_SCALE;
1074
1303
  titleBands.set(id, { x, y, width: size.width, height: zoneGeo.headerInset + header.height });
1075
1304
  const footerReserve = sceneBoxAt(representativeOf(id), size.width, false).footerReserve;
1076
1305
  if (footerReserve > 0)
@@ -1174,39 +1403,44 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1174
1403
  // Footer bands constrain text placement. Routes may cross a zone's
1175
1404
  // footer while leaving it; a label on that route still has to clear it.
1176
1405
  // Header measurement ends at the rule's top. Reserve its non-scaling
1177
- // paint plus one CSS px at the display floor for label placement.
1406
+ // paint plus one CSS px at the fixed reference scale for label placement.
1178
1407
  // Routes may cross a rule while leaving their own zone.
1179
- const ruleClearance = (ZONE_GEOMETRY.ruleHeight / 2 + 1) / DEFAULT_MIN_READABLE_SCALE;
1408
+ const ruleClearance = (ZONE_GEOMETRY.ruleHeight / 2 + 1) / LABEL_CLEARANCE_REFERENCE_SCALE;
1180
1409
  const fixedShapes = [...routeShapes, ...[...titleBands.values()].map(band => ({
1181
1410
  x: band.x, y: band.y + band.height, width: band.width,
1182
1411
  height: ZONE_GEOMETRY.ruleHeight / 2 + ruleClearance,
1183
1412
  })), ...footerBands.values()];
1184
1413
  const zoneShapes = [...rects].filter(([id]) => isStretchedBox(id));
1185
1414
  const shapesByEdge = new Map();
1415
+ const passableZonesByEdge = new Map();
1186
1416
  for (const edge of drawnEdges) {
1187
1417
  const own = new Set();
1188
1418
  for (const end of [edge.source.entity, edge.target.entity]) {
1189
1419
  for (let current = placementParentOf(end); current !== undefined; current = placementParentOf(current))
1190
1420
  own.add(current);
1191
1421
  }
1192
- shapesByEdge.set(edge.occurrence, [
1422
+ const edgeId = edge.occurrence;
1423
+ shapesByEdge.set(edgeId, [
1193
1424
  ...routeShapes,
1194
1425
  ...zoneShapes.filter(([id]) => !own.has(id)).map(([, rect]) => rect),
1195
1426
  ]);
1427
+ passableZonesByEdge.set(edgeId, zoneShapes.filter(([id]) => own.has(id)).map(([, rect]) => rect));
1196
1428
  }
1197
1429
  const shapesOf = (id) => shapesByEdge.get(id) ?? routeShapes;
1198
- /** BF-3 `inner(C)`: the routable interior of an expanded container (BLK-3). */
1430
+ const passableZonesOf = (id) => passableZonesByEdge.get(id) ?? [];
1431
+ /** BF-3 `inner(C)`: the routable interior of an expanded container (BLK-3, DE-2 15px border clearance). */
1199
1432
  const innerOf = (container) => {
1200
1433
  const rect = rects.get(container);
1201
1434
  const band = titleBands.get(container);
1202
1435
  if (rect === undefined || band === undefined)
1203
1436
  return undefined;
1204
- const top = band.y + band.height + 4;
1437
+ const inset = routeSpacing > 0 ? Math.max(4, borderClearance) : 4;
1438
+ const top = band.y + band.height + inset;
1205
1439
  return {
1206
- x: rect.x + 4,
1440
+ x: rect.x + inset,
1207
1441
  y: top,
1208
- width: Math.max(0, rect.width - 8),
1209
- height: Math.max(0, rect.y + rect.height - top - 4),
1442
+ width: Math.max(0, rect.width - 2 * inset),
1443
+ height: Math.max(0, rect.y + rect.height - top - inset),
1210
1444
  };
1211
1445
  };
1212
1446
  const withinOf = new Map();
@@ -1282,9 +1516,12 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1282
1516
  const trackKey = `${containerKey}|${sideBySide ? Math.max(a.y + a.height, b.y + b.height) : Math.max(a.x + a.width, b.x + b.width)}`;
1283
1517
  const used = usedUTracks.get(trackKey) ?? 0;
1284
1518
  const depth = (sideBySide ? size.height : size.width) + 2 * probe;
1285
- const pitch = depth + 2 * metrics.labelMargin;
1519
+ const pitch = Math.max(depth + 2 * metrics.labelMargin, routeSpacing > 0 ? routeSpacing : 0);
1520
+ const uEdgeClearance = routeSpacing > 0 ? borderClearance : 0;
1286
1521
  const laneFreeRow = (side, attempt) => {
1287
- const base = side === "south" ? Math.max(a.y + a.height, b.y + b.height) : Math.min(a.y, b.y) - depth;
1522
+ const base = side === "south"
1523
+ ? Math.max(a.y + a.height, b.y + b.height) + uEdgeClearance
1524
+ : Math.min(a.y, b.y) - depth - uEdgeClearance;
1288
1525
  const top = side === "south" ? base + attempt * pitch : base - attempt * pitch;
1289
1526
  const centres = [a.x + a.width / 2, b.x + b.width / 2];
1290
1527
  const lane = { x: Math.min(...centres), y: top, width: Math.abs(centres[0] - centres[1]), height: depth };
@@ -1295,13 +1532,18 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1295
1532
  lane.y + lane.height > within.y + within.height)) {
1296
1533
  return false;
1297
1534
  }
1535
+ const laneCheck = uEdgeClearance > 0
1536
+ ? { x: lane.x, y: lane.y - uEdgeClearance, width: lane.width, height: lane.height + 2 * uEdgeClearance }
1537
+ : lane;
1298
1538
  const legs = [a, b].map((rect) => side === "south"
1299
1539
  ? { x: rect.x + rect.width / 2 - 1, y: rect.y + rect.height, width: 2, height: top - (rect.y + rect.height) }
1300
1540
  : { x: rect.x + rect.width / 2 - 1, y: top + depth, width: 2, height: rect.y - (top + depth) });
1301
- return ![lane, ...legs.filter((leg) => leg.height > 0)].some((zone) => shapesOf(id).some((shape) => rectsIntersect(shape, zone)));
1541
+ return ![laneCheck, ...legs.filter((leg) => leg.height > 0)].some((zone) => shapesOf(id).some((shape) => rectsIntersect(shape, zone)));
1302
1542
  };
1303
1543
  const laneFreeCol = (side, attempt) => {
1304
- const base = side === "east" ? Math.max(a.x + a.width, b.x + b.width) : Math.min(a.x, b.x) - depth;
1544
+ const base = side === "east"
1545
+ ? Math.max(a.x + a.width, b.x + b.width) + uEdgeClearance
1546
+ : Math.min(a.x, b.x) - depth - uEdgeClearance;
1305
1547
  const left = side === "east" ? base + attempt * pitch : base - attempt * pitch;
1306
1548
  const centres = [a.y + a.height / 2, b.y + b.height / 2];
1307
1549
  const lane = { x: left, y: Math.min(...centres), width: depth, height: Math.abs(centres[0] - centres[1]) };
@@ -1312,10 +1554,13 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1312
1554
  lane.y + lane.height > within.y + within.height)) {
1313
1555
  return false;
1314
1556
  }
1557
+ const laneCheck = uEdgeClearance > 0
1558
+ ? { x: lane.x - uEdgeClearance, y: lane.y, width: lane.width + 2 * uEdgeClearance, height: lane.height }
1559
+ : lane;
1315
1560
  const legs = [a, b].map((rect) => side === "east"
1316
1561
  ? { x: rect.x + rect.width, y: rect.y + rect.height / 2 - 1, width: left - (rect.x + rect.width), height: 2 }
1317
1562
  : { x: left + depth, y: rect.y + rect.height / 2 - 1, width: rect.x - (left + depth), height: 2 });
1318
- return ![lane, ...legs.filter((leg) => leg.width > 0)].some((zone) => shapesOf(id).some((shape) => rectsIntersect(shape, zone)));
1563
+ return ![laneCheck, ...legs.filter((leg) => leg.width > 0)].some((zone) => shapesOf(id).some((shape) => rectsIntersect(shape, zone)));
1319
1564
  };
1320
1565
  const outside = within !== undefined || !sideBySide
1321
1566
  ? undefined
@@ -1359,6 +1604,146 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1359
1604
  }
1360
1605
  }
1361
1606
  }
1607
+ // When route spacing is active:
1608
+ // 1. Avoid docking on the north face of an entity directly beneath its parent
1609
+ // zone's title band (gap < 2 * borderClearance cannot clear the title barrier).
1610
+ // 2. For cross-zone edges leaving an expanded zone `Z`, prefer an outer wall of
1611
+ // `Z` touched by the entity that faces toward the other end (and stays inside
1612
+ // any shared ancestor container `within`) over diving inward through `Z`'s
1613
+ // internal sibling gutters.
1614
+ const isNorthBlockedByTitle = (entity) => {
1615
+ const parent = placementParentOf(entity);
1616
+ if (parent === undefined)
1617
+ return false;
1618
+ const band = titleBands.get(parent);
1619
+ const rect = rects.get(entity);
1620
+ if (band === undefined || rect === undefined)
1621
+ return false;
1622
+ return rect.y - (band.y + band.height) < 2 * borderClearance - 1e-4;
1623
+ };
1624
+ const sideStaysInWithin = (entity, side, within) => {
1625
+ if (within === undefined)
1626
+ return true;
1627
+ const r = rects.get(entity);
1628
+ // Check that exiting on `side` by `borderClearance` (and clearing any immediate
1629
+ // parent wall between `entity` and `within`) stays inside `within`.
1630
+ const need = borderClearance;
1631
+ if (side === "west")
1632
+ return r.x - need >= within.x - 1e-4;
1633
+ if (side === "east")
1634
+ return r.x + r.width + need <= within.x + within.width + 1e-4;
1635
+ if (side === "north")
1636
+ return r.y - need >= within.y - 1e-4;
1637
+ return r.y + r.height + need <= within.y + within.height + 1e-4;
1638
+ };
1639
+ if (routeSpacing > 0) {
1640
+ const isDescendantOrSame = (node, ancestor) => {
1641
+ for (let cur = node; cur !== undefined; cur = placementParentOf(cur)) {
1642
+ if (cur === ancestor)
1643
+ return true;
1644
+ }
1645
+ return false;
1646
+ };
1647
+ const outerWallsOf = (entity, parent, within) => {
1648
+ const r = rects.get(entity);
1649
+ const p = rects.get(parent);
1650
+ const footerH = footerBands.get(parent)?.height ?? 0;
1651
+ const walls = [];
1652
+ // When `within` is defined (nested zones inside a shared ancestor), an outer wall
1653
+ // of `parent` is only usable if exiting `parent` by `borderClearance` still stays in `within`.
1654
+ const inWithin = (side) => {
1655
+ if (within === undefined)
1656
+ return true;
1657
+ if (side === "west")
1658
+ return p.x - borderClearance >= within.x - 1e-4;
1659
+ if (side === "east")
1660
+ return p.x + p.width + borderClearance <= within.x + within.width + 1e-4;
1661
+ return p.y + p.height + borderClearance <= within.y + within.height + 1e-4;
1662
+ };
1663
+ if (r.x - p.x <= contentInset + 1 && inWithin("west"))
1664
+ walls.push("west");
1665
+ if (p.x + p.width - (r.x + r.width) <= contentInset + 1 && inWithin("east"))
1666
+ walls.push("east");
1667
+ if (p.y + p.height - footerH - (r.y + r.height) <= contentInset + 1 && inWithin("south"))
1668
+ walls.push("south");
1669
+ return walls;
1670
+ };
1671
+ const redirectSide = (selfId, otherId, chosen, within) => {
1672
+ const self = rects.get(selfId);
1673
+ const other = rects.get(otherId);
1674
+ const selfCx = self.x + self.width / 2;
1675
+ const selfCy = self.y + self.height / 2;
1676
+ const otherCx = other.x + other.width / 2;
1677
+ const otherCy = other.y + other.height / 2;
1678
+ const parent = placementParentOf(selfId);
1679
+ // Cross-zone endpoint: prefer an outer wall of its immediate zone facing `other`
1680
+ // (never forcing a route away from `other` into an opposite saturated gutter).
1681
+ if (parent !== undefined && !isDescendantOrSame(otherId, parent)) {
1682
+ const outer = outerWallsOf(selfId, parent, within);
1683
+ if (outer.includes(chosen))
1684
+ return chosen;
1685
+ const facingOuter = outer.filter((side) => {
1686
+ if (side === "west")
1687
+ return otherCx < selfCx;
1688
+ if (side === "east")
1689
+ return otherCx > selfCx;
1690
+ return otherCy > selfCy;
1691
+ });
1692
+ if (facingOuter.length > 0) {
1693
+ const score = (side) => {
1694
+ if (side === "west")
1695
+ return -(selfCx - otherCx);
1696
+ if (side === "east")
1697
+ return -(otherCx - selfCx);
1698
+ return -(otherCy - selfCy);
1699
+ };
1700
+ return [...facingOuter].sort((a, b) => score(a) - score(b))[0];
1701
+ }
1702
+ }
1703
+ if (chosen !== "north" || !isNorthBlockedByTitle(selfId))
1704
+ return chosen;
1705
+ const candidates = ["east", "west", "south"].filter((s) => sideStaysInWithin(selfId, s, within));
1706
+ if (candidates.length === 0)
1707
+ return chosen;
1708
+ if (other.x >= self.x + self.width && candidates.includes("east"))
1709
+ return "east";
1710
+ if (self.x >= other.x + other.width && candidates.includes("west"))
1711
+ return "west";
1712
+ if (Math.abs(otherCx - selfCx) > 1e-4) {
1713
+ const pref = otherCx > selfCx ? "east" : "west";
1714
+ if (candidates.includes(pref))
1715
+ return pref;
1716
+ }
1717
+ if (parent !== undefined) {
1718
+ const parentRect = rects.get(parent);
1719
+ const distLeft = self.x - parentRect.x;
1720
+ const distRight = parentRect.x + parentRect.width - (self.x + self.width);
1721
+ const pref = distLeft <= distRight ? "west" : "east";
1722
+ if (candidates.includes(pref))
1723
+ return pref;
1724
+ }
1725
+ return candidates[0];
1726
+ };
1727
+ for (const edge of drawnEdges) {
1728
+ const id = edge.occurrence;
1729
+ if (sideOverrides.has(id))
1730
+ continue;
1731
+ const source = edge.source.entity;
1732
+ const target = edge.target.entity;
1733
+ if (source === target)
1734
+ continue;
1735
+ if (isAncestor(filteredGraph, source, target) || isAncestor(filteredGraph, target, source))
1736
+ continue;
1737
+ const within = withinOf.get(id);
1738
+ const sDefault = sideToward(rects.get(source), rects.get(target), "top-to-bottom");
1739
+ const tDefault = sideToward(rects.get(target), rects.get(source), "top-to-bottom");
1740
+ const sSide = redirectSide(source, target, sDefault, within);
1741
+ const tSide = redirectSide(target, source, tDefault, within);
1742
+ if (sSide !== sDefault || tSide !== tDefault) {
1743
+ sideOverrides.set(id, { source: sSide, target: tSide, turn: false });
1744
+ }
1745
+ }
1746
+ }
1362
1747
  // Dock and route against fixed boxes (§4.6.4/§4.6.5). Slots keep the
1363
1748
  // declared spacing: a label sits in a lane, not at its dock, so a side
1364
1749
  // does not spread its slots by the label width.
@@ -1370,6 +1755,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1370
1755
  metrics,
1371
1756
  labelSizes: new Map(),
1372
1757
  fixed: true,
1758
+ cornerInset: dockCornerInset,
1373
1759
  sideOverrides,
1374
1760
  });
1375
1761
  const finalDocks = new Map(docked.docks);
@@ -1399,18 +1785,12 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1399
1785
  });
1400
1786
  }
1401
1787
  }
1402
- const requests = drawnEdges.map((edge) => {
1788
+ const buildRequests = (docksMap) => drawnEdges.map((edge) => {
1403
1789
  const occurrence = projected.relationOccurrences[edge.occurrence];
1404
1790
  const sourceRole = occurrence.endpoints.find((endpoint) => endpoint.role === "source");
1405
1791
  const targetRole = occurrence.endpoints.find((endpoint) => endpoint.role === "target");
1406
1792
  const occurrenceId = edge.occurrence;
1407
- const pair = finalDocks.get(occurrenceId);
1408
- // BLK-3: containment is enforced by the `within` clamp (4 px insets) +
1409
- // escaped warnings below. Ancestors stay passable so the interior of the
1410
- // shared container remains routable; the clamp prevents exiting it.
1411
- // (Excluding the shared container itself from `passable` blocks its
1412
- // whole grown box, leaving no route inside `within` — evidenced by
1413
- // 0→93 escapes — so it is not done here.)
1793
+ const pair = docksMap.get(occurrenceId);
1414
1794
  const passable = new Set([
1415
1795
  ...projectedAncestorsOf(sourceRole.occurrence),
1416
1796
  ...projectedAncestorsOf(targetRole.occurrence),
@@ -1429,6 +1809,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1429
1809
  ...(within === undefined ? {} : { within }),
1430
1810
  };
1431
1811
  });
1812
+ let requests = buildRequests(finalDocks);
1432
1813
  // Lanes outside the drawing, over and under it, one label pitch apart:
1433
1814
  // labelled routes going round the drawing spread over them instead of
1434
1815
  // sharing the one clearance line, so each keeps room for its label.
@@ -1441,25 +1822,26 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1441
1822
  const outerLanesX = [];
1442
1823
  let labelLimit;
1443
1824
  const markSizes = [...routeSizes.values()];
1825
+ const edgeClearance = Math.max(metrics.clearance, borderClearance);
1444
1826
  if (markSizes.length > 0 && rects.size > 0) {
1445
- const pitch = Math.max(...markSizes.map((size) => size.height)) + 2 * metrics.labelMargin;
1446
- const pitchX = Math.max(...markSizes.map((size) => size.width)) + 2 * metrics.labelMargin;
1827
+ const pitch = Math.max(routeSpacing, ...markSizes.map((size) => size.height + 2 * metrics.labelMargin));
1828
+ const pitchX = Math.max(routeSpacing, ...markSizes.map((size) => size.width + 2 * metrics.labelMargin));
1447
1829
  const left = Math.min(...[...rects.values()].map((rect) => rect.x));
1448
1830
  const right = Math.max(...[...rects.values()].map((rect) => rect.x + rect.width));
1449
1831
  const width = right - left;
1450
1832
  const height = drawingBottom - drawingTop;
1451
1833
  const spareX = Math.max(0, height * rowPack.targetAspect - width) / 2;
1452
1834
  const spareY = Math.max(0, width / rowPack.targetAspect - height) / 2;
1453
- const allowance = metrics.clearance + pitch;
1835
+ const allowance = edgeClearance + pitch;
1454
1836
  labelLimit = {
1455
- x: left - spareX - metrics.clearance - pitchX,
1837
+ x: left - spareX - edgeClearance - pitchX,
1456
1838
  y: drawingTop - spareY - allowance,
1457
- width: width + 2 * (spareX + metrics.clearance + pitchX),
1839
+ width: width + 2 * (spareX + edgeClearance + pitchX),
1458
1840
  height: height + 2 * (spareY + allowance),
1459
1841
  };
1460
1842
  const lanes = Math.min(markSizes.length, OUTER_LANES, 1 + Math.floor(spareY / pitch));
1461
1843
  for (let lane = 1; lane <= lanes; lane += 1) {
1462
- outerLanes.push(drawingTop - metrics.clearance - lane * pitch, drawingBottom + metrics.clearance + lane * pitch);
1844
+ outerLanes.push(drawingTop - edgeClearance - lane * pitch, drawingBottom + edgeClearance + lane * pitch);
1463
1845
  }
1464
1846
  // AC-25: dense folded roots need left/right outside corridors as well —
1465
1847
  // the A* grid had no X lane outside the drawing, so a route that must go
@@ -1467,20 +1849,272 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1467
1849
  // side mirrors the Y lanes above.
1468
1850
  const lanesX = Math.min(markSizes.length, OUTER_LANES, 1 + Math.floor(spareX / pitchX));
1469
1851
  for (let lane = 1; lane <= lanesX; lane += 1) {
1470
- outerLanesX.push(left - metrics.clearance - lane * pitchX, right + metrics.clearance + lane * pitchX);
1852
+ outerLanesX.push(left - edgeClearance - lane * pitchX, right + edgeClearance + lane * pitchX);
1471
1853
  }
1472
1854
  }
1473
1855
  // The title band of an expanded container is an obstacle for every route,
1474
1856
  // the ones that may cross the container wall included: a route leaving a
1475
1857
  // zone goes round its title, never through it.
1476
- const routed = routeEdges({
1858
+ const sortedBarrierEntries = [...titleBands].sort(([left], [right]) => byString(left, right));
1859
+ const sortedBarriers = sortedBarrierEntries.map(([, band]) => band);
1860
+ const auditBarriers = sortedBarrierEntries.map(([entity, rect]) => ({ entity: String(entity), rect }));
1861
+ const runRouter = (reqs, priority) => routeEdges({
1477
1862
  rects,
1478
- requests,
1863
+ requests: reqs,
1479
1864
  avoidFallbackInteriors: true,
1480
- clearance: metrics.clearance,
1481
- barriers: [...titleBands].sort(([left], [right]) => byString(left, right)).map(([, band]) => band),
1865
+ clearance: borderClearance,
1866
+ routeSpacing,
1867
+ barriers: sortedBarriers,
1482
1868
  lanes: { xs: outerLanesX, ys: outerLanes },
1869
+ ...(priority === undefined ? {} : { priority }),
1483
1870
  });
1871
+ let routed = runRouter(requests);
1872
+ // Deterministic conflict repair (DE-2 ask 2): when strict route spacing has
1873
+ // conflicts (e.g. a fixed 96 px gutter saturated on one face or an earlier
1874
+ // route claiming a choke-point track), first try promoting conflicted routes
1875
+ // in routing order, then greedily re-dock the most-conflicted ordinary edge
1876
+ // onto a less-congested unblocked face (updating all docks together so port
1877
+ // spacing stays exact). Zero overhead when pass 1 already yields 0 conflicts.
1878
+ if (routeSpacing > 0 && drawnEdges.length > 1) {
1879
+ const quickAudit = (outcome) => {
1880
+ const checked = [];
1881
+ for (const edge of drawnEdges) {
1882
+ const id = edge.occurrence;
1883
+ const pts = outcome.routes.get(id);
1884
+ if (pts === undefined)
1885
+ continue;
1886
+ const occ = projected.relationOccurrences[edge.occurrence];
1887
+ const sRole = occ.endpoints.find((ep) => ep.role === "source");
1888
+ const tRole = occ.endpoints.find((ep) => ep.role === "target");
1889
+ const style = relationPresentationFor(presentation.relations, occ.id, occ.relation);
1890
+ const arrowhead = resolveArrowhead(occ.arrowhead ?? style?.arrowhead).canonicalKind;
1891
+ const passable = new Set([
1892
+ ...projectedAncestorsOf(sRole.occurrence),
1893
+ ...projectedAncestorsOf(tRole.occurrence),
1894
+ ]);
1895
+ checked.push({
1896
+ id: String(edge.occurrence),
1897
+ source: String(edge.source.entity),
1898
+ target: String(edge.target.entity),
1899
+ points: pts,
1900
+ ...(edge.source.port === undefined ? {} : { sourcePort: String(edge.source.port) }),
1901
+ ...(edge.target.port === undefined ? {} : { targetPort: String(edge.target.port) }),
1902
+ arrowhead,
1903
+ passable,
1904
+ });
1905
+ }
1906
+ return checkRouteSpacing({
1907
+ rects,
1908
+ routes: checked,
1909
+ routeSpacing,
1910
+ borderClearance,
1911
+ barriers: auditBarriers,
1912
+ });
1913
+ };
1914
+ const scoreOf = (outcome, report) => outcome.obstructed.length * 10000 + outcome.escaped.length * 1000 + report.conflictCount;
1915
+ let bestReport = quickAudit(routed);
1916
+ let bestScore = scoreOf(routed, bestReport);
1917
+ let bestPriority;
1918
+ // Stage 1: promote conflicted / escaped / obstructed routes in routing order.
1919
+ // On large scenes (> 25 boxes) with > 5 initial conflicts, cap promotion to
1920
+ // one pass to keep cold layout latency well under budget.
1921
+ if (bestScore > 0) {
1922
+ const maxStage1Rounds = rects.size > 25 && bestReport.conflictCount > 5 && routed.obstructed.length === 0 ? 1 : 3;
1923
+ const promoted = new Set();
1924
+ for (let round = 0; round < maxStage1Rounds && bestScore > 0; round += 1) {
1925
+ const beforeSize = promoted.size;
1926
+ for (const r of routed.obstructed)
1927
+ promoted.add(r);
1928
+ for (const r of routed.escaped)
1929
+ promoted.add(r);
1930
+ for (const conflict of bestReport.conflicts) {
1931
+ for (const r of conflict.routes)
1932
+ promoted.add(r);
1933
+ }
1934
+ if (promoted.size === beforeSize)
1935
+ break;
1936
+ const candidate = runRouter(requests, promoted);
1937
+ const candReport = quickAudit(candidate);
1938
+ const candScore = scoreOf(candidate, candReport);
1939
+ if (candScore < bestScore) {
1940
+ routed = candidate;
1941
+ bestReport = candReport;
1942
+ bestScore = candScore;
1943
+ bestPriority = new Set(promoted);
1944
+ }
1945
+ else {
1946
+ break;
1947
+ }
1948
+ }
1949
+ }
1950
+ // Stage 2: re-dock congested / escaped ordinary edges onto an unblocked face.
1951
+ // Skip Stage 2 on large scenes (> 25 boxes) that remain structurally saturated
1952
+ // (> 5 conflicts after Stage 1) so heavy legacy scenes stay well within budget.
1953
+ if (bestScore > 0 && (bestReport.conflictCount <= 5 || rects.size <= 25)) {
1954
+ const workingOverrides = new Map(sideOverrides);
1955
+ const allSides = ["west", "east", "south", "north"];
1956
+ const sideScoreToward = (fromId, toId, side) => {
1957
+ const a = rects.get(fromId);
1958
+ const b = rects.get(toId);
1959
+ const dx = (b.x + b.width / 2) - (a.x + a.width / 2);
1960
+ const dy = (b.y + b.height / 2) - (a.y + a.height / 2);
1961
+ if (side === "east")
1962
+ return -dx;
1963
+ if (side === "west")
1964
+ return dx;
1965
+ if (side === "south")
1966
+ return -dy;
1967
+ return dy;
1968
+ };
1969
+ const maxStage2Calls = rects.size > 25 ? 6 : 18;
1970
+ let stage2Calls = 0;
1971
+ for (let round = 0; round < 4 && bestScore > 0 && stage2Calls < maxStage2Calls; round += 1) {
1972
+ const counts = new Map();
1973
+ for (const r of routed.obstructed)
1974
+ counts.set(String(r), (counts.get(String(r)) ?? 0) + 10);
1975
+ for (const r of routed.escaped)
1976
+ counts.set(String(r), (counts.get(String(r)) ?? 0) + 5);
1977
+ for (const conflict of bestReport.conflicts) {
1978
+ for (const r of conflict.routes)
1979
+ counts.set(r, (counts.get(r) ?? 0) + 1);
1980
+ }
1981
+ const rankedEdges = [...counts.entries()]
1982
+ .sort((a, b) => b[1] - a[1] || byString(a[0], b[0]))
1983
+ .map(([id]) => drawnEdges.find((e) => String(e.occurrence) === id))
1984
+ .filter((e) => {
1985
+ if (e === undefined)
1986
+ return false;
1987
+ if (e.source.entity === e.target.entity)
1988
+ return false;
1989
+ if (e.source.port !== undefined || e.target.port !== undefined)
1990
+ return false;
1991
+ if (isAncestor(filteredGraph, e.source.entity, e.target.entity) || isAncestor(filteredGraph, e.target.entity, e.source.entity))
1992
+ return false;
1993
+ return true;
1994
+ });
1995
+ let improved = false;
1996
+ for (const edge of rankedEdges.slice(0, 2)) {
1997
+ if (stage2Calls >= maxStage2Calls)
1998
+ break;
1999
+ const id = edge.occurrence;
2000
+ const within = withinOf.get(id);
2001
+ const currentDock = finalDocks.get(id);
2002
+ const validSourceSides = allSides
2003
+ .filter((s) => (s !== "north" || !isNorthBlockedByTitle(edge.source.entity)) && sideStaysInWithin(edge.source.entity, s, within))
2004
+ .sort((a, b) => sideScoreToward(edge.source.entity, edge.target.entity, a) - sideScoreToward(edge.source.entity, edge.target.entity, b));
2005
+ const validTargetSides = allSides
2006
+ .filter((s) => (s !== "north" || !isNorthBlockedByTitle(edge.target.entity)) && sideStaysInWithin(edge.target.entity, s, within))
2007
+ .sort((a, b) => sideScoreToward(edge.target.entity, edge.source.entity, a) - sideScoreToward(edge.target.entity, edge.source.entity, b));
2008
+ const faceCandidates = [];
2009
+ for (const s of validSourceSides) {
2010
+ if (s !== currentDock.source.side)
2011
+ faceCandidates.push([s, currentDock.target.side]);
2012
+ }
2013
+ for (const t of validTargetSides) {
2014
+ if (t !== currentDock.target.side)
2015
+ faceCandidates.push([currentDock.source.side, t]);
2016
+ }
2017
+ let bestCandOverrides;
2018
+ let bestCandDocks;
2019
+ let bestCandRequests;
2020
+ let bestCandOutcome;
2021
+ let bestCandReport;
2022
+ let bestCandScore = bestScore;
2023
+ for (const [s, t] of faceCandidates) {
2024
+ if (stage2Calls >= maxStage2Calls)
2025
+ break;
2026
+ stage2Calls += 1;
2027
+ const candOverrides = new Map(workingOverrides);
2028
+ candOverrides.set(id, { source: s, target: t, turn: false });
2029
+ const candDocked = dockEdges({
2030
+ ...(hasFlows ? { flowBadgeSize: flowTokens.flowBadgeSize } : {}),
2031
+ graph: filteredGraph,
2032
+ rects,
2033
+ direction: "top-to-bottom",
2034
+ metrics,
2035
+ labelSizes: new Map(),
2036
+ fixed: true,
2037
+ cornerInset: dockCornerInset,
2038
+ sideOverrides: candOverrides,
2039
+ });
2040
+ if (candDocked.fixedOverflows.length > docked.fixedOverflows.length)
2041
+ continue;
2042
+ const candRequests = buildRequests(candDocked.docks);
2043
+ const candOutcome = runRouter(candRequests, bestPriority);
2044
+ const candReport = quickAudit(candOutcome);
2045
+ const candScore = scoreOf(candOutcome, candReport);
2046
+ if (candScore < bestCandScore) {
2047
+ bestCandScore = candScore;
2048
+ bestCandOverrides = candOverrides;
2049
+ bestCandDocks = candDocked.docks;
2050
+ bestCandRequests = candRequests;
2051
+ bestCandOutcome = candOutcome;
2052
+ bestCandReport = candReport;
2053
+ break;
2054
+ }
2055
+ }
2056
+ if (bestCandOutcome !== undefined && bestCandDocks !== undefined && bestCandRequests !== undefined && bestCandReport !== undefined && bestCandOverrides !== undefined) {
2057
+ workingOverrides.clear();
2058
+ for (const [k, v] of bestCandOverrides)
2059
+ workingOverrides.set(k, v);
2060
+ sideOverrides.clear();
2061
+ for (const [k, v] of bestCandOverrides)
2062
+ sideOverrides.set(k, v);
2063
+ finalDocks.clear();
2064
+ for (const [k, v] of bestCandDocks)
2065
+ finalDocks.set(k, v);
2066
+ requests = bestCandRequests;
2067
+ routed = bestCandOutcome;
2068
+ bestReport = bestCandReport;
2069
+ bestScore = bestCandScore;
2070
+ improved = true;
2071
+ break;
2072
+ }
2073
+ }
2074
+ if (!improved)
2075
+ break;
2076
+ }
2077
+ }
2078
+ // Stage 3: if pair conflicts still remain on a modest scene after Stage 1+2,
2079
+ // try promoting only the later-routed route of each remaining conflict (on
2080
+ // the current docks) so constrained routes claim tracks before their blockers.
2081
+ if (bestScore > 0 && rects.size <= 25) {
2082
+ const orderRank = new Map();
2083
+ [...requests]
2084
+ .sort((a, b) => {
2085
+ const aIn = a.within !== undefined ? 0 : 1;
2086
+ const bIn = b.within !== undefined ? 0 : 1;
2087
+ if (aIn !== bIn)
2088
+ return aIn - bIn;
2089
+ const aDist = Math.abs(a.start.x - a.end.x) + Math.abs(a.start.y - a.end.y);
2090
+ const bDist = Math.abs(b.start.x - b.end.x) + Math.abs(b.start.y - b.end.y);
2091
+ if (Math.abs(aDist - bDist) > 1e-4)
2092
+ return aDist - bDist;
2093
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
2094
+ })
2095
+ .forEach((req, idx) => orderRank.set(String(req.id), idx));
2096
+ const victims = new Set();
2097
+ for (const r of routed.obstructed)
2098
+ victims.add(r);
2099
+ for (const r of routed.escaped)
2100
+ victims.add(r);
2101
+ for (const conflict of bestReport.conflicts) {
2102
+ const sorted = [...conflict.routes].sort((a, b) => (orderRank.get(b) ?? 0) - (orderRank.get(a) ?? 0));
2103
+ if (sorted.length > 0)
2104
+ victims.add(sorted[0]);
2105
+ }
2106
+ if (victims.size > 0) {
2107
+ const candidate = runRouter(requests, victims);
2108
+ const candReport = quickAudit(candidate);
2109
+ const candScore = scoreOf(candidate, candReport);
2110
+ if (candScore < bestScore) {
2111
+ routed = candidate;
2112
+ bestReport = candReport;
2113
+ bestScore = candScore;
2114
+ }
2115
+ }
2116
+ }
2117
+ }
1484
2118
  // AC-25: an 8 px dock exit can be blocked where a 2 px exit still threads
1485
2119
  // through — the retry is local (only the obstructed requests, same rects,
1486
2120
  // barriers and outer lanes, smaller inflation) and still avoids every raw
@@ -1488,6 +2122,10 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1488
2122
  // A retry that finds a clean A* route replaces the obstructed elbow.
1489
2123
  const retryRoutes = new Map(routed.routes);
1490
2124
  const retryObstructed = new Set(routed.obstructed);
2125
+ const otherRoutesOf = (id) => requests
2126
+ .filter((candidate) => candidate.id !== id && !retryObstructed.has(candidate.id))
2127
+ .map((candidate) => retryRoutes.get(candidate.id))
2128
+ .filter((route) => route !== undefined);
1491
2129
  // Parallel unlabelled bridges use a centred comb. Docks and the middle
1492
2130
  // legs share the same pitch. Preserve every constraint of the router.
1493
2131
  const parallel = new Map();
@@ -1505,8 +2143,9 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1505
2143
  const first = pair[0];
1506
2144
  const horizontal = Math.abs(first.start.x - first.end.x) >= Math.abs(first.start.y - first.end.y);
1507
2145
  const center = horizontal ? (first.start.x + first.end.x) / 2 : (first.start.y + first.end.y) / 2;
2146
+ const combPitch = Math.max(routeSpacing, (horizontal ? metrics.trackSpacing : metrics.trackSpacingBlock) ?? (horizontal ? 14 : 7));
1508
2147
  pair.forEach((request, index) => {
1509
- const lane = center + (index - (pair.length - 1) / 2) * ((horizontal ? metrics.trackSpacing : metrics.trackSpacingBlock) ?? (horizontal ? 14 : 7));
2148
+ const lane = center + (index - (pair.length - 1) / 2) * combPitch;
1510
2149
  const points = horizontal
1511
2150
  ? [request.start, { x: lane, y: request.start.y }, { x: lane, y: request.end.y }, request.end]
1512
2151
  : [request.start, { x: request.start.x, y: lane }, { x: request.end.x, y: lane }, request.end];
@@ -1516,6 +2155,10 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1516
2155
  || (firstLeg.x - request.start.x) * request.startExit.x + (firstLeg.y - request.start.y) * request.startExit.y <= 0
1517
2156
  || (lastLeg.x - request.end.x) * request.endExit.x + (lastLeg.y - request.end.y) * request.endExit.y <= 0)
1518
2157
  return;
2158
+ const firstLen = Math.hypot(firstLeg.x - request.start.x, firstLeg.y - request.start.y);
2159
+ const lastLen = Math.hypot(lastLeg.x - request.end.x, lastLeg.y - request.end.y);
2160
+ if (routeSpacing > 0 && (firstLen < borderClearance - 1e-4 || lastLen < borderClearance - 1e-4))
2161
+ return;
1519
2162
  const within = request.within;
1520
2163
  if (within !== undefined && points.some(point => point.x < within.x || point.y < within.y
1521
2164
  || point.x > within.x + within.width || point.y > within.y + within.height))
@@ -1523,16 +2166,64 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1523
2166
  if (requests.some(other => other.id !== request.id && other.pairKey === request.pairKey
1524
2167
  && routesConflict(points, retryRoutes.get(other.id))))
1525
2168
  return;
1526
- if (points.slice(1).some((point, i) => shapesOf(request.id).some(shape => rectsIntersect(shape, {
1527
- x: Math.min(point.x, points[i].x), y: Math.min(point.y, points[i].y),
1528
- width: Math.abs(point.x - points[i].x), height: Math.abs(point.y - points[i].y),
1529
- }))))
2169
+ if (points.slice(1).some((point, i) => {
2170
+ const prev = points[i];
2171
+ if (shapesOf(request.id).some(shape => {
2172
+ if (rectsIntersect(shape, {
2173
+ x: Math.min(point.x, prev.x), y: Math.min(point.y, prev.y),
2174
+ width: Math.abs(point.x - prev.x), height: Math.abs(point.y - prev.y),
2175
+ }))
2176
+ return true;
2177
+ if (!(routeSpacing > 0))
2178
+ return false;
2179
+ if (i === 0 && (Math.abs(prev.x - shape.x) < 1e-4 || Math.abs(prev.x - (shape.x + shape.width)) < 1e-4 || Math.abs(prev.y - shape.y) < 1e-4 || Math.abs(prev.y - (shape.y + shape.height)) < 1e-4))
2180
+ return false;
2181
+ if (i === points.length - 2 && (Math.abs(point.x - shape.x) < 1e-4 || Math.abs(point.x - (shape.x + shape.width)) < 1e-4 || Math.abs(point.y - shape.y) < 1e-4 || Math.abs(point.y - (shape.y + shape.height)) < 1e-4))
2182
+ return false;
2183
+ return segmentToRectDistance(prev, point, shape) < borderClearance - 1e-4;
2184
+ }))
2185
+ return true;
2186
+ if (routeSpacing > 0 && passableZonesOf(request.id).some(zone => segmentToPassableBorderDistance(prev, point, zone) < borderClearance - 1e-4)) {
2187
+ return true;
2188
+ }
2189
+ return false;
2190
+ }))
1530
2191
  return;
2192
+ if (routeSpacing > 0) {
2193
+ const candidateElbows = points.slice(1, -1);
2194
+ const violatesSpacing = otherRoutesOf(request.id).some((other) => {
2195
+ for (let i = 1; i < points.length; i += 1) {
2196
+ const a1 = points[i - 1];
2197
+ const a2 = points[i];
2198
+ for (let j = 1; j < other.length; j += 1) {
2199
+ const b1 = other[j - 1];
2200
+ const b2 = other[j];
2201
+ if (Math.abs(a1.y - a2.y) < 1e-4 && Math.abs(b1.y - b2.y) < 1e-4 && Math.abs(a1.y - b1.y) < routeSpacing - 1e-4) {
2202
+ if (Math.min(Math.max(a1.x, a2.x), Math.max(b1.x, b2.x)) - Math.max(Math.min(a1.x, a2.x), Math.min(b1.x, b2.x)) > 1e-4)
2203
+ return true;
2204
+ }
2205
+ if (Math.abs(a1.x - a2.x) < 1e-4 && Math.abs(b1.x - b2.x) < 1e-4 && Math.abs(a1.x - b1.x) < routeSpacing - 1e-4) {
2206
+ if (Math.min(Math.max(a1.y, a2.y), Math.max(b1.y, b2.y)) - Math.max(Math.min(a1.y, a2.y), Math.min(b1.y, b2.y)) > 1e-4)
2207
+ return true;
2208
+ }
2209
+ }
2210
+ }
2211
+ for (const e1 of candidateElbows) {
2212
+ for (let k = 1; k < other.length - 1; k += 1) {
2213
+ if (Math.hypot(e1.x - other[k].x, e1.y - other[k].y) < routeSpacing - 1e-4)
2214
+ return true;
2215
+ }
2216
+ }
2217
+ return false;
2218
+ });
2219
+ if (violatesSpacing)
2220
+ return;
2221
+ }
1531
2222
  retryRoutes.set(request.id, points);
1532
2223
  retryObstructed.delete(request.id);
1533
2224
  });
1534
2225
  }
1535
- if (retryObstructed.size > 0) {
2226
+ if (retryObstructed.size > 0 && !(routeSpacing > 0)) {
1536
2227
  const failed = new Set(retryObstructed);
1537
2228
  const retryRequests = requests.filter((request) => failed.has(request.id));
1538
2229
  const retried = routeEdges({
@@ -1591,6 +2282,8 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1591
2282
  const labelBoxes = new Map();
1592
2283
  const taken = [...marks.taken];
1593
2284
  const unplaced = [];
2285
+ const detourStep = routeSpacing > 0 ? borderClearance : 2;
2286
+ const detourClearance = routeSpacing > 0 ? borderClearance : 0;
1594
2287
  for (const entry of entries) {
1595
2288
  const edge = drawnEdges.find((candidate) => candidate.occurrence === entry.id);
1596
2289
  let choice = placePackedLabel(entry, fixedShapes, taken, metrics.labelMargin);
@@ -1608,6 +2301,11 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1608
2301
  const { limit: _limit, ...unbounded } = entry;
1609
2302
  const route = labelDetour({ request, shapes: shapesOf(entry.id),
1610
2303
  earlier: requests.filter(other => other.id !== request.id && other.pairKey === request.pairKey && !retryObstructed.has(other.id)).map(other => retryRoutes.get(other.id)),
2304
+ allFixed: otherRoutesOf(entry.id),
2305
+ passableZones: passableZonesOf(entry.id),
2306
+ step: detourStep,
2307
+ routeSpacing,
2308
+ borderClearance: detourClearance,
1611
2309
  xs: [...new Set([request.start.x, request.end.x, ...outerLanesX])].sort((a, b) => a - b),
1612
2310
  ys: [...new Set([request.start.y, request.end.y, ...outerLanes])].sort((a, b) => a - b),
1613
2311
  accepts: points => {
@@ -1634,34 +2332,55 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1634
2332
  const request = requests.find((candidate) => candidate.id === entry.id);
1635
2333
  const samePair = requests.filter((candidate) => candidate.id !== entry.id && candidate.pairKey === request.pairKey && !retryObstructed.has(candidate.id))
1636
2334
  .map((candidate) => retryRoutes.get(candidate.id));
2335
+ const allFixed = otherRoutesOf(entry.id);
1637
2336
  const shapes = shapesOf(entry.id);
1638
2337
  const margin = probeMargin;
1639
2338
  const xs = new Set([request.start.x, request.end.x]);
1640
2339
  const ys = new Set(outerLanes);
1641
2340
  for (const rect of shapes) {
1642
- xs.add(rect.x - metrics.clearance);
1643
- xs.add(rect.x + rect.width + metrics.clearance);
2341
+ xs.add(rect.x - edgeClearance);
2342
+ xs.add(rect.x + rect.width + edgeClearance);
1644
2343
  for (const pad of [metrics.labelMargin, Math.max(0, margin)]) {
1645
- ys.add(rect.y - entry.size.height / 2 - pad);
1646
- ys.add(rect.y + rect.height + entry.size.height / 2 + pad);
2344
+ const dy = Math.max(edgeClearance, entry.size.height / 2 + pad);
2345
+ ys.add(rect.y - dy);
2346
+ ys.add(rect.y + rect.height + dy);
1647
2347
  }
1648
2348
  }
1649
2349
  for (const end of [request.start, request.end]) {
1650
2350
  xs.add(end.x - entry.size.width - 2 * metrics.labelMargin);
1651
2351
  xs.add(end.x + entry.size.width + 2 * metrics.labelMargin);
1652
2352
  }
1653
- const detour = labelDetour({ request, shapes, earlier: samePair, xs: [...xs].sort((a, b) => a - b), ys: [...ys].sort((a, b) => a - b),
2353
+ const sortedXs = [...xs].sort((a, b) => a - b);
2354
+ const sortedYs = [...ys].sort((a, b) => a - b);
2355
+ const edgePassableZones = passableZonesOf(entry.id);
2356
+ let detour = labelDetour({ request, shapes, earlier: samePair, allFixed, passableZones: edgePassableZones, step: detourStep, routeSpacing, borderClearance: detourClearance,
2357
+ xs: sortedXs, ys: sortedYs,
1654
2358
  accepts: (points) => {
1655
2359
  return placePackedLabel({ ...entry, route: points }, fixedShapes, taken, metrics.labelMargin) !== undefined;
1656
2360
  },
1657
2361
  });
2362
+ if (detour === undefined && routeSpacing > 0) {
2363
+ const wideXs = new Set([...xs, ...outerLanesX]);
2364
+ const wideYs = new Set(ys);
2365
+ for (const x of [request.start.x, request.end.x, ...outerLanesX])
2366
+ wideXs.add(x - routeSpacing), wideXs.add(x + routeSpacing);
2367
+ for (const y of [request.start.y, request.end.y, ...outerLanes])
2368
+ wideYs.add(y - routeSpacing), wideYs.add(y + routeSpacing);
2369
+ detour = labelDetour({ request, shapes, earlier: samePair, allFixed, passableZones: edgePassableZones, step: detourStep, routeSpacing, borderClearance: detourClearance,
2370
+ xs: [...wideXs].sort((a, b) => a - b), ys: [...wideYs].sort((a, b) => a - b),
2371
+ accepts: (points) => {
2372
+ return placePackedLabel({ ...entry, route: points }, fixedShapes, taken, metrics.labelMargin) !== undefined;
2373
+ },
2374
+ });
2375
+ }
1658
2376
  if (detour !== undefined) {
1659
2377
  retryRoutes.set(entry.id, detour);
1660
2378
  retryObstructed.delete(entry.id);
1661
2379
  choice = placePackedLabel({ ...entry, route: detour }, fixedShapes, taken, metrics.labelMargin);
1662
2380
  }
1663
2381
  else if (margin >= 0) {
1664
- const probeRoute = labelDetour({ request, shapes, earlier: samePair, xs: [...xs].sort((a, b) => a - b), ys: [...ys].sort((a, b) => a - b),
2382
+ const probeRoute = labelDetour({ request, shapes, earlier: samePair, allFixed, passableZones: edgePassableZones, step: detourStep, routeSpacing, borderClearance: detourClearance,
2383
+ xs: sortedXs, ys: sortedYs,
1665
2384
  accepts: (points) => placePackedLabel({ ...entry, route: points }, fixedShapes, taken, metrics.labelMargin, margin) !== undefined,
1666
2385
  });
1667
2386
  if (probeRoute !== undefined)
@@ -1680,15 +2399,38 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1680
2399
  ...sides.map((side) => [side, side]),
1681
2400
  ...sides.flatMap((source) => sides.filter((target) => target !== source).map((target) => [source, target])),
1682
2401
  ];
2402
+ const docksClear = (candidate) => {
2403
+ if (!(routeSpacing > 0))
2404
+ return true;
2405
+ for (const [otherId, otherDocks] of finalDocks) {
2406
+ if (otherId === entry.id)
2407
+ continue;
2408
+ for (const cDock of [candidate.source, candidate.target]) {
2409
+ for (const oDock of [otherDocks.source, otherDocks.target]) {
2410
+ if (cDock.entity === oDock.entity && cDock.port !== undefined && cDock.port === oDock.port)
2411
+ continue;
2412
+ if (cDock.entity === oDock.entity && Math.hypot(cDock.point.x - oDock.point.x, cDock.point.y - oDock.point.y) < routeSpacing - 1e-4) {
2413
+ return false;
2414
+ }
2415
+ }
2416
+ }
2417
+ if (Math.hypot(candidate.target.point.x - otherDocks.target.point.x, candidate.target.point.y - otherDocks.target.point.y) < routeSpacing - 1e-4) {
2418
+ return false;
2419
+ }
2420
+ }
2421
+ return true;
2422
+ };
1683
2423
  for (const [source, target] of facePairs) {
1684
2424
  const overrides = new Map(sideOverrides);
1685
2425
  overrides.set(entry.id, { source, target, turn: source === target });
1686
2426
  const pair = dockEdges({ graph: filteredGraph, rects, direction: "top-to-bottom", metrics,
1687
- labelSizes: new Map(), fixed: true, sideOverrides: overrides }).docks.get(entry.id);
2427
+ labelSizes: new Map(), fixed: true, cornerInset: dockCornerInset, sideOverrides: overrides }).docks.get(entry.id);
2428
+ if (!docksClear(pair))
2429
+ continue;
1688
2430
  const alternative = { ...request, start: pair.source.point, startExit: pair.source.exit,
1689
2431
  end: pair.target.point, endExit: pair.target.exit };
1690
- const route = labelDetour({ request: alternative, shapes, earlier: samePair,
1691
- xs: [...xs].sort((a, b) => a - b), ys: [...ys].sort((a, b) => a - b),
2432
+ const route = labelDetour({ request: alternative, shapes, earlier: samePair, allFixed, passableZones: edgePassableZones, step: detourStep, routeSpacing, borderClearance: detourClearance,
2433
+ xs: sortedXs, ys: sortedYs,
1692
2434
  accepts: (points) => placePackedLabel({ ...entry, route: points }, fixedShapes, taken, metrics.labelMargin) !== undefined,
1693
2435
  });
1694
2436
  if (route === undefined)
@@ -1708,14 +2450,16 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1708
2450
  const request = requests.find(candidate => candidate.id === entry.id);
1709
2451
  if (entry.within === undefined) {
1710
2452
  const right = Math.max(...[...rects.values()].map(rect => rect.x + rect.width));
1711
- const pitch = Math.max(...[...labelSizes.values()].map(size => size.height)) + 2 * metrics.labelMargin;
1712
- const column = right + Math.max(...[...labelSizes.values()].map(size => size.width)) / 2 + metrics.clearance;
1713
- const row = drawingBottom + metrics.clearance + (entries.indexOf(entry) + 1) * pitch;
1714
- const upperRow = drawingTop - metrics.clearance - (entries.indexOf(entry) + 1) * pitch;
2453
+ const pitch = Math.max(routeSpacing, ...[...labelSizes.values()].map(size => size.height + 2 * metrics.labelMargin));
2454
+ const column = right + Math.max(...[...labelSizes.values()].map(size => size.width)) / 2 + edgeClearance;
2455
+ const row = drawingBottom + edgeClearance + (entries.indexOf(entry) + 1) * pitch;
2456
+ const upperRow = drawingTop - edgeClearance - (entries.indexOf(entry) + 1) * pitch;
1715
2457
  const { limit: _limit, ...unbounded } = entry;
1716
2458
  const samePair = requests.filter(candidate => candidate.id !== entry.id && candidate.pairKey === request.pairKey && !retryObstructed.has(candidate.id))
1717
2459
  .map(candidate => retryRoutes.get(candidate.id));
1718
- const comb = (earlier) => labelDetour({ request, shapes: shapesOf(entry.id), earlier,
2460
+ const allFixed = otherRoutesOf(entry.id);
2461
+ const comb = (earlier) => labelDetour({ request, shapes: shapesOf(entry.id), earlier, allFixed, passableZones: passableZonesOf(entry.id),
2462
+ step: detourStep, routeSpacing, borderClearance: detourClearance,
1719
2463
  xs: [...new Set([request.start.x, request.end.x, column, ...outerLanesX])].sort((a, b) => a - b),
1720
2464
  ys: [...new Set([request.start.y, request.end.y, upperRow, row, ...outerLanes])].sort((a, b) => a - b),
1721
2465
  accepts: points => placePackedLabel({ ...unbounded, route: points }, fixedShapes, taken, metrics.labelMargin) !== undefined,
@@ -1750,7 +2494,11 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1750
2494
  continue;
1751
2495
  const rows = packed.rows;
1752
2496
  const zone = runHasZone(packed.run);
1753
- const axisAuthored = (horizontal) => (horizontal ? (zone ? hints?.zoneGapX : hints?.cardGapX) : (zone ? hints?.zoneGapY : hints?.cardGapY)) !== undefined;
2497
+ const axisAuthored = (horizontal, isZone) => (horizontal ? (isZone ? hints?.zoneGapX : hints?.cardGapX) : (isZone ? hints?.zoneGapY : hints?.cardGapY)) !== undefined;
2498
+ const cardAlongBase = rows ? rowGaps.cardX : rowGaps.cardY;
2499
+ const cardAcrossBase = rows ? rowGaps.cardY : rowGaps.cardX;
2500
+ const zoneAlongBase = rows ? rowGaps.zoneX : rowGaps.zoneY;
2501
+ const zoneAcrossBase = rows ? rowGaps.zoneY : rowGaps.zoneX;
1754
2502
  const gapAfter = (slot) => { const item = packed.run.items[slot]; return "run" in item ? item.gapAfter : undefined; };
1755
2503
  const alongOf = (rect) => (rows ? [rect.x, rect.x + rect.width] : [rect.y, rect.y + rect.height]);
1756
2504
  const acrossOf = (rect) => (rows ? [rect.y, rect.y + rect.height] : [rect.x, rect.x + rect.width]);
@@ -1768,14 +2516,22 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1768
2516
  const next = packed.shelves[shelfIndex + 1];
1769
2517
  if (next !== undefined) {
1770
2518
  const nextStart = acrossOf(boxes[next[0]])[0];
2519
+ const currentZone = shelfHasZone(packed.run, shelf);
2520
+ const nextZone = shelfHasZone(packed.run, next);
2521
+ const acrossZone = r7Routing ? currentZone && nextZone : zone;
2522
+ const bordersZone = currentZone || nextZone;
2523
+ const base = r7Routing
2524
+ ? (acrossZone ? zoneGutter : (gapAfter(shelf.at(-1)) ?? (bordersZone ? zoneAcrossBase : cardAcrossBase)))
2525
+ : (gapAfter(shelf.at(-1)) ?? packed.acrossBase);
1771
2526
  gutters.push({
1772
2527
  id: `${key}|across|${String(shelfIndex)}`,
1773
2528
  horizontal: rows,
1774
2529
  strips: [stripOf(extent, [end, nextStart])],
1775
2530
  gap: nextStart - end,
1776
- base: gapAfter(shelf.at(-1)) ?? packed.acrossBase,
1777
- authoredBase: gapAfter(shelf.at(-1)) !== undefined || axisAuthored(!rows),
2531
+ base,
2532
+ authoredBase: r7Routing && acrossZone ? false : gapAfter(shelf.at(-1)) !== undefined || axisAuthored(!rows, r7Routing ? bordersZone : zone),
1778
2533
  max: rows ? rowGaps.maxY : rowGaps.maxX,
2534
+ zone: acrossZone,
1779
2535
  });
1780
2536
  }
1781
2537
  shelf.forEach((slot, index) => {
@@ -1783,7 +2539,12 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1783
2539
  if (following === undefined)
1784
2540
  return;
1785
2541
  const strip = stripOf([alongOf(boxes[slot])[1], alongOf(boxes[following])[0]], [start, end]);
1786
- (alongStrips.get(index) ?? alongStrips.set(index, []).get(index)).push({ shelf: shelfIndex, slot, strip });
2542
+ const leftZone = itemHasZone(packed.run.items[slot]);
2543
+ const rightZone = itemHasZone(packed.run.items[following]);
2544
+ const pairZone = r7Routing ? leftZone && rightZone : zone;
2545
+ (alongStrips.get(index) ?? alongStrips.set(index, []).get(index)).push({
2546
+ shelf: shelfIndex, slot, strip, zone: pairZone, bordersZone: r7Routing ? leftZone || rightZone : zone,
2547
+ });
1787
2548
  });
1788
2549
  });
1789
2550
  for (const [index, strips] of [...alongStrips].sort(([left], [right]) => left - right)) {
@@ -1791,29 +2552,46 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1791
2552
  const startOf = (strip) => (rows ? strip.x : strip.y);
1792
2553
  // Boxes of equal size line up: the gutters after slot `index` are one
1793
2554
  // lane of the level and widen together, so the grid keeps its column
1794
- // starts. Where they do not line up there is no lane to keep, and
1795
- // each shelf widens its own gutter.
1796
- const lane = strips.every(({ strip }) => Math.abs(startOf(strip) - startOf(strips[0].strip)) <= LANE_TOLERANCE);
2555
+ // starts. Where they do not line up — or where one shelf borders a zone
2556
+ // while another separates leaf cards on r7 — each shelf keeps its own gutter.
2557
+ const lane = strips.every(({ strip, zone: stripZone, bordersZone }) => Math.abs(startOf(strip) - startOf(strips[0].strip)) <= LANE_TOLERANCE &&
2558
+ stripZone === strips[0].zone && bordersZone === strips[0].bordersZone);
1797
2559
  const max = rows ? rowGaps.maxX : rowGaps.maxY;
2560
+ const baseFor = (slot, stripZone, bordersZone) => r7Routing
2561
+ ? (stripZone ? zoneGutter : (gapAfter(slot) ?? (bordersZone ? zoneAlongBase : cardAlongBase)))
2562
+ : (gapAfter(slot) ?? packed.alongBase);
1798
2563
  if (lane) {
2564
+ const laneZone = strips[0].zone;
1799
2565
  gutters.push({
1800
2566
  id: `${key}|along|${String(index)}`,
1801
2567
  horizontal: !rows,
1802
2568
  strips: strips.map(({ strip }) => strip),
1803
2569
  gap: Math.max(...strips.map(({ strip }) => thickness(strip))),
1804
- base: Math.max(...strips.map(({ slot }) => gapAfter(slot) ?? packed.alongBase)),
1805
- authoredBase: strips.some(({ slot }) => gapAfter(slot) !== undefined) || axisAuthored(rows),
2570
+ base: Math.max(...strips.map(({ slot, zone: stripZone, bordersZone }) => baseFor(slot, stripZone, bordersZone))),
2571
+ authoredBase: r7Routing && laneZone ? false : strips.some(({ slot }) => gapAfter(slot) !== undefined) || axisAuthored(rows, strips[0].bordersZone),
1806
2572
  max,
2573
+ zone: laneZone,
1807
2574
  });
1808
2575
  }
1809
2576
  else {
1810
- for (const { shelf, slot, strip } of strips) {
1811
- gutters.push({ id: `${key}|along|${String(index)}|${String(shelf)}`, horizontal: !rows, strips: [strip], gap: thickness(strip), base: gapAfter(slot) ?? packed.alongBase, authoredBase: gapAfter(slot) !== undefined || axisAuthored(rows), max });
2577
+ for (const { shelf, slot, strip, zone: stripZone, bordersZone } of strips) {
2578
+ gutters.push({
2579
+ id: `${key}|along|${String(index)}|${String(shelf)}`,
2580
+ horizontal: !rows,
2581
+ strips: [strip],
2582
+ gap: thickness(strip),
2583
+ base: baseFor(slot, stripZone, bordersZone),
2584
+ authoredBase: r7Routing && stripZone ? false : gapAfter(slot) !== undefined || axisAuthored(rows, bordersZone),
2585
+ max,
2586
+ zone: stripZone,
2587
+ });
1812
2588
  }
1813
2589
  }
1814
2590
  }
1815
2591
  }
1816
2592
  // Count each routed occurrence once in the physical channel, including lifted bundle traffic.
2593
+ // REQ-R7-14 (DE-2 ask 3): sibling-zone gutters (`gutter.zone === true`) stay fixed at `zoneGutter`
2594
+ // and never widen for traffic or labels; all other channels keep dynamic widening.
1817
2595
  const channels = gutters.map(gutter => {
1818
2596
  const edges = [...retryRoutes].filter(([, route]) => gutter.strips.some(strip => route.some((point, i) => {
1819
2597
  const next = route[i + 1];
@@ -1825,22 +2603,36 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1825
2603
  const n = edges.reduce((sum, id) => sum + (edgeBundles[id]?.members.length ?? 1), 0);
1826
2604
  const intersecting = [...labelBoxes.values()].filter(box => gutter.strips.some(strip => rectsIntersect(strip, box)));
1827
2605
  const labelled = intersecting.length > 0;
1828
- const placedFloor = Math.max(0, ...intersecting.map(box => (gutter.horizontal ? box.height : box.width) + 2 * metrics.labelMargin).filter(needed => needed <= gutter.max));
1829
2606
  const axis = gutter.horizontal ? 'vertical' : 'horizontal';
1830
2607
  const parameters = channelMetrics(metrics, axis === 'horizontal');
1831
- return { id: gutter.id, axis, edges, strips: gutter.strips, n, labelled, gap: gutter.gap,
1832
- expected: Math.min(gutter.max, Math.max(placedFloor, channelGap(n, labelled, { ...parameters, gapMin: gutter.authoredBase ? gutter.base : Math.max(parameters.gapMin, gutter.base) }))) };
2608
+ const expected = r7Routing && gutter.zone
2609
+ ? gutter.base
2610
+ : (() => {
2611
+ const placedFloor = Math.max(0, ...intersecting.map(box => (gutter.horizontal ? box.height : box.width) + 2 * metrics.labelMargin).filter(needed => needed <= gutter.max));
2612
+ return Math.min(gutter.max, Math.max(placedFloor, channelGap(n, labelled, { ...parameters, gapMin: gutter.authoredBase ? gutter.base : Math.max(parameters.gapMin, gutter.base) })));
2613
+ })();
2614
+ return {
2615
+ id: gutter.id,
2616
+ axis,
2617
+ edges,
2618
+ strips: gutter.strips,
2619
+ n,
2620
+ labelled,
2621
+ gap: gutter.gap,
2622
+ expected,
2623
+ ...(r7Routing ? { capacity: channelCapacity(gutter.gap, routeSpacing, borderClearance), zone: gutter.zone } : {}),
2624
+ };
1833
2625
  });
1834
- // A widened gutter in which no placed label sits is an empty lane: a bare
1835
- // route needs no more than the base gap (two clearances).
2626
+ // A widened leaf gutter that disappeared is dropped; r7 sibling-zone gutters stay fixed (REQ-R7-14).
1836
2627
  const unused = [];
1837
2628
  const gutterIds = new Set(gutters.map((gutter) => gutter.id));
1838
2629
  for (const id of [...(plan?.widen.keys() ?? [])].sort(byString))
1839
2630
  if (!gutterIds.has(id))
1840
2631
  unused.push(id);
1841
2632
  // A label with no room is probed with the free space of a base gap above
1842
- // and under it: where it then fits, the lanes it sits in are asked to
1843
- // widen to its thickness plus its two margins — never past the axis cap.
2633
+ // and under it: where it then fits, leaf-card lanes (and v1 lanes) it sits in
2634
+ // are asked to widen to its thickness plus its two margins — never past the
2635
+ // axis cap, and never on r7 fixed sibling-zone gutters (`r7Routing && gutter.zone`).
1844
2636
  const requested = new Map();
1845
2637
  const probed = [...taken];
1846
2638
  for (const entry of unplaced) {
@@ -1855,6 +2647,8 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1855
2647
  const shared = sharedContainerOf(edge.source.entity, edge.target.entity);
1856
2648
  const level = shared === undefined ? ROOT_LEVEL_KEY : representativeOf(shared);
1857
2649
  for (const gutter of gutters) {
2650
+ if (r7Routing && gutter.zone)
2651
+ continue;
1858
2652
  // S-1: an outgoing edge may use a level's base gutter, but cannot
1859
2653
  // change its geometry when a different level is folded.
1860
2654
  if (!gutter.id.startsWith(`${level}|`))
@@ -1868,14 +2662,115 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1868
2662
  }
1869
2663
  }
1870
2664
  for (const channel of channels) {
2665
+ if (r7Routing && channel.zone) {
2666
+ requested.delete(channel.id);
2667
+ continue;
2668
+ }
1871
2669
  const target = Math.max(requested.get(channel.id) ?? 0, channel.expected);
1872
2670
  if (Math.abs(target - channel.gap) > 0.5)
1873
2671
  requested.set(channel.id, target);
1874
2672
  else
1875
2673
  requested.delete(channel.id);
1876
2674
  }
2675
+ // Built-in geometric check for minimum route spacing (DE-2 ask 2).
2676
+ const checkedRoutes = [];
2677
+ const conventionEdges = [];
2678
+ for (const edge of drawnEdges) {
2679
+ const id = edge.occurrence;
2680
+ const points = retryRoutes.get(id);
2681
+ if (points === undefined)
2682
+ continue;
2683
+ const occurrence = projected.relationOccurrences[edge.occurrence];
2684
+ const sourceRole = occurrence.endpoints.find((endpoint) => endpoint.role === "source");
2685
+ const targetRole = occurrence.endpoints.find((endpoint) => endpoint.role === "target");
2686
+ const style = relationPresentationFor(presentation.relations, occurrence.id, occurrence.relation);
2687
+ const arrowhead = resolveArrowhead(occurrence.arrowhead ?? style?.arrowhead)?.canonicalKind ?? "arrow";
2688
+ const passable = new Set([
2689
+ ...projectedAncestorsOf(sourceRole.occurrence),
2690
+ ...projectedAncestorsOf(targetRole.occurrence),
2691
+ ]);
2692
+ const flowArrows = marks.arrows[edge.occurrence];
2693
+ const startPt = points[0];
2694
+ const startArrowhead = flowArrows !== undefined &&
2695
+ startPt !== undefined &&
2696
+ flowArrows.some((a) => Math.hypot(a.tip.x - startPt.x, a.tip.y - startPt.y) <= 1e-4);
2697
+ checkedRoutes.push({
2698
+ id: String(edge.occurrence),
2699
+ source: String(edge.source.entity),
2700
+ target: String(edge.target.entity),
2701
+ points,
2702
+ ...(edge.source.port === undefined ? {} : { sourcePort: String(edge.source.port) }),
2703
+ ...(edge.target.port === undefined ? {} : { targetPort: String(edge.target.port) }),
2704
+ arrowhead,
2705
+ ...(startArrowhead ? { startArrowhead: true } : {}),
2706
+ passable,
2707
+ });
2708
+ if (options.conventions?.arrowDirection === true) {
2709
+ const semanticRelation = document.relations[occurrence.relation];
2710
+ const semSource = semanticRelation?.endpoints.find((ep) => ep.role === "source")?.target;
2711
+ const semTarget = semanticRelation?.endpoints.find((ep) => ep.role === "target")?.target;
2712
+ conventionEdges.push({
2713
+ id: String(edge.occurrence),
2714
+ relationId: String(occurrence.relation),
2715
+ sourceEntity: String(edge.source.entity),
2716
+ targetEntity: String(edge.target.entity),
2717
+ sourceOccurrence: String(sourceRole.occurrence),
2718
+ targetOccurrence: String(targetRole.occurrence),
2719
+ ...(semSource === undefined ? {} : { semanticSourceEntity: String(semSource) }),
2720
+ ...(semTarget === undefined ? {} : { semanticTargetEntity: String(semTarget) }),
2721
+ arrowhead,
2722
+ });
2723
+ }
2724
+ }
2725
+ if (options.conventions !== undefined) {
2726
+ const conventionZones = [];
2727
+ if (options.conventions.zoneTagAcronyms === true) {
2728
+ for (const id of [...rects.keys()].sort(byString)) {
2729
+ const kind = kinds.get(id);
2730
+ if (kind !== "container-expanded" && kind !== "container-collapsed")
2731
+ continue;
2732
+ const occ = representativeOf(id);
2733
+ const entry = presentation.entities[occ];
2734
+ conventionZones.push({ id: String(occ), tag: entry?.text?.kicker });
2735
+ }
2736
+ }
2737
+ warnings.push(...lintDiagramConventions({
2738
+ options: options.conventions,
2739
+ document,
2740
+ edges: conventionEdges,
2741
+ zones: conventionZones,
2742
+ }));
2743
+ }
2744
+ const routeSpacingReport = routeSpacing > 0
2745
+ ? checkRouteSpacing({
2746
+ rects,
2747
+ routes: checkedRoutes,
2748
+ routeSpacing,
2749
+ borderClearance,
2750
+ channels,
2751
+ barriers: auditBarriers,
2752
+ })
2753
+ : undefined;
2754
+ if (routeSpacingReport !== undefined) {
2755
+ for (const conflict of routeSpacingReport.conflicts) {
2756
+ warnings.push({
2757
+ severity: "info",
2758
+ code: conflict.kind === "channel-capacity-exceeded" ? "channel-capacity-exceeded" : "route-spacing-conflict",
2759
+ refs: conflict.routes,
2760
+ message: conflict.message,
2761
+ details: {
2762
+ kind: conflict.kind,
2763
+ actual: conflict.actual,
2764
+ required: conflict.required,
2765
+ ...(conflict.entity === undefined ? {} : { entity: conflict.entity }),
2766
+ ...(conflict.channelId === undefined ? {} : { channelId: conflict.channelId }),
2767
+ },
2768
+ });
2769
+ }
2770
+ }
1877
2771
  // Emit the view plus measurements.
1878
- const placedView = buildMeasuredView(document, filteredGraph, rects, finalDocks, retryRoutes, options, foldMetadata, drawnEdges);
2772
+ const placedView = buildMeasuredView(document, filteredGraph, rects, finalDocks, retryRoutes, options, foldMetadata, drawnEdges, r7Routing && sourceView !== undefined && sourceView.presentation.diagram?.contractPin === undefined
2773
+ && isPresentationContractV2Pin(presentation.contractPin));
1879
2774
  const bounds = unionOf(rects, retryRoutes, new Map([...labelBoxes, ...Object.entries(marks.badges).map(([id, box]) => [id, box]), ...Object.entries(marks.arrows).flatMap(([id, arrows]) => arrows.map((arrow, i) => [(id + String(i)), arrow.box]))]));
1880
2775
  const width = bounds.width;
1881
2776
  const zoom = bounds.empty ? 1 : Math.min(1, Math.max(MIN_ZOOM, options.targetWidth / width));
@@ -1908,6 +2803,7 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1908
2803
  measurements,
1909
2804
  orientations: Object.fromEntries([...orientationRecord].sort(([left], [right]) => byString(left, right))),
1910
2805
  channels,
2806
+ ...(routeSpacingReport === undefined ? {} : { routeSpacing: routeSpacingReport }),
1911
2807
  labelBoxes: Object.fromEntries([...labelBoxes]
1912
2808
  .sort(([left], [right]) => byString(left, right))
1913
2809
  .map(([id, box]) => [id, { x: clean(box.x), y: clean(box.y), width: box.width, height: box.height }])),
@@ -1959,6 +2855,50 @@ function layoutMeasuredPass(document, options, sourceView, forced) {
1959
2855
  previous = outcome;
1960
2856
  outcome = runPass({ frozen, widen, external });
1961
2857
  }
2858
+ // When strict route spacing reports channel capacity overflow inside an
2859
+ // auto-packed level (e.g. a folded child causes a column/row stack whose
2860
+ // single fixed gutter has lower capacity than the edges crossing it), try
2861
+ // flipping that level's orientation (`rows` <-> `columns`) and adopt it ONLY
2862
+ // when it completely resolves all route-spacing conflicts without introducing
2863
+ // obstructions.
2864
+ if (routeSpacing > 0 &&
2865
+ filteredGraph.nodes.size <= 25 &&
2866
+ outcome.result.status === "laid-out" &&
2867
+ (outcome.result.routeSpacing?.conflictCount ?? 0) > 0) {
2868
+ const candidateKeys = new Set();
2869
+ for (const conflict of outcome.result.routeSpacing.conflicts) {
2870
+ if (conflict.kind !== "channel-capacity-exceeded" || conflict.channelId === undefined)
2871
+ continue;
2872
+ const key = conflict.channelId.split("|")[0];
2873
+ if (key !== undefined && outcome.result.orientations?.[key] !== undefined) {
2874
+ candidateKeys.add(key);
2875
+ }
2876
+ }
2877
+ const metricOf = (pass) => {
2878
+ if (pass.result.status !== "laid-out")
2879
+ return [Infinity, Infinity, Infinity];
2880
+ const obs = pass.result.warnings.filter((w) => w.code === "route-obstructed").length;
2881
+ const cc = pass.result.routeSpacing?.conflictCount ?? 0;
2882
+ return [obs, cc, pass.unplaced];
2883
+ };
2884
+ let bestMetric = metricOf(outcome);
2885
+ const maxFlipCandidates = 2;
2886
+ for (const key of [...candidateKeys].sort(byString).slice(0, maxFlipCandidates)) {
2887
+ if (bestMetric[0] === 0 && bestMetric[1] === 0)
2888
+ break;
2889
+ const currentOrient = outcome.result.status === "laid-out" ? outcome.result.orientations?.[key] : undefined;
2890
+ if (currentOrient === undefined)
2891
+ continue;
2892
+ const flipped = currentOrient === "rows" ? "columns" : "rows";
2893
+ const overrides = new Map([[key, flipped]]);
2894
+ const candidate = runPass(undefined, overrides);
2895
+ const candMetric = metricOf(candidate);
2896
+ if (candMetric[0] === 0 && candMetric[1] === 0) {
2897
+ outcome = candidate;
2898
+ bestMetric = candMetric;
2899
+ }
2900
+ }
2901
+ }
1962
2902
  if (outcome.result.status === "laid-out" && outcome.requested.size > 0)
1963
2903
  return { ...outcome.result,
1964
2904
  warnings: [...outcome.result.warnings, { code: "channel-unresolved", refs: [...outcome.requested.keys()],
@@ -1997,7 +2937,7 @@ function unionOf(rects, routes, labels) {
1997
2937
  return { empty: true, xmin: 0, ymin: 0, width: 0, height: 0 };
1998
2938
  return { empty: false, xmin, ymin, width: xmax - xmin, height: ymax - ymin };
1999
2939
  }
2000
- function buildMeasuredView(document, graph, rects, docks, routes, options, foldMetadata, drawnEdges) {
2940
+ function buildMeasuredView(document, graph, rects, docks, routes, options, foldMetadata, drawnEdges, persistUnpinnedDashes) {
2001
2941
  const projected = foldMetadata.projected;
2002
2942
  const maxContainerDepth = Math.max(-1, ...[...graph.nodes.values()].filter((node) => node.kind === "container").map((node) => node.depth));
2003
2943
  const entityOccurrences = {};
@@ -2023,6 +2963,17 @@ function buildMeasuredView(document, graph, rects, docks, routes, options, foldM
2023
2963
  // occurrences take waypoints, looked up by occurrence id.
2024
2964
  const relationOccurrences = {};
2025
2965
  for (const occurrence of Object.values(projected.relationOccurrences).sort((left, right) => byString(left.id, right.id))) {
2966
+ const style = relationPresentationFor(options.presentation?.relations, occurrence.id, occurrence.relation);
2967
+ // A declared DE-2 stroke has an explicit default arrowhead when saved.
2968
+ // Bare dashed occurrences already existed on pinned full-size views.
2969
+ const authoredStroke = style?.strokeStyle !== undefined || (persistUnpinnedDashes && occurrence.strokeStyle === "dashed");
2970
+ const arrowhead = style?.arrowhead ?? (authoredStroke ? "arrow" : undefined);
2971
+ const styledOccurrence = {
2972
+ ...occurrence,
2973
+ ...(occurrence.strokeStyle === undefined && style?.strokeStyle !== undefined ? { strokeStyle: style.strokeStyle } : {}),
2974
+ ...(occurrence.arrowhead === undefined && arrowhead !== undefined ? { arrowhead } : {}),
2975
+ ...(occurrence.emphasis === undefined && style?.emphasis !== undefined ? { emphasis: style.emphasis } : {}),
2976
+ };
2026
2977
  const occurrenceId = occurrence.id;
2027
2978
  const pair = docks.get(occurrenceId);
2028
2979
  const route = routes.get(occurrenceId);
@@ -2030,11 +2981,11 @@ function buildMeasuredView(document, graph, rects, docks, routes, options, foldM
2030
2981
  const waypoints = route
2031
2982
  .slice(pair.source.port === undefined ? 0 : 1, pair.target.port === undefined ? route.length : route.length - 1)
2032
2983
  .map((point) => ({ x: clean(point.x), y: clean(point.y) }));
2033
- relationOccurrences[occurrence.id] = { ...occurrence, waypoints };
2984
+ relationOccurrences[occurrence.id] = { ...styledOccurrence, waypoints };
2034
2985
  }
2035
2986
  else {
2036
- const { waypoints: _oldRoute, ...retained } = occurrence;
2037
- relationOccurrences[occurrence.id] = document.relations[occurrence.relation]?.type === "flow-step" ? retained : { ...occurrence };
2987
+ const { waypoints: _oldRoute, ...retained } = styledOccurrence;
2988
+ relationOccurrences[occurrence.id] = document.relations[occurrence.relation]?.type === "flow-step" ? retained : { ...styledOccurrence };
2038
2989
  }
2039
2990
  }
2040
2991
  // Ports keep their projected identities: every drawn end landing on a