@transitrix/diagrams 1.5.0 → 1.6.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 (79) hide show
  1. package/dist/capability-map/CapabilityCardNode.d.ts +19 -0
  2. package/dist/capability-map/CapabilityCardNode.js +66 -0
  3. package/dist/capability-map/CapabilityMapView.d.ts +59 -0
  4. package/dist/capability-map/CapabilityMapView.js +204 -0
  5. package/dist/capability-map/CapabilityRootNode.d.ts +12 -0
  6. package/dist/capability-map/CapabilityRootNode.js +23 -0
  7. package/dist/capability-map/__tests__/CapabilityMapView.test.d.ts +1 -0
  8. package/dist/capability-map/__tests__/CapabilityMapView.test.js +217 -0
  9. package/dist/capability-map/__tests__/address.test.d.ts +1 -0
  10. package/dist/capability-map/__tests__/address.test.js +49 -0
  11. package/dist/capability-map/__tests__/dsm-layout.test.d.ts +1 -0
  12. package/dist/capability-map/__tests__/dsm-layout.test.js +46 -0
  13. package/dist/capability-map/__tests__/dsm-mutations.test.d.ts +1 -0
  14. package/dist/capability-map/__tests__/dsm-mutations.test.js +125 -0
  15. package/dist/capability-map/__tests__/dsm-validate.test.d.ts +1 -0
  16. package/dist/capability-map/__tests__/dsm-validate.test.js +56 -0
  17. package/dist/capability-map/address.d.ts +12 -0
  18. package/dist/capability-map/address.js +48 -0
  19. package/dist/capability-map/dsm-layout.d.ts +9 -0
  20. package/dist/capability-map/dsm-layout.js +125 -0
  21. package/dist/capability-map/dsm-mutations.d.ts +28 -0
  22. package/dist/capability-map/dsm-mutations.js +196 -0
  23. package/dist/capability-map/dsm-schema.d.ts +71 -0
  24. package/dist/capability-map/dsm-schema.js +14 -0
  25. package/dist/capability-map/dsm-theme.d.ts +20 -0
  26. package/dist/capability-map/dsm-theme.js +36 -0
  27. package/dist/capability-map/dsm-validate.d.ts +2 -0
  28. package/dist/capability-map/dsm-validate.js +93 -0
  29. package/dist/capability-map/index.d.ts +9 -0
  30. package/dist/capability-map/index.js +6 -0
  31. package/dist/compliance/__tests__/trace.test.d.ts +1 -0
  32. package/dist/compliance/__tests__/trace.test.js +144 -0
  33. package/dist/compliance/classify.js +7 -1
  34. package/dist/compliance/index.d.ts +2 -1
  35. package/dist/compliance/index.js +1 -0
  36. package/dist/compliance/reverse-index.js +4 -1
  37. package/dist/compliance/trace.d.ts +26 -0
  38. package/dist/compliance/trace.js +89 -0
  39. package/dist/compliance/types.d.ts +94 -1
  40. package/dist/goals/GoalNode.d.ts +18 -0
  41. package/dist/goals/GoalNode.js +91 -0
  42. package/dist/goals/GoalTreeView.d.ts +57 -0
  43. package/dist/goals/GoalTreeView.js +228 -0
  44. package/dist/goals/__tests__/GoalTreeView.test.d.ts +1 -0
  45. package/dist/goals/__tests__/GoalTreeView.test.js +296 -0
  46. package/dist/goals/index.d.ts +3 -0
  47. package/dist/goals/index.js +1 -0
  48. package/dist/goals/theme.d.ts +22 -0
  49. package/dist/goals/theme.js +32 -0
  50. package/dist/index.d.ts +2 -1
  51. package/dist/index.js +1 -1
  52. package/package.json +4 -1
  53. package/src/capability-map/CapabilityCardNode.tsx +146 -0
  54. package/src/capability-map/CapabilityMapView.tsx +331 -0
  55. package/src/capability-map/CapabilityRootNode.tsx +38 -0
  56. package/src/capability-map/__tests__/CapabilityMapView.test.tsx +232 -0
  57. package/src/capability-map/__tests__/address.test.ts +59 -0
  58. package/src/capability-map/__tests__/dsm-layout.test.ts +52 -0
  59. package/src/capability-map/__tests__/dsm-mutations.test.ts +141 -0
  60. package/src/capability-map/__tests__/dsm-validate.test.ts +65 -0
  61. package/src/capability-map/address.ts +48 -0
  62. package/src/capability-map/dsm-layout.ts +142 -0
  63. package/src/capability-map/dsm-mutations.ts +208 -0
  64. package/src/capability-map/dsm-schema.ts +80 -0
  65. package/src/capability-map/dsm-theme.ts +53 -0
  66. package/src/capability-map/dsm-validate.ts +103 -0
  67. package/src/capability-map/index.ts +35 -0
  68. package/src/compliance/__tests__/trace.test.ts +157 -0
  69. package/src/compliance/classify.ts +7 -1
  70. package/src/compliance/index.ts +6 -0
  71. package/src/compliance/reverse-index.ts +3 -1
  72. package/src/compliance/trace.ts +118 -0
  73. package/src/compliance/types.ts +101 -1
  74. package/src/goals/GoalNode.tsx +212 -0
  75. package/src/goals/GoalTreeView.tsx +350 -0
  76. package/src/goals/__tests__/GoalTreeView.test.tsx +313 -0
  77. package/src/goals/index.ts +4 -0
  78. package/src/goals/theme.ts +54 -0
  79. package/src/index.ts +29 -1
