@transitrix/diagrams 1.4.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 (90) hide show
  1. package/dist/activities/__tests__/gantt.test.js +39 -0
  2. package/dist/capability-map/CapabilityCardNode.d.ts +19 -0
  3. package/dist/capability-map/CapabilityCardNode.js +66 -0
  4. package/dist/capability-map/CapabilityMapView.d.ts +59 -0
  5. package/dist/capability-map/CapabilityMapView.js +204 -0
  6. package/dist/capability-map/CapabilityRootNode.d.ts +12 -0
  7. package/dist/capability-map/CapabilityRootNode.js +23 -0
  8. package/dist/capability-map/__tests__/CapabilityMapView.test.d.ts +1 -0
  9. package/dist/capability-map/__tests__/CapabilityMapView.test.js +217 -0
  10. package/dist/capability-map/__tests__/address.test.d.ts +1 -0
  11. package/dist/capability-map/__tests__/address.test.js +49 -0
  12. package/dist/capability-map/__tests__/dsm-layout.test.d.ts +1 -0
  13. package/dist/capability-map/__tests__/dsm-layout.test.js +46 -0
  14. package/dist/capability-map/__tests__/dsm-mutations.test.d.ts +1 -0
  15. package/dist/capability-map/__tests__/dsm-mutations.test.js +125 -0
  16. package/dist/capability-map/__tests__/dsm-validate.test.d.ts +1 -0
  17. package/dist/capability-map/__tests__/dsm-validate.test.js +56 -0
  18. package/dist/capability-map/address.d.ts +12 -0
  19. package/dist/capability-map/address.js +48 -0
  20. package/dist/capability-map/dsm-layout.d.ts +9 -0
  21. package/dist/capability-map/dsm-layout.js +125 -0
  22. package/dist/capability-map/dsm-mutations.d.ts +28 -0
  23. package/dist/capability-map/dsm-mutations.js +196 -0
  24. package/dist/capability-map/dsm-schema.d.ts +71 -0
  25. package/dist/capability-map/dsm-schema.js +14 -0
  26. package/dist/capability-map/dsm-theme.d.ts +20 -0
  27. package/dist/capability-map/dsm-theme.js +36 -0
  28. package/dist/capability-map/dsm-validate.d.ts +2 -0
  29. package/dist/capability-map/dsm-validate.js +93 -0
  30. package/dist/capability-map/index.d.ts +9 -0
  31. package/dist/capability-map/index.js +6 -0
  32. package/dist/compliance/__tests__/trace.test.d.ts +1 -0
  33. package/dist/compliance/__tests__/trace.test.js +144 -0
  34. package/dist/compliance/classify.js +7 -1
  35. package/dist/compliance/index.d.ts +2 -1
  36. package/dist/compliance/index.js +1 -0
  37. package/dist/compliance/reverse-index.js +4 -1
  38. package/dist/compliance/trace.d.ts +26 -0
  39. package/dist/compliance/trace.js +89 -0
  40. package/dist/compliance/types.d.ts +94 -1
  41. package/dist/goals/GoalNode.d.ts +18 -0
  42. package/dist/goals/GoalNode.js +91 -0
  43. package/dist/goals/GoalTreeView.d.ts +57 -0
  44. package/dist/goals/GoalTreeView.js +228 -0
  45. package/dist/goals/__tests__/GoalTreeView.test.d.ts +1 -0
  46. package/dist/goals/__tests__/GoalTreeView.test.js +296 -0
  47. package/dist/goals/index.d.ts +3 -0
  48. package/dist/goals/index.js +1 -0
  49. package/dist/goals/theme.d.ts +22 -0
  50. package/dist/goals/theme.js +32 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.js +1 -1
  53. package/dist/webview/__tests__/render-blocks.test.js +48 -0
  54. package/dist/webview/notation-style.d.ts +11 -0
  55. package/dist/webview/notation-style.js +11 -0
  56. package/dist/webview/render-blocks.js +8 -4
  57. package/dist/webview/render-goals.js +2 -1
  58. package/package.json +4 -1
  59. package/src/activities/__tests__/gantt.test.ts +45 -0
  60. package/src/capability-map/CapabilityCardNode.tsx +146 -0
  61. package/src/capability-map/CapabilityMapView.tsx +331 -0
  62. package/src/capability-map/CapabilityRootNode.tsx +38 -0
  63. package/src/capability-map/__tests__/CapabilityMapView.test.tsx +232 -0
  64. package/src/capability-map/__tests__/address.test.ts +59 -0
  65. package/src/capability-map/__tests__/dsm-layout.test.ts +52 -0
  66. package/src/capability-map/__tests__/dsm-mutations.test.ts +141 -0
  67. package/src/capability-map/__tests__/dsm-validate.test.ts +65 -0
  68. package/src/capability-map/address.ts +48 -0
  69. package/src/capability-map/dsm-layout.ts +142 -0
  70. package/src/capability-map/dsm-mutations.ts +208 -0
  71. package/src/capability-map/dsm-schema.ts +80 -0
  72. package/src/capability-map/dsm-theme.ts +53 -0
  73. package/src/capability-map/dsm-validate.ts +103 -0
  74. package/src/capability-map/index.ts +35 -0
  75. package/src/compliance/__tests__/trace.test.ts +157 -0
  76. package/src/compliance/classify.ts +7 -1
  77. package/src/compliance/index.ts +6 -0
  78. package/src/compliance/reverse-index.ts +3 -1
  79. package/src/compliance/trace.ts +118 -0
  80. package/src/compliance/types.ts +101 -1
  81. package/src/goals/GoalNode.tsx +212 -0
  82. package/src/goals/GoalTreeView.tsx +350 -0
  83. package/src/goals/__tests__/GoalTreeView.test.tsx +313 -0
  84. package/src/goals/index.ts +4 -0
  85. package/src/goals/theme.ts +54 -0
  86. package/src/index.ts +29 -1
  87. package/src/webview/__tests__/render-blocks.test.ts +54 -0
  88. package/src/webview/notation-style.ts +12 -0
  89. package/src/webview/render-blocks.ts +8 -4
  90. package/src/webview/render-goals.ts +2 -1
