@sentropic/diagram-canvas 0.1.0 → 0.2.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 (63) hide show
  1. package/README.md +9 -0
  2. package/contracts/diagram-anatomy.v1.json +2073 -0
  3. package/dist/camera.d.ts +9 -6
  4. package/dist/camera.js +14 -9
  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 +69 -2
  44. package/dist/presentation/diagramSceneModel.js +146 -25
  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/visibility.d.ts +1 -1
  62. package/dist/visibility.js +5 -4
  63. package/package.json +30 -4
package/dist/camera.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * DC-2a camera contract, the pure half (SPEC_EVOL_DC2A §5): maximum display
3
- * scale, fit on both axes against a 16:9 fit box, readability floor, clamp and
3
+ * scale, fit on both axes against a 16:9 fit box, clamp and
4
4
  * readout. No DOM and no camera UI live here: a scene host passes its measured
5
5
  * figure width and window height in, and applies the returned zoom as a
6
6
  * transform. Zoom never changes geometry (Z-6).
@@ -11,8 +11,8 @@
11
11
  /** Display scale at readout 100 % (Z-5): a 460 × 200 card renders at ≈ 285 × 124 CSS px. */
12
12
  export declare const DEFAULT_MAX_DISPLAY_SCALE = 0.62;
13
13
  /**
14
- * Readability floor of the fit: below it a fit stops shrinking and the host
15
- * pans. 0.45 is the smallest two-decimal scale holding both the 18 px edge
14
+ * Hard display floor: fit scales down to it, then the viewport scrolls.
15
+ * 0.45 is the smallest two-decimal scale holding both the 18 px edge
16
16
  * label (BF-2, the binding constraint: 18 × 0.45 = 8.1 CSS px ≥ 8 CSS px
17
17
  * floor; 0.42 gives 7.56) and the 22 px kicker (22 × 0.45 = 9.9 CSS px).
18
18
  */
@@ -21,7 +21,7 @@ export declare const DEFAULT_MIN_READABLE_SCALE = 0.45;
21
21
  export declare const DEFAULT_EDGE_LABEL_FONT_SIZE = 18;
22
22
  /** World line box of an edge label, px (token `diagramScene.edgeLabelLineHeight`). */
23
23
  export declare const DEFAULT_EDGE_LABEL_LINE_HEIGHT = 22;
24
- /** §5.3: an edge label never renders below this height at a fit, CSS px. */
24
+ /** Minimum rendered edge-label size, CSS px. */
25
25
  export declare const MIN_EDGE_LABEL_CSS_PX = 8;
26
26
  /** Share of the window height a figure may take (§5.1 fit box). */
27
27
  export declare const FIT_WINDOW_HEIGHT_SHARE = 0.85;
@@ -38,6 +38,7 @@ export interface CameraFitInput {
38
38
  /** `window.innerHeight`, CSS px. */
39
39
  readonly windowHeight: number;
40
40
  readonly maxDisplayScale?: number;
41
+ /** Optional higher readability floor; never lowers the absolute 0.45 floor. */
41
42
  readonly minReadableScale?: number;
42
43
  }
