@principal-ai/subsystems-react 0.56.21 → 0.56.23

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 (70) hide show
  1. package/dist/index.d.ts +5 -2
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/stories/Canvases/Aggregate/aggregateViewLargeFixture.d.ts +12 -0
  6. package/dist/stories/Canvases/Aggregate/aggregateViewLargeFixture.d.ts.map +1 -0
  7. package/dist/stories/Canvases/Aggregate/aggregateViewLargeFixture.js +4 -0
  8. package/dist/stories/Canvases/Aggregate/aggregateViewLargeFixture.js.map +1 -0
  9. package/dist/subsystem/C4Graph.d.ts +2 -69
  10. package/dist/subsystem/C4Graph.d.ts.map +1 -1
  11. package/dist/subsystem/C4Graph.js +8 -154
  12. package/dist/subsystem/C4Graph.js.map +1 -1
  13. package/dist/subsystem/C4NodeCard.d.ts +1 -47
  14. package/dist/subsystem/C4NodeCard.d.ts.map +1 -1
  15. package/dist/subsystem/C4NodeCard.js +6 -141
  16. package/dist/subsystem/C4NodeCard.js.map +1 -1
  17. package/dist/subsystem/ContainersPanel.d.ts +33 -0
  18. package/dist/subsystem/ContainersPanel.d.ts.map +1 -0
  19. package/dist/subsystem/ContainersPanel.js +116 -0
  20. package/dist/subsystem/ContainersPanel.js.map +1 -0
  21. package/dist/subsystem/SubsystemAggregateGraph.d.ts +14 -0
  22. package/dist/subsystem/SubsystemAggregateGraph.d.ts.map +1 -1
  23. package/dist/subsystem/SubsystemAggregateGraph.js +116 -69
  24. package/dist/subsystem/SubsystemAggregateGraph.js.map +1 -1
  25. package/dist/subsystem/SubsystemComponentGraph.d.ts +18 -1
  26. package/dist/subsystem/SubsystemComponentGraph.d.ts.map +1 -1
  27. package/dist/subsystem/SubsystemComponentGraph.js +143 -21
  28. package/dist/subsystem/SubsystemComponentGraph.js.map +1 -1
  29. package/dist/subsystem/containerCard.d.ts +132 -0
  30. package/dist/subsystem/containerCard.d.ts.map +1 -0
  31. package/dist/subsystem/containerCard.js +167 -0
  32. package/dist/subsystem/containerCard.js.map +1 -0
  33. package/dist/subsystem/graphChrome.d.ts +11 -8
  34. package/dist/subsystem/graphChrome.d.ts.map +1 -1
  35. package/dist/subsystem/graphChrome.js +11 -9
  36. package/dist/subsystem/graphChrome.js.map +1 -1
  37. package/dist/subsystem/graphMorph.d.ts +142 -0
  38. package/dist/subsystem/graphMorph.d.ts.map +1 -0
  39. package/dist/subsystem/graphMorph.js +177 -0
  40. package/dist/subsystem/graphMorph.js.map +1 -0
  41. package/dist/subsystem/model.d.ts +89 -0
  42. package/dist/subsystem/model.d.ts.map +1 -1
  43. package/dist/subsystem/model.js +224 -15
  44. package/dist/subsystem/model.js.map +1 -1
  45. package/dist/subsystem/nodes.d.ts +9 -3
  46. package/dist/subsystem/nodes.d.ts.map +1 -1
  47. package/dist/subsystem/nodes.js +134 -82
  48. package/dist/subsystem/nodes.js.map +1 -1
  49. package/dist/utils/elkLayout.d.ts +11 -0
  50. package/dist/utils/elkLayout.d.ts.map +1 -1
  51. package/dist/utils/elkLayout.js +4 -3
  52. package/dist/utils/elkLayout.js.map +1 -1
  53. package/package.json +1 -1
  54. package/src/index.ts +6 -0
  55. package/src/stories/Canvases/Aggregate/AggregateFrameGraph.stories.tsx +140 -2
  56. package/src/stories/Canvases/Aggregate/aggregateViewLargeFixture.ts +14 -0
  57. package/src/stories/Canvases/Subsystem/ContainerFrames.stories.tsx +132 -0
  58. package/src/subsystem/C4Graph.tsx +20 -180
  59. package/src/subsystem/C4NodeCard.tsx +34 -202
  60. package/src/subsystem/ContainersPanel.tsx +239 -0
  61. package/src/subsystem/SubsystemAggregateGraph.tsx +146 -78
  62. package/src/subsystem/SubsystemComponentGraph.tsx +222 -25
  63. package/src/subsystem/containerCard.tsx +264 -0
  64. package/src/subsystem/graphChrome.tsx +11 -9
  65. package/src/subsystem/graphMorph.tsx +212 -0
  66. package/src/subsystem/model.collapse.test.ts +128 -0
  67. package/src/subsystem/model.ts +306 -16
  68. package/src/subsystem/nodes.group.test.tsx +125 -16
  69. package/src/subsystem/nodes.tsx +201 -91
  70. package/src/utils/elkLayout.ts +16 -2
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The shared card vocabulary a container draws with — on the C4 canvas as a
3
+ * `C4NodeCard`, and on the component graph as a process / package frame.
4
+ *
5
+ * Both canvases draw the same two rows at the top of a container: the label
6
+ * (two lines, kind glyph on the right) and the technology row (brand mark,
7
+ * technology, member count). Keeping the rows and their metrics here is what
8
+ * lets the two cards read as one notation, and what keeps each card's chrome a
9
+ * known quantity for the layout that has to reserve room for it.
10
+ */
11
+
12
+ import { useTheme } from '@principal-ade/industry-theme';
13
+ import type { LucideIcon } from 'lucide-react';
14
+ import { TechMark } from './techIcons';
15
+ import type { TechBrand } from './techIcons';
16
+
17
+ /**
18
+ * Card box for a container: a wide rectangle. A container carries four things
19
+ * at once (technology row, label, description, and the notation gap it still
20
+ * has), and a strip would force the last two to wrap hard.
21
+ */
22
+ export const NODE_W = 250;
23
+ export const NODE_H = 150;
24
+
25
+ /**
26
+ * Fixed label slot, so the description below sits at the same y on every card
27
+ * even when a label is one line rather than two.
28
+ */
29
+ export const LABEL_SLOT_H = 40;
30
+
31
+ /**
32
+ * The technology row's height, pinned for the same reason as the label slot: the
33
+ * row is a line of text plus an optional 16px brand mark, so its natural height
34
+ * depends on which of those are present. Pinning it makes the card's chrome a
35
+ * known quantity, which is what lets `descriptionLineBudget` say how many
36
+ * description lines fit — and lets the footer pad and the header pad agree about
37
+ * where the card's content actually ends.
38
+ */
39
+ export const TECH_SLOT_H = 18;
40
+
41
+ /** The card's own vertical padding (`padding: '10px 12px'`). */
42
+ export const CARD_PAD_Y = 10;
43
+
44
+ /** The card's own horizontal padding. */
45
+ export const CARD_PAD_X = 12;
46
+
47
+ /** The card's flex `gap`, between each of its rows. */
48
+ export const CARD_GAP = 3;
49
+
50
+ /**
51
+ * Breathing room between a grown container's own chrome and the components nested
52
+ * inside it.
53
+ *
54
+ * The description is hidden while grown, so the components land where the
55
+ * description would have been — immediately under the technology row. Without
56
+ * this the gap is the width of one row gap, which reads as the components being
57
+ * crowded against the header while the sides and footer sit `OPEN_SIDE_PAD` away.
58
+ * This is not chrome: nothing is drawn in it.
59
+ */
60
+ export const OPEN_HEADER_AIR = 16;
61
+
62
+ /**
63
+ * Space a *grown* container reserves above its nested components: the card's own
64
+ * padding, its label slot, its technology row, the gaps between them, and a little
65
+ * air. The description is hidden while grown, so it is not part of this.
66
+ *
67
+ * Derived from the same constants the card is built from, rather than written as
68
+ * a literal, so it cannot drift from `descriptionLineBudget` — which subtracts
69
+ * exactly this chrome (and no air) to decide how much description a closed card
70
+ * can show. Those two disagreeing is how a card ends up taller than the box ELK
71
+ * laid out for it.
72
+ *
73
+ * The graph hands this to ELK as the compound parent's top padding rather than
74
+ * nudging the children down itself — so the parent's size and the children's
75
+ * placement are still one ELK fit, not our arithmetic layered on top of it.
76
+ */
77
+ export const OPEN_HEADER_PAD =
78
+ CARD_PAD_Y * 2 + LABEL_SLOT_H + CARD_GAP + TECH_SLOT_H + CARD_GAP + OPEN_HEADER_AIR;
79
+
80
+ /**
81
+ * The drill-down affordance, in the card's own box. Extracted from the button's
82
+ * style so the reserved footer cannot drift from the thing it is reserving for —
83
+ * the two numbers are the same number.
84
+ */
85
+ export const TOGGLE_SIZE = 22;
86
+ export const TOGGLE_INSET = 6;
87
+
88
+ /**
89
+ * Space a *grown* container reserves below its nested components, so the last row
90
+ * does not sit under the collapse affordance.
91
+ *
92
+ * The toggle is absolutely positioned, so it takes no space in the card's flow and
93
+ * ELK knows nothing about it: without this the parent is fitted to its children
94
+ * alone and the final row is drawn straight through the button. Reserving the
95
+ * toggle's own reach plus a little air keeps that an ELK fit too, rather than
96
+ * something we nudge afterwards.
97
+ */
98
+ export const OPEN_FOOTER_PAD = TOGGLE_INSET + TOGGLE_SIZE + 8;
99
+
100
+ /**
101
+ * Space a *grown* container reserves to the left and right of its nested
102
+ * components.
103
+ *
104
+ * Deliberately the footer's number rather than its own: the nested cards should
105
+ * sit in one uniform inset, not a wider one at the bottom than at the sides. Both
106
+ * are wider than the card's own 12px text inset — the label and technology row are
107
+ * the container's chrome and sit flush with its padding, while the nested cards
108
+ * are separate boxes it contains, and at the same inset they read as part of that
109
+ * chrome rather than held inside it.
110
+ */
111
+ export const OPEN_SIDE_PAD = OPEN_FOOTER_PAD;
112
+
113
+ export interface ContainerCardHeaderProps {
114
+ label: string;
115
+ /** The kind glyph beside the label — a container's sort, a package's mark. */
116
+ Icon?: LucideIcon;
117
+ /** Accessible name for the glyph. */
118
+ iconLabel?: string;
119
+ /** The border colour; the glyph takes it so the two read as one accent. */
120
+ color: string;
121
+ /** The technology row's text. Empty hides the text but not the row. */
122
+ topLabel?: string;
123
+ /** The official technology mark, when we hold one. */
124
+ brand?: TechBrand;
125
+ /**
126
+ * Whether the technology row is pinned to `TECH_SLOT_H`. A container always has
127
+ * one (at minimum its member count); a person never does, and its row stays
128
+ * zero-height so the description gets the line.
129
+ */
130
+ hasTechRow: boolean;
131
+ /** Right-aligned count in the technology row — how many members the box groups. */
132
+ count?: { value: number; Icon: LucideIcon };
133
+ /** Centre the rows (components, people) instead of left-aligning them. */
134
+ centered?: boolean;
135
+ }
136
+
137
+ /**
138
+ * The two rows at the top of every container card: label, then technology.
139
+ *
140
+ * Heights are pinned (`LABEL_SLOT_H`, `TECH_SLOT_H`) so the rows land at the same
141
+ * y on every card and the chrome below them can be reserved exactly — see
142
+ * `OPEN_HEADER_PAD`.
143
+ */
144
+ export function ContainerCardHeader({
145
+ label,
146
+ Icon,
147
+ iconLabel,
148
+ color,
149
+ topLabel,
150
+ brand,
151
+ hasTechRow,
152
+ count,
153
+ centered = false,
154
+ }: ContainerCardHeaderProps) {
155
+ const { theme } = useTheme();
156
+ const muted = theme.colors.textMuted ?? theme.colors.textSecondary;
157
+ return (
158
+ <>
159
+ {/* The label row: the name, then the kind mark. Two lines rather than an
160
+ ellipsis — a truncated label hides the very thing that distinguishes
161
+ two containers from each other. The fixed height reserves both lines
162
+ even for a one-line label, so the row below sits at the same y on
163
+ every card. */}
164
+ <span
165
+ style={{
166
+ display: 'flex',
167
+ alignItems: 'flex-start',
168
+ justifyContent: centered ? 'center' : 'space-between',
169
+ gap: 6,
170
+ height: LABEL_SLOT_H,
171
+ // Without this the slot shrinks when the content exceeds the card's fixed
172
+ // height, and `descriptionLineBudget`'s chrome stops being the chrome —
173
+ // measured at 39.11px instead of 40 the moment the description ran long.
174
+ flexShrink: 0,
175
+ minWidth: 0,
176
+ }}
177
+ >
178
+ <span
179
+ style={{
180
+ fontFamily: theme.fonts.body,
181
+ fontWeight: 600,
182
+ fontSize: theme.fontSizes[2],
183
+ color: theme.colors.text,
184
+ lineHeight: 1.25,
185
+ maxHeight: LABEL_SLOT_H,
186
+ display: '-webkit-box',
187
+ WebkitLineClamp: 2,
188
+ WebkitBoxOrient: 'vertical',
189
+ overflow: 'hidden',
190
+ textAlign: centered ? 'center' : 'left',
191
+ minWidth: 0,
192
+ }}
193
+ >
194
+ {label}
195
+ </span>
196
+ {Icon && (
197
+ <span
198
+ aria-label={iconLabel}
199
+ style={{
200
+ display: 'inline-flex',
201
+ flexShrink: 0,
202
+ color,
203
+ // Nudge down so the glyph optically centres on the first text line.
204
+ marginTop: 3,
205
+ }}
206
+ >
207
+ <Icon size={16} strokeWidth={2.25} />
208
+ </span>
209
+ )}
210
+ </span>
211
+ {/* The technology row: the brand mark when we hold the official one, then
212
+ the technology. Right-aligned, the number of members the box groups. */}
213
+ <span
214
+ style={{
215
+ display: 'flex',
216
+ alignItems: 'center',
217
+ justifyContent: centered ? 'center' : 'space-between',
218
+ gap: 6,
219
+ fontFamily: theme.fonts.monospace,
220
+ fontSize: theme.fontSizes[0],
221
+ color: muted,
222
+ letterSpacing: 0.5,
223
+ textTransform: 'uppercase',
224
+ minWidth: 0,
225
+ // Pinned, like the label slot above it: an empty row would otherwise be
226
+ // zero-height and the description budget would have to guess which cards
227
+ // have a technology row. Empty stays zero — a person has no technology.
228
+ ...(hasTechRow ? { height: TECH_SLOT_H, flexShrink: 0 } : {}),
229
+ }}
230
+ >
231
+ {topLabel && (
232
+ <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
233
+ {brand && <TechMark brand={brand} />}
234
+ <span
235
+ style={{
236
+ fontWeight: 600,
237
+ whiteSpace: 'nowrap',
238
+ overflow: 'hidden',
239
+ textOverflow: 'ellipsis',
240
+ minWidth: 0,
241
+ }}
242
+ >
243
+ {topLabel}
244
+ </span>
245
+ </span>
246
+ )}
247
+ {count && (
248
+ <span
249
+ style={{
250
+ flexShrink: 0,
251
+ letterSpacing: 0,
252
+ display: 'inline-flex',
253
+ alignItems: 'center',
254
+ gap: 4,
255
+ }}
256
+ >
257
+ {count.value}
258
+ <count.Icon size={12} strokeWidth={2.25} />
259
+ </span>
260
+ )}
261
+ </span>
262
+ </>
263
+ );
264
+ }
@@ -31,15 +31,18 @@ export const GRAPH_NAV_PROPS = {
31
31
  } satisfies Partial<ReactFlowProps>;
