@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
@@ -4,8 +4,9 @@
4
4
  // single-product view here, and the gap dashboard in Phase 4.
5
5
 
6
6
  import type { AssertionStatus } from '../assertion/types.js';
7
+ import type { ComplianceCodexDoc } from './classify.js';
7
8
 
8
- /** Projection of a REQUIREMENT the compliance views need. */
9
+ /** Projection of a REQUIREMENT (or CONSTRAINT) the compliance views need. */
9
10
  export interface IndexRequirement {
10
11
  id: string;
11
12
  name: string;
@@ -20,6 +21,38 @@ export interface IndexRequirement {
20
21
  * past or imminent, CV-3 renders an urgent decoration on the cell.
21
22
  */
22
23
  deadline?: string;
24
+ /**
25
+ * Origin taxonomy (15-requirement.md §2.1): `legislative`, `process-product`,
26
+ * or `project-product`. Distinguishes the context from which the obligation
27
+ * was derived. Undefined for existing pre-taxonomy admissions (treated as
28
+ * `legislative` by tooling that supports origin-based filtering).
29
+ */
30
+ origin?: 'legislative' | 'process-product' | 'project-product';
31
+ /**
32
+ * Same-TYPE `parent` reference: the higher-scale obligation this one
33
+ * decomposes from (15-requirement.md §2.4; ELEMENT_PRIMITIVES.md §7.13 for
34
+ * CONSTRAINT). Origin-agnostic, structure-only. Enables the hierarchy half
35
+ * of the requirement traceability view.
36
+ */
37
+ parent?: string;
38
+ /**
39
+ * Motivation-layer element kind. `requirement` = positive obligation
40
+ * (15-requirement.md); `constraint` = restriction / prohibition
41
+ * (ELEMENT_PRIMITIVES.md §7.13). ASSERTION coverage applies to `requirement`
42
+ * only (16-assertion.md §1); the hierarchy half applies to both.
43
+ */
44
+ element_kind?: 'requirement' | 'constraint';
45
+ /**
46
+ * Longer-form description of the obligation (15-requirement.md §2). Optional;
47
+ * used by the requirement traceability view to show the requirement body
48
+ * inline. Not used by matrix / list views.
49
+ */
50
+ description?: string;
51
+ /**
52
+ * `next_review_at` review-checkpoint date (15-requirement.md §2.3; ISO 8601).
53
+ * Present when the author has scheduled a review; drives `REQ-STALE-001`.
54
+ */
55
+ next_review_at?: string;
23
56
  }
24
57
 
25
58
  // ── Temporal status (CV-3) ──────────────────────────────────────────────────
@@ -106,6 +139,11 @@ export interface ComplianceIndex {
106
139
  assertionsByRequirement: Map<string, IndexAssertion[]>;
107
140
  /** Subject id (product / process / capability) → assertions about it. */
108
141
  assertionsBySubject: Map<string, IndexAssertion[]>;
142
+ /**
143
+ * Parent id → the requirements/constraints that name it in `parent`
144
+ * (15-requirement.md §2.4). Enables the requirement-hierarchy view.
145
+ */
146
+ requirementsByParent: Map<string, IndexRequirement[]>;
109
147
  }
110
148
 
111
149
  // ── Single-law tree ─────────────────────────────────────────────────────────
@@ -134,3 +172,65 @@ export interface ProductView {
134
172
  /** Requirements bound to the product via an assertion, requirement-id-sorted. */
135
173
  requirements: ProductRequirementStatus[];
136
174
  }
175
+
176
+ // ── Requirement traceability + hierarchy view ───────────────────────────────
177
+
178
+ /** A codex artefact resolved from a requirement's `derived_from` reference. */
179
+ export interface TraceSourceRef {
180
+ /** Verbatim id from `derived_from`. Always present. */
181
+ id: string;
182
+ /** The codex artefact, when resolved by the scan. Absent for dangling refs. */
183
+ codex?: ComplianceCodexDoc;
184
+ }
185
+
186
+ /** A named element (subject or realising element) resolved by the trace. */
187
+ export interface TraceElementRef {
188
+ id: string;
189
+ /** Element name when resolved by the scan; absent for dangling refs. */
190
+ name?: string;
191
+ }
192
+
193
+ /** One ASSERTION targeting the traced requirement, with subject + realising elements. */
194
+ export interface TraceAssertionRow {
195
+ assertion: IndexAssertion;
196
+ subject: TraceElementRef;
197
+ /** Elements named in the assertion's `realised_via` list (may be empty). */
198
+ realisedVia: TraceElementRef[];
199
+ }
200
+
201
+ /**
202
+ * Requirement traceability + hierarchy view.
203
+ *
204
+ * Two halves, both origin-agnostic (15-requirement.md §2.1):
205
+ * 1. Trace chain — `derived_from` source(s) → the element itself → any
206
+ * ASSERTION targeting it (`about`) → the asserted `subject` + `realised_via`
207
+ * elements. Origin-agnostic per 15-requirement.md §2.1; assertion coverage
208
+ * applies to REQUIREMENT only (16-assertion.md §1) — CONSTRAINT trace shows
209
+ * only the source chain + hierarchy.
210
+ * 2. Hierarchy — `parent` chain (ancestors, root last of the array) + children
211
+ * (any element whose `parent` names this one), sorted by id.
212
+ */
213
+ export interface RequirementTrace {
214
+ /** The element being traced (REQUIREMENT or CONSTRAINT). Falls back to a
215
+ * stub carrying the id as its name when the element is missing from the
216
+ * scan (a dangling `parent` or a repository being edited). */
217
+ requirement: IndexRequirement;
218
+ /** Backward-trace: `derived_from` codex artefacts, verbatim order. */
219
+ sources: TraceSourceRef[];
220
+ /** Forward-trace via ASSERTION. Empty for CONSTRAINT elements (16-assertion.md §1) or for a REQUIREMENT with no filed assertion. */
221
+ assertions: TraceAssertionRow[];
222
+ /** Parent chain: immediate parent first, root last. Empty when the element has no `parent`. */
223
+ ancestors: IndexRequirement[];
224
+ /** Direct children: elements naming this one as their `parent`, id-sorted. */
225
+ children: IndexRequirement[];
226
+ }
227
+
228
+ /**
229
+ * The complementary data the trace builder needs to name subjects and realising
230
+ * elements. Names are resolved by looking up the id in this map; unresolved ids
231
+ * surface as the id alone (a dangling reference).
232
+ */
233
+ export interface TraceElementCatalog {
234
+ /** id → human-readable name (or the id itself when unnamed). */
235
+ nameById: Map<string, string>;
236
+ }
@@ -0,0 +1,212 @@
1
+ import React, { memo, useState } from 'react';
2
+ import { Handle, Position } from 'reactflow';
3
+ import type { Factor, Goal } from './types.js';
4
+ import type { ThemeTokens } from './theme.js';
5
+
6
+ const NODE_WIDTH = 250;
7
+ const NODE_HEIGHT = 80;
8
+
9
+ function impactSign(f: Factor): 'positive' | 'negative' | 'both' {
10
+ const t = f.impact_type;
11
+ if (t === 'mixed') return 'both';
12
+ if (t === 'opportunity' || t === 'positive') return 'positive';
13
+ return 'negative';
14
+ }
15
+
16
+ export interface GoalNodeData {
17
+ goal: Goal;
18
+ theme: Required<ThemeTokens>;
19
+ readOnly: boolean;
20
+ isDropTarget: boolean;
21
+ hasHiddenChildren: boolean;
22
+ isCollapsed: boolean;
23
+ onAddChild: (parentId: number, parentLevel: number) => void;
24
+ onDelete: (id: number) => void;
25
+ onToggleCollapse: (id: number) => void;
26
+ }
27
+
28
+ const GoalNode = memo(({ data }: { data: GoalNodeData }) => {
29
+ const { goal, theme, readOnly, isDropTarget, hasHiddenChildren, isCollapsed } = data;
30
+ const [openPanel, setOpenPanel] = useState<'positive' | 'negative' | null>(null);
31
+
32
+ const positive = (goal.factors ?? []).filter((f) => impactSign(f) !== 'negative');
33
+ const negative = (goal.factors ?? []).filter((f) => impactSign(f) !== 'positive');
34
+ const bg = theme.goalLevelColors[goal.level] ?? theme.goalLevelColors[0];
35
+
36
+ return (
37
+ <div
38
+ className="tx-goal-node"
39
+ style={{
40
+ position: 'relative',
41
+ width: NODE_WIDTH,
42
+ height: NODE_HEIGHT,
43
+ background: bg,
44
+ borderRadius: 12,
45
+ borderStyle: 'solid',
46
+ borderWidth: isDropTarget ? 2 : theme.cardBorderWidth,
47
+ borderColor: isDropTarget ? theme.dropTargetBorderColor : theme.cardBorderColor,
48
+ boxShadow: '0 1px 4px rgba(0,0,0,0.12)',
49
+ padding: '6px 8px',
50
+ fontSize: 12,
51
+ display: 'flex',
52
+ alignItems: 'stretch',
53
+ justifyContent: 'center',
54
+ }}
55
+ >
56
+ <Handle type="target" position={Position.Left} style={{ opacity: 0 }} />
57
+ <Handle type="source" position={Position.Right} style={{ opacity: 0 }} />
58
+
59
+ <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', width: 16 }}>
60
+ {positive.length > 0 && (
61
+ <span
62
+ role="button"
63
+ aria-label={`${positive.length} positive factor${positive.length > 1 ? 's' : ''}`}
64
+ title={`${positive.length} positive factor${positive.length > 1 ? 's' : ''}`}
65
+ onClick={(e) => {
66
+ e.stopPropagation();
67
+ setOpenPanel(openPanel === 'positive' ? null : 'positive');
68
+ }}
69
+ style={{ cursor: 'pointer', color: '#16a34a', fontSize: 14, lineHeight: 1, userSelect: 'none' }}
70
+ >
71
+ &#9650;
72
+ {positive.length > 1 && <span style={{ fontSize: 9, fontWeight: 700, marginLeft: 2 }}>{positive.length}</span>}
73
+ </span>
74
+ )}
75
+ </div>
76
+
77
+ <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', padding: '0 4px' }}>
78
+ <div
79
+ title={goal.name}
80
+ style={{
81
+ fontWeight: 600,
82
+ color: theme.cardTextColor,
83
+ lineHeight: 1.2,
84
+ overflow: 'hidden',
85
+ display: '-webkit-box',
86
+ WebkitLineClamp: 2,
87
+ WebkitBoxOrient: 'vertical',
88
+ wordBreak: 'break-word',
89
+ }}
90
+ >
91
+ {goal.name}
92
+ </div>
93
+ <div style={{ fontSize: 10, color: theme.cardMetaColor, marginTop: 2 }}>
94
+ ID: {goal.id} | Lvl: {goal.level}
95
+ {goal.tag ? ` | #${goal.tag}` : ''}
96
+ </div>
97
+ </div>
98
+
99
+ <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', width: 16, justifyContent: 'flex-end' }}>
100
+ {negative.length > 0 && (
101
+ <span
102
+ role="button"
103
+ aria-label={`${negative.length} negative factor${negative.length > 1 ? 's' : ''}`}
104
+ title={`${negative.length} negative factor${negative.length > 1 ? 's' : ''}`}
105
+ onClick={(e) => {
106
+ e.stopPropagation();
107
+ setOpenPanel(openPanel === 'negative' ? null : 'negative');
108
+ }}
109
+ style={{ cursor: 'pointer', color: '#dc2626', fontSize: 14, lineHeight: 1, userSelect: 'none' }}
110
+ >
111
+ &#9660;
112
+ {negative.length > 1 && <span style={{ fontSize: 9, fontWeight: 700, marginLeft: 2 }}>{negative.length}</span>}
113
+ </span>
114
+ )}
115
+ </div>
116
+
117
+ {openPanel && (
118
+ <div
119
+ style={{
120
+ position: 'absolute',
121
+ left: 0,
122
+ width: '100%',
123
+ zIndex: 20,
124
+ display: 'flex',
125
+ flexDirection: 'column',
126
+ gap: 4,
127
+ ...(openPanel === 'positive' ? { bottom: 'calc(100% + 8px)' } : { top: 'calc(100% + 8px)' }),
128
+ }}
129
+ >
130
+ {(openPanel === 'positive' ? positive : negative).map((f) => (
131
+ <div
132
+ key={f.id}
133
+ style={{
134
+ background: openPanel === 'positive' ? '#f0fdf4' : '#fef2f2',
135
+ border: `1px solid ${openPanel === 'positive' ? '#bbf7d0' : '#fecaca'}`,
136
+ color: openPanel === 'positive' ? '#166534' : '#991b1b',
137
+ borderRadius: 4,
138
+ padding: '4px 6px',
139
+ fontSize: 10,
140
+ textAlign: 'left',
141
+ }}
142
+ >
143
+ <div style={{ fontWeight: 700 }}>{f.name}</div>
144
+ {f.description && <div style={{ opacity: 0.85 }}>{f.description}</div>}
145
+ </div>
146
+ ))}
147
+ </div>
148
+ )}
149
+
150
+ {!readOnly && (
151
+ <button
152
+ type="button"
153
+ aria-label="Add child goal"
154
+ title="Add child goal"
155
+ onClick={(e) => {
156
+ e.stopPropagation();
157
+ data.onAddChild(goal.id, goal.level);
158
+ }}
159
+ style={{
160
+ position: 'absolute', top: -8, right: -8, width: 16, height: 16,
161
+ borderRadius: '50%', border: '1px solid #86efac', background: '#ffffff',
162
+ color: '#16a34a', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
163
+ }}
164
+ >
165
+ +
166
+ </button>
167
+ )}
168
+
169
+ {!readOnly && (
170
+ <button
171
+ type="button"
172
+ aria-label="Delete goal"
173
+ title="Delete goal and descendants"
174
+ onClick={(e) => {
175
+ e.stopPropagation();
176
+ data.onDelete(goal.id);
177
+ }}
178
+ style={{
179
+ position: 'absolute', bottom: -8, right: -8, width: 16, height: 16,
180
+ borderRadius: '50%', border: '1px solid #fca5a5', background: '#ffffff',
181
+ color: '#dc2626', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
182
+ }}
183
+ >
184
+ &times;
185
+ </button>
186
+ )}
187
+
188
+ {hasHiddenChildren && (
189
+ <button
190
+ type="button"
191
+ aria-label={isCollapsed ? 'Expand branch' : 'Collapse branch'}
192
+ title={isCollapsed ? 'Expand branch' : 'Collapse branch'}
193
+ onClick={(e) => {
194
+ e.stopPropagation();
195
+ data.onToggleCollapse(goal.id);
196
+ }}
197
+ style={{
198
+ position: 'absolute', top: '50%', right: -8, transform: 'translateY(-50%)',
199
+ width: 16, height: 16, borderRadius: '50%', border: `1px solid ${theme.cardBorderColor}`,
200
+ background: '#ffffff', color: theme.cardBorderColor, fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
201
+ }}
202
+ >
203
+ {isCollapsed ? '+' : '−'}
204
+ </button>
205
+ )}
206
+ </div>
207
+ );
208
+ });
209
+
210
+ GoalNode.displayName = 'GoalNode';
211
+
212
+ export default GoalNode;
@@ -0,0 +1,350 @@
1
+ import React, { useCallback, useMemo, useState, useEffect } from 'react';
2
+ import ReactFlow, {
3
+ Controls,
4
+ MiniMap,
5
+ Background,
6
+ ConnectionLineType,
7
+ useNodesState,
8
+ useEdgesState,
9
+ type Node,
10
+ type Edge,
11
+ type NodeMouseHandler,
12
+ type NodeDragHandler,
13
+ } from 'reactflow';
14
+ import 'reactflow/dist/style.css';
15
+ import type { Goal, GoalTree, GoalTreeLayout, LayoutOptions } from './types.js';
16
+ import { layoutGoalTree } from './layout.js';
17
+ import { reparent, addChild, deleteWithDescendants, moveToBacklog, restoreFromBacklog } from './mutations.js';
18
+ import type { ThemeTokens } from './theme.js';
19
+ import { resolveTheme } from './theme.js';
20
+ import GoalNode, { type GoalNodeData } from './GoalNode.js';
21
+
22
+ export type { ThemeTokens } from './theme.js';
23
+
24
+ export interface GoalTreeViewProps {
25
+ tree: GoalTree;
26
+ layout?: GoalTreeLayout;
27
+ layoutOptions?: LayoutOptions;
28
+ theme?: ThemeTokens;
29
+ readOnly?: boolean;
30
+ showBacklog?: boolean;
31
+ showMiniMap?: boolean;
32
+ onChange?: (event: GoalTreeChange) => void;
33
+ onEditRequest?: (goal: Goal) => void;
34
+ }
35
+
36
+ export type GoalTreeChange =
37
+ | { kind: 'reparent'; sourceId: number; targetId: number; result: GoalTree }
38
+ | { kind: 'addChild'; parentId: number; newGoal: Goal; result: GoalTree }
39
+ | { kind: 'delete'; id: number; result: GoalTree }
40
+ | { kind: 'moveToBacklog'; id: number; result: GoalTree }
41
+ | { kind: 'restoreFromBacklog'; id: number; newParentId: number; result: GoalTree };
42
+
43
+ const BACKLOG_DRAG_MIME = 'application/x-transitrix-goal-id';
44
+ const nodeTypes = { goalNode: GoalNode };
45
+
46
+ /** Where a card was dropped, as classified from the pointer position at drag-stop. */
47
+ export type DropTarget = { kind: 'node'; id: number } | { kind: 'backlog' } | null;
48
+
49
+ /**
50
+ * Pure decision: given where a dragged card was dropped, compute the mutation
51
+ * and the GoalTreeChange to report (or null for a no-op drop). Kept separate
52
+ * from the DOM/pointer-event glue in onNodeDragStop so the mutation-selection
53
+ * logic — which card wins reparent vs moveToBacklog vs a refused mutation —
54
+ * is unit-testable without needing a real drag gesture through reactflow's
55
+ * internal, DOM-measurement-gated dragging.
56
+ */
57
+ export function computeDragOutcome(tree: GoalTree, sourceId: number, dropTarget: DropTarget): GoalTreeChange | null {
58
+ if (!dropTarget) return null;
59
+ if (dropTarget.kind === 'backlog') {
60
+ const mutation = moveToBacklog(tree, sourceId);
61
+ if (!mutation.ok || !mutation.result) return null;
62
+ return { kind: 'moveToBacklog', id: sourceId, result: mutation.result };
63
+ }
64
+ if (dropTarget.id === sourceId) return null;
65
+ const mutation = reparent(tree, sourceId, dropTarget.id);
66
+ if (!mutation.ok || !mutation.result) return null;
67
+ return { kind: 'reparent', sourceId, targetId: dropTarget.id, result: mutation.result };
68
+ }
69
+
70
+ /** Goals reachable from a root (level 0 or parent_id 0) via valid parent_id chains. */
71
+ function partitionCanvasAndBacklog(goals: Goal[]): { canvas: Goal[]; backlog: Goal[] } {
72
+ const children = new Map<number, Goal[]>();
73
+ for (const g of goals) {
74
+ if (!children.has(g.parent_id)) children.set(g.parent_id, []);
75
+ children.get(g.parent_id)!.push(g);
76
+ }
77
+ const roots = goals.filter((g) => g.level === 0 || g.parent_id === 0);
78
+ const reachable = new Set<number>();
79
+ const stack = [...roots.map((r) => r.id)];
80
+ while (stack.length > 0) {
81
+ const id = stack.pop()!;
82
+ if (reachable.has(id)) continue;
83
+ reachable.add(id);
84
+ for (const child of children.get(id) ?? []) stack.push(child.id);
85
+ }
86
+ const canvas: Goal[] = [];
87
+ const backlog: Goal[] = [];
88
+ for (const g of goals) {
89
+ if (reachable.has(g.id)) canvas.push(g);
90
+ else backlog.push(g); // unreachable from any root — broken/orphaned parent chain
91
+ }
92
+ return { canvas, backlog };
93
+ }
94
+
95
+ function GoalTreeViewInner({
96
+ tree,
97
+ layout: layoutProp,
98
+ layoutOptions,
99
+ theme: themeProp,
100
+ readOnly = false,
101
+ showBacklog = false,
102
+ showMiniMap = false,
103
+ onChange,
104
+ onEditRequest,
105
+ }: GoalTreeViewProps): React.ReactElement {
106
+ const theme = useMemo(() => resolveTheme(themeProp), [themeProp]);
107
+ const [collapsedIds, setCollapsedIds] = useState<Set<number>>(new Set());
108
+ const [hoveredId, setHoveredId] = useState<number | null>(null);
109
+
110
+ const { canvas: canvasGoals, backlog: backlogGoals } = useMemo(
111
+ () => partitionCanvasAndBacklog(tree.goals),
112
+ [tree.goals],
113
+ );
114
+
115
+ const layout = useMemo<GoalTreeLayout>(() => {
116
+ if (layoutProp) return layoutProp;
117
+ const hideCollapsed = [...(layoutOptions?.hideCollapsed ?? []), ...collapsedIds];
118
+ return layoutGoalTree(
119
+ { goal_types: tree.goal_types, goals: canvasGoals },
120
+ { ...layoutOptions, hideCollapsed },
121
+ );
122
+ }, [layoutProp, layoutOptions, collapsedIds, tree.goal_types, canvasGoals]);
123
+
124
+ const onAddChild = useCallback(
125
+ (parentId: number, parentLevel: number) => {
126
+ if (readOnly) return;
127
+ const before = new Set(tree.goals.map((g) => g.id));
128
+ const mutation = addChild(tree, parentId, { name: 'New goal', type: '', level: parentLevel + 1, parent_id: parentId });
129
+ if (!mutation.ok || !mutation.result) return;
130
+ const newGoal = mutation.result.goals.find((g) => !before.has(g.id));
131
+ if (!newGoal) return;
132
+ onChange?.({ kind: 'addChild', parentId, newGoal, result: mutation.result });
133
+ },
134
+ [tree, readOnly, onChange],
135
+ );
136
+
137
+ const onDeleteNode = useCallback(
138
+ (id: number) => {
139
+ if (readOnly) return;
140
+ const mutation = deleteWithDescendants(tree, id);
141
+ if (!mutation.ok || !mutation.result) return;
142
+ onChange?.({ kind: 'delete', id, result: mutation.result });
143
+ },
144
+ [tree, readOnly, onChange],
145
+ );
146
+
147
+ const onRestoreFromBacklog = useCallback(
148
+ (id: number, newParentId: number) => {
149
+ if (readOnly) return;
150
+ const mutation = restoreFromBacklog(tree, id, newParentId);
151
+ if (!mutation.ok || !mutation.result) return;
152
+ onChange?.({ kind: 'restoreFromBacklog', id, newParentId, result: mutation.result });
153
+ },
154
+ [tree, readOnly, onChange],
155
+ );
156
+
157
+ const onToggleCollapse = useCallback((id: number) => {
158
+ setCollapsedIds((prev) => {
159
+ const next = new Set(prev);
160
+ if (next.has(id)) next.delete(id);
161
+ else next.add(id);
162
+ return next;
163
+ });
164
+ }, []);
165
+
166
+ const buildNodes = useCallback((): Node<GoalNodeData>[] => {
167
+ return layout.nodes.map((n) => ({
168
+ id: String(n.id),
169
+ type: 'goalNode',
170
+ position: { x: n.x, y: n.y },
171
+ draggable: !readOnly,
172
+ data: {
173
+ goal: n.data,
174
+ theme,
175
+ readOnly,
176
+ isDropTarget: hoveredId === n.id,
177
+ hasHiddenChildren: n.hasHiddenChildren,
178
+ isCollapsed: collapsedIds.has(n.id),
179
+ onAddChild,
180
+ onDelete: onDeleteNode,
181
+ onToggleCollapse,
182
+ },
183
+ }));
184
+ }, [layout.nodes, theme, readOnly, hoveredId, collapsedIds, onAddChild, onDeleteNode, onToggleCollapse]);
185
+
186
+ const buildEdges = useCallback((): Edge[] => {
187
+ return layout.edges.map((e) => ({
188
+ id: `e${e.source}-${e.target}`,
189
+ source: String(e.source),
190
+ target: String(e.target),
191
+ type: 'default',
192
+ style: { stroke: theme.edgeColor, strokeWidth: theme.edgeWidth },
193
+ }));
194
+ }, [layout.edges, theme]);
195
+
196
+ const [nodes, setNodes, onNodesChange] = useNodesState<GoalNodeData>(buildNodes());
197
+ const [edges, setEdges, onEdgesChange] = useEdgesState(buildEdges());
198
+
199
+ // Re-sync whenever the underlying layout/theme/interaction state changes —
200
+ // tree/layout are host-controlled props, not owned by this component.
201
+ useEffect(() => {
202
+ setNodes(buildNodes());
203
+ setEdges(buildEdges());
204
+ // eslint-disable-next-line react-hooks/exhaustive-deps
205
+ }, [layout, theme, readOnly, hoveredId, collapsedIds]);
206
+
207
+ const checkIntersection = useCallback(
208
+ (a: Node<GoalNodeData>, b: Node<GoalNodeData>): boolean => {
209
+ const midX = a.position.x + 125;
210
+ const midY = a.position.y + 40;
211
+ return midX > b.position.x && midX < b.position.x + 250 && midY > b.position.y && midY < b.position.y + 80;
212
+ },
213
+ [],
214
+ );
215
+
216
+ const onNodeDrag: NodeDragHandler = useCallback(
217
+ (_event, node) => {
218
+ if (readOnly) return;
219
+ const hit = nodes.find((n) => n.id !== node.id && checkIntersection(node as Node<GoalNodeData>, n));
220
+ setHoveredId(hit ? Number(hit.id) : null);
221
+ },
222
+ [readOnly, nodes, checkIntersection],
223
+ );
224
+
225
+ const onNodeDragStop: NodeDragHandler = useCallback(
226
+ (event, node) => {
227
+ if (readOnly) {
228
+ setHoveredId(null);
229
+ return;
230
+ }
231
+ const sourceId = Number(node.id);
232
+ const mouseEvent = event as unknown as MouseEvent;
233
+ const dropEl = typeof document !== 'undefined' && 'clientX' in mouseEvent
234
+ ? document.elementFromPoint(mouseEvent.clientX, mouseEvent.clientY)
235
+ : null;
236
+ const dropTarget: DropTarget = dropEl?.closest('[data-goaltree-backlog-zone]')
237
+ ? { kind: 'backlog' }
238
+ : hoveredId != null ? { kind: 'node', id: hoveredId } : null;
239
+ const change = computeDragOutcome(tree, sourceId, dropTarget);
240
+ if (change) onChange?.(change);
241
+ setHoveredId(null);
242
+ },
243
+ [readOnly, hoveredId, tree, onChange],
244
+ );
245
+
246
+ const onNodeDoubleClick: NodeMouseHandler = useCallback(
247
+ (_event, node) => {
248
+ const goal = tree.goals.find((g) => g.id === Number(node.id));
249
+ if (goal) onEditRequest?.(goal);
250
+ },
251
+ [tree.goals, onEditRequest],
252
+ );
253
+
254
+ const onBacklogItemDragStart = useCallback((event: React.DragEvent, goalId: number) => {
255
+ event.dataTransfer.setData(BACKLOG_DRAG_MIME, String(goalId));
256
+ event.dataTransfer.effectAllowed = 'move';
257
+ }, []);
258
+
259
+ const onCanvasDragOver = useCallback(
260
+ (event: React.DragEvent) => {
261
+ if (readOnly) return;
262
+ event.preventDefault();
263
+ },
264
+ [readOnly],
265
+ );
266
+
267
+ const onCanvasDrop = useCallback(
268
+ (event: React.DragEvent) => {
269
+ if (readOnly) return;
270
+ event.preventDefault();
271
+ const idStr = event.dataTransfer.getData(BACKLOG_DRAG_MIME);
272
+ if (!idStr) return;
273
+ const goalId = Number(idStr);
274
+ const targetEl = document.elementFromPoint(event.clientX, event.clientY);
275
+ const nodeEl = targetEl?.closest('.react-flow__node');
276
+ const targetIdAttr = nodeEl?.getAttribute('data-id');
277
+ if (targetIdAttr == null) return;
278
+ onRestoreFromBacklog(goalId, Number(targetIdAttr));
279
+ },
280
+ [readOnly, onRestoreFromBacklog],
281
+ );
282
+
283
+ const showBacklogPanel = showBacklog && backlogGoals.length > 0;
284
+
285
+ return (
286
+ <div style={{ display: 'flex', width: '100%', height: '100%' }}>
287
+ {showBacklogPanel && (
288
+ <div
289
+ data-goaltree-backlog-zone
290
+ style={{
291
+ width: 220,
292
+ flexShrink: 0,
293
+ borderRight: '1px solid #e2e8f0',
294
+ padding: 10,
295
+ overflowY: 'auto',
296
+ background: '#f8fafc',
297
+ }}
298
+ >
299
+ <div style={{ fontWeight: 700, fontSize: 12, color: '#334155', marginBottom: 8 }}>Backlog</div>
300
+ {backlogGoals.map((goal) => (
301
+ <div
302
+ key={goal.id}
303
+ draggable={!readOnly}
304
+ onDragStart={(e) => onBacklogItemDragStart(e, goal.id)}
305
+ onDoubleClick={() => onEditRequest?.(goal)}
306
+ title="Drag onto a canvas card to set its parent"
307
+ style={{
308
+ padding: 8,
309
+ marginBottom: 6,
310
+ background: '#ffffff',
311
+ border: '1px solid #cbd5e1',
312
+ borderRadius: 6,
313
+ fontSize: 11,
314
+ cursor: readOnly ? 'default' : 'grab',
315
+ }}
316
+ >
317
+ <div style={{ fontWeight: 600 }}>{goal.name}</div>
318
+ <div style={{ color: '#64748b' }}>Level: {goal.level}</div>
319
+ </div>
320
+ ))}
321
+ </div>
322
+ )}
323
+
324
+ <div style={{ flex: 1, position: 'relative' }} onDragOver={onCanvasDragOver} onDrop={onCanvasDrop}>
325
+ <ReactFlow
326
+ nodes={nodes}
327
+ edges={edges}
328
+ onNodesChange={readOnly ? undefined : onNodesChange}
329
+ onEdgesChange={readOnly ? undefined : onEdgesChange}
330
+ nodeTypes={nodeTypes}
331
+ nodesDraggable={!readOnly}
332
+ nodesConnectable={false}
333
+ onNodeDrag={onNodeDrag}
334
+ onNodeDragStop={onNodeDragStop}
335
+ onNodeDoubleClick={onNodeDoubleClick}
336
+ connectionLineType={ConnectionLineType.Bezier}
337
+ fitView
338
+ >
339
+ <Background />
340
+ <Controls />
341
+ {showMiniMap && <MiniMap pannable zoomable />}
342
+ </ReactFlow>
343
+ </div>
344
+ </div>
345
+ );
346
+ }
347
+
348
+ export function GoalTreeView(props: GoalTreeViewProps): React.ReactElement {
349
+ return <GoalTreeViewInner {...props} />;
350
+ }