43
44
  export interface CameraFit {
@@ -46,14 +47,16 @@ export interface CameraFit {
46
47
  readonly fitHeight: number;
47
48
  /** Zoom framing the whole drawing on both axes, never above the maximum display scale. */
48
49
  readonly zoomFit: number;
49
- /** Zoom a fit or reset applies: `zoomFit`, held at the readability floor when the drawing is larger. */
50
+ /** Zoom a fit or reset applies: `zoomFit` clamped to the readability floor. */
50
51
  readonly zoom: number;
51
- /** Interactive range: zoom-out reaches `zoomFit`, zoom-in stops at the maximum display scale (Z-1, Z-2). */
52
+ /** Interactive range: zoom-out stops at the readable fit, zoom-in at the display cap. */
52
53
  readonly minZoom: number;
53
54
  readonly maxZoom: number;
54
55
  /** True when the applied zoom shows only part of the drawing: the host pans. */
55
56
  readonly pans: boolean;
56
57
  }
58
+ /** Screen-space inset for non-scaling strokes and CSS layout rounding. */
59
+ export declare const FIT_PAINT_INSET = 1;
57
60
  /** §5.1: `fitW = viewW`, `fitH = min(viewW × 9/16, 0.85 × windowH)`. */
58
61
  export declare function fitBox(viewWidth: number, windowHeight: number): {
59
62
  readonly width: number;
package/dist/camera.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * DC-2a camera contract, the pure half (SPEC_EVOL_DC2A §5): maximum display
3
- * scale, fit on both axes against a 16:9 fit box, readability floor, clamp and
3
+ * scale, fit on both axes against a 16:9 fit box, clamp and
4
4
  * readout. No DOM and no camera UI live here: a scene host passes its measured
5
5
  * figure width and window height in, and applies the returned zoom as a
6
6
  * transform. Zoom never changes geometry (Z-6).
@@ -11,8 +11,8 @@
11
11
  /** Display scale at readout 100 % (Z-5): a 460 × 200 card renders at ≈ 285 × 124 CSS px. */
12
12
  export const DEFAULT_MAX_DISPLAY_SCALE = 0.62;
13
13
  /**
14
- * Readability floor of the fit: below it a fit stops shrinking and the host
15
- * pans. 0.45 is the smallest two-decimal scale holding both the 18 px edge
14
+ * Hard display floor: fit scales down to it, then the viewport scrolls.
15
+ * 0.45 is the smallest two-decimal scale holding both the 18 px edge
16
16
  * label (BF-2, the binding constraint: 18 × 0.45 = 8.1 CSS px ≥ 8 CSS px
17
17
  * floor; 0.42 gives 7.56) and the 22 px kicker (22 × 0.45 = 9.9 CSS px).
18
18
  */
@@ -21,28 +21,33 @@ export const DEFAULT_MIN_READABLE_SCALE = 0.45;
21
21
  export const DEFAULT_EDGE_LABEL_FONT_SIZE = 18;
22
22
  /** World line box of an edge label, px (token `diagramScene.edgeLabelLineHeight`). */
23
23
  export const DEFAULT_EDGE_LABEL_LINE_HEIGHT = 22;
24
- /** §5.3: an edge label never renders below this height at a fit, CSS px. */
24
+ /** Minimum rendered edge-label size, CSS px. */
25
25
  export const MIN_EDGE_LABEL_CSS_PX = 8;
26
26
  /** Share of the window height a figure may take (§5.1 fit box). */
27
27
  export const FIT_WINDOW_HEIGHT_SHARE = 0.85;
28
28
  /** Fit box aspect (§5.1): 16:9. */
29
29
  export const FIT_ASPECT = 16 / 9;
30
+ /** Screen-space inset for non-scaling strokes and CSS layout rounding. */
31
+ export const FIT_PAINT_INSET = 1;
30
32
  /** §5.1: `fitW = viewW`, `fitH = min(viewW × 9/16, 0.85 × windowH)`. */
31
33
  export function fitBox(viewWidth, windowHeight) {
32
34
  return { width: viewWidth, height: Math.min(viewWidth / FIT_ASPECT, FIT_WINDOW_HEIGHT_SHARE * windowHeight) };
33
35
  }
34
36
  export function cameraFit(input) {
35
- const maxZoom = input.maxDisplayScale ?? DEFAULT_MAX_DISPLAY_SCALE;
36
- const floor = Math.min(input.minReadableScale ?? DEFAULT_MIN_READABLE_SCALE, maxZoom);
37
+ const maxZoom = Math.max(DEFAULT_MIN_READABLE_SCALE, input.maxDisplayScale ?? DEFAULT_MAX_DISPLAY_SCALE);
38
+ const readableFloor = Math.min(maxZoom, Math.max(DEFAULT_MIN_READABLE_SCALE, input.minReadableScale ?? DEFAULT_MIN_READABLE_SCALE));
37
39
  const box = fitBox(input.viewWidth, input.windowHeight);
38
40
  const bounds = input.bounds;
39
41
  if (bounds === undefined || !(bounds.width > 0) || !(bounds.height > 0)) {
40
42
  // Empty scene: readout 100 %.
41
43
  return { fitWidth: box.width, fitHeight: box.height, zoomFit: maxZoom, zoom: maxZoom, minZoom: maxZoom, maxZoom, pans: false };
42
44
  }
43
- const zoomFit = Math.min(box.width / bounds.width, box.height / bounds.height, maxZoom);
44
- const zoom = Math.max(zoomFit, floor);
45
- return { fitWidth: box.width, fitHeight: box.height, zoomFit, zoom, minZoom: zoomFit, maxZoom, pans: zoom > zoomFit };
45
+ const zoomFit = Math.min(Math.max(0, box.width - 2 * FIT_PAINT_INSET) / bounds.width, Math.max(0, box.height - 2 * FIT_PAINT_INSET) / bounds.height, maxZoom);
46
+ // All hosts and camera inputs share this range. A small frame or a large
47
+ // unfolded scene reaches the floor, then scrolls instead of shrinking text.
48
+ const zoom = Math.max(readableFloor, zoomFit);
49
+ const fitHeight = zoomFit === maxZoom ? Math.min(box.height, Math.ceil((bounds.height * zoom + 2 * FIT_PAINT_INSET) * 64) / 64) : box.height;
50
+ return { fitWidth: box.width, fitHeight, zoomFit, zoom, minZoom: zoom, maxZoom, pans: zoom > zoomFit };
46
51
  }
47
52
  /** Z-1/Z-7: any requested zoom lands inside `[minZoom, maxZoom]` of the current fit. */
48
53
  export function clampZoom(zoom, fit) {
package/dist/index.d.ts CHANGED
@@ -22,4 +22,5 @@ export * from "./visibility.js";
22
22
  export * from "./scene.js";
23
23
  export * from "./hit.js";
24
24
  export * from "./layout/index.js";
25
+ export * from "./presentation/erd.js";
25
26
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -22,4 +22,5 @@ export * from "./visibility.js";
22
22
  export * from "./scene.js";
23
23
  export * from "./hit.js";
24
24
  export * from "./layout/index.js";
25
+ export * from "./presentation/erd.js";
25
26
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import type { LineLayout, LineMeasurer } from './measure.js';
2
+ export interface BundleLabelGroup {
3
+ readonly lines: readonly string[];
4
+ readonly top: number;
5
+ readonly height: number;
6
+ }
7
+ export declare function measureBundleLabel(relations: readonly string[], measure: LineMeasurer, maxWidth?: number, relationCount?: number): {
8
+ header: string;
9
+ groups: BundleLabelGroup[];
10
+ layout: LineLayout;
11
+ };
12
+ //# sourceMappingURL=bundleLabel.d.ts.map
@@ -0,0 +1,16 @@
1
+ export function measureBundleLabel(relations, measure, maxWidth = 320, relationCount = relations.length) {
2
+ const line = (text, width) => measure({ text, role: 'edge-label', availableWidth: width,
3
+ allocatedLines: Number.MAX_SAFE_INTEGER, folded: false });
4
+ const header = `${relationCount} liaisons`;
5
+ const heading = line(header, maxWidth - 8);
6
+ let top = heading.height + 8;
7
+ const groups = relations.map(text => {
8
+ const measured = line(text, maxWidth - 24);
9
+ const group = { lines: measured.lines, top, height: measured.height + 8 };
10
+ top += group.height;
11
+ return group;
12
+ });
13
+ const layout = { lines: [header, ...groups.flatMap(group => group.lines)], width: maxWidth, height: top, overflow: false };
14
+ return { header, groups, layout };
15
+ }
16
+ //# sourceMappingURL=bundleLabel.js.map
@@ -23,7 +23,7 @@ function utf8ByteLength(text) {
23
23
  }
24
24
  return bytes;
25
25
  }
26
- const roles = ["kicker", "title", "body", "detail", "footer", "subtitle", "legend-label", "edge-label"];
26
+ const roles = ["kicker", "title", "body", "detail", "footer", "subtitle", "legend-label", "edge-label", "flow-badge"];
27
27
  const cameraTokens = new Set([
28
28
  "--st-component-diagramScene-maxDisplayScale", "--st-component-diagramScene-minReadableScale",
29
29
  "--st-component-diagramScene-transitionDuration", "--st-foundation-motion-easing",
@@ -57,18 +57,18 @@ export function createLayoutCache(config = {}) {
57
57
  inputDigests.set(value, digest);
58
58
  return digest;
59
59
  }
60
- function measurerDigest(options, measured) {
60
+ function measurerDigest(options, measured, flows) {
61
61
  const fn = measured ? options.measureLines : options.measureText;
62
62
  if (fn === undefined)
63
63
  return "missing";
64
64
  const known = measurers.get(fn);
65
- if (known !== undefined && known.version === fn.version)
65
+ if (known !== undefined && known.version === fn.version && known.flows === flows)
66
66
  return known.digest;
67
67
  const probe = measured
68
- ? roles.map((role) => options.measureLines({ text: "Mm09 É—", role, availableWidth: 290, allocatedLines: DEFAULT_ALLOCATED_LINES[role], folded: false }))
68
+ ? roles.filter((role) => flows || role !== "flow-badge").map((role) => options.measureLines({ text: "Mm09 É—", role, availableWidth: 290, allocatedLines: DEFAULT_ALLOCATED_LINES[role], folded: false }))
69
69
  : ["node", "container-title", "edge-label"].map((role) => options.measureText("Mm09 É—", role));
70
70
  const digest = digestOf(canonicalise({ version: fn.version, probe }));
71
- measurers.set(fn, { version: fn.version, digest });
71
+ measurers.set(fn, { version: fn.version, flows, digest });
72
72
  return digest;
73
73
  }
74
74
  function keys(document, options, sourceView) {
@@ -103,7 +103,7 @@ export function createLayoutCache(config = {}) {
103
103
  // Invalid serialisable inputs still reach the engine's normal refusal path.
104
104
  if (!input.ok)
105
105
  return undefined;
106
- const base = digestOf(input.text) + measurerDigest(options, measured);
106
+ const base = digestOf(input.text) + measurerDigest(options, measured, Object.values(document.relations).some((r) => r.type === "flow-step"));
107
107
  return { base, exact: base + digestOf(canonicalise(options.previousOrientation ?? {})) };
108
108
  }
109
109
  function find(key, previous = {}) {
@@ -147,7 +147,7 @@ export function createLayoutCache(config = {}) {
147
147
  if (disposed || key === undefined || result.status === "refused" || maxEntries === 0)
148
148
  return result;
149
149
  const viewText = canonicalise(result.view, "view");
150
- const size = utf8ByteLength(viewText) + utf8ByteLength(canonicalise(result.measurements ?? null)) + utf8ByteLength(canonicalise(result.labelBoxes ?? null));
150
+ const size = utf8ByteLength(viewText) + utf8ByteLength(canonicalise(result.measurements ?? null)) + utf8ByteLength(canonicalise(result.labelBoxes ?? null)) + utf8ByteLength(canonicalise(result.edgeBundles ?? null)) + utf8ByteLength(canonicalise(result.channels ?? null));
151
151
  if (size > maxBytes)
152
152
  return result;
153
153
  const stored = {
@@ -0,0 +1,28 @@
1
+ /** Flow-sized channels. All dimensions are world px, independent of the viewport. */
2
+ import type { LayoutMetrics } from './types.js';
3
+ export interface ChannelMetrics {
4
+ readonly gapMin: number;
5
+ readonly gapBase: number;
6
+ readonly trackSpacing: number;
7
+ readonly labelBand: number;
8
+ readonly gapMax: number;
9
+ }
10
+ export declare function channelMetrics(metrics: Partial<LayoutMetrics>, horizontal: boolean): ChannelMetrics;
11
+ export declare function channelGap(n: number, labelled: boolean, metrics: ChannelMetrics): number;
12
+ export interface LayoutChannel {
13
+ readonly id: string;
14
+ /** Axis of the gap (horizontal gap separates columns). */
15
+ readonly axis: 'horizontal' | 'vertical';
16
+ readonly edges: readonly string[];
17
+ readonly strips: readonly {
18
+ readonly x: number;
19
+ readonly y: number;
20
+ readonly width: number;
21
+ readonly height: number;
22
+ }[];
23
+ readonly n: number;
24
+ readonly labelled: boolean;
25
+ readonly gap: number;
26
+ readonly expected: number;
27
+ }
28
+ //# sourceMappingURL=channels.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { DIAGRAM_SCENE_SPACING as spacing } from './spacing.generated.js';
2
+ export function channelMetrics(metrics, horizontal) {
3
+ return {
4
+ gapMin: (horizontal ? metrics.gapMin : metrics.gapMinBlock) ?? (horizontal ? spacing.gapMin : spacing.gapMinBlock),
5
+ gapBase: (horizontal ? metrics.gapBase : metrics.gapBaseBlock) ?? (horizontal ? spacing.gapBase : spacing.gapBaseBlock),
6
+ trackSpacing: (horizontal ? metrics.trackSpacing : metrics.trackSpacingBlock) ?? (horizontal ? spacing.trackSpacing : spacing.trackSpacingBlock),
7
+ labelBand: metrics.labelBand ?? spacing.labelBand,
8
+ gapMax: (horizontal ? metrics.gapInlineMax : metrics.gapBlockMax) ?? metrics.gapMax ?? spacing.gapMax,
9
+ };
10
+ }
11
+ export function channelGap(n, labelled, metrics) {
12
+ return n === 0 ? metrics.gapMin : Math.min(metrics.gapMax, Math.max(metrics.gapMin, metrics.gapBase + n * metrics.trackSpacing + (labelled ? metrics.labelBand : 0)));
13
+ }
14
+ //# sourceMappingURL=channels.js.map
@@ -81,6 +81,7 @@ export declare function sideToward(self: Rect, other: Rect, direction: FlowDirec
81
81
  */
82
82
  export declare function parallelRelations(graph: LayoutGraph): ReadonlySet<RelationRef>;
83
83
  export declare function dockEdges(input: {
84
+ readonly flowBadgeSize?: number;
84
85
  readonly graph: LayoutGraph;
85
86
  readonly rects: ReadonlyMap<EntityRef, Rect>;
86
87
  readonly direction: FlowDirection;
@@ -1,37 +1,4 @@
1
- /**
2
- * Docking: which side of its entity each edge end uses, and where on that side.
3
- *
4
- * L-R1 — side choice and lone edge at the centre. An end's side is a function
5
- * of the two entity rectangles and the direction only. Ordinary pair: the flow
6
- * side first when the other entity is separated on that axis; the cross side
7
- * when the entities overlap along the flow and are separated across it; when
8
- * they overlap on both axes, the axis of the greater centre offset, horizontal
9
- * on an exact tie, then east/south for a non-negative offset and west/north
10
- * otherwise. Ancestor pair: both ends take the inner entity's nearest
11
- * container wall (ties east, south, west, north); the container end exits
12
- * inward, the inner end outward. Self-loop: the source end exits east
13
- * (left-to-right) or south (top-to-bottom) and the target end enters north
14
- * (left-to-right) or west (top-to-bottom). An end alone in its (entity, side)
15
- * group docks at the exact centre of that side (anchor 0.5).
16
- * L-R2 — shared side spread symmetrically; L-R9 takes priority over port
17
- * sharing. Side is fixed first: ends carrying the same semantic port are
18
- * forced to one side — the side of the port's representative end, smallest by
19
- * (relation id, role). A relation is parallel when another relation has the
20
- * same unordered entity pair (direction ignored; two self-loops on one
21
- * entity are parallel). Slot keys: a parallel end takes
22
- * `<relation-id>#<role>` (never the port key); a non-parallel end on a port
23
- * takes `~<port-id>`; otherwise `<relation-id>#<role>`. A slot's ordering
24
- * position is the other-end centre of its representative end (smallest by
25
- * relation id, role). Offsets `(i − (n−1)/2) · s` from the side's start,
26
- * summing to zero. Spacing `s` from `slotSpacing`, raised for labelled sides
27
- * to the widest label thickness plus `labelMargin`; with `n ≥ 2` and
28
- * `s · (n+1)` past the side length, the node grows to `s · (n+1)` effective
29
- * from the next placement attempt, the docked spacing then
30
- * `min(s, length / (n+1))`.
31
- * L-R9 — parallel edges (same unordered entity pair) never share a slot, at
32
- * either end, including on a shared port; their slot order is the same at
33
- * both ends, so they do not cross each other.
34
- */
1
+ import { permuteFlowRuns } from "./flow-order.js";
35
2
  import { isAncestor } from "./graph.js";
36
3
  import { slotSpacingFor } from "./place.js";
37
4
  export const SIDE_NORMAL = {
@@ -106,6 +73,7 @@ export function dockEdges(input) {
106
73
  const target = edge.target.entity;
107
74
  const label = labelSizes.get(edge.id);
108
75
  const push = (role, entity, other, side, inner) => ends.push({
76
+ slot: edge[role].slot,
109
77
  edge: edge.id,
110
78
  role,
111
79
  entity,
@@ -164,7 +132,8 @@ export function dockEdges(input) {
164
132
  const vertical = side === "east" || side === "west";
165
133
  // L-R9 takes priority over port sharing: a parallel end never takes the
166
134
  // port key, even when it carries a port.
167
- const slotKey = (end) => end.port !== undefined && !parallel.has(end.edge) ? `~${end.port}` : `${end.edge}#${end.role}`;
135
+ const slotKey = (end) => end.slot !== undefined ? "~" + end.slot :
136
+ end.port !== undefined && !parallel.has(end.edge) ? `~${end.port}` : `${end.edge}#${end.role}`;
168
137
  const representative = (members) => [...members].sort((left, right) => byString(left.edge, right.edge) || byString(left.role, right.role))[0];
169
138
  const turns = (end) => input.sideOverrides?.get(end.edge)?.turn === true;
170
139
  const selfCentre = centreOf(rect);
@@ -180,7 +149,7 @@ export function dockEdges(input) {
180
149
  const slots = new Map();
181
150
  for (const end of group)
182
151
  (slots.get(slotKey(end)) ?? slots.set(slotKey(end), []).get(slotKey(end))).push(end);
183
- const orderedKeys = [...slots.keys()].sort((left, right) => {
152
+ const sortedKeys = [...slots.keys()].sort((left, right) => {
184
153
  const first = representative(slots.get(left));
185
154
  const second = representative(slots.get(right));
186
155
  const a = position(first);
@@ -193,10 +162,22 @@ export function dockEdges(input) {
193
162
  return byString(right, left);
194
163
  return byString(left, right);
195
164
  });
165
+ const flowEdge = new Map(graph.edges.filter((edge) => edge.flowRank !== undefined && edge.source.slot === undefined && edge.target.slot === undefined).map((edge) => [edge.id, edge]));
166
+ const runOf = (key) => {
167
+ const members = slots.get(key);
168
+ const end = representative(members);
169
+ const edge = flowEdge.get(end.edge);
170
+ return members.length !== 1 || edge === undefined ? undefined : [edge.source.entity, edge.target.entity].sort().join("|") + "|" + String(turns(end));
171
+ };
172
+ const orderedKeys = permuteFlowRuns(sortedKeys, runOf, (key) => flowEdge.get(representative(slots.get(key)).edge).flowRank, (key) => {
173
+ const end = representative(slots.get(key));
174
+ return turns(end) && position(end) > 0;
175
+ });
176
+ const flowRun = sortedKeys.some((key) => runOf(key) !== undefined && sortedKeys.filter((other) => runOf(other) === runOf(key)).length > 1);
196
177
  const thickness = group.reduce((widest, end) => (end.label === undefined ? widest : Math.max(widest, vertical ? end.label.height : end.label.width)), 0);
197
178
  const length = vertical ? rect.height : rect.width;
198
179
  const count = orderedKeys.length;
199
- const wanted = slotSpacingFor(metrics, count >= 2 ? thickness : 0);
180
+ const wanted = Math.max(slotSpacingFor(metrics, count >= 2 ? thickness : 0), flowRun ? (input.flowBadgeSize ?? 0) + metrics.labelMargin : 0);
200
181
  if (fixed === true) {
201
182
  const capacity = Math.max(1, Math.floor(length / wanted) + 1);
202
183
  const centre = centreOf(rect);
@@ -52,7 +52,7 @@
52
52
  * a document record's insertion order. The same document laid out twice, or
53
53
  * with its records shuffled, gives the same canonical bytes (`serialiseView`).
54
54
  */
55
- import { hasErrors, localIdOf, occurrenceRef, validateDocument, viewRef, } from "@sentropic/diagram-core";
55
+ import { hasErrors, localIdOf, occurrenceRef, validateDocument, validateFlows, viewRef, } from "@sentropic/diagram-core";
56
56
  import { rectsIntersect } from "../geometry.js";
57
57
  import { layoutMeasured } from "./measured.js";
58
58
  import { dockEdges, parallelRelations } from "./dock.js";
@@ -829,7 +829,7 @@ export function layoutDocument(document, options) {
829
829
  // path below runs untouched, byte-identical (§4.8).
830
830
  if (options.presentation !== undefined)
831
831
  return layoutMeasured(document, options);
832
- const diagnostics = validateDocument(document, { registry: options.registry });
832
+ const diagnostics = [...validateDocument(document, { registry: options.registry }), ...validateFlows(document)];
833
833
  if (hasErrors(diagnostics)) {
834
834
  return {
835
835
  status: "refused",
@@ -881,7 +881,7 @@ export function layoutDocument(document, options) {
881
881
  pans: width * zoom > target,
882
882
  phone,
883
883
  },
884
- warnings: drawing.warnings,
884
+ warnings: [...drawing.warnings, ...Object.values(document.relations).filter((r) => r.type === "flow-step").map((r) => ({ code: "flow-layout-unsupported", refs: [r.id], message: "numbered marks require measured layout; laid out as link" }))],
885
885
  };
886
886
  }
887
887
  function pickDrawing(leftToRight, topToBottom, target) {
@@ -912,7 +912,7 @@ export function diagnoseLabels(document, options) {
912
912
  }
913
913
  if (options.presentation !== undefined)
914
914
  return diagnoseMeasuredLabels(document, options);
915
- const diagnostics = validateDocument(document, { registry: options.registry });
915
+ const diagnostics = [...validateDocument(document, { registry: options.registry }), ...validateFlows(document)];
916
916
  if (hasErrors(diagnostics)) {
917
917
  return {
918
918
  status: "refused",
@@ -0,0 +1,5 @@
1
+ import { type SemanticDocument, type ViewDocument } from '@sentropic/diagram-core';
2
+ import { type LayoutOptions, type LayoutResult } from './types.js';
3
+ /** ERD measurement plugs into the existing variable-size shelf packer and orthogonal router. */
4
+ export declare function layoutErd(document: SemanticDocument, options: LayoutOptions, source?: ViewDocument): LayoutResult;
5
+ //# sourceMappingURL=erd.d.ts.map
@@ -0,0 +1,85 @@
1
+ import { validateDocument, createView, occurrenceRef, viewRef, erdEntityOccurrence, erdPortOccurrence } from '@sentropic/diagram-core';
2
+ import { ERD_GEOMETRY as T, measureErdCard, erdFields } from '../presentation/erd.js';
3
+ import { packRows } from './pack.js';
4
+ import { routeEdges } from './route.js';
5
+ import { resolveRowPack, validateRowPack } from './types.js';
6
+ /** ERD measurement plugs into the existing variable-size shelf packer and orthogonal router. */
7
+ export function layoutErd(document, options, source) {
8
+ const diagnostics = validateDocument(document, { registry: options.registry, ...(options.bindings ? { bindings: options.bindings } : {}) });
9
+ if (diagnostics.some(d => d.severity === 'error'))
10
+ return { status: 'refused', refusals: [{ code: 'document-invalid', path: 'document', message: 'Invalid ERD document' }], diagnostics };
11
+ if (!Number.isFinite(options.targetWidth) || options.targetWidth <= 0)
12
+ return { status: 'refused', refusals: [{ code: 'target-width-invalid', path: 'targetWidth', message: 'Positive finite width required' }], diagnostics: [] };
13
+ const objective = resolveRowPack(options.rowPack), refusals = validateRowPack(objective);
14
+ if (refusals.length)
15
+ return { status: 'refused', refusals, diagnostics: [] };
16
+ const collapsed = new Set(options.collapsed ?? Object.values(source?.groups ?? {}).filter(g => g.collapsed).map(g => g.occurrence));
17
+ const entities = Object.values(document.entities).sort((a, b) => a.id < b.id ? -1 : 1);
18
+ const ids = new Map(entities.map(e => [e.id, Object.values(source?.entityOccurrences ?? {}).find(o => o.entity === e.id)?.id ?? erdEntityOccurrence(e.id)]));
19
+ const cards = entities.map(e => measureErdCard(document, e.id, collapsed.has(ids.get(e.id)), options.measureLines));
20
+ const packed = packRows(cards, { targetAspect: objective.targetAspect, tallBias: objective.tallBias, emptyPenaltyWeight: objective.emptyPenaltyWeight, gapX: Math.max(T.gapInline, options.metrics?.rowGapInline ?? 0), gapY: Math.max(T.gapBlock, options.metrics?.rowGapBlock ?? 0), chromeWidth: 0, chromeHeight: 0 });
21
+ const entityOccurrences = {}, portOccurrences = {}, relationOccurrences = {}, groups = {};
22
+ const rects = new Map(), headers = new Map();
23
+ entities.forEach((entity, index) => {
24
+ const id = ids.get(entity.id), card = cards[index], pos = packed.positions[index];
25
+ const geometry = { x: pos.x + T.gapInline, y: pos.y + T.gapBlock, width: card.width, height: card.height };
26
+ entityOccurrences[id] = { id, entity: entity.id, geometry };
27
+ rects.set(entity.id, geometry);
28
+ headers.set(entity.id, card.headerHeight);
29
+ groups['fold.' + id.slice(11)] = { id: 'fold.' + id.slice(11), occurrence: id, collapsed: collapsed.has(id) };
30
+ for (const field of erdFields(document, entity.id))
31
+ for (const side of ['west', 'east']) {
32
+ const row = card.rows.find(r => r.field.id === field.id), idp = erdPortOccurrence(field.id, side);
33
+ portOccurrences[idp] = { id: idp, port: field.id, ownerOccurrence: id, side, order: row ? card.rows.indexOf(row) : 0, anchor: row ? (row.y + row.height / 2) / card.height : 0.5 };
34
+ }
35
+ });
36
+ const relations = Object.values(document.relations).sort((a, b) => a.id < b.id ? -1 : 1);
37
+ const ends = relations.flatMap(r => ['from', 'to'].map(role => {
38
+ const end = r.endpoints.find(e => e.role === role), other = r.endpoints.find(e => e.role !== role);
39
+ const entity = (document.ports[end.target]?.owner ?? end.target), peer = (document.ports[other.target]?.owner ?? other.target);
40
+ const rect = rects.get(entity), rectOther = rects.get(peer);
41
+ return { entity, side: rectOther.x + rectOther.width / 2 < rect.x + rect.width / 2 ? 'west' : 'east', target: end.target, role, relation: r.id };
42
+ }));
43
+ const requests = [], selfRoutes = new Map();
44
+ const selfCountByEntity = new Map();
45
+ for (const relation of relations) {
46
+ const occurrence = Object.values(source?.relationOccurrences ?? {}).find(o => o.relation === relation.id)?.id ?? occurrenceRef(relation.id.slice(9));
47
+ const points = [], exits = [], eps = [];
48
+ for (const end of ends.filter(e => e.relation === relation.id)) {
49
+ const owner = ids.get(end.entity), rect = rects.get(end.entity), port = document.ports[end.target];
50
+ const folded = collapsed.has(owner), po = port ? erdPortOccurrence(port.id, end.side) : undefined;
51
+ const slots = ends.filter(e => e.entity === end.entity && e.side === end.side && (collapsed.has(owner) || !document.ports[e.target]));
52
+ const slot = slots.indexOf(end), header = headers.get(end.entity);
53
+ const y = port && !folded ? rect.y + portOccurrences[po].anchor * rect.height : rect.y + T.markerHalfWidth + (slot + 1) * (header - 2 * T.markerHalfWidth) / (slots.length + 1);
54
+ points.push({ x: rect.x + (end.side === 'east' ? rect.width : 0), y });
55
+ exits.push({ x: end.side === 'east' ? 1 : -1, y: 0 });
56
+ eps.push({ role: end.role, occurrence: port && !folded ? po : owner, ...(port && folded ? { semanticTarget: port.id, sourceOccurrence: po } : {}) });
57
+ }
58
+ relationOccurrences[occurrence] = { id: occurrence, relation: relation.id, endpoints: eps };
59
+ const pair = ends.filter(e => e.relation === relation.id).map(e => e.entity);
60
+ if (pair[0] === pair[1]) {
61
+ const entity = pair[0], selfIndex = (selfCountByEntity.get(entity) ?? 0) + 1;
62
+ selfCountByEntity.set(entity, selfIndex);
63
+ const rect = rects.get(entity), lane = rect.x + rect.width + T.markerLength + T.markerGap * selfIndex * 2;
64
+ const start = points[0], end = points[1];
65
+ selfRoutes.set(relation.id, start.y === end.y
66
+ ? [start, { x: lane, y: start.y }, { x: lane, y: start.y + T.rowHeight }, { x: lane + T.markerGap, y: start.y + T.rowHeight }, { x: lane + T.markerGap, y: end.y }, end]
67
+ : [start, { x: lane, y: start.y }, { x: lane, y: end.y }, end]);
68
+ }
69
+ else
70
+ // FK edges may converge on one PK row or have opposite row order. Reserve each
71
+ // independently: overlap stays penalized, while the entity-pair crossing ban
72
+ // (which assumes freely ordered header docks) does not apply to fixed rows.
73
+ requests.push({ id: relation.id, pairKey: relation.id, start: points[0], end: points[1], startExit: exits[0], endExit: exits[1], passable: new Set() });
74
+ }
75
+ const routed = routeEdges({ rects, requests, clearance: T.markerLength + T.markerGap });
76
+ const warnings = routed.obstructed.map(id => ({ code: 'route-obstructed', refs: [id], message: 'Dense ERD routing uses an elbow fallback' }));
77
+ for (const o of Object.values(relationOccurrences)) {
78
+ const route = selfRoutes.get(o.relation) ?? routed.routes.get(o.relation) ?? [];
79
+ const fromPort = portOccurrences[o.endpoints[0].occurrence], toPort = portOccurrences[o.endpoints[1].occurrence];
80
+ relationOccurrences[o.id] = { ...o, waypoints: route.slice(fromPort ? 1 : 0, toPort ? route.length - 1 : route.length) };
81
+ }
82
+ const view = { ...createView({ viewId: options.viewId ?? source?.viewId ?? viewRef('erd'), semanticDocumentId: document.documentId, revision: document.revision }), entityOccurrences, portOccurrences, relationOccurrences, groups };
83
+ return { status: 'laid-out', view, fit: { direction: 'left-to-right', width: packed.width + 2 * T.gapInline, height: packed.height + 2 * T.gapBlock, zoom: 1, pans: packed.width > options.targetWidth, phone: options.targetWidth <= 390 }, warnings, orientations: { root: 'rows' } };
84
+ }
85
+ //# sourceMappingURL=erd.js.map
@@ -1,9 +1,9 @@
1
1
  import type { LayoutMeasurements } from "./measure.js";
2
2
  import { type LayoutOptions } from "./types.js";
3
3
  /** Bumped whenever measured placement changes for unchanged inputs. */
4
- export declare const LAYOUT_ENGINE_VERSION = "dc2a.1";
4
+ export declare const LAYOUT_ENGINE_VERSION = "dc2c.owner.5";
5
5
  export interface LayoutFingerprintInput {
6
- readonly options: Pick<LayoutOptions, "collapsed" | "hints" | "metrics" | "rowPack" | "previousOrientation" | "viewId">;
6
+ readonly options: Pick<LayoutOptions, "collapsed" | "hints" | "metrics" | "rowPack" | "previousOrientation" | "viewId" | "flows" | "flowTokens">;
7
7
  /** Measured sizes of a previous call on the same document and measurer, when a cache has them. */
8
8
  readonly measurements?: LayoutMeasurements;
9
9
  /** Resolved token numbers the host read (gaps, caps, target aspect, display scales, …), by token name. */
@@ -16,9 +16,10 @@
16
16
  * the call that observes it, with no token-version export.
17
17
  */
18
18
  import { isLayoutGroup, resolveRowGaps } from "./hints.js";
19
+ import { channelMetrics } from "./channels.js";
19
20
  import { DEFAULT_LAYOUT_METRICS, resolveRowPack } from "./types.js";
20
21
  /** Bumped whenever measured placement changes for unchanged inputs. */
21
- export const LAYOUT_ENGINE_VERSION = "dc2a.1";
22
+ export const LAYOUT_ENGINE_VERSION = "dc2c.owner.5";
22
23
  const byString = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
23
24
  /** JSON with object keys sorted: equal values give equal text, whatever the insertion order. */
24
25
  function canonical(value) {
@@ -61,10 +62,13 @@ export function layoutFingerprintInputs(input) {
61
62
  const tokens = input.tokens ?? {};
62
63
  return {
63
64
  engine: LAYOUT_ENGINE_VERSION,
65
+ flows: options.flows,
66
+ flowTokens: options.flowTokens,
64
67
  fold: [...(options.collapsed ?? [])].map(String).sort(byString),
65
68
  rowPack: resolveRowPack(options.rowPack),
66
69
  gaps,
67
- metrics: { clearance: metrics.clearance, labelMargin: metrics.labelMargin, slotSpacing: metrics.slotSpacing, nodeGap: metrics.nodeGap },
70
+ channels: { inline: channelMetrics(metrics, true), block: channelMetrics(metrics, false), bundleLabelMaxWidth: metrics.bundleLabelMaxWidth ?? 320 },
71
+ metrics: { clearance: metrics.clearance, labelMargin: metrics.labelMargin, slotSpacing: options.metrics?.slotSpacing ?? options.metrics?.trackSpacing ?? 14, nodeGap: metrics.nodeGap },
68
72
  previousOrientation: Object.entries(options.previousOrientation ?? {}).sort(([left], [right]) => byString(left, right)),
69
73
  hints: {
70
74
  ordering: hints.ordering,
@@ -0,0 +1,3 @@
1
+ /** Reassign only the positions held by a run; all ordinary positions stay fixed. */
2
+ export declare function permuteFlowRuns<T>(sequence: readonly T[], keyOf: (entry: T) => string | undefined, rankOf: (entry: T) => number, reverse?: (entry: T) => boolean): T[];
3
+ //# sourceMappingURL=flow-order.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** Reassign only the positions held by a run; all ordinary positions stay fixed. */
2
+ export function permuteFlowRuns(sequence, keyOf, rankOf, reverse = () => false) {
3
+ const result = [...sequence], groups = new Map();
4
+ sequence.forEach((entry, i) => { const key = keyOf(entry); if (key !== undefined)
5
+ (groups.get(key) ?? groups.set(key, []).get(key)).push(i); });
6
+ for (const positions of groups.values()) {
7
+ const entries = positions.map((i) => sequence[i]).sort((a, b) => rankOf(a) - rankOf(b));
8
+ if (reverse(entries[0]))
9
+ entries.reverse();
10
+ positions.forEach((position, i) => { result[position] = entries[i]; });
11
+ }
12
+ return result;
13
+ }
14
+ //# sourceMappingURL=flow-order.js.map
@@ -0,0 +1,89 @@
1
+ /** Flow-only layout metadata and mark placement. No host or DOM state. */
2
+ import { type FlowIndex, type FlowStep, type OccurrenceRef, type ProfileRegistry, type SemanticDocument, type ViewDocument } from "@sentropic/diagram-core";
3
+ import type { Rect, Vec2 } from "../transform.js";
4
+ import type { LineMeasurer } from "./measure.js";
5
+ import type { LayoutOptions, LayoutWarning } from "./types.js";
6
+ export interface FlowTokens {
7
+ readonly flowBadgeSize: number;
8
+ readonly flowBadgePaddingX: number;
9
+ readonly flowArrowLength: number;
10
+ readonly flowArrowWidth: number;
11
+ readonly flowTargetMinSize: number;
12
+ readonly flowFanOutMax: number;
13
+ readonly flowArrowPath: string;
14
+ }
15
+ export declare const FLOW_BADGE_FONT_SIZE = 16;
16
+ export declare const FLOW_BADGE_LINE_HEIGHT = 20;
17
+ export declare const DEFAULT_FLOW_TOKENS: FlowTokens;
18
+ export interface FlowArrow {
19
+ readonly tip: Vec2;
20
+ readonly angle: 0 | 90 | 180 | 270;
21
+ readonly box: Rect;
22
+ }
23
+ export interface FlowBundle {
24
+ readonly id: string;
25
+ readonly reason: "fold" | "fan-out" | "obstructed";
26
+ readonly carrier: OccurrenceRef;
27
+ readonly members: readonly {
28
+ readonly occurrence: OccurrenceRef;
29
+ readonly relation: string;
30
+ readonly direction: "forward" | "backward";
31
+ readonly source: string;
32
+ readonly target: string;
33
+ }[];
34
+ readonly forward: number;
35
+ readonly backward: number;
36
+ readonly summaries: readonly string[];
37
+ }
38
+ export type FlowVisibleTarget = {
39
+ readonly kind: "edge";
40
+ readonly occurrence: OccurrenceRef;
41
+ readonly badge: boolean;
42
+ } | {
43
+ readonly kind: "bundle";
44
+ readonly id: string;
45
+ readonly occurrence: OccurrenceRef;
46
+ readonly badge: boolean;
47
+ } | {
48
+ readonly kind: "internal";
49
+ readonly box: OccurrenceRef;
50
+ };
51
+ export interface FlowMember {
52
+ readonly occurrence: OccurrenceRef;
53
+ readonly step: FlowStep;
54
+ readonly source: OccurrenceRef;
55
+ readonly target: OccurrenceRef;
56
+ readonly retargeted: boolean;
57
+ readonly key: string;
58
+ readonly rank: number;
59
+ }
60
+ export interface FlowPlan {
61
+ readonly index: FlowIndex;
62
+ readonly members: readonly FlowMember[];
63
+ readonly groups: ReadonlyMap<string, readonly FlowMember[]>;
64
+ readonly bundles: readonly FlowBundle[];
65
+ readonly suppressed: ReadonlySet<string>;
66
+ readonly targets: Readonly<Record<string, FlowVisibleTarget>>;
67
+ readonly ranks: ReadonlyMap<string, number>;
68
+ }
69
+ export declare function planFlows(document: SemanticDocument, view: ViewDocument, registry: ProfileRegistry, options: LayoutOptions, forced: ReadonlySet<string>): FlowPlan;
70
+ export declare function arrowAt(route: readonly Vec2[], start: boolean, tokens: FlowTokens): FlowArrow | undefined;
71
+ export declare function placeFlowMarks(input: {
72
+ plan: FlowPlan;
73
+ routes: ReadonlyMap<string, readonly Vec2[]>;
74
+ shapes: readonly Rect[];
75
+ within: ReadonlyMap<string, Rect>;
76
+ limit?: Rect;
77
+ measure: LineMeasurer;
78
+ options: LayoutOptions;
79
+ margin: number;
80
+ }): {
81
+ arrows: Record<string, FlowArrow[]>;
82
+ badges: Record<string, Rect>;
83
+ targets: {
84
+ [x: string]: FlowVisibleTarget;
85
+ };
86
+ warnings: LayoutWarning[];
87
+ taken: Rect[];
88
+ };
89
+ //# sourceMappingURL=flows.d.ts.map