@atolis-hq/corum 0.1.26 → 0.1.28

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.
package/web/graph.jsx ADDED
@@ -0,0 +1,441 @@
1
+ /* Graph view: interactive three-level canvas using React Flow + Dagre. */
2
+
3
+ const { useState, useEffect, useMemo, useCallback, useRef } = React;
4
+ const { navigate, Icon, TemplateBadge, StateTag, StabilityTag } = window.CorumPrimitives;
5
+ const { buildRoute, parseRoute } = window.CorumRouter;
6
+ const { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName } = window.CorumGraphUtils;
7
+
8
+ const RF = window.ReactFlow;
9
+ const ReactFlowCanvas = RF.ReactFlow || RF.default;
10
+ const { MiniMap, Background, useNodesState, useEdgesState, MarkerType, ReactFlowProvider } = RF;
11
+
12
+ const EDGE_STYLES = {
13
+ 'triggers': { stroke: '#b45309', strokeWidth: 1.5 },
14
+ 'produces': { stroke: '#0f766e', strokeWidth: 1.5 },
15
+ 'calls': { stroke: '#6d28d9', strokeWidth: 1.5 },
16
+ 'implements': { stroke: '#475569', strokeWidth: 1.5 },
17
+ 'reads': { stroke: '#1d4ed8', strokeWidth: 1.5 },
18
+ 'maps-to': { stroke: '#be185d', strokeWidth: 1.5 },
19
+ 'derived-from': { stroke: '#6b7280', strokeWidth: 1.5, strokeDasharray: '5,5' },
20
+ };
21
+
22
+ const EDGE_PILL_STYLES = {
23
+ 'triggers': { background: '#fef3c7', color: '#b45309' },
24
+ 'produces': { background: '#ccfbf1', color: '#0f766e' },
25
+ 'calls': { background: '#ede9fe', color: '#6d28d9' },
26
+ 'implements': { background: '#f1f5f9', color: '#475569' },
27
+ 'reads': { background: '#dbeafe', color: '#1d4ed8' },
28
+ 'maps-to': { background: '#fce7f3', color: '#be185d' },
29
+ 'derived-from': { background: '#f3f4f6', color: '#6b7280' },
30
+ };
31
+
32
+ const ALL_EDGE_TYPES = ['triggers', 'produces', 'reads', 'calls', 'implements', 'maps-to', 'derived-from'];
33
+
34
+ const NODE_W = 210;
35
+ const NODE_H = 88;
36
+ const COMP_W = 180;
37
+ const COMP_H = 72;
38
+
39
+ function loadVisibleEdgeTypes() {
40
+ try {
41
+ const stored = localStorage.getItem('corum:graphEdgeTypes');
42
+ if (stored) return new Set(JSON.parse(stored));
43
+ } catch {}
44
+ return new Set(ALL_EDGE_TYPES);
45
+ }
46
+
47
+ function saveVisibleEdgeTypes(types) {
48
+ try { localStorage.setItem('corum:graphEdgeTypes', JSON.stringify([...types])); } catch {}
49
+ }
50
+
51
+ function computeLayout(rfNodes, rfEdges, nodeW, nodeH) {
52
+ if (!rfNodes.length) return rfNodes;
53
+ const g = new dagre.graphlib.Graph();
54
+ g.setDefaultEdgeLabel(() => ({}));
55
+ g.setGraph({ rankdir: 'LR', nodesep: 50, ranksep: 80 });
56
+ rfNodes.forEach(n => g.setNode(n.id, { width: nodeW, height: nodeH }));
57
+ rfEdges.forEach(e => g.setEdge(e.source, e.target));
58
+ dagre.layout(g);
59
+ return rfNodes.map(n => {
60
+ const pos = g.node(n.id);
61
+ return { ...n, position: { x: pos.x - nodeW / 2, y: pos.y - nodeH / 2 } };
62
+ });
63
+ }
64
+
65
+ function makeRFEdge(edge, edgeStyles) {
66
+ const style = edgeStyles[edge.type] || { stroke: '#a8acb5', strokeWidth: 1.5 };
67
+ return {
68
+ id: edge.id,
69
+ source: edge.from,
70
+ target: edge.to,
71
+ label: edge.type,
72
+ labelStyle: { fontSize: 10, fill: style.stroke },
73
+ labelBgStyle: { fill: 'var(--paper)', fillOpacity: 0.85 },
74
+ style: { stroke: style.stroke, strokeWidth: style.strokeWidth, strokeDasharray: style.strokeDasharray },
75
+ markerEnd: { type: MarkerType.ArrowClosed, color: style.stroke, width: 14, height: 14 },
76
+ type: 'default',
77
+ };
78
+ }
79
+
80
+ function buildRFNodesForNodes(graphNodes, templateMap, onNodeClick, viewingRef) {
81
+ return graphNodes.map(n => {
82
+ const tmpl = templateMap.get(n.template);
83
+ const colour = tmpl?.ui?.colour ?? 'var(--ink-4)';
84
+ return {
85
+ id: n.id,
86
+ type: 'nodeCard',
87
+ position: { x: 0, y: 0 },
88
+ data: {
89
+ nodeId: n.id,
90
+ label: getDisplayName(n.id),
91
+ component: n.component,
92
+ templateLabel: tmpl?.ui?.displayName ?? n.template,
93
+ colour,
94
+ state: n.state,
95
+ stability: n.stability,
96
+ onClick: () => onNodeClick(n.id),
97
+ viewingRef,
98
+ },
99
+ };
100
+ });
101
+ }
102
+
103
+ function buildRFEdgesForEdges(edges, visibleEdgeTypes) {
104
+ return applyEdgeTypeFilter(edges, visibleEdgeTypes).map(e => makeRFEdge(e, EDGE_STYLES));
105
+ }
106
+
107
+ // Level 1: component card node
108
+ function ComponentCardNode({ data }) {
109
+ return (
110
+ <div className="graph-component-card" onClick={data.onClick}>
111
+ <RF.Handle type="target" position={RF.Position.Left} style={{ opacity: 0 }} />
112
+ <div className="graph-component-card-name">{data.label}</div>
113
+ <div className="graph-component-card-count">{data.count} {data.count === 1 ? 'node' : 'nodes'}</div>
114
+ <RF.Handle type="source" position={RF.Position.Right} style={{ opacity: 0 }} />
115
+ </div>
116
+ );
117
+ }
118
+
119
+ // Level 2/3: node card node
120
+ function NodeCardNode({ data }) {
121
+ const colour = data.colour ?? 'var(--ink-4)';
122
+ return (
123
+ <div className="graph-node-card" onClick={data.onClick}>
124
+ <RF.Handle type="target" position={RF.Position.Left} style={{ opacity: 0 }} />
125
+ <div className="graph-node-card-bar" style={{ background: colour }} />
126
+ <div className="graph-node-card-header">
127
+ <TemplateBadge name={data.templateLabel} colour={colour} />
128
+ <StateTag state={data.state} />
129
+ </div>
130
+ <div className="graph-node-card-body">
131
+ <div className="graph-node-card-name" title={data.nodeId}>{data.label}</div>
132
+ <div className="graph-node-card-component">{data.component}</div>
133
+ </div>
134
+ <div className="graph-node-card-footer">
135
+ <StabilityTag stability={data.stability} />
136
+ <button
137
+ className="graph-node-card-link"
138
+ title="View node details"
139
+ onClick={e => { e.stopPropagation(); navigate(buildRoute({ pathname: '/node', params: { id: data.nodeId }, branch: data.viewingRef })); }}
140
+ >
141
+ <Icon name="arrow-up-right-from-square" size={11} />
142
+ </button>
143
+ </div>
144
+ <RF.Handle type="source" position={RF.Position.Right} style={{ opacity: 0 }} />
145
+ </div>
146
+ );
147
+ }
148
+
149
+ const nodeTypes = { componentCard: ComponentCardNode, nodeCard: NodeCardNode };
150
+
151
+ function GraphBreadcrumb({ level, selectedComponent, focalNodeId, onNavigateToRoot, onNavigateToComponent }) {
152
+ return (
153
+ <div className="graph-breadcrumb">
154
+ <button className="graph-breadcrumb-item" onClick={onNavigateToRoot}>Graph</button>
155
+ {(level === 'interior' || level === 'focus') && selectedComponent && (
156
+ <>
157
+ <span className="graph-breadcrumb-sep">/</span>
158
+ {level === 'interior'
159
+ ? <span className="graph-breadcrumb-current">{selectedComponent}</span>
160
+ : <button className="graph-breadcrumb-item" onClick={() => onNavigateToComponent(selectedComponent)}>{selectedComponent}</button>
161
+ }
162
+ </>
163
+ )}
164
+ {level === 'focus' && focalNodeId && (
165
+ <>
166
+ <span className="graph-breadcrumb-sep">/</span>
167
+ <span className="graph-breadcrumb-current">{getDisplayName(focalNodeId)}</span>
168
+ </>
169
+ )}
170
+ </div>
171
+ );
172
+ }
173
+
174
+ function GraphToolbar({ visibleEdgeTypes, onToggleEdgeType, showMinimap, onToggleMinimap, onResetLayout, level, depth, onDepth, allNodes, focalNodeId, onFocalNode }) {
175
+ const [searchQuery, setSearchQuery] = useState('');
176
+ const [searchOpen, setSearchOpen] = useState(false);
177
+ const searchRef = useRef(null);
178
+
179
+ const searchResults = useMemo(() => {
180
+ if (!searchQuery.trim()) return [];
181
+ const q = searchQuery.toLowerCase();
182
+ return allNodes
183
+ .filter(n => n.id.toLowerCase().includes(q))
184
+ .slice(0, 8);
185
+ }, [searchQuery, allNodes]);
186
+
187
+ useEffect(() => {
188
+ if (!searchOpen) return;
189
+ function handleClick(e) {
190
+ if (searchRef.current && !searchRef.current.contains(e.target)) setSearchOpen(false);
191
+ }
192
+ document.addEventListener('mousedown', handleClick);
193
+ return () => document.removeEventListener('mousedown', handleClick);
194
+ }, [searchOpen]);
195
+
196
+ return (
197
+ <div className="graph-toolbar">
198
+ {ALL_EDGE_TYPES.map(type => {
199
+ const active = visibleEdgeTypes.has(type);
200
+ const pill = EDGE_PILL_STYLES[type] || {};
201
+ return (
202
+ <span
203
+ key={type}
204
+ className={`graph-edge-pill${active ? '' : ' inactive'}`}
205
+ style={active ? pill : {}}
206
+ onClick={() => onToggleEdgeType(type)}
207
+ >
208
+ {type}
209
+ </span>
210
+ );
211
+ })}
212
+ <div className="graph-toolbar-sep" />
213
+ {level === 'focus' && (
214
+ <>
215
+ <div className="graph-depth-seg">
216
+ {[['1', 1], ['2', 2], ['∞', Infinity]].map(([label, val]) => (
217
+ <button
218
+ key={label}
219
+ className={`graph-depth-item${depth === val ? ' active' : ''}`}
220
+ onClick={() => onDepth(val)}
221
+ >
222
+ {label}
223
+ </button>
224
+ ))}
225
+ </div>
226
+ <div className="graph-focus-search" ref={searchRef}>
227
+ <input
228
+ className="graph-focus-search-input"
229
+ placeholder="Focus node..."
230
+ value={searchQuery}
231
+ onChange={e => { setSearchQuery(e.target.value); setSearchOpen(true); }}
232
+ onFocus={() => setSearchOpen(true)}
233
+ />
234
+ {searchOpen && searchResults.length > 0 && (
235
+ <div className="graph-focus-search-dropdown">
236
+ {searchResults.map(n => (
237
+ <div
238
+ key={n.id}
239
+ className={`graph-focus-search-item${n.id === focalNodeId ? ' selected' : ''}`}
240
+ onClick={() => { onFocalNode(n.id); setSearchQuery(''); setSearchOpen(false); }}
241
+ >
242
+ <span style={{ fontWeight: 500 }}>{getDisplayName(n.id)}</span>
243
+ <span style={{ color: 'var(--ink-3)', fontSize: 10, marginLeft: 4 }}>{n.component}</span>
244
+ </div>
245
+ ))}
246
+ </div>
247
+ )}
248
+ </div>
249
+ <div className="graph-toolbar-sep" />
250
+ </>
251
+ )}
252
+ <button className="graph-toolbar-btn" onClick={onResetLayout}>Reset layout</button>
253
+ <button className={`graph-toolbar-btn${showMinimap ? ' active' : ''}`} onClick={onToggleMinimap}>Minimap</button>
254
+ </div>
255
+ );
256
+ }
257
+
258
+ function GraphView({ route, viewingRef, templates }) {
259
+ const [graphData, setGraphData] = useState(null);
260
+ const [error, setError] = useState(null);
261
+ const [visibleEdgeTypes, setVisibleEdgeTypes] = useState(loadVisibleEdgeTypes);
262
+ const [showMinimap, setShowMinimap] = useState(false);
263
+ const [depth, setDepth] = useState(1);
264
+ const [layoutKey, setLayoutKey] = useState(0);
265
+ const [rfNodes, setRfNodes, onNodesChange] = useNodesState([]);
266
+ const [rfEdges, setRfEdges, onEdgesChange] = useEdgesState([]);
267
+
268
+ // Derive level and selection from URL
269
+ const selectedComponent = route.params.get('component') ?? null;
270
+ const focalNodeId = route.params.get('focus') ?? null;
271
+ const level = focalNodeId ? 'focus' : selectedComponent ? 'interior' : 'component';
272
+
273
+ const navToRoot = useCallback(() => {
274
+ navigate(buildRoute({ pathname: '/graph', params: {}, branch: viewingRef }));
275
+ }, [viewingRef]);
276
+
277
+ const navToComponent = useCallback(component => {
278
+ navigate(buildRoute({ pathname: '/graph', params: { component }, branch: viewingRef }));
279
+ }, [viewingRef]);
280
+
281
+ const navToFocus = useCallback(nodeId => {
282
+ const params = { focus: nodeId };
283
+ if (selectedComponent) params.component = selectedComponent;
284
+ navigate(buildRoute({ pathname: '/graph', params, branch: viewingRef }));
285
+ }, [viewingRef, selectedComponent]);
286
+
287
+ useEffect(() => {
288
+ setGraphData(null);
289
+ setError(null);
290
+ const refParam = viewingRef ? `?ref=${encodeURIComponent(viewingRef)}` : '';
291
+ fetch(`/api/graph${refParam}`)
292
+ .then(r => r.ok ? r.json() : Promise.reject(r.status))
293
+ .then(setGraphData)
294
+ .catch(err => setError(String(err)));
295
+ }, [viewingRef]);
296
+
297
+ const templateMap = useMemo(() => new Map((templates ?? []).map(t => [t.name, t])), [templates]);
298
+
299
+ const templateColour = useCallback(templateName => {
300
+ return templateMap.get(templateName)?.ui?.colour ?? 'var(--ink-4)';
301
+ }, [templateMap]);
302
+
303
+ // Level 1: component map
304
+ const level1 = useMemo(() => {
305
+ if (!graphData) return null;
306
+ const { nodes: cmNodes, edges: cmEdges } = buildComponentMap(graphData.nodes, graphData.edges);
307
+ const filteredCmEdges = cmEdges.filter(e => e.types.some(t => visibleEdgeTypes.has(t)));
308
+ const rfN = cmNodes.map(n => ({
309
+ id: n.id,
310
+ type: 'componentCard',
311
+ position: { x: 0, y: 0 },
312
+ data: { label: n.component, count: n.count, onClick: () => navToComponent(n.component) },
313
+ }));
314
+ const rfE = filteredCmEdges.map(e => {
315
+ const repType = e.types.find(t => visibleEdgeTypes.has(t)) ?? e.types[0];
316
+ return {
317
+ ...makeRFEdge({ ...e, type: repType }, EDGE_STYLES),
318
+ label: e.types.join(', '),
319
+ };
320
+ });
321
+ return { rfN: computeLayout(rfN, rfE, COMP_W, COMP_H), rfE };
322
+ }, [graphData, visibleEdgeTypes, layoutKey, navToComponent]);
323
+
324
+ useEffect(() => {
325
+ if (level !== 'component' || !level1) return;
326
+ setRfNodes(level1.rfN);
327
+ setRfEdges(level1.rfE);
328
+ }, [level, level1]);
329
+
330
+ // Level 2: component interior
331
+ const level2 = useMemo(() => {
332
+ if (!graphData || !selectedComponent) return null;
333
+ const compNodes = graphData.nodes.filter(n => n.component === selectedComponent);
334
+ const compNodeIds = new Set(compNodes.map(n => n.id));
335
+ const internalEdges = graphData.edges.filter(e => compNodeIds.has(e.from) && compNodeIds.has(e.to));
336
+ const crossEdges = graphData.edges.filter(e =>
337
+ (compNodeIds.has(e.from) && !compNodeIds.has(e.to)) ||
338
+ (!compNodeIds.has(e.from) && compNodeIds.has(e.to))
339
+ );
340
+ const externalNodeIds = new Set([
341
+ ...crossEdges.map(e => e.from).filter(id => !compNodeIds.has(id)),
342
+ ...crossEdges.map(e => e.to).filter(id => !compNodeIds.has(id)),
343
+ ]);
344
+ const externalNodes = graphData.nodes.filter(n => externalNodeIds.has(n.id));
345
+ const allVisibleNodes = [...compNodes, ...externalNodes];
346
+ const allVisibleEdges = [...internalEdges, ...crossEdges];
347
+ const rfN = buildRFNodesForNodes(allVisibleNodes, templateMap, navToFocus, viewingRef);
348
+ const rfE = buildRFEdgesForEdges(allVisibleEdges, visibleEdgeTypes).map(e => {
349
+ const isCross = crossEdges.some(ce => ce.id === e.id);
350
+ return isCross ? { ...e, style: { ...e.style, opacity: 0.45 }, labelStyle: { ...e.labelStyle, opacity: 0.45 } } : e;
351
+ });
352
+ return { rfN: computeLayout(rfN, rfE, NODE_W, NODE_H), rfE };
353
+ }, [graphData, selectedComponent, visibleEdgeTypes, templateMap, layoutKey, navToFocus]);
354
+
355
+ useEffect(() => {
356
+ if (level !== 'interior' || !level2) return;
357
+ setRfNodes(level2.rfN);
358
+ setRfEdges(level2.rfE);
359
+ }, [level, level2]);
360
+
361
+ // Level 3: node focus
362
+ const level3 = useMemo(() => {
363
+ if (!graphData || !focalNodeId) return null;
364
+ const { nodes: focusNodes, edges: focusEdges } = buildFocusGraph(
365
+ focalNodeId, graphData.nodes, graphData.edges, depth
366
+ );
367
+ const rfN = buildRFNodesForNodes(focusNodes, templateMap, nodeId => {
368
+ navigate(buildRoute({ pathname: '/graph', params: { focus: nodeId }, branch: viewingRef }));
369
+ }, viewingRef);
370
+ const rfE = buildRFEdgesForEdges(focusEdges, visibleEdgeTypes);
371
+ const layoutedN = computeLayout(rfN, rfE, NODE_W, NODE_H);
372
+ return {
373
+ rfN: layoutedN.map(n => n.id === focalNodeId
374
+ ? { ...n, style: { outline: '2px solid var(--accent)', outlineOffset: '2px', borderRadius: 'var(--radius)' } }
375
+ : n
376
+ ),
377
+ rfE,
378
+ };
379
+ }, [graphData, focalNodeId, depth, visibleEdgeTypes, templateMap, layoutKey, viewingRef]);
380
+
381
+ useEffect(() => {
382
+ if (level !== 'focus' || !level3) return;
383
+ setRfNodes(level3.rfN);
384
+ setRfEdges(level3.rfE);
385
+ }, [level, level3]);
386
+
387
+ function handleToggleEdgeType(type) {
388
+ setVisibleEdgeTypes(prev => {
389
+ const next = new Set(prev);
390
+ next.has(type) ? next.delete(type) : next.add(type);
391
+ saveVisibleEdgeTypes(next);
392
+ return next;
393
+ });
394
+ }
395
+
396
+ if (!graphData && !error) return <div className="graph-section"><p className="label-sm" style={{ padding: 24 }}>Loading graph...</p></div>;
397
+ if (error) return <div className="graph-section"><p style={{ color: 'var(--warn)', padding: 24 }}>Error loading graph: {error}</p></div>;
398
+
399
+ return (
400
+ <div className="graph-section">
401
+ <GraphBreadcrumb
402
+ level={level}
403
+ selectedComponent={selectedComponent}
404
+ focalNodeId={focalNodeId}
405
+ onNavigateToRoot={navToRoot}
406
+ onNavigateToComponent={navToComponent}
407
+ />
408
+ <GraphToolbar
409
+ visibleEdgeTypes={visibleEdgeTypes}
410
+ onToggleEdgeType={handleToggleEdgeType}
411
+ showMinimap={showMinimap}
412
+ onToggleMinimap={() => setShowMinimap(v => !v)}
413
+ onResetLayout={() => setLayoutKey(k => k + 1)}
414
+ level={level}
415
+ depth={depth}
416
+ onDepth={setDepth}
417
+ allNodes={graphData?.nodes ?? []}
418
+ focalNodeId={focalNodeId}
419
+ onFocalNode={navToFocus}
420
+ />
421
+ <div className="graph-canvas-wrap">
422
+ <ReactFlowProvider>
423
+ <ReactFlowCanvas
424
+ nodes={rfNodes}
425
+ edges={rfEdges}
426
+ onNodesChange={onNodesChange}
427
+ onEdgesChange={onEdgesChange}
428
+ nodeTypes={nodeTypes}
429
+ fitView
430
+ proOptions={{ hideAttribution: true }}
431
+ >
432
+ <Background />
433
+ {showMinimap && <MiniMap />}
434
+ </ReactFlowCanvas>
435
+ </ReactFlowProvider>
436
+ </div>
437
+ </div>
438
+ );
439
+ }
440
+
441
+ window.CorumGraph = { GraphView };
package/web/index.html CHANGED
@@ -10,6 +10,7 @@
10
10
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
11
11
  <link rel="stylesheet" href="style.css" />
