@sentropic/diagram-canvas 0.1.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +9 -0
  2. package/contracts/diagram-anatomy.v1.json +2073 -0
  3. package/dist/camera.d.ts +12 -7
  4. package/dist/camera.js +18 -10
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/layout/bundleLabel.d.ts +12 -0
  8. package/dist/layout/bundleLabel.js +16 -0
  9. package/dist/layout/cache.js +7 -7
  10. package/dist/layout/channels.d.ts +28 -0
  11. package/dist/layout/channels.js +14 -0
  12. package/dist/layout/dock.d.ts +1 -0
  13. package/dist/layout/dock.js +18 -37
  14. package/dist/layout/engine.js +4 -4
  15. package/dist/layout/erd.d.ts +5 -0
  16. package/dist/layout/erd.js +85 -0
  17. package/dist/layout/fingerprint.d.ts +2 -2
  18. package/dist/layout/fingerprint.js +6 -2
  19. package/dist/layout/flow-order.d.ts +3 -0
  20. package/dist/layout/flow-order.js +14 -0
  21. package/dist/layout/flows.d.ts +89 -0
  22. package/dist/layout/flows.js +120 -0
  23. package/dist/layout/graph.d.ts +2 -0
  24. package/dist/layout/graph.js +5 -2
  25. package/dist/layout/hints.js +7 -6
  26. package/dist/layout/index.d.ts +3 -0
  27. package/dist/layout/index.js +3 -0
  28. package/dist/layout/labels.d.ts +1 -0
  29. package/dist/layout/labels.js +1 -1
  30. package/dist/layout/measure.d.ts +3 -3
  31. package/dist/layout/measure.js +5 -3
  32. package/dist/layout/measured.js +406 -75
  33. package/dist/layout/route.d.ts +2 -0
  34. package/dist/layout/route.js +2 -70
  35. package/dist/layout/sceneMeasure.d.ts +13 -0
  36. package/dist/layout/sceneMeasure.js +57 -0
  37. package/dist/layout/spacing.generated.d.ts +13 -0
  38. package/dist/layout/spacing.generated.js +8 -0
  39. package/dist/layout/types.d.ts +33 -4
  40. package/dist/layout/types.js +4 -10
  41. package/dist/presentation/diagramCardModel.d.ts +660 -0
  42. package/dist/presentation/diagramCardModel.js +1150 -0
  43. package/dist/presentation/diagramSceneModel.d.ts +70 -2
  44. package/dist/presentation/diagramSceneModel.js +165 -30
  45. package/dist/presentation/diagramSceneTypes.d.ts +91 -0
  46. package/dist/presentation/diagramSceneTypes.js +2 -0
  47. package/dist/presentation/erd.d.ts +81 -0
  48. package/dist/presentation/erd.js +156 -0
  49. package/dist/presentation/flowModel.d.ts +82 -0
  50. package/dist/presentation/flowModel.js +206 -0
  51. package/dist/presentation/index.d.ts +20 -0
  52. package/dist/presentation/index.js +14 -0
  53. package/dist/presentation/registry.d.ts +52 -0
  54. package/dist/presentation/registry.js +81 -0
  55. package/dist/presentation/renderCardSvg.d.ts +73 -0
  56. package/dist/presentation/renderCardSvg.js +144 -0
  57. package/dist/presentation/renderSceneSvg.d.ts +38 -0
  58. package/dist/presentation/renderSceneSvg.js +56 -0
  59. package/dist/presentation/renderZoneSvg.d.ts +79 -0
  60. package/dist/presentation/renderZoneSvg.js +180 -0
  61. package/dist/presentation/sceneLabelClearance.d.ts +8 -0
  62. package/dist/presentation/sceneLabelClearance.js +85 -0
  63. package/dist/visibility.d.ts +1 -1
  64. package/dist/visibility.js +5 -4
  65. package/package.json +31 -5
@@ -1,3 +1,9 @@
1
+ import { relationBaseType } from "@sentropic/diagram-core";
2
+ import { validateFlows } from "@sentropic/diagram-core";
3
+ import { relationVerdict } from "../visibility.js";
4
+ import { DEFAULT_FLOW_TOKENS, planFlows, placeFlowMarks } from "./flows.js";
5
+ import { layoutErd } from "./erd.js";
6
+ import { DEFAULT_MIN_READABLE_SCALE } from "../camera.js";
1
7
  /**
2
8
  * Measured diagram layout (M3 §4.6–§4.8, layout half of §5.6; placement by
3
9
  * SPEC_EVOL_DC2A §3–§4).
@@ -28,8 +34,12 @@ import { collapsedOf, createTypeResolver, foldGroupId, GENERIC_PROFILE_ID, hasEr
28
34
  import { dockEdges } from "./dock.js";
29
35
  import { isAncestor } from "./graph.js";
30
36
  import { effectiveStretch, groupLeaves, isLayoutGroup, resolveGaps, resolveOrder, resolveRowGaps, validateHints, } from "./hints.js";
37
+ import { measureSceneBox } from "./sceneMeasure.js";
38
+ import { ZONE_GEOMETRY } from "../presentation/diagramCardModel.js";
31
39
  import { placePackedLabel } from "./labels.js";
32
- import { CONTENT_INSET, DEFAULT_ALLOCATED_LINES, FIXED_CARD_HEIGHT, FIXED_CARD_WIDTH, headerAvailableWidth, headerOverflows, innerWidthOf, LAST_CHILD_TO_BOTTOM_GAP, LEGEND_KEY_HEIGHT, measureHeader, RULE_TO_FIRST_CHILD_GAP, SWATCH_ALLOCATION, TOGGLE_ALLOCATION, UNWRAPPED_PROBE_WIDTH, } from "./measure.js";
40
+ import { 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";
41
+ import { measureBundleLabel } from "./bundleLabel.js";
42
+ import { channelGap, channelMetrics } from "./channels.js";
33
43
  import { chooseOrientation, packColumns, packRows, seatShelves } from "./pack.js";
34
44
  import { labelDetour, routeEdges, routesConflict } from "./route.js";
35
45
  import { rectsIntersect } from "../geometry.js";
@@ -132,6 +142,24 @@ const OUTER_LANES = 6;
132
142
  /** MAJ-1: at most one widening round after pass 1 (BF-6); afterwards the set only shrinks. */
133
143
  const WIDEN_ROUNDS = 1;