@@ -17,14 +17,17 @@ export function buildComplianceIndex(input) {
17
17
  const requirementsByLaw = new Map();
18
18
  const assertionsByRequirement = new Map();
19
19
  const assertionsBySubject = new Map();
20
+ const requirementsByParent = new Map();
20
21
  for (const r of input.requirements) {
21
22
  requirementById.set(r.id, r);
22
23
  for (const law of r.derived_from ?? [])
23
24
  push(requirementsByLaw, law, r);
25
+ if (r.parent)
26
+ push(requirementsByParent, r.parent, r);
24
27
  }
25
28
  for (const a of input.assertions) {
26
29
  push(assertionsByRequirement, a.about, a);
27
30
  push(assertionsBySubject, a.subject, a);
28
31
  }
29
- return { requirementById, requirementsByLaw, assertionsByRequirement, assertionsBySubject };
32
+ return { requirementById, requirementsByLaw, assertionsByRequirement, assertionsBySubject, requirementsByParent };
30
33
  }
@@ -0,0 +1,26 @@
1
+ import type { ComplianceIndex, RequirementTrace, TraceElementCatalog } from './types.js';
2
+ import type { ComplianceCodexDoc } from './classify.js';
3
+ /**
4
+ * Builds the REQUIREMENT / CONSTRAINT traceability view.
5
+ *
6
+ * @param requirementId typed id of the element to trace
7
+ * @param index reverse index built by `buildComplianceIndex`
8
+ * @param catalog name-resolution map for subject / realised_via refs
9
+ * @param codex optional codex artefact list (from the scanner); when
10
+ * supplied, `sources[].codex` is populated with the
11
+ * resolved codex artefact for jurisdiction display
12
+ */
13
+ export declare function buildRequirementTrace(requirementId: string, index: ComplianceIndex, catalog: TraceElementCatalog, codex?: ComplianceCodexDoc[]): RequirementTrace;
14
+ /**
15
+ * Convenience: build a `TraceElementCatalog` from the scanned canon's product
16
+ * and subject buckets. Requirements/assertions are excluded — they are indexed
17
+ * separately by `buildComplianceIndex`; the catalog is only for resolving the
18
+ * elements a trace references (subjects + realised_via).
19
+ */
20
+ export declare function buildTraceElementCatalog(products: Array<{
21
+ id: string;
22
+ name: string;
23
+ }>, subjects: Array<{
24
+ id: string;
25
+ name: string;
26
+ }>): TraceElementCatalog;
@@ -0,0 +1,89 @@
1
+ // Requirement traceability + hierarchy builder.
2
+ //
3
+ // Two halves, both origin-agnostic per 15-requirement.md §2.1:
4
+ //
5
+ // 1. Trace chain — `derived_from` sources → the REQUIREMENT / CONSTRAINT
6
+ // itself → any ASSERTION targeting it (`about`) → the asserted `subject`
7
+ // + `realised_via` elements. Assertion coverage applies to REQUIREMENT
8
+ // only (16-assertion.md §1); CONSTRAINT trace shows sources + hierarchy
9
+ // only.
10
+ //
11
+ // 2. Hierarchy — the `parent` chain (ancestors, root last) plus the direct
12
+ // children (elements whose `parent` names this one). Same-TYPE only per
13
+ // 15-requirement.md §2.4; the chain terminates at the first missing or
14
+ // cyclic parent so a broken model still renders something useful.
15
+ //
16
+ // Pure: takes the reverse index + a name-resolution map + optional codex list;
17
+ // no IO. `ComplianceCodexDoc` comes from the scanner so we get jurisdiction
18
+ // alongside the codex id in the sources block.
19
+ function byId(a, b) {
20
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
21
+ }
22
+ function resolveElement(id, catalog) {
23
+ const name = catalog.nameById.get(id);
24
+ return name ? { id, name } : { id };
25
+ }
26
+ /**
27
+ * Walk the `parent` chain upward from `requirement`, stopping at the first
28
+ * missing or already-seen parent (cycle guard). Returns immediate parent first,
29
+ * root last. Empty array when the element has no `parent`.
30
+ */
31
+ function collectAncestors(requirement, index) {
32
+ const out = [];
33
+ const seen = new Set([requirement.id]);
34
+ let current = requirement;
35
+ while (current?.parent && !seen.has(current.parent)) {
36
+ seen.add(current.parent);
37
+ const next = index.requirementById.get(current.parent);
38
+ if (!next)
39
+ break;
40
+ out.push(next);
41
+ current = next;
42
+ }
43
+ return out;
44
+ }
45
+ /**
46
+ * Builds the REQUIREMENT / CONSTRAINT traceability view.
47
+ *
48
+ * @param requirementId typed id of the element to trace
49
+ * @param index reverse index built by `buildComplianceIndex`
50
+ * @param catalog name-resolution map for subject / realised_via refs
51
+ * @param codex optional codex artefact list (from the scanner); when
52
+ * supplied, `sources[].codex` is populated with the
53
+ * resolved codex artefact for jurisdiction display
54
+ */
55
+ export function buildRequirementTrace(requirementId, index, catalog, codex = []) {
56
+ const requirement = index.requirementById.get(requirementId) ?? { id: requirementId, name: requirementId };
57
+ const codexById = new Map();
58
+ for (const c of codex)
59
+ codexById.set(c.id, c);
60
+ const sources = (requirement.derived_from ?? []).map(sid => {
61
+ const c = codexById.get(sid);
62
+ return c ? { id: sid, codex: c } : { id: sid };
63
+ });
64
+ const rawAssertions = index.assertionsByRequirement.get(requirementId) ?? [];
65
+ const assertions = [...rawAssertions]
66
+ .sort(byId)
67
+ .map(assertion => ({
68
+ assertion,
69
+ subject: resolveElement(assertion.subject, catalog),
70
+ realisedVia: (assertion.realised_via ?? []).map(rid => resolveElement(rid, catalog)),
71
+ }));
72
+ const ancestors = collectAncestors(requirement, index);
73
+ const children = [...(index.requirementsByParent.get(requirementId) ?? [])].sort(byId);
74
+ return { requirement, sources, assertions, ancestors, children };
75
+ }
76
+ /**
77
+ * Convenience: build a `TraceElementCatalog` from the scanned canon's product
78
+ * and subject buckets. Requirements/assertions are excluded — they are indexed
79
+ * separately by `buildComplianceIndex`; the catalog is only for resolving the
80
+ * elements a trace references (subjects + realised_via).
81
+ */
82
+ export function buildTraceElementCatalog(products, subjects) {
83
+ const nameById = new Map();
84
+ for (const p of products)
85
+ nameById.set(p.id, p.name);
86
+ for (const s of subjects)
87
+ nameById.set(s.id, s.name);
88
+ return { nameById };
89
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AssertionStatus } from '../assertion/types.js';
2
- /** Projection of a REQUIREMENT the compliance views need. */
2
+ import type { ComplianceCodexDoc } from './classify.js';
3
+ /** Projection of a REQUIREMENT (or CONSTRAINT) the compliance views need. */
3
4
  export interface IndexRequirement {
4
5
  id: string;
5
6
  name: string;
@@ -14,6 +15,38 @@ export interface IndexRequirement {
14
15
  * past or imminent, CV-3 renders an urgent decoration on the cell.
15
16
  */
16
17
  deadline?: string;
18
+ /**
19
+ * Origin taxonomy (15-requirement.md §2.1): `legislative`, `process-product`,
20
+ * or `project-product`. Distinguishes the context from which the obligation
21
+ * was derived. Undefined for existing pre-taxonomy admissions (treated as
22
+ * `legislative` by tooling that supports origin-based filtering).
23
+ */
24
+ origin?: 'legislative' | 'process-product' | 'project-product';
25
+ /**
26
+ * Same-TYPE `parent` reference: the higher-scale obligation this one
27
+ * decomposes from (15-requirement.md §2.4; ELEMENT_PRIMITIVES.md §7.13 for
28
+ * CONSTRAINT). Origin-agnostic, structure-only. Enables the hierarchy half
29
+ * of the requirement traceability view.
30
+ */
31
+ parent?: string;
32
+ /**
33
+ * Motivation-layer element kind. `requirement` = positive obligation
34
+ * (15-requirement.md); `constraint` = restriction / prohibition
35
+ * (ELEMENT_PRIMITIVES.md §7.13). ASSERTION coverage applies to `requirement`
36
+ * only (16-assertion.md §1); the hierarchy half applies to both.
37
+ */
38
+ element_kind?: 'requirement' | 'constraint';
39
+ /**
40
+ * Longer-form description of the obligation (15-requirement.md §2). Optional;
41
+ * used by the requirement traceability view to show the requirement body
42
+ * inline. Not used by matrix / list views.
43
+ */
44
+ description?: string;
45
+ /**
46
+ * `next_review_at` review-checkpoint date (15-requirement.md §2.3; ISO 8601).
47
+ * Present when the author has scheduled a review; drives `REQ-STALE-001`.
48
+ */
49
+ next_review_at?: string;
17
50
  }
18
51
  /**
19
52
  * Temporal status of a requirement deadline relative to today.
@@ -93,6 +126,11 @@ export interface ComplianceIndex {
93
126
  assertionsByRequirement: Map<string, IndexAssertion[]>;
94
127
  /** Subject id (product / process / capability) → assertions about it. */
95
128
  assertionsBySubject: Map<string, IndexAssertion[]>;
129
+ /**
130
+ * Parent id → the requirements/constraints that name it in `parent`
131
+ * (15-requirement.md §2.4). Enables the requirement-hierarchy view.
132
+ */
133
+ requirementsByParent: Map<string, IndexRequirement[]>;
96
134
  }