32
32
 
33
33
  /**
34
- * React Flow mounts its edge SVG (`.react-flow__edges`) and node layer
35
- * (`.react-flow__nodes`) as sibling containers inside the viewport, both at
36
- * `z-index: auto`, and leans on DOM order (edges first, nodes second) to keep
37
- * nodes on top. Nodes carry an inline `z-index: 0`, which on its own does not
38
- * reliably beat the edge layer, so an edge routing into a boundary frame's top
39
- * border paints *over* that frame's label. Lift the whole node layer above the
40
- * edge layer once for every graph that spreads `GRAPH_NAV_PROPS`.
34
+ * Class on every canvas that spreads `GRAPH_NAV_PROPS`; scopes `GRAPH_LAYER_CSS`
35
+ * so it only touches our canvases.
41
36
  *
42
- * Scoped by `GRAPH_CANVAS_CLASS` so it only touches our canvases.
37
+ * Paint order rides React Flow's own per-element z-indices. The viewport is one
38
+ * stacking context holding the edge layer (one absolutely positioned `<svg>` per
39
+ * edge, `z-index` = the deepest nested endpoint's depth) and the node layer
40
+ * (each node `z-index` = its nesting depth, a child always one above its
41
+ * parent). Neither layer may be lifted as a whole: a boundary frame is a filled
42
+ * container card, so a line between two members has to paint *above* the frame
43
+ * that holds them yet *below* the member cards — and that is exactly the
44
+ * interleave the per-element indices give (edge depth ≥ frame depth, and at
45
+ * equal depth the node layer wins by DOM order).
43
46
  */