134
144
  export function layoutMeasured(document, options, sourceView) {
145
+ if (document.profileRefs.length === 1 && document.profileRefs[0] === "erd@1")
146
+ return layoutErd(document, options, sourceView);
147
+ const first = layoutMeasuredPass(document, options, sourceView, new Set());
148
+ if (first.status !== "laid-out" || first.flowTargets === undefined)
149
+ return first;
150
+ const forced = new Set();
151
+ const failed = new Set(first.warnings.filter((w) => w.code === "route-obstructed" || w.code === "badge-unplaced").flatMap((w) => w.refs));
152
+ const plan = planFlows(document, first.view, options.registry, options, new Set());
153
+ for (const [key, members] of plan.groups) {
154
+ if (members.length >= 2 && !first.flowBundles?.some((b) => b.id === key) && members.some((m) => failed.has(m.occurrence)))
155
+ forced.add(key);
156
+ }
157
+ if (forced.size === 0)
158
+ return first;
159
+ const repaired = layoutMeasuredPass(document, options, sourceView, forced);
160
+ return repaired.status === "laid-out" ? { ...repaired, flowRepairPasses: 1 } : repaired;
161
+ }
162
+ function layoutMeasuredPass(document, options, sourceView, forced) {
135
163
  if (!Number.isFinite(options.targetWidth) || options.targetWidth <= 0) {
136
164
  return {
137
165
  status: "refused",
@@ -145,6 +173,8 @@ export function layoutMeasured(document, options, sourceView) {
145
173
  diagnostics: [],
146
174
  };
147
175
  }
176
+ if (sourceView !== undefined && Object.values(sourceView.entityOccurrences).some((occurrence) => document.entities[occurrence.entity]?.type === "flow-scenario"))
177
+ return { status: "refused", refusals: [{ code: "document-invalid", path: "sourceView.entityOccurrences", message: "flow scenarios have no view occurrence" }], diagnostics: [] };
148
178
  const presentation = options.presentation;
149
179
  if (presentation === undefined) {
150
180
  return {
@@ -167,8 +197,21 @@ export function layoutMeasured(document, options, sourceView) {
167
197
  };
168
198
  }
169
199
  const measure = options.measureLines;
200
+ const sceneBoxCache = new Map();
201
+ const sceneBoxAt = (id, width, collapsed) => {
202
+ const key = `${id}|${width}|${collapsed}`;
203
+ let box = sceneBoxCache.get(key);
204
+ if (box === undefined) {
205
+ const entry = presentation.entities[id];
206
+ const kind = kinds.get(projected.entityOccurrences[id]?.entity);
207
+ const expanded = kind === "container-expanded" || kind === "legend-expanded";
208
+ box = measureSceneBox(expanded && entry?.form === "card" ? { ...entry, form: "container" } : entry, id, width, collapsed, measure, metrics.containerPadding);
209
+ sceneBoxCache.set(key, box);
210
+ }
211
+ return box;
212
+ };
170
213
  const validationOptions = options.bindings === undefined ? { registry: options.registry } : { registry: options.registry, bindings: options.bindings };
171
- const diagnostics = validateDocument(document, validationOptions);
214
+ const diagnostics = [...validateDocument(document, validationOptions), ...validateFlows(document)];
172
215
  if (hasErrors(diagnostics)) {
173
216
  return {
174
217
  status: "refused",
@@ -180,13 +223,14 @@ export function layoutMeasured(document, options, sourceView) {
180
223
  if ("refusals" in read)
181
224
  return { status: "refused", refusals: read.refusals, diagnostics: [] };
182
225
  const graph = read.graph;
183
- const metrics = { ...DEFAULT_LAYOUT_METRICS, ...options.metrics };
226
+ const metrics = { ...DEFAULT_LAYOUT_METRICS, ...options.metrics, slotSpacing: options.metrics?.slotSpacing ?? options.metrics?.trackSpacing ?? channelMetrics({}, true).trackSpacing };
184
227
  const hints = options.hints ?? {};
185
228
  const gaps = resolveGaps(options.hints, metrics);
186
229
  const globalStretch = hints.stretch ?? false;
187
230
  // DC-2a row-pack (SPEC_EVOL_DC2A §3–§4, AC-1): every measured view is
188
231
  // packed; `options.rowPack` only tunes the objective.
189
232
  const rowPack = resolveRowPack(options.rowPack);
233
+ const contentInset = metrics.containerPadding;
190
234
  const rowGaps = resolveRowGaps(hints, metrics);
191
235
  {
192
236
  const refusals = [...validateRowPack(rowPack)];
@@ -330,6 +374,17 @@ export function layoutMeasured(document, options, sourceView) {
330
374
  projected = retained;
331
375
  }
332
376
  }
377
+ const flowOccurrences = new Set();
378
+ for (const occurrence of Object.values(projected.relationOccurrences)) {
379
+ if (document.relations[occurrence.relation]?.type !== "flow-step")
380
+ continue;
381
+ if (flowOccurrences.has(occurrence.relation))
382
+ return { status: "refused", refusals: [{ code: "document-invalid", path: "sourceView.relationOccurrences", message: "one flow step must have at most one occurrence per view" }], diagnostics: [] };
383
+ flowOccurrences.add(occurrence.relation);
384
+ }
385
+ const flowPlan = planFlows(document, projected, options.registry, options, forced);
386
+ const hasFlows = flowOccurrences.size > 0;
387
+ const flowTokens = { ...DEFAULT_FLOW_TOKENS, ...options.flowTokens };
333
388
  const entityToOccurrences = new Map();
334
389
  for (const occurrence of Object.values(projected.entityOccurrences)) {
335
390
  const list = entityToOccurrences.get(occurrence.entity) ?? [];
@@ -498,7 +553,7 @@ export function layoutMeasured(document, options, sourceView) {
498
553
  : { run: buildGroupRun(part.group, `${key}#${part.group.id}`, globalStretch), gapAfter: part.group.gapAfter });
499
554
  return { key, mode: "auto", items, stretch: false };
500
555
  };
501
- const runHasZone = (run) => run.items.some((item) => ("entity" in item ? isStretchedBox(item.entity) : runHasZone(item.run)));
556
+ const runHasZone = (run) => run.items.some((item) => ("entity" in item ? kinds.get(item.entity) !== "leaf" : runHasZone(item.run)));
502
557
  // Drawn edges: the link occurrences the projected view draws. Internal
503
558
  // edges under a collapse are excluded by the same visibility; every
504
559
  // surviving edge carries its projected representative endpoints, and
@@ -519,7 +574,9 @@ export function layoutMeasured(document, options, sourceView) {
519
574
  };
520
575
  const drawnEdges = [];
521
576
  for (const occurrence of Object.values(projected.relationOccurrences).sort((left, right) => byString(left.id, right.id))) {
522
- if (document.relations[occurrence.relation]?.type !== "link")
577
+ const semantic = document.relations[occurrence.relation];
578
+ const owner = semantic === undefined ? undefined : options.registry.get(semantic.profile);
579
+ if (semantic === undefined || owner === undefined || relationBaseType(document, owner, semantic) !== "link" || !relationVerdict(projected, semantic, document).visible)
523
580
  continue;
524
581
  const sourceEnd = occurrence.endpoints.find((endpoint) => endpoint.role === "source");
525
582
  const targetEnd = occurrence.endpoints.find((endpoint) => endpoint.role === "target");
@@ -529,39 +586,102 @@ export function layoutMeasured(document, options, sourceView) {
529
586
  const target = resolveDrawnEnd(targetEnd.occurrence);
530
587
  if (source === undefined || target === undefined)
531
588
  continue;
589
+ if (flowPlan.suppressed.has(occurrence.id))
590
+ continue;
532
591
  drawnEdges.push({ occurrence: occurrence.id, relation: occurrence.relation, source, target });
533
592
  }
593
+ const edgeBundles = {};
594
+ const liftedPairs = new Map();
595
+ for (const edge of drawnEdges) {
596
+ // Numbered steps retain the flow planner's bundle carriers and targets.
597
+ if (flowOccurrences.has(edge.relation))
598
+ continue;
599
+ const projectedEdge = projected.relationOccurrences[edge.occurrence];
600
+ if (!projectedEdge.endpoints.some(end => end.sourceOccurrence !== undefined))
601
+ continue;
602
+ const key = JSON.stringify([edge.source.entity, edge.target.entity]);
603
+ const pair = liftedPairs.get(key) ?? [];
604
+ pair.push(edge);
605
+ liftedPairs.set(key, pair);
606
+ }
607
+ const bundled = new Set();
608
+ for (const pair of liftedPairs.values()) {
609
+ if (pair.length < 2)
610
+ continue;
611
+ const first = pair[0];
612
+ edgeBundles[first.occurrence] = { members: pair.map(edge => edge.occurrence),
613
+ label: `${pair.length} liaisons`,
614
+ relations: pair.map(edge => edgeLabelOf(document, edge.relation)).filter((label) => label !== undefined),
615
+ title: pair.map(edge => edgeLabelOf(document, edge.relation)).filter((label) => label !== undefined).join("\n") };
616
+ pair.slice(1).forEach(edge => bundled.add(edge.occurrence));
617
+ }
618
+ for (let index = drawnEdges.length - 1; index >= 0; index -= 1) {
619
+ if (bundled.has(drawnEdges[index].occurrence))
620
+ drawnEdges.splice(index, 1);
621
+ }
622
+ const portClaims = new Map();
623
+ if (hasFlows)
624
+ for (const edge of drawnEdges)
625
+ for (const end of projected.relationOccurrences[edge.occurrence].endpoints) {
626
+ if (projected.portOccurrences[end.occurrence] !== undefined)
627
+ portClaims.set(end.occurrence, (portClaims.get(end.occurrence) ?? 0) + 1);
628
+ }
629
+ const slotOf = (edge, role) => {
630
+ const occurrence = projected.relationOccurrences[edge.occurrence].endpoints.find((end) => end.role === role)?.occurrence;
631
+ return occurrence !== undefined && (portClaims.get(occurrence) ?? 0) > 1 ? occurrence : undefined;
632
+ };
633
+ const flowRunRanks = new Map([...flowPlan.ranks].filter(([id]) => {
634
+ const edge = drawnEdges.find((candidate) => candidate.occurrence === id);
635
+ return edge !== undefined && slotOf(edge, "source") === undefined && slotOf(edge, "target") === undefined;
636
+ }));
534
637
  const filteredGraph = {
535
638
  nodes: new Map([...graph.nodes].filter(([id]) => visible(id))),
536
639
  roots: graph.roots.filter(visible),
537
640
  edges: drawnEdges.map((edge) => ({
641
+ ...(flowRunRanks.has(edge.occurrence) ? { flowRank: flowRunRanks.get(edge.occurrence) } : {}),
538
642
  id: edge.occurrence,
539
643
  source: edge.source.port === undefined
540
644
  ? { entity: edge.source.entity }
541
- : { entity: edge.source.entity, port: edge.source.port },
645
+ : { entity: edge.source.entity, port: edge.source.port, ...(slotOf(edge, "source") === undefined ? {} : { slot: slotOf(edge, "source") }) },
542
646
  target: edge.target.port === undefined
543
647
  ? { entity: edge.target.entity }
544
- : { entity: edge.target.entity, port: edge.target.port },
648
+ : { entity: edge.target.entity, port: edge.target.port, ...(slotOf(edge, "target") === undefined ? {} : { slot: slotOf(edge, "target") }) },
545
649
  })),
546
650
  };
547
651
  // Edge labels, measured once: keyed by the projected relation occurrence id.
548
652
  const labelSizes = new Map();
549
653
  const edgeLayouts = new Map();
550
654
  for (const edge of drawnEdges) {
551
- const label = edgeLabelOf(document, edge.relation);
655
+ if (flowPlan.bundles.some((bundle) => bundle.carrier === edge.occurrence))
656
+ continue;
657
+ const label = edgeBundles[edge.occurrence]?.label ?? edgeLabelOf(document, edge.relation);
552
658
  if (label === undefined)
553
659
  continue;
554
- const layout = measure({
660
+ const bundle = edgeBundles[edge.occurrence];
661
+ const chip = bundle?.relations === undefined ? undefined : measureBundleLabel(bundle.relations, measure, metrics.bundleLabelMaxWidth, bundle.members.length);
662
+ const layout = chip === undefined ? measure({
555
663
  text: label,
556
664
  role: "edge-label",
557
665
  availableWidth: EDGE_LABEL_WIDTH,
558
666
  allocatedLines: DEFAULT_ALLOCATED_LINES["edge-label"],
559
667
  folded: false,
560
- });
668
+ }) : chip.layout;
669
+ if (bundle !== undefined && chip !== undefined)
670
+ bundle.chip = chip;
561
671
  const occurrenceId = edge.occurrence;
562
672
  edgeLayouts.set(occurrenceId, layout);
563
673
  labelSizes.set(occurrenceId, { width: layout.width, height: layout.height });
564
674
  }
675
+ const routeSizes = new Map(labelSizes);
676
+ for (const member of flowPlan.members) {
677
+ if (flowPlan.suppressed.has(member.occurrence))
678
+ continue;
679
+ const bundle = flowPlan.bundles.find((b) => b.carrier === member.occurrence);
680
+ const text = bundle === undefined ? member.step.badge : (options.flows?.countTemplate ?? "{n}").replaceAll("{n}", String(bundle.members.length));
681
+ const badge = measure({ text, role: "flow-badge", availableWidth: Number.MAX_SAFE_INTEGER, allocatedLines: 1, folded: false });
682
+ const old = routeSizes.get(member.occurrence);
683
+ routeSizes.set(member.occurrence, { width: Math.max(old?.width ?? 0, flowTokens.flowBadgeSize, badge.width + 2 * flowTokens.flowBadgePaddingX), height: Math.max(old?.height ?? 0, flowTokens.flowBadgeSize) });
684
+ }
565
685
  // A route may cross the boundaries of its own occurrence-group ancestors
566
686
  // (L-R8): the chain is read from the projected view, never from the
567
687
  // semantic containment tree.
@@ -641,7 +761,9 @@ export function layoutMeasured(document, options, sourceView) {
641
761
  availableWidth: inner,
642
762
  allocatedLines: { ...DEFAULT_ALLOCATED_LINES },
643
763
  };
644
- const header = measureHeader(input, measure);
764
+ const entry = presentation.entities[representativeOf(id)];
765
+ const header = entry === undefined ? measureHeader(input, measure)
766
+ : sceneBoxAt(representativeOf(id), inner + 2 * ZONE_GEOMETRY.headerInset, input.folded).header;
645
767
  headers.set(id, header);
646
768
  headerInputs.set(id, input);
647
769
  headerWidths.set(id, inner);
@@ -695,6 +817,13 @@ export function layoutMeasured(document, options, sourceView) {
695
817
  orientation = run.mode;
696
818
  shelves = (run.mode === "rows" ? packRows : packColumns)(boxes, packOptions).rows;
697
819
  }
820
+ // A column shelf containing one box per column paints the same single
821
+ // row. Canonicalize that equivalent arrangement before feeding fold
822
+ // hysteresis back; otherwise the metadata can alternate without a move.
823
+ if (run.mode === "auto" && orientation === "columns" && shelves.every(shelf => shelf.length === 1)) {
824
+ orientation = "rows";
825
+ shelves = [shelves.flat()];
826
+ }
698
827
  chosen.set(run.key, { orientation, shelves });
699
828
  if (run.mode === "auto" && boxes.length > 0)
700
829
  orientationRecord.set(run.key, orientation);
@@ -719,11 +848,18 @@ export function layoutMeasured(document, options, sourceView) {
719
848
  const kind = kinds.get(id);
720
849
  if (kind === "leaf" || kind === "container-collapsed" || kind === "legend-collapsed") {
721
850
  outerWidths.set(id, FIXED_CARD_WIDTH);
722
- return { width: FIXED_CARD_WIDTH, height: FIXED_CARD_HEIGHT };
851
+ const entry = presentation.entities[representativeOf(id)];
852
+ const measured = entry === undefined ? { width: FIXED_CARD_WIDTH, height: FIXED_CARD_HEIGHT }
853
+ : sceneBoxAt(representativeOf(id), FIXED_CARD_WIDTH, kind !== "leaf");
854
+ const size = { width: measured.width, height: measured.height };
855
+ packedSizes.set(id, size);
856
+ return size;
723
857
  }
724
858
  if (kind === "legend-key")
725
859
  return { width: innerWidthOf(FIXED_CARD_WIDTH), height: LEGEND_KEY_HEIGHT };
726
- const headerDriven = unwrappedHeaderWidth(id) + 2 * CONTENT_INSET + TOGGLE_ALLOCATION;
860
+ const hasIcon = presentation.entities[representativeOf(id)]?.icon !== "none";
861
+ const headerReserve = ZONE_GEOMETRY.headerTextInset - (hasIcon ? 0 : ZONE_GEOMETRY.iconSize + ZONE_GEOMETRY.iconTextGap);
862
+ const headerDriven = unwrappedHeaderWidth(id) + headerReserve;
727
863
  const floor = Math.max(FIXED_CARD_WIDTH, headerDriven);
728
864
  const ordered = orderedChildrenOf(id);
729
865
  const headerHeight = headerHeightOf(id, floor);
@@ -731,13 +867,13 @@ export function layoutMeasured(document, options, sourceView) {
731
867
  // A legend stays a single-column list of keys (DLR-341): exempt from packing.
732
868
  outerWidths.set(id, floor);
733
869
  const keys = ordered.length * LEGEND_KEY_HEIGHT + Math.max(0, ordered.length - 1) * gaps.cardGapY;
734
- const size = { width: floor, height: CONTENT_INSET + headerHeight + RULE_TO_FIRST_CHILD_GAP + keys + LAST_CHILD_TO_BOTTOM_GAP };
870
+ const size = { width: floor, height: ZONE_GEOMETRY.headerInset + headerHeight + contentInset + keys + contentInset };
735
871
  packedSizes.set(id, size);
736
872
  return size;
737
873
  }
738
874
  const run = buildLevelRun(id, ordered);
739
875
  levelRuns.set(id, run);
740
- const level = sizeRun(run, 2 * CONTENT_INSET, CONTENT_INSET + headerHeight + RULE_TO_FIRST_CHILD_GAP + LAST_CHILD_TO_BOTTOM_GAP);
876
+ const level = sizeRun(run, 2 * contentInset, ZONE_GEOMETRY.headerInset + headerHeight + contentInset + contentInset);
741
877
  // BF-6: reserve measured U-channel headroom for labelled edges on one
742
878
  // shelf, including wrapped labels and parallel channels. This is
743
879
  // container content below its children; sibling gutters keep their cap.
@@ -765,11 +901,12 @@ export function layoutMeasured(document, options, sourceView) {
765
901
  }
766
902
  }
767
903
  const levelHeight = level.height + uExtra;
768
- const outer = Math.max(floor, level.width + (ordered.length > 0 ? 2 * CONTENT_INSET : 0));
904
+ const outer = Math.max(floor, level.width + (ordered.length > 0 ? 2 * contentInset : 0));
769
905
  outerWidths.set(id, outer);
770
906
  const size = {
771
907
  width: outer,
772
- height: CONTENT_INSET + headerHeight + RULE_TO_FIRST_CHILD_GAP + levelHeight + LAST_CHILD_TO_BOTTOM_GAP,
908
+ height: ZONE_GEOMETRY.headerInset + headerHeight + contentInset + levelHeight + contentInset
909
+ + sceneBoxAt(representativeOf(id), outer, false).footerReserve,
773
910
  };
774
911
  packedSizes.set(id, size);
775
912
  return size;
@@ -802,14 +939,27 @@ export function layoutMeasured(document, options, sourceView) {
802
939
  break;
803
940
  }
804
941
  for (const id of headerIds) {
805
- for (const overflow of headerOverflows(headerInputs.get(id), headers.get(id), lineHeightOf)) {
806
- warnOverflow(overflow, kinds.get(id) !== "leaf");
942
+ const size = packedSizes.get(id);
943
+ const occurrence = representativeOf(id);
944
+ if (presentation.entities[occurrence] !== undefined && size !== undefined) {
945
+ for (const diagnostic of sceneBoxAt(occurrence, size.width, isCollapsed(id)).diagnostics) {
946
+ if (diagnostic.reason !== "truncated")
947
+ continue;
948
+ warnings.push({ code: kinds.get(id) === "leaf" ? "card-overflow" : "zone-overflow", severity: "info",
949
+ refs: [occurrence, diagnostic.slot], message: "truncated " + diagnostic.slot + ": " + diagnostic.hiddenLength + " hidden characters; full text in title/aria",
950
+ details: { slot: diagnostic.slot, reason: "truncated", hiddenLength: diagnostic.hiddenLength, neededHeight: diagnostic.neededPx, allocatedHeight: diagnostic.allocatedPx } });
951
+ }
807
952
  }
953
+ else
954
+ for (const overflow of headerOverflows(headerInputs.get(id), headers.get(id), lineHeightOf)) {
955
+ warnOverflow(overflow, kinds.get(id) !== "leaf");
956
+ }
808
957
  }
809
958
  // Seating: every run at its packed positions. The root is one more run
810
959
  // with zero chrome and the same token gaps — never `rankGap` (§3.5).
811
960
  const rects = new Map();
812
961
  const titleBands = new Map();
962
+ const footerBands = new Map();
813
963
  const legendInner = new Map();
814
964
  const seatedBoxes = new Map();
815
965
  const seatRun = (run, originX, originY) => {
@@ -831,7 +981,7 @@ export function layoutMeasured(document, options, sourceView) {
831
981
  const seatBox = (id, x, y) => {
832
982
  const kind = kinds.get(id);
833
983
  if (kind === "leaf" || kind === "container-collapsed" || kind === "legend-collapsed") {
834
- rects.set(id, { x, y, width: FIXED_CARD_WIDTH, height: FIXED_CARD_HEIGHT });
984
+ rects.set(id, { x, y, ...packedSizes.get(id) });
835
985
  return;
836
986
  }
837
987
  if (kind === "legend-key") {
@@ -842,9 +992,16 @@ export function layoutMeasured(document, options, sourceView) {
842
992
  const header = headers.get(id);
843
993
  const inner = innerWidthOf(size.width);
844
994
  rects.set(id, { x, y, width: size.width, height: size.height });
845
- titleBands.set(id, { x: x + CONTENT_INSET, y: y + CONTENT_INSET, width: inner, height: header.height });
846
- const contentX = x + CONTENT_INSET;
847
- const contentY = y + CONTENT_INSET + header.height + RULE_TO_FIRST_CHILD_GAP;
995
+ const ruleClearance = (ZONE_GEOMETRY.ruleHeight / 2 + 1) / DEFAULT_MIN_READABLE_SCALE;
996
+ titleBands.set(id, { x, y, width: size.width, height: ZONE_GEOMETRY.headerInset + header.height });
997
+ const footerReserve = sceneBoxAt(representativeOf(id), size.width, false).footerReserve;
998
+ if (footerReserve > 0)
999
+ footerBands.set(id, {
1000
+ x, y: y + size.height - footerReserve - ZONE_GEOMETRY.borderWidth - ruleClearance,
1001
+ width: size.width, height: footerReserve + ZONE_GEOMETRY.borderWidth + ruleClearance,
1002
+ });
1003
+ const contentX = x + contentInset;
1004
+ const contentY = y + ZONE_GEOMETRY.headerInset + header.height + contentInset;
848
1005
  if (kind === "legend-expanded") {
849
1006
  legendInner.set(id, inner);
850
1007
  orderedChildrenOf(id).forEach((key, index) => {
@@ -878,7 +1035,7 @@ export function layoutMeasured(document, options, sourceView) {
878
1035
  }, zone);
879
1036
  return;
880
1037
  }
881
- if (layout.overflow) {
1038
+ if (layout.overflow && (role === "edge-label" || presentation.entities[occurrence] === undefined)) {
882
1039
  const allocatedLines = DEFAULT_ALLOCATED_LINES[role];
883
1040
  warnOverflow({
884
1041
  occurrence,
@@ -910,13 +1067,14 @@ export function layoutMeasured(document, options, sourceView) {
910
1067
  }
911
1068
  const expanded = kind === "container-expanded" || kind === "legend-expanded";
912
1069
  const inner = expanded ? innerWidthOf(outerWidths.get(id) ?? FIXED_CARD_WIDTH) : innerWidthOf(FIXED_CARD_WIDTH);
1070
+ const rendered = sceneBoxAt(occurrence, rects.get(id).width, !expanded && kind !== "leaf");
913
1071
  for (const role of ["body", "detail", "footer"]) {
914
1072
  if (text[role] === undefined)
915
1073
  continue;
916
1074
  recordSlot(occurrence, role, measure({
917
1075
  text: text[role],
918
1076
  role,
919
- availableWidth: inner,
1077
+ availableWidth: role === "footer" ? rendered.footerWidth : rendered.bodyWidth,
920
1078
  allocatedLines: DEFAULT_ALLOCATED_LINES[role],
921
1079
  folded: !expanded && kind !== "leaf",
922
1080
  }), expanded);
@@ -931,10 +1089,20 @@ export function layoutMeasured(document, options, sourceView) {
931
1089
  // collapsed boxes, legend keys and the title bands, plus every expanded
932
1090
  // zone the edge has no end in. The interior of the zones an edge starts
933
1091
  // or ends in is free (BF-6): a label may sit inside its own zone.
934
- const fixedShapes = [
1092
+ const routeShapes = [
935
1093
  ...[...rects].filter(([id]) => !isStretchedBox(id)).map(([, rect]) => rect),
936
1094
  ...titleBands.values(),
937
1095
  ];
1096
+ // Footer bands constrain text placement. Routes may cross a zone's
1097
+ // footer while leaving it; a label on that route still has to clear it.
1098
+ // Header measurement ends at the rule's top. Reserve its non-scaling
1099
+ // paint plus one CSS px at the display floor for label placement.
1100
+ // Routes may cross a rule while leaving their own zone.
1101
+ const ruleClearance = (ZONE_GEOMETRY.ruleHeight / 2 + 1) / DEFAULT_MIN_READABLE_SCALE;
1102
+ const fixedShapes = [...routeShapes, ...[...titleBands.values()].map(band => ({
1103
+ x: band.x, y: band.y + band.height, width: band.width,
1104
+ height: ZONE_GEOMETRY.ruleHeight / 2 + ruleClearance,
1105
+ })), ...footerBands.values()];
938
1106
  const zoneShapes = [...rects].filter(([id]) => isStretchedBox(id));
939
1107
  const shapesByEdge = new Map();
940
1108
  for (const edge of drawnEdges) {
@@ -944,11 +1112,11 @@ export function layoutMeasured(document, options, sourceView) {
944
1112
  own.add(current);
945
1113
  }
946
1114
  shapesByEdge.set(edge.occurrence, [
947
- ...fixedShapes,
1115
+ ...routeShapes,
948
1116
  ...zoneShapes.filter(([id]) => !own.has(id)).map(([, rect]) => rect),
949
1117
  ]);
950
1118
  }
951
- const shapesOf = (id) => shapesByEdge.get(id) ?? fixedShapes;
1119
+ const shapesOf = (id) => shapesByEdge.get(id) ?? routeShapes;
952
1120
  /** BF-3 `inner(C)`: the routable interior of an expanded container (BLK-3). */
953
1121
  const innerOf = (container) => {
954
1122
  const rect = rects.get(container);
@@ -988,7 +1156,7 @@ export function layoutMeasured(document, options, sourceView) {
988
1156
  const usedUTracks = new Map();
989
1157
  for (const edge of [...drawnEdges].sort((left, right) => byString(left.occurrence, right.occurrence))) {
990
1158
  const id = edge.occurrence;
991
- const size = labelSizes.get(id);
1159
+ const size = routeSizes.get(id);
992
1160
  const source = edge.source.entity;
993
1161
  const target = edge.target.entity;
994
1162
  if (size === undefined || source === target)
@@ -1117,6 +1285,7 @@ export function layoutMeasured(document, options, sourceView) {
1117
1285
  // declared spacing: a label sits in a lane, not at its dock, so a side
1118
1286
  // does not spread its slots by the label width.
1119
1287
  const docked = dockEdges({
1288
+ ...(hasFlows ? { flowBadgeSize: flowTokens.flowBadgeSize } : {}),
1120
1289
  graph: filteredGraph,
1121
1290
  rects,
1122
1291
  direction: "top-to-bottom",
@@ -1170,6 +1339,7 @@ export function layoutMeasured(document, options, sourceView) {
1170
1339
  ]);
1171
1340
  const within = withinOf.get(occurrenceId);
1172
1341
  return {
1342
+ ...(flowRunRanks.has(edge.occurrence) ? { flowRank: flowRunRanks.get(edge.occurrence), flowRun: [edge.source.entity, edge.target.entity].sort().join("|") + "|" + String(sideOverrides.get(occurrenceId)?.turn === true) } : {}),
1173
1343
  id: occurrenceId,
1174
1344
  pairKey: [edge.source.entity, edge.target.entity].sort().join("|"),
1175
1345
  start: pair.source.point,
@@ -1192,9 +1362,10 @@ export function layoutMeasured(document, options, sourceView) {
1192
1362
  const outerLanes = [];
1193
1363
  const outerLanesX = [];
1194
1364
  let labelLimit;
1195
- if (labelSizes.size > 0 && rects.size > 0) {
1196
- const pitch = Math.max(...[...labelSizes.values()].map((size) => size.height)) + 2 * metrics.labelMargin;
1197
- const pitchX = Math.max(...[...labelSizes.values()].map((size) => size.width)) + 2 * metrics.labelMargin;
1365
+ const markSizes = [...routeSizes.values()];
1366
+ if (markSizes.length > 0 && rects.size > 0) {
1367
+ const pitch = Math.max(...markSizes.map((size) => size.height)) + 2 * metrics.labelMargin;
1368
+ const pitchX = Math.max(...markSizes.map((size) => size.width)) + 2 * metrics.labelMargin;
1198
1369
  const left = Math.min(...[...rects.values()].map((rect) => rect.x));
1199
1370
  const right = Math.max(...[...rects.values()].map((rect) => rect.x + rect.width));
1200
1371
  const width = right - left;
@@ -1208,7 +1379,7 @@ export function layoutMeasured(document, options, sourceView) {
1208
1379
  width: width + 2 * (spareX + metrics.clearance + pitchX),
1209
1380
  height: height + 2 * (spareY + allowance),
1210
1381
  };
1211
- const lanes = Math.min(labelSizes.size, OUTER_LANES, 1 + Math.floor(spareY / pitch));
1382
+ const lanes = Math.min(markSizes.length, OUTER_LANES, 1 + Math.floor(spareY / pitch));
1212
1383
  for (let lane = 1; lane <= lanes; lane += 1) {
1213
1384
  outerLanes.push(drawingTop - metrics.clearance - lane * pitch, drawingBottom + metrics.clearance + lane * pitch);
1214
1385
  }
@@ -1216,7 +1387,7 @@ export function layoutMeasured(document, options, sourceView) {
1216
1387
  // the A* grid had no X lane outside the drawing, so a route that must go
1217
1388
  // round via the side fell back to an obstructed elbow. One X lane per
1218
1389
  // side mirrors the Y lanes above.
1219
- const lanesX = Math.min(labelSizes.size, OUTER_LANES, 1 + Math.floor(spareX / pitchX));
1390
+ const lanesX = Math.min(markSizes.length, OUTER_LANES, 1 + Math.floor(spareX / pitchX));
1220
1391
  for (let lane = 1; lane <= lanesX; lane += 1) {
1221
1392
  outerLanesX.push(left - metrics.clearance - lane * pitchX, right + metrics.clearance + lane * pitchX);
1222
1393
  }
@@ -1239,6 +1410,50 @@ export function layoutMeasured(document, options, sourceView) {
1239
1410
  // A retry that finds a clean A* route replaces the obstructed elbow.
1240
1411
  const retryRoutes = new Map(routed.routes);
1241
1412
  const retryObstructed = new Set(routed.obstructed);
1413
+ // Parallel unlabelled bridges use a centred comb. Docks and the middle
1414
+ // legs share the same pitch. Preserve every constraint of the router.
1415
+ const parallel = new Map();
1416
+ for (const request of requests) {
1417
+ if (edgeLayouts.has(request.id))
1418
+ continue;
1419
+ const pair = parallel.get(request.pairKey) ?? [];
1420
+ pair.push(request);
1421
+ parallel.set(request.pairKey, pair);
1422
+ }
1423
+ for (const pair of parallel.values()) {
1424
+ if (pair.length < 2)
1425
+ continue;
1426
+ pair.sort((a, b) => byString(a.id, b.id));
1427
+ const first = pair[0];
1428
+ const horizontal = Math.abs(first.start.x - first.end.x) >= Math.abs(first.start.y - first.end.y);
1429
+ const center = horizontal ? (first.start.x + first.end.x) / 2 : (first.start.y + first.end.y) / 2;
1430
+ pair.forEach((request, index) => {
1431
+ const lane = center + (index - (pair.length - 1) / 2) * ((horizontal ? metrics.trackSpacing : metrics.trackSpacingBlock) ?? (horizontal ? 14 : 7));
1432
+ const points = horizontal
1433
+ ? [request.start, { x: lane, y: request.start.y }, { x: lane, y: request.end.y }, request.end]
1434
+ : [request.start, { x: request.start.x, y: lane }, { x: request.end.x, y: lane }, request.end];
1435
+ const firstLeg = points.find(point => point.x !== request.start.x || point.y !== request.start.y);
1436
+ const lastLeg = [...points].reverse().find(point => point.x !== request.end.x || point.y !== request.end.y);
1437
+ if (firstLeg === undefined || lastLeg === undefined
1438
+ || (firstLeg.x - request.start.x) * request.startExit.x + (firstLeg.y - request.start.y) * request.startExit.y <= 0
1439
+ || (lastLeg.x - request.end.x) * request.endExit.x + (lastLeg.y - request.end.y) * request.endExit.y <= 0)
1440
+ return;
1441
+ const within = request.within;
1442
+ if (within !== undefined && points.some(point => point.x < within.x || point.y < within.y
1443
+ || point.x > within.x + within.width || point.y > within.y + within.height))
1444
+ return;
1445
+ if (requests.some(other => other.id !== request.id && other.pairKey === request.pairKey
1446
+ && routesConflict(points, retryRoutes.get(other.id))))
1447
+ return;
1448
+ if (points.slice(1).some((point, i) => shapesOf(request.id).some(shape => rectsIntersect(shape, {
1449
+ x: Math.min(point.x, points[i].x), y: Math.min(point.y, points[i].y),
1450
+ width: Math.abs(point.x - points[i].x), height: Math.abs(point.y - points[i].y),
1451
+ }))))
1452
+ return;
1453
+ retryRoutes.set(request.id, points);
1454
+ retryObstructed.delete(request.id);
1455
+ });
1456
+ }
1242
1457
  if (retryObstructed.size > 0) {
1243
1458
  const failed = new Set(retryObstructed);
1244
1459
  const retryRequests = requests.filter((request) => failed.has(request.id));
@@ -1287,12 +1502,46 @@ export function layoutMeasured(document, options, sourceView) {
1287
1502
  ...(labelLimit === undefined ? {} : { limit: labelLimit }),
1288
1503
  };
1289
1504
  });
1505
+ const frameWalls = zoneShapes.flatMap(([, rect]) => [
1506
+ { x: rect.x, y: rect.y, width: rect.width, height: metrics.labelMargin },
1507
+ { x: rect.x, y: rect.y + rect.height - metrics.labelMargin, width: rect.width, height: metrics.labelMargin },
1508
+ { x: rect.x, y: rect.y, width: metrics.labelMargin, height: rect.height },
1509
+ { x: rect.x + rect.width - metrics.labelMargin, y: rect.y, width: metrics.labelMargin, height: rect.height },
1510
+ ]);
1511
+ const marks = placeFlowMarks({ plan: flowPlan, routes: retryRoutes, shapes: [...fixedShapes, ...frameWalls], within: withinOf, ...(labelLimit === undefined ? {} : { limit: labelLimit }), measure, options, margin: metrics.labelMargin });
1512
+ warnings.push(...marks.warnings);
1290
1513
  const labelBoxes = new Map();
1291
- const taken = [];
1514
+ const taken = [...marks.taken];
1292
1515
  const unplaced = [];
1293
1516
  for (const entry of entries) {
1294
1517
  const edge = drawnEdges.find((candidate) => candidate.occurrence === entry.id);
1295
1518
  let choice = placePackedLabel(entry, fixedShapes, taken, metrics.labelMargin);
1519
+ if (flowPlan.ranks.has(entry.id)) {
1520
+ if (choice === undefined)
1521
+ unplaced.push(entry);
1522
+ else {
1523
+ labelBoxes.set(entry.id, choice.box);
1524
+ taken.push(choice.box);
1525
+ }
1526
+ continue;
1527
+ }
1528
+ if (plan?.external.has(entry.id) && sharedContainerOf(edge.source.entity, edge.target.entity) === undefined) {
1529
+ const request = requests.find(candidate => candidate.id === entry.id);
1530
+ const { limit: _limit, ...unbounded } = entry;
1531
+ const route = labelDetour({ request, shapes: shapesOf(entry.id),
1532
+ earlier: requests.filter(other => other.id !== request.id && other.pairKey === request.pairKey && !retryObstructed.has(other.id)).map(other => retryRoutes.get(other.id)),
1533
+ xs: [...new Set([request.start.x, request.end.x, ...outerLanesX])].sort((a, b) => a - b),
1534
+ ys: [...new Set([request.start.y, request.end.y, ...outerLanes])].sort((a, b) => a - b),
1535
+ accepts: points => {
1536
+ const label = placePackedLabel({ ...unbounded, route: points }, fixedShapes, taken, metrics.labelMargin);
1537
+ return label !== undefined && (label.box.y >= drawingBottom || label.box.y + label.box.height <= drawingTop);
1538
+ }, });
1539
+ if (route !== undefined) {
1540
+ retryRoutes.set(entry.id, route);
1541
+ retryObstructed.delete(entry.id);
1542
+ choice = placePackedLabel({ ...unbounded, route }, fixedShapes, taken, metrics.labelMargin);
1543
+ }
1544
+ }
1296
1545
  const probeMargin = probeMarginOf(entry.size.height);
1297
1546
  // Prefer the existing bridge in a capped, label-bearing gutter to an
1298
1547
  // exterior detour. Pass 2 will supply its measured transverse margin.
@@ -1305,7 +1554,7 @@ export function layoutMeasured(document, options, sourceView) {
1305
1554
  if (choice === undefined || retryObstructed.has(entry.id)) {
1306
1555
  choice = undefined;
1307
1556
  const request = requests.find((candidate) => candidate.id === entry.id);
1308
- const samePair = requests.filter((candidate) => candidate.id !== entry.id && candidate.pairKey === request.pairKey)
1557
+ const samePair = requests.filter((candidate) => candidate.id !== entry.id && candidate.pairKey === request.pairKey && !retryObstructed.has(candidate.id))
1309
1558
  .map((candidate) => retryRoutes.get(candidate.id));
1310
1559
  const shapes = shapesOf(entry.id);
1311
1560
  const margin = probeMargin;
@@ -1374,6 +1623,35 @@ export function layoutMeasured(document, options, sourceView) {
1374
1623
  }
1375
1624
  }
1376
1625
  }
1626
+ if (choice === undefined) {
1627
+ // Dense inter-zone channels may exceed the aspect-based allowance.
1628
+ // Comb their labels outside the drawing rather than dropping them or
1629
+ // painting through a card. The full union below includes this column.
1630
+ const request = requests.find(candidate => candidate.id === entry.id);
1631
+ if (entry.within === undefined) {
1632
+ const right = Math.max(...[...rects.values()].map(rect => rect.x + rect.width));
1633
+ const pitch = Math.max(...[...labelSizes.values()].map(size => size.height)) + 2 * metrics.labelMargin;
1634
+ const column = right + Math.max(...[...labelSizes.values()].map(size => size.width)) / 2 + metrics.clearance;
1635
+ const row = drawingBottom + metrics.clearance + (entries.indexOf(entry) + 1) * pitch;
1636
+ const upperRow = drawingTop - metrics.clearance - (entries.indexOf(entry) + 1) * pitch;
1637
+ const { limit: _limit, ...unbounded } = entry;
1638
+ const samePair = requests.filter(candidate => candidate.id !== entry.id && candidate.pairKey === request.pairKey && !retryObstructed.has(candidate.id))
1639
+ .map(candidate => retryRoutes.get(candidate.id));
1640
+ const comb = (earlier) => labelDetour({ request, shapes: shapesOf(entry.id), earlier,
1641
+ xs: [...new Set([request.start.x, request.end.x, column, ...outerLanesX])].sort((a, b) => a - b),
1642
+ ys: [...new Set([request.start.y, request.end.y, upperRow, row, ...outerLanes])].sort((a, b) => a - b),
1643
+ accepts: points => placePackedLabel({ ...unbounded, route: points }, fixedShapes, taken, metrics.labelMargin) !== undefined,
1644
+ });
1645
+ // A saturated channel still reserves every parallel route. If no
1646
+ // exterior lane is safe, retain the explicit placement diagnostic.
1647
+ const route = comb(samePair);
1648
+ if (route !== undefined) {
1649
+ retryRoutes.set(entry.id, route);
1650
+ retryObstructed.delete(entry.id);
1651
+ choice = placePackedLabel({ ...unbounded, route }, fixedShapes, taken, metrics.labelMargin);
1652
+ }
1653
+ }
1654
+ }
1377
1655
  if (choice === undefined) {
1378
1656
  unplaced.push({ ...entry, route: retryRoutes.get(entry.id) });
1379
1657
  continue;
@@ -1393,6 +1671,9 @@ export function layoutMeasured(document, options, sourceView) {
1393
1671
  if (boxes === undefined || boxes.length < 2)
1394
1672
  continue;
1395
1673
  const rows = packed.rows;
1674
+ const zone = runHasZone(packed.run);
1675
+ const axisAuthored = (horizontal) => (horizontal ? (zone ? hints?.zoneGapX : hints?.cardGapX) : (zone ? hints?.zoneGapY : hints?.cardGapY)) !== undefined;
1676
+ const gapAfter = (slot) => { const item = packed.run.items[slot]; return "run" in item ? item.gapAfter : undefined; };
1396
1677
  const alongOf = (rect) => (rows ? [rect.x, rect.x + rect.width] : [rect.y, rect.y + rect.height]);
1397
1678
  const acrossOf = (rect) => (rows ? [rect.y, rect.y + rect.height] : [rect.x, rect.x + rect.width]);
1398
1679
  const stripOf = (along, across) => rows
@@ -1414,6 +1695,8 @@ export function layoutMeasured(document, options, sourceView) {
1414
1695
  horizontal: rows,
1415
1696
  strips: [stripOf(extent, [end, nextStart])],
1416
1697
  gap: nextStart - end,
1698
+ base: gapAfter(shelf.at(-1)) ?? packed.acrossBase,
1699
+ authoredBase: gapAfter(shelf.at(-1)) !== undefined || axisAuthored(!rows),
1417
1700
  max: rows ? rowGaps.maxY : rowGaps.maxX,
1418
1701
  });
1419
1702
  }
@@ -1422,7 +1705,7 @@ export function layoutMeasured(document, options, sourceView) {
1422
1705
  if (following === undefined)
1423
1706
  return;
1424
1707
  const strip = stripOf([alongOf(boxes[slot])[1], alongOf(boxes[following])[0]], [start, end]);
1425
- (alongStrips.get(index) ?? alongStrips.set(index, []).get(index)).push({ shelf: shelfIndex, strip });
1708
+ (alongStrips.get(index) ?? alongStrips.set(index, []).get(index)).push({ shelf: shelfIndex, slot, strip });
1426
1709
  });
1427
1710
  });
1428
1711
  for (const [index, strips] of [...alongStrips].sort(([left], [right]) => left - right)) {
@@ -1440,16 +1723,36 @@ export function layoutMeasured(document, options, sourceView) {
1440
1723
  horizontal: !rows,
1441
1724
  strips: strips.map(({ strip }) => strip),
1442
1725
  gap: Math.max(...strips.map(({ strip }) => thickness(strip))),
1726
+ base: Math.max(...strips.map(({ slot }) => gapAfter(slot) ?? packed.alongBase)),
1727
+ authoredBase: strips.some(({ slot }) => gapAfter(slot) !== undefined) || axisAuthored(rows),
1443
1728
  max,
1444
1729
  });
1445
1730
  }
1446
1731
  else {
1447
- for (const { shelf, strip } of strips) {
1448
- gutters.push({ id: `${key}|along|${String(index)}|${String(shelf)}`, horizontal: !rows, strips: [strip], gap: thickness(strip), max });
1732
+ for (const { shelf, slot, strip } of strips) {
1733
+ 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 });
1449
1734
  }
1450
1735
  }
1451
1736
  }
1452
1737
  }
1738
+ // Count each routed occurrence once in the physical channel, including lifted bundle traffic.
1739
+ const channels = gutters.map(gutter => {
1740
+ const edges = [...retryRoutes].filter(([, route]) => gutter.strips.some(strip => route.some((point, i) => {
1741
+ const next = route[i + 1];
1742
+ if (next === undefined)
1743
+ return false;
1744
+ return rectsIntersect(strip, { x: Math.min(point.x, next.x), y: Math.min(point.y, next.y),
1745
+ width: Math.abs(point.x - next.x), height: Math.abs(point.y - next.y) });
1746
+ }))).map(([id]) => String(id)).sort(byString);
1747
+ const n = edges.reduce((sum, id) => sum + (edgeBundles[id]?.members.length ?? 1), 0);
1748
+ const intersecting = [...labelBoxes.values()].filter(box => gutter.strips.some(strip => rectsIntersect(strip, box)));
1749
+ const labelled = intersecting.length > 0;
1750
+ const placedFloor = Math.max(0, ...intersecting.map(box => (gutter.horizontal ? box.height : box.width) + 2 * metrics.labelMargin).filter(needed => needed <= gutter.max));
1751
+ const axis = gutter.horizontal ? 'vertical' : 'horizontal';
1752
+ const parameters = channelMetrics(metrics, axis === 'horizontal');
1753
+ return { id: gutter.id, axis, edges, strips: gutter.strips, n, labelled, gap: gutter.gap,
1754
+ expected: Math.min(gutter.max, Math.max(placedFloor, channelGap(n, labelled, { ...parameters, gapMin: gutter.authoredBase ? gutter.base : Math.max(parameters.gapMin, gutter.base) }))) };
1755
+ });
1453
1756
  // A widened gutter in which no placed label sits is an empty lane: a bare
1454
1757
  // route needs no more than the base gap (two clearances).
1455
1758
  const unused = [];
@@ -1457,12 +1760,6 @@ export function layoutMeasured(document, options, sourceView) {
1457
1760
  for (const id of [...(plan?.widen.keys() ?? [])].sort(byString))
1458
1761
  if (!gutterIds.has(id))
1459
1762
  unused.push(id);
1460
- for (const gutter of gutters) {
1461
- if (plan?.widen.get(gutter.id) === undefined)
1462
- continue;
1463
- if (![...labelBoxes.values()].some((box) => gutter.strips.some((strip) => rectsIntersect(strip, box))))
1464
- unused.push(gutter.id);
1465
- }
1466
1763
  // A label with no room is probed with the free space of a base gap above
1467
1764
  // and under it: where it then fits, the lanes it sits in are asked to
1468
1765
  // widen to its thickness plus its two margins — never past the axis cap.
@@ -1492,9 +1789,16 @@ export function layoutMeasured(document, options, sourceView) {
1492
1789
  requested.set(gutter.id, Math.max(requested.get(gutter.id) ?? 0, needed));
1493
1790
  }
1494
1791
  }
1792
+ for (const channel of channels) {
1793
+ const target = Math.max(requested.get(channel.id) ?? 0, channel.expected);
1794
+ if (Math.abs(target - channel.gap) > 0.5)
1795
+ requested.set(channel.id, target);
1796
+ else
1797
+ requested.delete(channel.id);
1798
+ }
1495
1799
  // Emit the view plus measurements.
1496
1800
  const placedView = buildMeasuredView(document, filteredGraph, rects, finalDocks, retryRoutes, options, foldMetadata, drawnEdges);
1497
- const bounds = unionOf(rects, retryRoutes, labelBoxes);
1801
+ 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]))]));
1498
1802
  const width = bounds.width;
1499
1803
  const zoom = bounds.empty ? 1 : Math.min(1, Math.max(MIN_ZOOM, options.targetWidth / width));
1500
1804
  const camera = bounds.empty ? { x: 0, y: 0 } : { x: bounds.xmin, y: bounds.ymin };
@@ -1512,6 +1816,7 @@ export function layoutMeasured(document, options, sourceView) {
1512
1816
  };
1513
1817
  const result = {
1514
1818
  status: "laid-out",
1819
+ ...(hasFlows ? { badgeBoxes: marks.badges, arrowBoxes: marks.arrows, flowBundles: flowPlan.bundles, flowTargets: marks.targets, flowRepairPasses: 0 } : {}),
1515
1820
  view,
1516
1821
  fit: {
1517
1822
  direction: "top-to-bottom",
@@ -1524,42 +1829,63 @@ export function layoutMeasured(document, options, sourceView) {
1524
1829
  warnings,
1525
1830
  measurements,
1526
1831
  orientations: Object.fromEntries([...orientationRecord].sort(([left], [right]) => byString(left, right))),
1832
+ channels,
1527
1833
  labelBoxes: Object.fromEntries([...labelBoxes]
1528
1834
  .sort(([left], [right]) => byString(left, right))
1529
1835
  .map(([id, box]) => [id, { x: clean(box.x), y: clean(box.y), width: box.width, height: box.height }])),
1836
+ ...(Object.keys(edgeBundles).length === 0 ? {} : { edgeBundles }),
1530
1837
  };
1531
1838
  return { result, chosen, requested, unused, unplaced: unplaced.length };
1532
1839
  };
1533
- // BF-6 two-pass placement. Pass 1 packs every level at its base gaps,
1534
- // routes, and places the labels; its shelves and orientations are frozen.
1535
- // Later passes only widen the gutters in which a label of pass 1 had no
1536
- // room, then drop every widened gutter that ends up holding no label: the
1537
- // asked set grows at most `WIDEN_ROUNDS` times and then only shrinks, so
1538
- // the sequence ends. A drawing never keeps a lane no label sits in.
1840
+ // Freeze the figure arrangement, then solve channel demand from actual routes and labels.
1539
1841
  const first = runPass(undefined);
1540
- if (first.requested.size === 0)
1541
- return first.result;
1542
1842
  const frozen = first.chosen;
1543
- const widen = new Map(first.requested);
1544
- let outcome = runPass({ frozen, widen });
1545
- for (let round = 1; round < WIDEN_ROUNDS; round += 1) {
1546
- const more = [...outcome.requested].filter(([id, gap]) => (widen.get(id) ?? 0) < gap);
1547
- if (more.length === 0)
1548
- break;
1549
- for (const [id, gap] of more)
1550
- widen.set(id, gap);
1551
- outcome = runPass({ frozen, widen });
1552
- }
1553
- while (outcome.unused.length > 0) {
1843
+ const widen = new Map();
1844
+ const external = new Set();
1845
+ const seen = new Map();
1846
+ let outcome = first;
1847
+ let previous;
1848
+ for (let round = 0; round < 24 && (outcome.requested.size > 0 || outcome.unused.length > 0); round += 1) {
1849
+ const signature = JSON.stringify(outcome.result.status === "laid-out" ? outcome.result.channels?.map(channel => [channel.id, channel.gap, channel.n, channel.labelled]) : []);
1850
+ const repeated = seen.get(signature);
1851
+ if (repeated !== undefined && outcome.result.status === "laid-out") {
1852
+ // A label switching between two available U channels can otherwise
1853
+ // oscillate with their demands. Give that root-level relation an
1854
+ // exterior comb slot; cards and headers remain routing obstacles.
1855
+ const current = outcome.result.channels ?? [];
1856
+ for (const edge of drawnEdges) {
1857
+ if (sharedContainerOf(edge.source.entity, edge.target.entity) !== undefined)
1858
+ continue;
1859
+ const id = edge.occurrence;
1860
+ if (!edgeLayouts.has(id))
1861
+ continue;
1862
+ const memberships = previous?.result.status === "laid-out"
1863
+ ? (previous.result.channels ?? []).filter(channel => channel.edges.includes(id)).map(channel => channel.id) : [];
1864
+ const now = current.filter(channel => channel.edges.includes(id)).map(channel => channel.id);
1865
+ const oldBox = previous?.result.status === "laid-out" ? previous.result.labelBoxes?.[id] : undefined;
1866
+ const newBox = outcome.result.labelBoxes?.[id];
1867
+ const oldLabels = previous?.result.status === "laid-out" && oldBox !== undefined
1868
+ ? (previous.result.channels ?? []).filter(channel => channel.strips.some(strip => rectsIntersect(strip, oldBox))).map(channel => channel.id) : [];
1869
+ const newLabels = newBox === undefined ? []
1870
+ : current.filter(channel => channel.strips.some(strip => rectsIntersect(strip, newBox))).map(channel => channel.id);
1871
+ if (JSON.stringify(memberships) !== JSON.stringify(now) || JSON.stringify(oldLabels) !== JSON.stringify(newLabels))
1872
+ external.add(id);
1873
+ }
1874
+ seen.clear();
1875
+ }
1876
+ seen.set(signature, outcome);
1554
1877
  for (const id of outcome.unused)
1555
1878
  widen.delete(id);
1556
- if (widen.size === 0)
1557
- return first.result;
1558
- outcome = runPass({ frozen, widen });
1879
+ for (const [id, gap] of outcome.requested)
1880
+ widen.set(id, gap);
1881
+ previous = outcome;
1882
+ outcome = runPass({ frozen, widen, external });
1559
1883
  }
1560
- // Widening never costs a label: the wider drawing is kept only when it
1561
- // places at least as many labels as the base one.
1562
- return outcome.unplaced <= first.unplaced ? outcome.result : first.result;
1884
+ if (outcome.result.status === "laid-out" && outcome.requested.size > 0)
1885
+ return { ...outcome.result,
1886
+ warnings: [...outcome.result.warnings, { code: "channel-unresolved", refs: [...outcome.requested.keys()],
1887
+ message: "Channel demands did not settle within the bounded routing pass" }] };
1888
+ return outcome.result;
1563
1889
  }
1564
1890
  function unionOf(rects, routes, labels) {
1565
1891
  let empty = true;
@@ -1629,7 +1955,8 @@ function buildMeasuredView(document, graph, rects, docks, routes, options, foldM
1629
1955
  relationOccurrences[occurrence.id] = { ...occurrence, waypoints };
1630
1956
  }
1631
1957
  else {
1632
- relationOccurrences[occurrence.id] = { ...occurrence };
1958
+ const { waypoints: _oldRoute, ...retained } = occurrence;
1959
+ relationOccurrences[occurrence.id] = document.relations[occurrence.relation]?.type === "flow-step" ? retained : { ...occurrence };
1633
1960
  }
1634
1961
  }
1635
1962
  // Ports keep their projected identities: every drawn end landing on a
@@ -1702,6 +2029,8 @@ function readMeasuredGraph(document, registry) {
1702
2029
  const kinds = new Map();
1703
2030
  for (const key of Object.keys(document.entities).sort(byString)) {
1704
2031
  const entity = document.entities[key];
2032
+ if (entity.type === "flow-scenario")
2033
+ continue;
1705
2034
  const profile = registry.get(entity.profile);
1706
2035
  if (profile === undefined) {
1707
2036
  refusals.push({
@@ -1749,9 +2078,11 @@ function readMeasuredGraph(document, registry) {
1749
2078
  const edges = [];
1750
2079
  for (const key of Object.keys(document.relations).sort(byString)) {
1751
2080
  const relation = document.relations[key];
2081
+ const owner = registry.get(relation.profile);
2082
+ const baseType = owner === undefined ? relation.type : relationBaseType(document, owner, relation);
1752
2083
  if ((relation.profile !== "generic@1" && relation.profile !== "generic@2") ||
1753
- (relation.type !== "contains" && relation.type !== "link")) {
1754
- if (relation.type === "contains" || relation.type === "link") {
2084
+ (baseType !== "contains" && baseType !== "link")) {
2085
+ if (baseType === "contains" || baseType === "link") {
1755
2086
  refusals.push({
1756
2087
  code: "entity-profile-unsupported",
1757
2088
  path: `relations.${key}.profile`,
@@ -1770,7 +2101,7 @@ function readMeasuredGraph(document, registry) {
1770
2101
  continue;
1771
2102
  }
1772
2103
  const role = (name) => relation.endpoints.find((endpoint) => endpoint.role === name)?.target;
1773
- if (relation.type === "contains") {
2104
+ if (baseType === "contains") {
1774
2105
  const parent = role("parent");
1775
2106
  const child = role("child");
1776
2107
  if (parent !== undefined && child !== undefined)