97
135
  export interface LawTreeRequirement {
98
136
  requirement: IndexRequirement;
@@ -115,3 +153,58 @@ export interface ProductView {
115
153
  /** Requirements bound to the product via an assertion, requirement-id-sorted. */
116
154
  requirements: ProductRequirementStatus[];
117
155
  }
156
+ /** A codex artefact resolved from a requirement's `derived_from` reference. */
157
+ export interface TraceSourceRef {
158
+ /** Verbatim id from `derived_from`. Always present. */
159
+ id: string;
160
+ /** The codex artefact, when resolved by the scan. Absent for dangling refs. */
161
+ codex?: ComplianceCodexDoc;
162
+ }
163
+ /** A named element (subject or realising element) resolved by the trace. */
164
+ export interface TraceElementRef {
165
+ id: string;
166
+ /** Element name when resolved by the scan; absent for dangling refs. */
167
+ name?: string;
168
+ }
169
+ /** One ASSERTION targeting the traced requirement, with subject + realising elements. */
170
+ export interface TraceAssertionRow {
171
+ assertion: IndexAssertion;
172
+ subject: TraceElementRef;
173
+ /** Elements named in the assertion's `realised_via` list (may be empty). */
174
+ realisedVia: TraceElementRef[];
175
+ }
176
+ /**
177
+ * Requirement traceability + hierarchy view.
178
+ *
179
+ * Two halves, both origin-agnostic (15-requirement.md §2.1):
180
+ * 1. Trace chain — `derived_from` source(s) → the element itself → any
181
+ * ASSERTION targeting it (`about`) → the asserted `subject` + `realised_via`
182
+ * elements. Origin-agnostic per 15-requirement.md §2.1; assertion coverage
183
+ * applies to REQUIREMENT only (16-assertion.md §1) — CONSTRAINT trace shows
184
+ * only the source chain + hierarchy.
185
+ * 2. Hierarchy — `parent` chain (ancestors, root last of the array) + children
186
+ * (any element whose `parent` names this one), sorted by id.
187
+ */
188
+ export interface RequirementTrace {
189
+ /** The element being traced (REQUIREMENT or CONSTRAINT). Falls back to a
190
+ * stub carrying the id as its name when the element is missing from the
191
+ * scan (a dangling `parent` or a repository being edited). */
192
+ requirement: IndexRequirement;
193
+ /** Backward-trace: `derived_from` codex artefacts, verbatim order. */
194
+ sources: TraceSourceRef[];
195
+ /** Forward-trace via ASSERTION. Empty for CONSTRAINT elements (16-assertion.md §1) or for a REQUIREMENT with no filed assertion. */
196
+ assertions: TraceAssertionRow[];
197
+ /** Parent chain: immediate parent first, root last. Empty when the element has no `parent`. */
198
+ ancestors: IndexRequirement[];
199
+ /** Direct children: elements naming this one as their `parent`, id-sorted. */
200
+ children: IndexRequirement[];
201
+ }
202
+ /**
203
+ * The complementary data the trace builder needs to name subjects and realising
204
+ * elements. Names are resolved by looking up the id in this map; unresolved ids
205
+ * surface as the id alone (a dangling reference).
206
+ */
207
+ export interface TraceElementCatalog {
208
+ /** id → human-readable name (or the id itself when unnamed). */
209
+ nameById: Map<string, string>;
210
+ }
@@ -0,0 +1,18 @@
1
+ import React from 'react';
2
+ import type { Goal } from './types.js';
3
+ import type { ThemeTokens } from './theme.js';
4
+ export interface GoalNodeData {
5
+ goal: Goal;
6
+ theme: Required<ThemeTokens>;
7
+ readOnly: boolean;
8
+ isDropTarget: boolean;
9
+ hasHiddenChildren: boolean;
10
+ isCollapsed: boolean;
11
+ onAddChild: (parentId: number, parentLevel: number) => void;
12
+ onDelete: (id: number) => void;
13
+ onToggleCollapse: (id: number) => void;
14
+ }
15
+ declare const GoalNode: React.MemoExoticComponent<({ data }: {
16
+ data: GoalNodeData;
17
+ }) => import("react/jsx-runtime").JSX.Element>;
18
+ export default GoalNode;
@@ -0,0 +1,91 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { memo, useState } from 'react';
3
+ import { Handle, Position } from 'reactflow';
4
+ const NODE_WIDTH = 250;
5
+ const NODE_HEIGHT = 80;
6
+ function impactSign(f) {
7
+ const t = f.impact_type;
8
+ if (t === 'mixed')
9
+ return 'both';
10
+ if (t === 'opportunity' || t === 'positive')
11
+ return 'positive';
12
+ return 'negative';
13
+ }
14
+ const GoalNode = memo(({ data }) => {
15
+ const { goal, theme, readOnly, isDropTarget, hasHiddenChildren, isCollapsed } = data;
16
+ const [openPanel, setOpenPanel] = useState(null);
17
+ const positive = (goal.factors ?? []).filter((f) => impactSign(f) !== 'negative');
18
+ const negative = (goal.factors ?? []).filter((f) => impactSign(f) !== 'positive');
19
+ const bg = theme.goalLevelColors[goal.level] ?? theme.goalLevelColors[0];
20
+ return (_jsxs("div", { className: "tx-goal-node", style: {
21
+ position: 'relative',
22
+ width: NODE_WIDTH,
23
+ height: NODE_HEIGHT,
24
+ background: bg,
25
+ borderRadius: 12,
26
+ borderStyle: 'solid',
27
+ borderWidth: isDropTarget ? 2 : theme.cardBorderWidth,
28
+ borderColor: isDropTarget ? theme.dropTargetBorderColor : theme.cardBorderColor,
29
+ boxShadow: '0 1px 4px rgba(0,0,0,0.12)',
30
+ padding: '6px 8px',
31
+ fontSize: 12,
32
+ display: 'flex',
33
+ alignItems: 'stretch',
34
+ justifyContent: 'center',
35
+ }, children: [_jsx(Handle, { type: "target", position: Position.Left, style: { opacity: 0 } }), _jsx(Handle, { type: "source", position: Position.Right, style: { opacity: 0 } }), _jsx("div", { style: { flexShrink: 0, display: 'flex', alignItems: 'center', width: 16 }, children: positive.length > 0 && (_jsxs("span", { role: "button", "aria-label": `${positive.length} positive factor${positive.length > 1 ? 's' : ''}`, title: `${positive.length} positive factor${positive.length > 1 ? 's' : ''}`, onClick: (e) => {
36
+ e.stopPropagation();
37
+ setOpenPanel(openPanel === 'positive' ? null : 'positive');
38
+ }, style: { cursor: 'pointer', color: '#16a34a', fontSize: 14, lineHeight: 1, userSelect: 'none' }, children: ["\u25B2", positive.length > 1 && _jsx("span", { style: { fontSize: 9, fontWeight: 700, marginLeft: 2 }, children: positive.length })] })) }), _jsxs("div", { style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', padding: '0 4px' }, children: [_jsx("div", { title: goal.name, style: {
39
+ fontWeight: 600,
40
+ color: theme.cardTextColor,
41
+ lineHeight: 1.2,
42
+ overflow: 'hidden',
43
+ display: '-webkit-box',
44
+ WebkitLineClamp: 2,
45
+ WebkitBoxOrient: 'vertical',
46
+ wordBreak: 'break-word',
47
+ }, children: goal.name }), _jsxs("div", { style: { fontSize: 10, color: theme.cardMetaColor, marginTop: 2 }, children: ["ID: ", goal.id, " | Lvl: ", goal.level, goal.tag ? ` | #${goal.tag}` : ''] })] }), _jsx("div", { style: { flexShrink: 0, display: 'flex', alignItems: 'center', width: 16, justifyContent: 'flex-end' }, children: negative.length > 0 && (_jsxs("span", { role: "button", "aria-label": `${negative.length} negative factor${negative.length > 1 ? 's' : ''}`, title: `${negative.length} negative factor${negative.length > 1 ? 's' : ''}`, onClick: (e) => {
48
+ e.stopPropagation();
49
+ setOpenPanel(openPanel === 'negative' ? null : 'negative');
50
+ }, style: { cursor: 'pointer', color: '#dc2626', fontSize: 14, lineHeight: 1, userSelect: 'none' }, children: ["\u25BC", negative.length > 1 && _jsx("span", { style: { fontSize: 9, fontWeight: 700, marginLeft: 2 }, children: negative.length })] })) }), openPanel && (_jsx("div", { style: {
51
+ position: 'absolute',
52
+ left: 0,
53
+ width: '100%',
54
+ zIndex: 20,
55
+ display: 'flex',
56
+ flexDirection: 'column',
57
+ gap: 4,
58
+ ...(openPanel === 'positive' ? { bottom: 'calc(100% + 8px)' } : { top: 'calc(100% + 8px)' }),
59
+ }, children: (openPanel === 'positive' ? positive : negative).map((f) => (_jsxs("div", { style: {
60
+ background: openPanel === 'positive' ? '#f0fdf4' : '#fef2f2',
61
+ border: `1px solid ${openPanel === 'positive' ? '#bbf7d0' : '#fecaca'}`,
62
+ color: openPanel === 'positive' ? '#166534' : '#991b1b',
63
+ borderRadius: 4,
64
+ padding: '4px 6px',
65
+ fontSize: 10,
66
+ textAlign: 'left',
67
+ }, children: [_jsx("div", { style: { fontWeight: 700 }, children: f.name }), f.description && _jsx("div", { style: { opacity: 0.85 }, children: f.description })] }, f.id))) })), !readOnly && (_jsx("button", { type: "button", "aria-label": "Add child goal", title: "Add child goal", onClick: (e) => {
68
+ e.stopPropagation();
69
+ data.onAddChild(goal.id, goal.level);
70
+ }, style: {
71
+ position: 'absolute', top: -8, right: -8, width: 16, height: 16,
72
+ borderRadius: '50%', border: '1px solid #86efac', background: '#ffffff',
73
+ color: '#16a34a', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
74
+ }, children: "+" })), !readOnly && (_jsx("button", { type: "button", "aria-label": "Delete goal", title: "Delete goal and descendants", onClick: (e) => {
75
+ e.stopPropagation();
76
+ data.onDelete(goal.id);
77
+ }, style: {
78
+ position: 'absolute', bottom: -8, right: -8, width: 16, height: 16,
79
+ borderRadius: '50%', border: '1px solid #fca5a5', background: '#ffffff',
80
+ color: '#dc2626', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
81
+ }, children: "\u00D7" })), hasHiddenChildren && (_jsx("button", { type: "button", "aria-label": isCollapsed ? 'Expand branch' : 'Collapse branch', title: isCollapsed ? 'Expand branch' : 'Collapse branch', onClick: (e) => {
82
+ e.stopPropagation();
83
+ data.onToggleCollapse(goal.id);
84
+ }, style: {
85
+ position: 'absolute', top: '50%', right: -8, transform: 'translateY(-50%)',
86
+ width: 16, height: 16, borderRadius: '50%', border: `1px solid ${theme.cardBorderColor}`,
87
+ background: '#ffffff', color: theme.cardBorderColor, fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
88
+ }, children: isCollapsed ? '+' : '−' }))] }));
89
+ });
90
+ GoalNode.displayName = 'GoalNode';
91
+ export default GoalNode;
@@ -0,0 +1,57 @@
1
+ import React from 'react';
2
+ import 'reactflow/dist/style.css';
3
+ import type { Goal, GoalTree, GoalTreeLayout, LayoutOptions } from './types.js';
4
+ import type { ThemeTokens } from './theme.js';
5
+ export type { ThemeTokens } from './theme.js';
6
+ export interface GoalTreeViewProps {
7
+ tree: GoalTree;
8
+ layout?: GoalTreeLayout;
9
+ layoutOptions?: LayoutOptions;
10
+ theme?: ThemeTokens;
11
+ readOnly?: boolean;
12
+ showBacklog?: boolean;
13
+ showMiniMap?: boolean;
14
+ onChange?: (event: GoalTreeChange) => void;
15
+ onEditRequest?: (goal: Goal) => void;
16
+ }
17
+ export type GoalTreeChange = {
18
+ kind: 'reparent';
19
+ sourceId: number;
20
+ targetId: number;
21
+ result: GoalTree;
22
+ } | {
23
+ kind: 'addChild';
24
+ parentId: number;
25
+ newGoal: Goal;
26
+ result: GoalTree;
27
+ } | {
28
+ kind: 'delete';
29
+ id: number;
30
+ result: GoalTree;
31
+ } | {
32
+ kind: 'moveToBacklog';
33
+ id: number;
34
+ result: GoalTree;
35
+ } | {
36
+ kind: 'restoreFromBacklog';
37
+ id: number;
38
+ newParentId: number;
39
+ result: GoalTree;
40
+ };
41
+ /** Where a card was dropped, as classified from the pointer position at drag-stop. */
42
+ export type DropTarget = {
43
+ kind: 'node';
44
+ id: number;
45
+ } | {
46
+ kind: 'backlog';
47
+ } | null;
48
+ /**
49
+ * Pure decision: given where a dragged card was dropped, compute the mutation
50
+ * and the GoalTreeChange to report (or null for a no-op drop). Kept separate
51
+ * from the DOM/pointer-event glue in onNodeDragStop so the mutation-selection
52
+ * logic — which card wins reparent vs moveToBacklog vs a refused mutation —
53
+ * is unit-testable without needing a real drag gesture through reactflow's
54
+ * internal, DOM-measurement-gated dragging.
55
+ */
56
+ export declare function computeDragOutcome(tree: GoalTree, sourceId: number, dropTarget: DropTarget): GoalTreeChange | null;
57
+ export declare function GoalTreeView(props: GoalTreeViewProps): React.ReactElement;
@@ -0,0 +1,228 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useMemo, useState, useEffect } from 'react';
3
+ import ReactFlow, { Controls, MiniMap, Background, ConnectionLineType, useNodesState, useEdgesState, } from 'reactflow';
4
+ import 'reactflow/dist/style.css';
5
+ import { layoutGoalTree } from './layout.js';
6
+ import { reparent, addChild, deleteWithDescendants, moveToBacklog, restoreFromBacklog } from './mutations.js';
7
+ import { resolveTheme } from './theme.js';
8
+ import GoalNode from './GoalNode.js';
9
+ const BACKLOG_DRAG_MIME = 'application/x-transitrix-goal-id';
10
+ const nodeTypes = { goalNode: GoalNode };
11
+ /**
12
+ * Pure decision: given where a dragged card was dropped, compute the mutation
13
+ * and the GoalTreeChange to report (or null for a no-op drop). Kept separate
14
+ * from the DOM/pointer-event glue in onNodeDragStop so the mutation-selection
15
+ * logic — which card wins reparent vs moveToBacklog vs a refused mutation —
16
+ * is unit-testable without needing a real drag gesture through reactflow's
17
+ * internal, DOM-measurement-gated dragging.
18
+ */
19
+ export function computeDragOutcome(tree, sourceId, dropTarget) {
20
+ if (!dropTarget)
21
+ return null;
22
+ if (dropTarget.kind === 'backlog') {
23
+ const mutation = moveToBacklog(tree, sourceId);
24
+ if (!mutation.ok || !mutation.result)
25
+ return null;
26
+ return { kind: 'moveToBacklog', id: sourceId, result: mutation.result };
27
+ }
28
+ if (dropTarget.id === sourceId)
29
+ return null;
30
+ const mutation = reparent(tree, sourceId, dropTarget.id);
31
+ if (!mutation.ok || !mutation.result)
32
+ return null;
33
+ return { kind: 'reparent', sourceId, targetId: dropTarget.id, result: mutation.result };
34
+ }
35
+ /** Goals reachable from a root (level 0 or parent_id 0) via valid parent_id chains. */
36
+ function partitionCanvasAndBacklog(goals) {
37
+ const children = new Map();
38
+ for (const g of goals) {
39
+ if (!children.has(g.parent_id))
40
+ children.set(g.parent_id, []);
41
+ children.get(g.parent_id).push(g);
42
+ }
43
+ const roots = goals.filter((g) => g.level === 0 || g.parent_id === 0);
44
+ const reachable = new Set();
45
+ const stack = [...roots.map((r) => r.id)];
46
+ while (stack.length > 0) {
47
+ const id = stack.pop();
48
+ if (reachable.has(id))
49
+ continue;
50
+ reachable.add(id);
51
+ for (const child of children.get(id) ?? [])
52
+ stack.push(child.id);
53
+ }
54
+ const canvas = [];
55
+ const backlog = [];
56
+ for (const g of goals) {
57
+ if (reachable.has(g.id))
58
+ canvas.push(g);
59
+ else
60
+ backlog.push(g); // unreachable from any root — broken/orphaned parent chain
61
+ }
62
+ return { canvas, backlog };
63
+ }
64
+ function GoalTreeViewInner({ tree, layout: layoutProp, layoutOptions, theme: themeProp, readOnly = false, showBacklog = false, showMiniMap = false, onChange, onEditRequest, }) {
65
+ const theme = useMemo(() => resolveTheme(themeProp), [themeProp]);
66
+ const [collapsedIds, setCollapsedIds] = useState(new Set());
67
+ const [hoveredId, setHoveredId] = useState(null);
68
+ const { canvas: canvasGoals, backlog: backlogGoals } = useMemo(() => partitionCanvasAndBacklog(tree.goals), [tree.goals]);
69
+ const layout = useMemo(() => {
70
+ if (layoutProp)
71
+ return layoutProp;
72
+ const hideCollapsed = [...(layoutOptions?.hideCollapsed ?? []), ...collapsedIds];
73
+ return layoutGoalTree({ goal_types: tree.goal_types, goals: canvasGoals }, { ...layoutOptions, hideCollapsed });
74
+ }, [layoutProp, layoutOptions, collapsedIds, tree.goal_types, canvasGoals]);
75
+ const onAddChild = useCallback((parentId, parentLevel) => {
76
+ if (readOnly)
77
+ return;
78
+ const before = new Set(tree.goals.map((g) => g.id));
79
+ const mutation = addChild(tree, parentId, { name: 'New goal', type: '', level: parentLevel + 1, parent_id: parentId });
80
+ if (!mutation.ok || !mutation.result)
81
+ return;
82
+ const newGoal = mutation.result.goals.find((g) => !before.has(g.id));
83
+ if (!newGoal)
84
+ return;
85
+ onChange?.({ kind: 'addChild', parentId, newGoal, result: mutation.result });
86
+ }, [tree, readOnly, onChange]);
87
+ const onDeleteNode = useCallback((id) => {
88
+ if (readOnly)
89
+ return;
90
+ const mutation = deleteWithDescendants(tree, id);
91
+ if (!mutation.ok || !mutation.result)
92
+ return;
93
+ onChange?.({ kind: 'delete', id, result: mutation.result });
94
+ }, [tree, readOnly, onChange]);
95
+ const onRestoreFromBacklog = useCallback((id, newParentId) => {
96
+ if (readOnly)
97
+ return;
98
+ const mutation = restoreFromBacklog(tree, id, newParentId);
99
+ if (!mutation.ok || !mutation.result)
100
+ return;
101
+ onChange?.({ kind: 'restoreFromBacklog', id, newParentId, result: mutation.result });
102
+ }, [tree, readOnly, onChange]);
103
+ const onToggleCollapse = useCallback((id) => {
104
+ setCollapsedIds((prev) => {
105
+ const next = new Set(prev);
106
+ if (next.has(id))
107
+ next.delete(id);
108
+ else
109
+ next.add(id);
110
+ return next;
111
+ });
112
+ }, []);
113
+ const buildNodes = useCallback(() => {
114
+ return layout.nodes.map((n) => ({
115
+ id: String(n.id),
116
+ type: 'goalNode',
117
+ position: { x: n.x, y: n.y },
118
+ draggable: !readOnly,
119
+ data: {
120
+ goal: n.data,
121
+ theme,
122
+ readOnly,
123
+ isDropTarget: hoveredId === n.id,
124
+ hasHiddenChildren: n.hasHiddenChildren,
125
+ isCollapsed: collapsedIds.has(n.id),
126
+ onAddChild,
127
+ onDelete: onDeleteNode,
128
+ onToggleCollapse,
129
+ },
130
+ }));
131
+ }, [layout.nodes, theme, readOnly, hoveredId, collapsedIds, onAddChild, onDeleteNode, onToggleCollapse]);
132
+ const buildEdges = useCallback(() => {
133
+ return layout.edges.map((e) => ({
134
+ id: `e${e.source}-${e.target}`,
135
+ source: String(e.source),
136
+ target: String(e.target),
137
+ type: 'default',
138
+ style: { stroke: theme.edgeColor, strokeWidth: theme.edgeWidth },
139
+ }));
140
+ }, [layout.edges, theme]);
141
+ const [nodes, setNodes, onNodesChange] = useNodesState(buildNodes());
142
+ const [edges, setEdges, onEdgesChange] = useEdgesState(buildEdges());
143
+ // Re-sync whenever the underlying layout/theme/interaction state changes —
144
+ // tree/layout are host-controlled props, not owned by this component.
145
+ useEffect(() => {
146
+ setNodes(buildNodes());
147
+ setEdges(buildEdges());
148
+ // eslint-disable-next-line react-hooks/exhaustive-deps
149
+ }, [layout, theme, readOnly, hoveredId, collapsedIds]);
150
+ const checkIntersection = useCallback((a, b) => {
151
+ const midX = a.position.x + 125;
152
+ const midY = a.position.y + 40;
153
+ return midX > b.position.x && midX < b.position.x + 250 && midY > b.position.y && midY < b.position.y + 80;
154
+ }, []);
155
+ const onNodeDrag = useCallback((_event, node) => {
156
+ if (readOnly)
157
+ return;
158
+ const hit = nodes.find((n) => n.id !== node.id && checkIntersection(node, n));
159
+ setHoveredId(hit ? Number(hit.id) : null);
160
+ }, [readOnly, nodes, checkIntersection]);
161
+ const onNodeDragStop = useCallback((event, node) => {
162
+ if (readOnly) {
163
+ setHoveredId(null);
164
+ return;
165
+ }
166
+ const sourceId = Number(node.id);
167
+ const mouseEvent = event;
168
+ const dropEl = typeof document !== 'undefined' && 'clientX' in mouseEvent
169
+ ? document.elementFromPoint(mouseEvent.clientX, mouseEvent.clientY)
170
+ : null;
171
+ const dropTarget = dropEl?.closest('[data-goaltree-backlog-zone]')
172
+ ? { kind: 'backlog' }
173
+ : hoveredId != null ? { kind: 'node', id: hoveredId } : null;
174
+ const change = computeDragOutcome(tree, sourceId, dropTarget);
175
+ if (change)
176
+ onChange?.(change);
177
+ setHoveredId(null);
178
+ }, [readOnly, hoveredId, tree, onChange]);
179
+ const onNodeDoubleClick = useCallback((_event, node) => {
180
+ const goal = tree.goals.find((g) => g.id === Number(node.id));
181
+ if (goal)
182
+ onEditRequest?.(goal);
183
+ }, [tree.goals, onEditRequest]);
184
+ const onBacklogItemDragStart = useCallback((event, goalId) => {
185
+ event.dataTransfer.setData(BACKLOG_DRAG_MIME, String(goalId));
186
+ event.dataTransfer.effectAllowed = 'move';
187
+ }, []);
188
+ const onCanvasDragOver = useCallback((event) => {
189
+ if (readOnly)
190
+ return;
191
+ event.preventDefault();
192
+ }, [readOnly]);
193
+ const onCanvasDrop = useCallback((event) => {
194
+ if (readOnly)
195
+ return;
196
+ event.preventDefault();
197
+ const idStr = event.dataTransfer.getData(BACKLOG_DRAG_MIME);
198
+ if (!idStr)
199
+ return;
200
+ const goalId = Number(idStr);
201
+ const targetEl = document.elementFromPoint(event.clientX, event.clientY);
202
+ const nodeEl = targetEl?.closest('.react-flow__node');
203
+ const targetIdAttr = nodeEl?.getAttribute('data-id');
204
+ if (targetIdAttr == null)
205
+ return;
206
+ onRestoreFromBacklog(goalId, Number(targetIdAttr));
207
+ }, [readOnly, onRestoreFromBacklog]);
208
+ const showBacklogPanel = showBacklog && backlogGoals.length > 0;
209
+ return (_jsxs("div", { style: { display: 'flex', width: '100%', height: '100%' }, children: [showBacklogPanel && (_jsxs("div", { "data-goaltree-backlog-zone": true, style: {
210
+ width: 220,
211
+ flexShrink: 0,
212
+ borderRight: '1px solid #e2e8f0',
213
+ padding: 10,
214
+ overflowY: 'auto',
215
+ background: '#f8fafc',
216
+ }, children: [_jsx("div", { style: { fontWeight: 700, fontSize: 12, color: '#334155', marginBottom: 8 }, children: "Backlog" }), backlogGoals.map((goal) => (_jsxs("div", { draggable: !readOnly, onDragStart: (e) => onBacklogItemDragStart(e, goal.id), onDoubleClick: () => onEditRequest?.(goal), title: "Drag onto a canvas card to set its parent", style: {
217
+ padding: 8,
218
+ marginBottom: 6,
219
+ background: '#ffffff',
220
+ border: '1px solid #cbd5e1',
221
+ borderRadius: 6,
222
+ fontSize: 11,
223
+ cursor: readOnly ? 'default' : 'grab',
224
+ }, children: [_jsx("div", { style: { fontWeight: 600 }, children: goal.name }), _jsxs("div", { style: { color: '#64748b' }, children: ["Level: ", goal.level] })] }, goal.id)))] })), _jsx("div", { style: { flex: 1, position: 'relative' }, onDragOver: onCanvasDragOver, onDrop: onCanvasDrop, children: _jsxs(ReactFlow, { nodes: nodes, edges: edges, onNodesChange: readOnly ? undefined : onNodesChange, onEdgesChange: readOnly ? undefined : onEdgesChange, nodeTypes: nodeTypes, nodesDraggable: !readOnly, nodesConnectable: false, onNodeDrag: onNodeDrag, onNodeDragStop: onNodeDragStop, onNodeDoubleClick: onNodeDoubleClick, connectionLineType: ConnectionLineType.Bezier, fitView: true, children: [_jsx(Background, {}), _jsx(Controls, {}), showMiniMap && _jsx(MiniMap, { pannable: true, zoomable: true })] }) })] }));
225
+ }
226
+ export function GoalTreeView(props) {
227
+ return _jsx(GoalTreeViewInner, { ...props });
228
+ }
@@ -0,0 +1 @@
1
+ export {};