44
47
  export const GRAPH_CANVAS_CLASS = 'subsystem-graph-canvas';
45
48
 
@@ -60,7 +63,6 @@ export const LAYOUT_FLIP_EDGE_MS = 180;
60
63
  export const LAYOUT_FLIP_NODE_MS = 320;
61
64
 
62
65
  export const GRAPH_LAYER_CSS = `
63
- .${GRAPH_CANVAS_CLASS} .react-flow__nodes { z-index: 1; }
64
66
  .${GRAPH_CANVAS_CLASS} .react-flow__edges { transition: opacity ${LAYOUT_FLIP_EDGE_MS}ms ease; }
65
67
  .${LAYOUT_FLIP_CLASS} .react-flow__edges { opacity: 0; }
66
68
  .${LAYOUT_FLIP_CLASS} .react-flow__node { transition: transform ${LAYOUT_FLIP_NODE_MS}ms cubic-bezier(0.4, 0, 0.2, 1); }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * The drill-down morph — the vocabulary a graph uses to grow, shrink, slide and
3
+ * fade its boxes between two ELK layouts, shared by the C4 canvas and the
4
+ * component graph so a container animates the same way on either.
5
+ *
6
+ * Nothing here knows about a particular node type. A graph diffs two layouts
7
+ * (`diffLayoutRects`), stamps the result on its nodes as `MorphNodeData`, and
8
+ * each node view turns that into a position-only FLIP (`useFlip`) plus a fade
9
+ * (`useFade`) through `useMorphStyle`. Size is never animated here: a box that
10
+ * grows transitions its own `width`/`height`, so a scale on the wrapper would
11
+ * distort its text and fight that transition.
12
+ */
13
+
14
+ import { useEffect, useState } from 'react';
15
+ import type { CSSProperties } from 'react';
16
+
17
+ /** How long a box takes to glide and grow, in ms. */
18
+ export const MORPH_MS = 420;
19
+
20
+ /**
21
+ * How long boxes arriving or leaving take to fade, in ms. The morph is
22
+ * sequenced: the fade runs first, and the surviving boxes wait it out before
23
+ * they move and grow (`moveDelayMs`). So the reveal clock is
24
+ * `FADE_MS + MORPH_MS`, not just `MORPH_MS`.
25
+ */
26
+ export const FADE_MS = 200;
27
+
28
+ /** Flow-space rect of a box node or a frame. */
29
+ export interface FlowRect { x: number; y: number; width: number; height: number }
30
+
31
+ /** A box's travel for the morph: its flow rect before → after. */
32
+ export interface FrameGrow { from: FlowRect; to: FlowRect }
33
+
34
+ /** What a node carries so its view can take part in the morph. */
35
+ export interface MorphNodeData {
36
+ /** FLIP: absolute flow rects — where this box was, and where it now is. */
37
+ growFrom?: FlowRect;
38
+ frameRect?: FlowRect;
39
+ /** Arriving in this layout — fades in. */
40
+ entering?: boolean;
41
+ /** Gone from this layout — kept for the morph, fades out. */
42
+ leaving?: boolean;
43
+ /** The move/grow waits this long for the fade to finish, in ms. */
44
+ moveDelayMs?: number;
45
+ }
46
+
47
+ /** The slice of a laid-out graph the morph reads rects from. */
48
+ export interface MorphLayout {
49
+ nodes: ReadonlyArray<{
50
+ id: string;
51
+ position: { x: number; y: number };
52
+ parentId?: string;
53
+ width?: number | null;
54
+ height?: number | null;
55
+ }>;
56
+ /** Frame rects, already absolute. */
57
+ groupBounds: ReadonlyMap<string, FlowRect>;
58
+ }
59
+
60
+ /**
61
+ * A node's rect in **absolute** flow space, walking the parent chain.
62
+ *
63
+ * `groupBounds` is already absolute; a leaf's `position` is relative to its
64
+ * parent, so each ancestor's origin is added in turn.
65
+ *
66
+ * The FLIP needs absolute rects, not parent-relative ones. React Flow places a
67
+ * node at its new absolute position (parent origin + relative position) and
68
+ * moves children along with the parent's *wrapper* — while our FLIP transform
69
+ * lives on the node's inner div, which the children do not inherit. So a node's
70
+ * own transform must cover its full absolute delta; rebasing it to the parent
71
+ * would leave it short by exactly the parent's movement (the "subtle drift"
72
+ * before a leaving box disappears).
73
+ */
74
+ export function absoluteRectOf(layout: MorphLayout, id: string): FlowRect | null {
75
+ const frame = layout.groupBounds.get(id);
76
+ if (frame) return { x: frame.x, y: frame.y, width: frame.width, height: frame.height };
77
+ const node = layout.nodes.find((n) => n.id === id);
78
+ if (!node) return null;
79
+ const origin = node.parentId ? absoluteRectOf(layout, node.parentId) : null;
80
+ return {
81
+ x: (origin?.x ?? 0) + node.position.x,
82
+ y: (origin?.y ?? 0) + node.position.y,
83
+ width: node.width ?? 0,
84
+ height: node.height ?? 0,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Every box whose rect changes between two layouts, so frames *and* cards grow,
90
+ * shrink and slide together. `null` when nothing moved (e.g. the initial paint),
91
+ * so a caller can tell "no morph" from "a morph of nothing".
92
+ *
93
+ * Covers nested boxes too: rects are absolute (`absoluteRectOf`), so a child's
94
+ * transform covers its full delta rather than fighting its parent's wrapper.
95
+ */
96
+ export function diffLayoutRects(prev: MorphLayout, next: MorphLayout): Map<string, FrameGrow> | null {
97
+ const grows = new Map<string, FrameGrow>();
98
+ const ids = new Set([
99
+ ...prev.groupBounds.keys(),
100
+ ...next.groupBounds.keys(),
101
+ ...prev.nodes.map((n) => n.id),
102
+ ...next.nodes.map((n) => n.id),
103
+ ]);
104
+ for (const id of ids) {
105
+ const from = absoluteRectOf(prev, id);
106
+ const to = absoluteRectOf(next, id);
107
+ if (!from || !to) continue;
108
+ if (from.x === to.x && from.y === to.y && from.width === to.width && from.height === to.height) {
109
+ continue;
110
+ }
111
+ grows.set(id, { from, to });
112
+ }
113
+ return grows.size > 0 ? grows : null;
114
+ }
115
+
116
+ /**
117
+ * Whether committing a layout should also move the camera.
118
+ *
119
+ * A morph — a commit that has rects to FLIP from — must not. Every element
120
+ * already on screen is sliding from the rect the reader last saw it at, and that
121
+ * anchoring *is* the morph; a viewport move on top of it makes each card's
122
+ * on-screen path the sum of two independent animations, so nothing lands where
123
+ * the FLIP said it would.
124
+ *
125
+ * A commit with no `grows` is a genuine change: the first paint, a new system, a
126
+ * different element set, or the grid fallback after an ELK failure. There is no
127
+ * continuity to preserve there and the content may genuinely not be on screen, so
128
+ * fit. An *empty* map fits for the same reason — no element is anchoring, so there
129
+ * is nothing a camera move could contradict.
130
+ *
131
+ * @param grows the rects to animate from, exactly as the nodes received them.
132
+ */
133
+ export function shouldRefitCamera(grows: Map<string, FrameGrow> | null): boolean {
134
+ return !grows || grows.size === 0;
135
+ }
136
+
137
+ /**
138
+ * FLIP between two absolute flow rects: render transformed back onto `from`,
139
+ * then release onto `to`.
140
+ *
141
+ * The step back **must** happen while rendering, not in an effect. An effect runs
142
+ * after the browser has already painted, so the element is painted at its new
143
+ * position for one frame and only then jumps back — a visible teleport, which is
144
+ * the exact thing this hook exists to remove. Adjusting state during render lets
145
+ * React apply the transform in the same commit, so the new position is never
146
+ * painted untransformed.
147
+ *
148
+ * The rects are keyed by value: a graph mints fresh rect objects each layout, so
149
+ * comparing identity would re-fire the whole morph on unrelated re-renders.
150
+ */
151
+ export function useFlip(from: FlowRect | undefined, to: FlowRect | undefined) {
152
+ const key = from && to ? `${from.x},${from.y},${to.x},${to.y}` : '';
153
+ const [lastKey, setLastKey] = useState(key);
154
+ const [placed, setPlaced] = useState(!key);
155
+ if (key !== lastKey) {
156
+ setLastKey(key);
157
+ setPlaced(false);
158
+ }
159
+ useEffect(() => {
160
+ if (!key) return;
161
+ const raf = requestAnimationFrame(() => setPlaced(true));
162
+ return () => cancelAnimationFrame(raf);
163
+ }, [key]);
164
+ return {
165
+ flipping: key !== '',
166
+ placed,
167
+ dx: from && to ? from.x - to.x : 0,
168
+ dy: from && to ? from.y - to.y : 0,
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Opacity for a box arriving or leaving the layout. An arriving box mounts
174
+ * hidden and fades in; a leaving box is kept (out of the new layout) for the
175
+ * morph, then fades out — a removal reads as a fade, not a pop.
176
+ */
177
+ export function useFade(entering?: boolean, leaving?: boolean) {
178
+ const animate = entering === true || leaving === true;
179
+ const [shown, setShown] = useState(entering !== true);
180
+ useEffect(() => {
181
+ if (!animate) return;
182
+ const raf = requestAnimationFrame(() => setShown(leaving !== true));
183
+ return () => cancelAnimationFrame(raf);
184
+ }, [animate, entering, leaving]);
185
+ if (!animate) return { opacity: 1, transition: undefined as string | undefined };
186
+ return { opacity: shown ? 1 : 0, transition: `opacity ${FADE_MS}ms ease` };
187
+ }
188
+
189
+ /**
190
+ * The position-only morph for a node's wrapper: the FLIP slide and the fade, as
191
+ * inline style. Size is left to the node's own transition, so the two compose
192
+ * without either fighting the other.
193
+ *
194
+ * `transform: none` needs no transition, and a box that only changed *size* has
195
+ * nothing to slide — so neither is listed unless it is actually animating.
196
+ */
197
+ export function useMorphStyle(data: MorphNodeData): CSSProperties {
198
+ const { growFrom, frameRect, entering, leaving, moveDelayMs = 0 } = data;
199
+ const { flipping, placed, dx, dy } = useFlip(growFrom, frameRect);
200
+ const sliding = flipping && (dx !== 0 || dy !== 0);
201
+ const fade = useFade(entering, leaving);
202
+ const transitions = [
203
+ ...(fade.transition ? [fade.transition] : []),
204
+ ...(sliding && placed ? [`transform ${MORPH_MS}ms ease-out ${moveDelayMs}ms`] : []),
205
+ ];
206
+ return {
207
+ transformOrigin: 'top left',
208
+ transform: sliding && !placed ? `translate(${dx}px, ${dy}px)` : 'none',
209
+ transition: transitions.length > 0 ? transitions.join(', ') : 'none',
210
+ opacity: fade.opacity,
211
+ };
212
+ }
@@ -0,0 +1,128 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { buildSubsystemGraph, collapseBoundaryGroups, type BoundaryLayoutGroup, type SubsystemGraphEdge, type SubsystemGraphNode, type SubsystemProcessRegion } from './model';
3
+ import { NODE_H, NODE_W } from './containerCard';
4
+
5
+ function region(kind: SubsystemProcessRegion['kind'], key: string, members: string[]): SubsystemProcessRegion {
6
+ return { kind, key, label: key, memberAliases: members } as SubsystemProcessRegion;
7
+ }
8
+ function leaf(id: string, parentId?: string): SubsystemGraphNode {
9
+ return {
10
+ id,
11
+ type: 'subsystem-component',
12
+ position: { x: 0, y: 0 },
13
+ data: {} as never,
14
+ ...(parentId ? { parentId } : {}),
15
+ } as SubsystemGraphNode;
16
+ }
17
+ function edge(from: string, to: string, mechanism = 'calls'): SubsystemGraphEdge {
18
+ return {
19
+ id: `${from}--${mechanism}-->${to}`,
20
+ source: from,
21
+ target: to,
22
+ data: { mechanism, refs: [`${from}:${to}`] } as never,
23
+ } as SubsystemGraphEdge;
24
+ }
25
+
26
+ // package P holds process A (a1, a2) and leaf p1; process B (b1) stands alone.
27
+ const groups: BoundaryLayoutGroup[] = [
28
+ { id: 'package:P', region: region('package', 'P', ['a1', 'a2', 'p1']), memberAliases: ['process:A', 'p1'] },
29
+ { id: 'process:A', region: region('process', 'A', ['a1', 'a2']), memberAliases: ['a1', 'a2'], parentId: 'package:P' },
30
+ { id: 'process:B', region: region('process', 'B', ['b1']), memberAliases: ['b1'] },
31
+ { id: 'module:m', region: region('module', 'm', ['b1']), memberAliases: ['b1'], parentId: 'process:B' },
32
+ ];
33
+ const nodes = [leaf('a1', 'process:A'), leaf('a2', 'process:A'), leaf('p1', 'package:P'), leaf('b1', 'module:m')];
34
+ const edges = [edge('a1', 'a2'), edge('a1', 'b1'), edge('a2', 'b1'), edge('a2', 'b1', 'uses'), edge('p1', 'a1'), edge('b1', 'p1')];
35
+
36
+ describe('collapseBoundaryGroups', () => {
37
+ test('nothing collapsed → inputs pass through', () => {
38
+ const out = collapseBoundaryGroups(nodes, edges, groups, new Set());
39
+ expect(out.nodes).toHaveLength(4);
40
+ expect(out.edges).toHaveLength(6);
41
+ expect(out.collapsedRegions).toEqual([]);
42
+ });
43
+
44
+ test('a module id is ignored — only card frames collapse', () => {
45
+ const out = collapseBoundaryGroups(nodes, edges, groups, new Set(['module:m']));
46
+ expect(out.nodes).toHaveLength(4);
47
+ expect(out.groups).toHaveLength(4);
48
+ });
49
+
50
+ test('a collapsed process becomes a card, its members leave, lines roll up', () => {
51
+ const out = collapseBoundaryGroups(nodes, edges, groups, new Set(['process:A']));
52
+ const ids = out.nodes.map((n) => n.id).sort();
53
+ expect(ids).toEqual(['b1', 'p1', 'process:A']);
54
+ const card = out.nodes.find((n) => n.id === 'process:A')!;
55
+ expect(card.type).toBe('subsystem-group');
56
+ expect(card.width).toBe(NODE_W);
57
+ expect(card.height).toBe(NODE_H);
58
+ expect(card.parentId).toBe('package:P');
59
+ expect((card.data as { collapsed?: boolean }).collapsed).toBe(true);
60
+ // The card is no longer an ELK parent; the package now holds the card.
61
+ expect(out.groups.map((g) => g.id)).toEqual(['package:P', 'process:B', 'module:m']);
62
+ expect(out.groups[0]!.memberAliases).toEqual(['process:A', 'p1']);
63
+ expect(out.collapsedRegions.map((r) => r.key)).toEqual(['A']);
64
+
65
+ const byId = new Map(out.edges.map((e) => [e.id, e]));
66
+ // a1→a2 was internal: gone.
67
+ expect(byId.has('a1--calls-->a2')).toBe(false);
68
+ // a1→b1 and a2→b1 fold to one `calls` line; a2→b1 `uses` stays its own.
69
+ const calls = byId.get('process:A--calls-->b1')!;
70
+ expect(calls.data?.rolledUp).toBe(2);
71
+ expect(calls.data?.rolledUpIds).toEqual(['a1--calls-->b1', 'a2--calls-->b1']);
72
+ expect(calls.data?.refs).toEqual(['a1:b1', 'a2:b1']);
73
+ expect(byId.get('process:A--uses-->b1')?.data?.rolledUp).toBe(1);
74
+ // p1→a1 re-targets the card; b1→p1 is untouched and keeps its id.
75
+ expect(byId.get('p1--calls-->process:A')?.target).toBe('process:A');
76
+ expect(byId.get('b1--calls-->p1')?.data?.rolledUp).toBeUndefined();
77
+ expect(out.edges).toHaveLength(4);
78
+ });
79
+
80
+ test('a collapsed package swallows the process nested inside it', () => {
81
+ const out = collapseBoundaryGroups(nodes, edges, groups, new Set(['package:P', 'process:A']));
82
+ expect(out.nodes.map((n) => n.id).sort()).toEqual(['b1', 'package:P']);
83
+ const card = out.nodes.find((n) => n.id === 'package:P')!;
84
+ expect(card.parentId).toBeUndefined();
85
+ expect(out.groups.map((g) => g.id)).toEqual(['process:B', 'module:m']);
86
+ expect(out.collapsedRegions.map((r) => r.key)).toEqual(['P']);
87
+ const ids = out.edges.map((e) => e.id).sort();
88
+ expect(ids).toEqual(['b1--calls-->package:P', 'package:P--calls-->b1', 'package:P--uses-->b1']);
89
+ });
90
+
91
+ test('does not mutate its inputs', () => {
92
+ const before = JSON.stringify({ nodes, edges, groups });
93
+ collapseBoundaryGroups(nodes, edges, groups, new Set(['package:P']));
94
+ expect(JSON.stringify({ nodes, edges, groups })).toBe(before);
95
+ });
96
+ });
97
+
98
+ describe('buildSubsystemGraph collapsed frames', () => {
99
+ const doc = {
100
+ components: [
101
+ { alias: 'a1', name: 'a1', construct: 'function', file: 'a1.ts', purl: 'pkg:github/acme/app', process: 'A' },
102
+ { alias: 'a2', name: 'a2', construct: 'function', file: 'a2.ts', purl: 'pkg:github/acme/app', process: 'A' },
103
+ { alias: 'b1', name: 'b1', construct: 'function', file: 'b1.ts', purl: 'pkg:github/acme/app', process: 'B' },
104
+ { alias: 'b2', name: 'b2', construct: 'function', file: 'b2.ts', purl: 'pkg:github/acme/app', process: 'B' },
105
+ ],
106
+ trails: [{ id: 't', title: 't', steps: [{ from: 'a1', to: 'b1', mechanism: 'calls' }, { from: 'a2', to: 'b2', mechanism: 'calls' }] }],
107
+ } as unknown as Parameters<typeof buildSubsystemGraph>[0];
108
+ const groupIds = (nodes: readonly SubsystemGraphNode[]) =>
109
+ nodes.filter((n) => n.type === 'subsystem-group').map((n) => [n.id, (n.data as { collapsed?: boolean }).collapsed === true]);
110
+
111
+ test('cardFramesCollapsed closes every card frame', async () => {
112
+ const built = await buildSubsystemGraph(doc, { cardFramesCollapsed: true });
113
+ expect(groupIds(built.nodes).sort()).toEqual([['process:A', true], ['process:B', true]]);
114
+ expect(built.nodes.some((n) => n.type === 'subsystem-component')).toBe(false);
115
+ expect(built.edges.map((e) => [e.source, e.target, e.data?.rolledUp])).toEqual([['process:A', 'process:B', 2]]);
116
+ expect(built.regions.map((r) => r.key).sort()).toEqual(['A', 'B']);
117
+ });
118
+
119
+ test('with cardFramesCollapsed the toggled set names the open frames', async () => {
120
+ const built = await buildSubsystemGraph(doc, { cardFramesCollapsed: true, collapsedGroupIds: new Set(['process:A']) });
121
+ expect(groupIds(built.nodes).sort()).toEqual([['process:A', false], ['process:B', true]]);
122
+ });
123
+
124
+ test('without it the toggled set names the closed frames', async () => {
125
+ const built = await buildSubsystemGraph(doc, { collapsedGroupIds: new Set(['process:A']) });
126
+ expect(groupIds(built.nodes).sort()).toEqual([['process:A', true], ['process:B', false]]);
127
+ });
128
+ });