@@ -0,0 +1,331 @@
1
+ import React, { useCallback, useMemo, useState, useEffect } from 'react';
2
+ import ReactFlow, {
3
+ Controls,
4
+ MiniMap,
5
+ Background,
6
+ Panel,
7
+ ConnectionLineType,
8
+ useNodesState,
9
+ useEdgesState,
10
+ type Node,
11
+ type Edge,
12
+ type NodeMouseHandler,
13
+ type NodeDragHandler,
14
+ } from 'reactflow';
15
+ import 'reactflow/dist/style.css';
16
+ import type { Capability, CapabilityMap, CapabilityMapLayout, LayoutOptions } from './dsm-schema.js';
17
+ import { layoutCapabilityMap } from './dsm-layout.js';
18
+ import { reparent, addChild, deleteWithDescendants, moveBranchToBacklog, restoreFromBacklog, normaliseAddresses } from './dsm-mutations.js';
19
+ import type { ThemeTokens } from './dsm-theme.js';
20
+ import { resolveTheme, DEFAULT_MATURITY_COLOURS } from './dsm-theme.js';
21
+ import CapabilityCardNode, { type CapabilityCardNodeData } from './CapabilityCardNode.js';
22
+ import CapabilityRootNode, { type CapabilityRootNodeData } from './CapabilityRootNode.js';
23
+
24
+ export type { ThemeTokens } from './dsm-theme.js';
25
+
26
+ export interface CapabilityMapViewProps {
27
+ map: CapabilityMap;
28
+ layout?: CapabilityMapLayout;
29
+ layoutOptions?: LayoutOptions;
30
+ theme?: ThemeTokens;
31
+ readOnly?: boolean;
32
+ showBacklog?: boolean;
33
+ showMiniMap?: boolean;
34
+ maturityColours?: Record<number, string>;
35
+ selectedSet?: string;
36
+ onChange?: (event: CapabilityMapChange) => void;
37
+ onEditRequest?: (cap: Capability) => void;
38
+ }
39
+
40
+ export type CapabilityMapChange =
41
+ | { kind: 'reparent'; sourceId: number; targetId: number; result: CapabilityMap }
42
+ | { kind: 'addChild'; parentId: number; newCap: Capability; result: CapabilityMap }
43
+ | { kind: 'delete'; id: number; result: CapabilityMap }
44
+ | { kind: 'moveBranchToBacklog'; id: number; result: CapabilityMap }
45
+ | { kind: 'restoreFromBacklog'; id: number; parentId: number; result: CapabilityMap }
46
+ | { kind: 'normaliseAddresses'; result: CapabilityMap };
47
+
48
+ const BACKLOG_DRAG_MIME = 'application/x-transitrix-capability-id';
49
+ const ROOT_NODE_ID = '__root__';
50
+ const nodeTypes = { capabilityCard: CapabilityCardNode, capabilityRoot: CapabilityRootNode };
51
+
52
+ /** Where a card was dropped, as classified from the pointer position at
53
+ * drag-stop — mirrors goals' computeDragOutcome split (see GoalTreeView.tsx)
54
+ * so the reparent/moveBranchToBacklog decision is unit-testable without a
55
+ * live drag through reactflow's DOM-measurement-gated dragging. */
56
+ export type DropTarget = { kind: 'node'; id: number } | { kind: 'root' } | { kind: 'backlog' } | null;
57
+
58
+ export function computeDragOutcome(map: CapabilityMap, sourceId: number, dropTarget: DropTarget): CapabilityMapChange | null {
59
+ if (!dropTarget) return null;
60
+ if (dropTarget.kind === 'backlog') {
61
+ const mutation = moveBranchToBacklog(map, sourceId);
62
+ if (!mutation.ok || !mutation.result) return null;
63
+ return { kind: 'moveBranchToBacklog', id: sourceId, result: mutation.result };
64
+ }
65
+ const targetId = dropTarget.kind === 'root' ? 0 : dropTarget.id;
66
+ if (targetId === sourceId) return null;
67
+ const mutation = reparent(map, sourceId, targetId);
68
+ if (!mutation.ok || !mutation.result) return null;
69
+ return { kind: 'reparent', sourceId, targetId, result: mutation.result };
70
+ }
71
+
72
+ function CapabilityMapViewInner({
73
+ map,
74
+ layout: layoutProp,
75
+ layoutOptions,
76
+ theme: themeProp,
77
+ readOnly = false,
78
+ showBacklog = false,
79
+ showMiniMap = false,
80
+ maturityColours = DEFAULT_MATURITY_COLOURS,
81
+ onChange,
82
+ onEditRequest,
83
+ }: CapabilityMapViewProps): React.ReactElement {
84
+ const theme = useMemo(() => resolveTheme(themeProp), [themeProp]);
85
+ const [collapsedIds, setCollapsedIds] = useState<Set<number>>(new Set());
86
+ const [hoveredId, setHoveredId] = useState<number | 'root' | null>(null);
87
+
88
+ const backlogCaps = useMemo(() => map.capabilities.filter((c) => c.backlog), [map.capabilities]);
89
+
90
+ const layout = useMemo<CapabilityMapLayout>(() => {
91
+ if (layoutProp) return layoutProp;
92
+ const hideCollapsed = [...(layoutOptions?.hideCollapsed ?? []), ...collapsedIds];
93
+ return layoutCapabilityMap(map, { ...layoutOptions, hideCollapsed });
94
+ }, [layoutProp, layoutOptions, collapsedIds, map]);
95
+
96
+ const rootLabel = layoutOptions?.organisationLabel ?? map.organisation;
97
+
98
+ const onAddChild = useCallback(
99
+ (parentId: number) => {
100
+ if (readOnly) return;
101
+ const before = new Set(map.capabilities.map((c) => c.id));
102
+ const mutation = addChild(map, parentId, { name: 'New capability' });
103
+ if (!mutation.ok || !mutation.result) return;
104
+ const newCap = mutation.result.capabilities.find((c) => !before.has(c.id));
105
+ if (!newCap) return;
106
+ onChange?.({ kind: 'addChild', parentId, newCap, result: mutation.result });
107
+ },
108
+ [map, readOnly, onChange],
109
+ );
110
+
111
+ const onDeleteNode = useCallback(
112
+ (id: number) => {
113
+ if (readOnly) return;
114
+ const mutation = deleteWithDescendants(map, id);
115
+ if (!mutation.ok || !mutation.result) return;
116
+ onChange?.({ kind: 'delete', id, result: mutation.result });
117
+ },
118
+ [map, readOnly, onChange],
119
+ );
120
+
121
+ const onRestoreFromBacklog = useCallback(
122
+ (id: number, parentId: number) => {
123
+ if (readOnly) return;
124
+ const mutation = restoreFromBacklog(map, id, parentId);
125
+ if (!mutation.ok || !mutation.result) return;
126
+ onChange?.({ kind: 'restoreFromBacklog', id, parentId, result: mutation.result });
127
+ },
128
+ [map, readOnly, onChange],
129
+ );
130
+
131
+ const onNormalise = useCallback(() => {
132
+ if (readOnly) return;
133
+ onChange?.({ kind: 'normaliseAddresses', result: normaliseAddresses(map) });
134
+ }, [map, readOnly, onChange]);
135
+
136
+ const onToggleCollapse = useCallback((id: number) => {
137
+ setCollapsedIds((prev) => {
138
+ const next = new Set(prev);
139
+ if (next.has(id)) next.delete(id);
140
+ else next.add(id);
141
+ return next;
142
+ });
143
+ }, []);
144
+
145
+ const buildNodes = useCallback((): Node[] => {
146
+ const rootNode: Node<CapabilityRootNodeData> = {
147
+ id: ROOT_NODE_ID,
148
+ type: 'capabilityRoot',
149
+ position: { x: layout.rootNode.x, y: layout.rootNode.y },
150
+ draggable: false,
151
+ data: { label: rootLabel, theme },
152
+ };
153
+ const cardNodes: Node<CapabilityCardNodeData>[] = layout.nodes.map((n) => ({
154
+ id: String(n.id),
155
+ type: 'capabilityCard',
156
+ position: { x: n.x, y: n.y },
157
+ draggable: !readOnly,
158
+ data: {
159
+ capability: n.data!,
160
+ theme,
161
+ maturityColours,
162
+ readOnly,
163
+ isDropTarget: hoveredId === n.id,
164
+ hasHiddenChildren: n.hasHiddenChildren,
165
+ isCollapsed: collapsedIds.has(n.id),
166
+ onAddChild,
167
+ onDelete: onDeleteNode,
168
+ onToggleCollapse,
169
+ },
170
+ }));
171
+ return [rootNode, ...cardNodes];
172
+ }, [layout, theme, rootLabel, readOnly, hoveredId, collapsedIds, maturityColours, onAddChild, onDeleteNode, onToggleCollapse]);
173
+
174
+ const buildEdges = useCallback((): Edge[] => {
175
+ return layout.edges.map((e) => ({
176
+ id: `e${e.source}-${e.target}`,
177
+ source: e.source === 'root' ? ROOT_NODE_ID : String(e.source),
178
+ target: String(e.target),
179
+ type: 'default',
180
+ style: { stroke: theme.edgeColor, strokeWidth: theme.edgeWidth },
181
+ }));
182
+ }, [layout.edges, theme]);
183
+
184
+ const [nodes, setNodes, onNodesChange] = useNodesState(buildNodes());
185
+ const [edges, setEdges, onEdgesChange] = useEdgesState(buildEdges());
186
+
187
+ useEffect(() => {
188
+ setNodes(buildNodes());
189
+ setEdges(buildEdges());
190
+ // eslint-disable-next-line react-hooks/exhaustive-deps
191
+ }, [layout, theme, readOnly, hoveredId, collapsedIds, maturityColours]);
192
+
193
+ const checkIntersection = useCallback((a: Node, b: Node): boolean => {
194
+ const midX = a.position.x + 125;
195
+ const midY = a.position.y + 32;
196
+ return midX > b.position.x && midX < b.position.x + 250 && midY > b.position.y && midY < b.position.y + 64;
197
+ }, []);
198
+
199
+ const onNodeDrag: NodeDragHandler = useCallback(
200
+ (_event, node) => {
201
+ if (readOnly) return;
202
+ const hit = nodes.find((n) => n.id !== node.id && checkIntersection(node, n));
203
+ if (!hit) {
204
+ setHoveredId(null);
205
+ } else {
206
+ setHoveredId(hit.id === ROOT_NODE_ID ? 'root' : Number(hit.id));
207
+ }
208
+ },
209
+ [readOnly, nodes, checkIntersection],
210
+ );
211
+
212
+ const onNodeDragStop: NodeDragHandler = useCallback(
213
+ (event, node) => {
214
+ if (readOnly) {
215
+ setHoveredId(null);
216
+ return;
217
+ }
218
+ const sourceId = Number(node.id);
219
+ const mouseEvent = event as unknown as MouseEvent;
220
+ const dropEl = typeof document !== 'undefined' && 'clientX' in mouseEvent
221
+ ? document.elementFromPoint(mouseEvent.clientX, mouseEvent.clientY)
222
+ : null;
223
+ let dropTarget: DropTarget;
224
+ if (dropEl?.closest('[data-capmap-backlog-zone]')) dropTarget = { kind: 'backlog' };
225
+ else if (hoveredId === 'root') dropTarget = { kind: 'root' };
226
+ else if (hoveredId != null) dropTarget = { kind: 'node', id: hoveredId };
227
+ else dropTarget = null;
228
+ const change = computeDragOutcome(map, sourceId, dropTarget);
229
+ if (change) onChange?.(change);
230
+ setHoveredId(null);
231
+ },
232
+ [readOnly, hoveredId, map, onChange],
233
+ );
234
+
235
+ const onNodeDoubleClick: NodeMouseHandler = useCallback(
236
+ (_event, node) => {
237
+ const cap = map.capabilities.find((c) => c.id === Number(node.id));
238
+ if (cap) onEditRequest?.(cap);
239
+ },
240
+ [map.capabilities, onEditRequest],
241
+ );
242
+
243
+ const onBacklogItemDragStart = useCallback((event: React.DragEvent, capId: number) => {
244
+ event.dataTransfer.setData(BACKLOG_DRAG_MIME, String(capId));
245
+ event.dataTransfer.effectAllowed = 'move';
246
+ }, []);
247
+
248
+ const onCanvasDragOver = useCallback(
249
+ (event: React.DragEvent) => {
250
+ if (readOnly) return;
251
+ event.preventDefault();
252
+ },
253
+ [readOnly],
254
+ );
255
+
256
+ const onCanvasDrop = useCallback(
257
+ (event: React.DragEvent) => {
258
+ if (readOnly) return;
259
+ event.preventDefault();
260
+ const idStr = event.dataTransfer.getData(BACKLOG_DRAG_MIME);
261
+ if (!idStr) return;
262
+ const capId = Number(idStr);
263
+ const targetEl = document.elementFromPoint(event.clientX, event.clientY);
264
+ const nodeEl = targetEl?.closest('.react-flow__node');
265
+ const targetIdAttr = nodeEl?.getAttribute('data-id');
266
+ if (targetIdAttr == null) return;
267
+ const parentId = targetIdAttr === ROOT_NODE_ID ? 0 : Number(targetIdAttr);
268
+ onRestoreFromBacklog(capId, parentId);
269
+ },
270
+ [readOnly, onRestoreFromBacklog],
271
+ );
272
+
273
+ const showBacklogPanel = showBacklog && backlogCaps.length > 0;
274
+
275
+ return (
276
+ <div style={{ display: 'flex', width: '100%', height: '100%' }}>
277
+ {showBacklogPanel && (
278
+ <div
279
+ data-capmap-backlog-zone
280
+ style={{ width: 220, flexShrink: 0, borderRight: '1px solid #e2e8f0', padding: 10, overflowY: 'auto', background: '#f8fafc' }}
281
+ >
282
+ <div style={{ fontWeight: 700, fontSize: 12, color: '#334155', marginBottom: 8 }}>Backlog</div>
283
+ {backlogCaps.map((cap) => (
284
+ <div
285
+ key={cap.id}
286
+ draggable={!readOnly}
287
+ onDragStart={(e) => onBacklogItemDragStart(e, cap.id)}
288
+ onDoubleClick={() => onEditRequest?.(cap)}
289
+ title="Drag onto a card (or the root) to set its parent"
290
+ style={{ padding: 8, marginBottom: 6, background: '#ffffff', border: '1px solid #cbd5e1', borderRadius: 6, fontSize: 11, cursor: readOnly ? 'default' : 'grab' }}
291
+ >
292
+ <div style={{ fontWeight: 600 }}>{cap.name}</div>
293
+ </div>
294
+ ))}
295
+ </div>
296
+ )}
297
+
298
+ <div style={{ flex: 1, position: 'relative' }} onDragOver={onCanvasDragOver} onDrop={onCanvasDrop}>
299
+ <ReactFlow
300
+ nodes={nodes}
301
+ edges={edges}
302
+ onNodesChange={readOnly ? undefined : onNodesChange}
303
+ onEdgesChange={readOnly ? undefined : onEdgesChange}
304
+ nodeTypes={nodeTypes}
305
+ nodesDraggable={!readOnly}
306
+ nodesConnectable={false}
307
+ onNodeDrag={onNodeDrag}
308
+ onNodeDragStop={onNodeDragStop}
309
+ onNodeDoubleClick={onNodeDoubleClick}
310
+ connectionLineType={ConnectionLineType.Bezier}
311
+ fitView
312
+ >
313
+ <Background />
314
+ <Controls />
315
+ {showMiniMap && <MiniMap pannable zoomable />}
316
+ {!readOnly && (
317
+ <Panel position="top-right">
318
+ <button type="button" onClick={onNormalise} style={{ fontSize: 11, padding: '4px 8px', cursor: 'pointer' }}>
319
+ Normalise addresses
320
+ </button>
321
+ </Panel>
322
+ )}
323
+ </ReactFlow>
324
+ </div>
325
+ </div>
326
+ );
327
+ }
328
+
329
+ export function CapabilityMapView(props: CapabilityMapViewProps): React.ReactElement {
330
+ return <CapabilityMapViewInner {...props} />;
331
+ }
@@ -0,0 +1,38 @@
1
+ import React, { memo } from 'react';
2
+ import { Handle, Position } from 'reactflow';
3
+ import type { ThemeTokens } from './dsm-theme.js';
4
+
5
+ export interface CapabilityRootNodeData {
6
+ label: string;
7
+ theme: Required<ThemeTokens>;
8
+ }
9
+
10
+ /** The virtual organisation root — single node, no maturity dot, no
11
+ * add/delete/collapse affordances (it isn't a mutable Capability). */
12
+ const CapabilityRootNode = memo(({ data }: { data: CapabilityRootNodeData }) => (
13
+ <div
14
+ style={{
15
+ width: 200,
16
+ height: 64,
17
+ background: data.theme.rootFill,
18
+ color: data.theme.rootTextColor,
19
+ borderRadius: 8,
20
+ border: `1px solid ${data.theme.cardBorderColor}`,
21
+ boxShadow: '0 1px 4px rgba(0,0,0,0.12)',
22
+ display: 'flex',
23
+ alignItems: 'center',
24
+ justifyContent: 'center',
25
+ textAlign: 'center',
26
+ fontWeight: 700,
27
+ fontSize: 12,
28
+ padding: '4px 10px',
29
+ }}
30
+ >
31
+ <Handle type="source" position={Position.Right} style={{ opacity: 0 }} />
32
+ {data.label}
33
+ </div>
34
+ ));
35
+
36
+ CapabilityRootNode.displayName = 'CapabilityRootNode';
37
+
38
+ export default CapabilityRootNode;
@@ -0,0 +1,232 @@
1
+ // @vitest-environment jsdom
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
3
+ import React from 'react';
4
+ import { render, screen, cleanup, waitFor } from '@testing-library/react';
5
+ import { CapabilityMapView, computeDragOutcome } from '../CapabilityMapView.js';
6
+ import type { CapabilityMap } from '../dsm-schema.js';
7
+ import type { CapabilityMapChange } from '../CapabilityMapView.js';
8
+
9
+ // See goals/__tests__/GoalTreeView.test.tsx for why these three shims are
10
+ // needed — reactflow keeps a node `visibility: hidden` (and inert to
11
+ // drag/measurement logic) until ResizeObserver reports its size, and reads
12
+ // the computed transform back out via DOMMatrixReadOnly; jsdom has neither.
13
+ class MockResizeObserver {
14
+ #callback: ResizeObserverCallback;
15
+ constructor(callback: ResizeObserverCallback) {
16
+ this.#callback = callback;
17
+ }
18
+ observe(target: Element) {
19
+ queueMicrotask(() => {
20
+ this.#callback([{ target, contentRect: target.getBoundingClientRect() } as ResizeObserverEntry], this as unknown as ResizeObserver);
21
+ });
22
+ }
23
+ unobserve() {}
24
+ disconnect() {}
25
+ }
26
+
27
+ class MockDOMMatrixReadOnly {
28
+ m41 = 0;
29
+ m42 = 0;
30
+ constructor(transform?: string) {
31
+ if (!transform || transform === 'none') return;
32
+ const t = /translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/.exec(transform);
33
+ if (t) {
34
+ this.m41 = Number(t[1]);
35
+ this.m42 = Number(t[2]);
36
+ }
37
+ }
38
+ }
39
+
40
+ function makeMap(): CapabilityMap {
41
+ return {
42
+ organisation: 'Acme Corp',
43
+ set_id: 'v1.0',
44
+ capabilities: [
45
+ { id: 1, name: 'Customer Acquisition', address: '1.0.0', maturity: [{ date: '2026-04-01', level: 3 }] },
46
+ { id: 2, name: 'Lead Qualification', address: '1.1.0' },
47
+ { id: 3, name: 'Inbound Lead Scoring', address: '1.1.1' },
48
+ ],
49
+ };
50
+ }
51
+
52
+ beforeEach(() => {
53
+ (global as unknown as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
54
+ (window as unknown as { DOMMatrixReadOnly: unknown }).DOMMatrixReadOnly = MockDOMMatrixReadOnly;
55
+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
56
+ const isNode = this.classList?.contains('react-flow__node');
57
+ const width = isNode ? 250 : 1000;
58
+ const height = isNode ? 64 : 800;
59
+ return { width, height, top: 0, left: 0, right: width, bottom: height, x: 0, y: 0, toJSON() { return this; } } as DOMRect;
60
+ });
61
+ });
62
+
63
+ afterEach(() => {
64
+ cleanup();
65
+ vi.restoreAllMocks();
66
+ });
67
+
68
+ describe('CapabilityMapView', () => {
69
+ it('renders the virtual root and every on-diagram capability', async () => {
70
+ render(<CapabilityMapView map={makeMap()} />);
71
+ await waitFor(() => {
72
+ expect(screen.getByText('Acme Corp')).toBeTruthy();
73
+ expect(screen.getByText('Customer Acquisition')).toBeTruthy();
74
+ expect(screen.getByText('Lead Qualification')).toBeTruthy();
75
+ expect(screen.getByText('Inbound Lead Scoring')).toBeTruthy();
76
+ });
77
+ });
78
+
79
+ it('renders a maturity dot only for capabilities with a maturity snapshot', async () => {
80
+ render(<CapabilityMapView map={makeMap()} />);
81
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
82
+ expect(screen.getByLabelText('Maturity 3')).toBeTruthy();
83
+ expect(screen.queryByLabelText(/Maturity/, { selector: '[aria-label="Maturity undefined"]' })).toBeNull();
84
+ });
85
+
86
+ it('shows backlog capabilities in the sidebar, not on canvas', async () => {
87
+ const map: CapabilityMap = {
88
+ organisation: 'Acme Corp',
89
+ set_id: 'v1.0',
90
+ capabilities: [
91
+ { id: 1, name: 'Customer Acquisition', address: '1.0.0' },
92
+ { id: 2, name: 'Parked idea', address: '0.0.0', backlog: true },
93
+ ],
94
+ };
95
+ render(<CapabilityMapView map={map} showBacklog />);
96
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
97
+ expect(screen.getByText('Backlog')).toBeTruthy();
98
+ expect(screen.getByText('Parked idea')).toBeTruthy();
99
+ });
100
+
101
+ it('does not render add/delete affordances when readOnly', async () => {
102
+ render(<CapabilityMapView map={makeMap()} readOnly />);
103
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
104
+ expect(screen.queryByLabelText('Add child capability')).toBeNull();
105
+ expect(screen.queryByLabelText('Delete capability')).toBeNull();
106
+ });
107
+
108
+ it('fires onChange with kind "addChild" when the add-child button is clicked', async () => {
109
+ const onChange = vi.fn<(e: CapabilityMapChange) => void>();
110
+ render(<CapabilityMapView map={makeMap()} onChange={onChange} />);
111
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
112
+ const rootCard = document.querySelector('.react-flow__node[data-id="1"]')!;
113
+ rootCard.querySelector<HTMLElement>('[aria-label="Add child capability"]')!
114
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
115
+
116
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
117
+ const event = onChange.mock.calls[0][0];
118
+ expect(event.kind).toBe('addChild');
119
+ if (event.kind === 'addChild') {
120
+ expect(event.newCap.address).toBe('1.2.0');
121
+ }
122
+ });
123
+
124
+ it('fires onChange with kind "delete" when the delete button is clicked', async () => {
125
+ const onChange = vi.fn<(e: CapabilityMapChange) => void>();
126
+ render(<CapabilityMapView map={makeMap()} onChange={onChange} />);
127
+ await waitFor(() => expect(screen.getByText('Inbound Lead Scoring')).toBeTruthy());
128
+ const leafCard = document.querySelector('.react-flow__node[data-id="3"]')!;
129
+ leafCard.querySelector<HTMLElement>('[aria-label="Delete capability"]')!
130
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
131
+
132
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
133
+ expect(onChange.mock.calls[0][0].kind).toBe('delete');
134
+ });
135
+
136
+ it('fires onEditRequest on double-click', async () => {
137
+ const onEditRequest = vi.fn();
138
+ render(<CapabilityMapView map={makeMap()} onEditRequest={onEditRequest} />);
139
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
140
+ document.querySelector('.react-flow__node[data-id="1"]')!
141
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
142
+
143
+ await waitFor(() => expect(onEditRequest).toHaveBeenCalledTimes(1));
144
+ expect(onEditRequest.mock.calls[0][0]).toMatchObject({ id: 1, name: 'Customer Acquisition' });
145
+ });
146
+
147
+ it('fires onChange with kind "normaliseAddresses" from the toolbar button', async () => {
148
+ const onChange = vi.fn<(e: CapabilityMapChange) => void>();
149
+ render(<CapabilityMapView map={makeMap()} onChange={onChange} />);
150
+ await waitFor(() => expect(screen.getByText('Customer Acquisition')).toBeTruthy());
151
+ screen.getByText('Normalise addresses').dispatchEvent(new MouseEvent('click', { bubbles: true }));
152
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
153
+ expect(onChange.mock.calls[0][0].kind).toBe('normaliseAddresses');
154
+ });
155
+
156
+ it('fires onChange with kind "restoreFromBacklog" when a backlog card is dropped onto a canvas card', async () => {
157
+ const map: CapabilityMap = {
158
+ organisation: 'Acme Corp',
159
+ set_id: 'v1.0',
160
+ capabilities: [
161
+ { id: 1, name: 'Customer Acquisition', address: '1.0.0' },
162
+ { id: 2, name: 'Parked idea', address: '0.0.0', backlog: true },
163
+ ],
164
+ };
165
+ const onChange = vi.fn<(e: CapabilityMapChange) => void>();
166
+ render(<CapabilityMapView map={map} onChange={onChange} showBacklog />);
167
+ await waitFor(() => expect(screen.getByText('Parked idea')).toBeTruthy());
168
+
169
+ const store = new Map<string, string>();
170
+ const dataTransfer = { setData: (k: string, v: string) => store.set(k, v), getData: (k: string) => store.get(k) ?? '', effectAllowed: 'move' };
171
+ function fireDnd(el: Element, type: string, coords: { clientX: number; clientY: number }) {
172
+ const event = new Event(type, { bubbles: true, cancelable: true });
173
+ Object.defineProperty(event, 'dataTransfer', { value: dataTransfer });
174
+ Object.assign(event, coords);
175
+ el.dispatchEvent(event);
176
+ }
177
+
178
+ const backlogItem = screen.getByText('Parked idea').closest('div[draggable]')!;
179
+ const rootCard = document.querySelector('.react-flow__node[data-id="1"]')!;
180
+ document.elementFromPoint = vi.fn().mockReturnValue(rootCard);
181
+
182
+ fireDnd(backlogItem, 'dragstart', { clientX: 0, clientY: 0 });
183
+ fireDnd(rootCard, 'drop', { clientX: 10, clientY: 10 });
184
+
185
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
186
+ const event = onChange.mock.calls[0][0];
187
+ expect(event.kind).toBe('restoreFromBacklog');
188
+ if (event.kind === 'restoreFromBacklog') {
189
+ expect(event.id).toBe(2);
190
+ expect(event.parentId).toBe(1);
191
+ }
192
+ });
193
+ });
194
+
195
+ // Dragging a card is choreographed by reactflow's own pointer/DOM-measurement
196
+ // machinery — see the equivalent note in goals/__tests__/GoalTreeView.test.tsx.
197
+ // computeDragOutcome() is the pure decision this component's onNodeDragStop
198
+ // calls once reactflow reports a drag, tested directly here.
199
+ describe('computeDragOutcome (reparent / moveBranchToBacklog decision logic)', () => {
200
+ const map = makeMap();
201
+
202
+ it('fires a "reparent" change when dropped onto another card', () => {
203
+ const change = computeDragOutcome(map, 3, { kind: 'node', id: 1 });
204
+ expect(change?.kind).toBe('reparent');
205
+ if (change?.kind === 'reparent') {
206
+ expect(change.sourceId).toBe(3);
207
+ expect(change.targetId).toBe(1);
208
+ }
209
+ });
210
+
211
+ it('fires a "reparent" change (promotion to L1) when dropped on the root', () => {
212
+ const change = computeDragOutcome(map, 2, { kind: 'root' });
213
+ expect(change?.kind).toBe('reparent');
214
+ if (change?.kind === 'reparent') {
215
+ expect(change.targetId).toBe(0);
216
+ expect(change.result.capabilities.find((c) => c.id === 2)?.address).toBe('2.0.0');
217
+ }
218
+ });
219
+
220
+ it('fires a "moveBranchToBacklog" change when dropped on the backlog zone', () => {
221
+ const change = computeDragOutcome(map, 2, { kind: 'backlog' });
222
+ expect(change?.kind).toBe('moveBranchToBacklog');
223
+ });
224
+
225
+ it('is a no-op when dropped nowhere in particular', () => {
226
+ expect(computeDragOutcome(map, 2, null)).toBeNull();
227
+ });
228
+
229
+ it('is a no-op when dropped on itself', () => {
230
+ expect(computeDragOutcome(map, 2, { kind: 'node', id: 2 })).toBeNull();
231
+ });
232
+ });
@@ -0,0 +1,59 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { parseAddress, formatAddress, getLevel, getParentAddress, getFirstFreeAddress, isAddressTaken } from '../address.js';
3
+ import type { Capability } from '../dsm-schema.js';
4
+
5
+ function cap(id: number, address: string, backlog = false): Capability {
6
+ return { id, name: `Cap ${id}`, address, backlog };
7
+ }
8
+
9
+ describe('parseAddress / formatAddress', () => {
10
+ it('round-trips X.Y.Z', () => {
11
+ for (const addr of ['1.0.0', '1.2.0', '1.2.3', '0.0.0', '42.7.19']) {
12
+ expect(formatAddress(parseAddress(addr))).toBe(addr);
13
+ }
14
+ });
15
+
16
+ it('throws on malformed input', () => {
17
+ expect(() => parseAddress('1.2')).toThrow();
18
+ expect(() => parseAddress('1.2.3.4')).toThrow();
19
+ expect(() => parseAddress('a.b.c')).toThrow();
20
+ });
21
+ });
22
+
23
+ describe('getLevel', () => {
24
+ it('classifies each address shape', () => {
25
+ expect(getLevel('1.0.0')).toBe(1);
26
+ expect(getLevel('1.2.0')).toBe(2);
27
+ expect(getLevel('1.2.3')).toBe(3);
28
+ expect(getLevel('0.0.0')).toBe('backlog');
29
+ });
30
+ });
31
+
32
+ describe('getParentAddress', () => {
33
+ it('walks up one level at a time', () => {
34
+ expect(getParentAddress('1.2.3')).toBe('1.2.0');
35
+ expect(getParentAddress('1.2.0')).toBe('1.0.0');
36
+ expect(getParentAddress('1.0.0')).toBeNull();
37
+ });
38
+ });
39
+
40
+ describe('getFirstFreeAddress / isAddressTaken', () => {
41
+ it('finds the first unused L2 slot under an L1 parent', () => {
42
+ const caps = [cap(1, '1.0.0'), cap(2, '1.1.0'), cap(3, '1.2.0')];
43
+ expect(getFirstFreeAddress('1.0.0', caps)).toBe('1.3.0');
44
+ });
45
+
46
+ it('finds the first unused L3 slot under an L2 parent', () => {
47
+ const caps = [cap(1, '1.0.0'), cap(2, '1.1.0'), cap(3, '1.1.1')];
48
+ expect(getFirstFreeAddress('1.1.0', caps)).toBe('1.1.2');
49
+ });
50
+
51
+ it('ignores backlog entries when checking occupancy', () => {
52
+ const caps = [cap(1, '1.0.0'), cap(2, '0.0.0', true)];
53
+ expect(isAddressTaken('1.1.0', caps)).toBe(false);
54
+ });
55
+
56
+ it('rejects an L3 address as a parent', () => {
57
+ expect(() => getFirstFreeAddress('1.1.1', [])).toThrow();
58
+ });
59
+ });