12
12
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" />
13
+ <link rel="stylesheet" href="https://unpkg.com/reactflow@11.11.4/dist/style.css" crossorigin="anonymous" />
13
14
  <script>
14
15
  window.CorumPlugins = {};
15
16
  </script>
@@ -19,11 +20,15 @@
19
20
 
20
21
  <script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js" crossorigin="anonymous"></script>
21
22
  <script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js" crossorigin="anonymous"></script>
23
+ <script src="https://unpkg.com/dagre@0.8.5/dist/dagre.min.js" crossorigin="anonymous"></script>
24
+ <script src="https://unpkg.com/reactflow@11.11.4/dist/umd/index.js" crossorigin="anonymous"></script>
22
25
  <script src="https://unpkg.com/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>
23
26
  <script src="nav.js"></script>
24
27
  <script src="router.js"></script>
28
+ <script src="graph-utils.js"></script>
25
29
  <script type="text/babel" src="primitives.jsx"></script>
26
30
  <script type="text/babel" src="search.jsx"></script>
31
+ <script type="text/babel" src="graph.jsx"></script>
27
32
  <script type="text/babel">
28
33
  fetch('/api/plugins')
29
34
  .then(response => response.ok ? response.json() : [])
@@ -0,0 +1 @@
1
+ { "type": "commonjs" }
package/web/router.js CHANGED
@@ -1,7 +1,7 @@
1
1
  (function () {
2
2
  'use strict';
3
3
 
4
- var KNOWN_PATHS = new Set(['/dashboard', '/components', '/node']);
4
+ var KNOWN_PATHS = new Set(['/dashboard', '/components', '/node', '/graph']);
5
5
 
6
6
  function parseRoute(hash) {
7
7
  var raw = (hash || '').replace(/^#/, '') || '/dashboard';