-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.template.html
More file actions
1649 lines (1389 loc) · 57.7 KB
/
Copy pathgraph.template.html
File metadata and controls
1649 lines (1389 loc) · 57.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dependency Graph</title>
<style>
:root {
--bg-color: #0f111a;
--sidebar-bg: #161b22;
--sidebar-border: #1f242e;
--text-color: #e6edf3;
--text-muted: #8b949e;
--accent-color: #58a6ff;
--node-bg: rgba(20, 25, 30, 0.9);
--node-border: #444c56;
--link-color: #58a6ff;
--input-bg: #0d1117;
--input-border: #30363d;
--highlight-color: #e2e8f0;
--tech-accent: #2ea44f;
--tech-dim: #3fb950;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
display: flex;
height: 100vh;
overflow: hidden;
}
/* Sidebar Styles */
aside {
width: 300px;
background-color: var(--sidebar-bg);
border-right: 1px solid var(--sidebar-border);
display: flex;
flex-direction: column;
padding: 20px;
box-sizing: border-box;
z-index: 10;
}
h1,
h2,
h3 {
margin: 0 0 10px 0;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--text-muted);
}
.section {
margin-bottom: 24px;
}
.control-group {
margin-bottom: 12px;
}
label {
display: block;
margin-bottom: 5px;
font-size: 15px;
}
select,
input[type="text"] {
width: 100%;
padding: 8px 12px;
background-color: var(--input-bg);
border: 1px solid var(--input-border);
border-radius: 6px;
color: var(--text-color);
font-size: 16px;
box-sizing: border-box;
}
select:focus,
input:focus {
outline: none;
border-color: var(--accent-color);
}
/* Main Canvas Area */
main {
flex-grow: 1;
position: relative;
overflow: hidden;
background-image: radial-gradient(#2d333b 1px, transparent 1px);
background-size: 20px 20px;
cursor: grab;
user-select: none;
-webkit-user-select: none;
}
main:active {
cursor: grabbing;
}
svg {
width: 100%;
height: 100%;
}
.node path.frame {
fill: var(--node-bg);
stroke: var(--node-border);
stroke-width: 1.5px;
fill-opacity: 0.95;
transition: stroke 0.2s, fill 0.2s, stroke-width 0.2s;
}
.node:hover path.frame {
stroke: var(--accent-color);
stroke-width: 2px;
fill: #1f242e;
}
.node path.header-bg {
fill: rgba(255, 255, 255, 0.05);
stroke: none;
}
.node text {
fill: var(--text-color);
font-family: monospace;
pointer-events: none;
/* text-anchor: middle; REMOVED to allow specific positioning */
}
.node text.main-label {
font-size: 28px;
font-weight: 700;
letter-spacing: 0.5px;
fill: #ffffff;
dominant-baseline: middle;
text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}
.node text.meta-label {
font-size: 13px;
fill: var(--text-muted);
dominant-baseline: hanging;
font-family: "Courier New", Courier, monospace;
opacity: 0.8;
}
.node text.method-label {
font-family: "Courier New", Courier, monospace;
fill: var(--text-muted);
pointer-events: auto;
/* Enable hover for tooltips */
cursor: help;
/* Visual cue for tooltip */
}
.node text.return-object,
.node text.return-array,
.node text.return-enum {
pointer-events: auto;
cursor: pointer;
}
.link {
stroke: var(--link-color);
stroke-width: 1.5px;
stroke-opacity: 0.6;
fill: none;
}
.arrowhead {
fill: var(--link-color);
}
#zoom-controls {
position: absolute;
bottom: 20px;
right: 20px;
display: flex;
background: var(--sidebar-bg);
border: 1px solid var(--sidebar-border);
border-radius: 6px;
overflow: hidden;
}
.btn {
padding: 8px 12px;
background: transparent;
border: none;
color: var(--text-color);
cursor: pointer;
border-right: 1px solid var(--sidebar-border);
font-size: 16px;
}
.btn:last-child {
border-right: none;
}
.btn:hover {
background-color: var(--node-bg);
}
.top-bar {
position: absolute;
top: 20px;
left: 20px;
display: flex;
gap: 10px;
}
</style>
</head>
<body>
<aside>
<div class="section">
<div class="control-group">
<input type="text" id="search-input" placeholder="🔍 Filter nodes...">
</div>
</div>
<div class="section">
<h3>Filters</h3>
<div class="control-group">
<label for="service-filter">Service Name</label>
<select id="service-filter">
<option value="all">All Services</option>
</select>
</div>
<div class="control-group">
<label for="version-filter">Version</label>
<select id="version-filter">
<option value="all">All Versions</option>
</select>
</div>
</div>
</aside>
<main id="graph-container">
<div class="top-bar">
</div>
<svg id="graph-svg">
<defs>
<marker id="arrow" viewBox="0 -5 10 10" refX="10" refY="0" markerWidth="6" markerHeight="6" orient="auto">
<path d="M0,-5L10,0L0,5" class="arrowhead"></path>
</marker>
</defs>
<g id="zoom-layer"></g>
</svg>
<div id="zoom-controls">
<button class="btn" id="btn-zoom-in">+</button>
<button class="btn" id="btn-zoom-out">-</button>
<button class="btn" id="btn-reset">Reset Zoom</button>
</div>
</main>
<script>
let GLOBAL_DEFINITIONS = {}; // {{ GLOBAL_DEFINITIONS_DATA }}
// Service Data Slots
let BUCHUNG_DATA = []; // {{ BUCHUNG_GRAPH_DATA }}
let DATALAKE_DATA = []; // {{ DATALAKE_GRAPH_DATA }}
let DEVICETOKEN_DATA = []; // {{ DEVICETOKEN_GRAPH_DATA }}
let KUNDENKONTO_DATA = []; // {{ KUNDENKONTO_GRAPH_DATA }}
let LOCATION_DATA = []; // {{ LOCATION_GRAPH_DATA }}
let PRIVATKUNDE_DATA = []; // {{ PRIVATKUNDE_GRAPH_DATA }}
let REISEN_DATA = []; // {{ REISEN_GRAPH_DATA }}
let REISEWUNSCH_DATA = []; // {{ REISEWUNSCH_GRAPH_DATA }}
let STAMMDATEN_DATA = []; // {{ STAMMDATEN_GRAPH_DATA }}
let WARENKORB_DATA = []; // {{ WARENKORB_GRAPH_DATA }}
let ZAHLUNG_DATA = []; // {{ ZAHLUNG_GRAPH_DATA }}
let RAW_DATA = [
...BUCHUNG_DATA,
...DATALAKE_DATA,
...DEVICETOKEN_DATA,
...KUNDENKONTO_DATA,
...LOCATION_DATA,
...PRIVATKUNDE_DATA,
...REISEN_DATA,
...REISEWUNSCH_DATA,
...STAMMDATEN_DATA,
...WARENKORB_DATA,
...ZAHLUNG_DATA,
];
// --- MOCK DATA FOR TESTING ---
if (typeof RAW_DATA === 'undefined' || (typeof RAW_DATA === 'object' && Object.keys(RAW_DATA).length === 0 && !Array.isArray(RAW_DATA))) {
console.warn('Using MOCK DATA');
RAW_DATA = [
[
{
node: { name: 'AppModule', containerName: 'core-service', version: '1.0.0' },
dependencies: [
{ name: 'GraphQLModule', containerName: 'core-service', version: '1.0.0' },
{ name: 'RecipesModule', containerName: 'recipe-service', version: '2.1.0' },
{ name: 'IamModule', containerName: 'auth-service', version: '1.2.0' },
],
},
{
node: { name: 'GraphQLModule', containerName: 'core-service', version: '1.0.0' },
dependencies: [
{ name: 'GraphQLSchemaBuilderModule', containerName: 'core-service', version: '1.0.0' },
],
},
{
node: { name: 'RecipesModule', containerName: 'recipe-service', version: '2.1.0' },
dependencies: [
{ name: 'InternalCoreModule', containerName: 'core-service', version: '1.0.0' },
],
},
{
node: { name: 'IamModule', containerName: 'auth-service', version: '1.2.0' },
dependencies: [
{ name: 'InternalCoreModule', containerName: 'core-service', version: '1.0.0' },
],
},
{
node: { name: 'InternalCoreModule', containerName: 'core-service', version: '1.0.0' },
dependencies: [],
},
],
];
}
class GraphVis {
constructor() {
this.svg = document.getElementById('graph-svg');
this.width = this.svg.clientWidth;
this.height = this.svg.clientHeight;
this.layer = document.getElementById('zoom-layer');
this.nodes = [];
this.links = [];
this.scale = 0.512; // 3 steps zoom out (0.8^3)
this.translateX = 40; // Initial padding
this.scale = 0.512; // 3 steps zoom out (0.8^3)
this.translateX = 40; // Initial padding
this.translateY = 40;
this.dragState = { isDragging: false, node: null, startX: 0, startY: 0, hasDragged: false };
this.panState = { isPanning: false, startX: 0, startY: 0 };
this.expandedReturns = new Set();
this.setupEventListeners();
this.processData();
window.addEventListener('resize', () => {
this.width = this.svg.clientWidth;
this.height = this.svg.clientHeight;
this.render();
});
}
processData() {
// Flatten data
const allNodes = new Map();
const allLinks = [];
const trees = Array.isArray(RAW_DATA) ? RAW_DATA : [RAW_DATA];
trees.forEach(tree => {
// Handle new structure: Array of { node, dependencies }
if (Array.isArray(tree)) {
tree.forEach(item => {
const sourceNode = item.node;
const dependencies = item.dependencies;
if (!allNodes.has(sourceNode.name)) {
allNodes.set(sourceNode.name, {
id: sourceNode.name,
containerName: sourceNode.containerName,
version: sourceNode.version,
width: 0, height: 0,
methods: sourceNode.methods || [],
showDetails: false,
});
} else {
// Update metadata if we previously saw it as a dependency (unknown metadata)
const node = allNodes.get(sourceNode.name);
if (node.containerName === 'unknown' && sourceNode.containerName) {
node.containerName = sourceNode.containerName;
node.version = sourceNode.version;
}
if ((!node.methods || node.methods.length === 0) && sourceNode.methods && sourceNode.methods.length > 0) {
node.methods = sourceNode.methods;
}
}
dependencies.forEach(dep => {
if (!allNodes.has(dep.name)) {
allNodes.set(dep.name, {
id: dep.name,
containerName: dep.containerName,
version: dep.version,
width: 0, height: 0,
methods: [], // Dependencies usually don't carry methods, will be filled when processed as sourceNode
showDetails: false,
});
} else {
const node = allNodes.get(dep.name);
if (node.containerName === 'unknown' && dep.containerName) {
node.containerName = dep.containerName;
node.version = dep.version;
}
}
// Avoid duplicates
const linkExists = allLinks.some(l => l.source === sourceNode.name && l.target === dep.name);
if (!linkExists) {
allLinks.push({ source: sourceNode.name, target: dep.name });
}
});
});
} else {
console.warn('Unknown tree structure encountered', tree);
}
});
this.allNodesData = Array.from(allNodes.values());
this.allLinksData = allLinks;
this.populateFilters();
this.filterData();
}
populateFilters() {
const services = new Set();
this.allNodesData.forEach(node => {
if (node.containerName && node.containerName !== 'unknown') services.add(node.containerName);
});
const serviceSelect = document.getElementById('service-filter');
// Clear existing options except the first one
while (serviceSelect.options.length > 1) {
serviceSelect.remove(1);
}
services.forEach(s => {
const opt = document.createElement('option');
opt.value = s;
opt.textContent = s;
serviceSelect.appendChild(opt);
});
// Initial population of versions
this.updateVersionOptions('all');
serviceSelect.addEventListener('change', () => {
this.updateVersionOptions(serviceSelect.value);
this.filterData();
});
const versionSelect = document.getElementById('version-filter');
versionSelect.addEventListener('change', () => this.filterData());
document.getElementById('search-input').addEventListener('input', () => this.filterData());
}
updateVersionOptions(selectedService) {
const versionSelect = document.getElementById('version-filter');
const currentVersion = versionSelect.value;
// Clear existing options except "All Versions"
while (versionSelect.options.length > 1) {
versionSelect.remove(1);
}
const versions = new Set();
this.allNodesData.forEach(node => {
if (selectedService === 'all' || node.containerName === selectedService) {
if (node.version && node.version !== 'unknown') {
versions.add(node.version);
}
}
});
// Sort versions semantically if possible, or just alphabetically
const sortedVersions = Array.from(versions).sort().reverse();
sortedVersions.forEach(v => {
const opt = document.createElement('option');
opt.value = v;
opt.textContent = v;
versionSelect.appendChild(opt);
});
// Try to preserve selection if valuable, else reset to 'all'
// If the previously selected version is still in the list, keep it.
// Otherwise, switch to 'all'.
if (versions.has(currentVersion)) {
versionSelect.value = currentVersion;
} else {
versionSelect.value = 'all';
}
}
getExpandedSet(nodeIds, includeRelated = true) {
if (!includeRelated) return nodeIds;
const expanded = new Set(nodeIds);
let added = true;
let iterations = 0;
while (added && iterations < 50) { // Limit increased to ensure deep chains are shown
added = false;
const currentIds = new Set(expanded);
this.allLinksData.forEach(l => {
const hasSource = currentIds.has(l.source);
const hasTarget = currentIds.has(l.target);
if (hasSource && !hasTarget) {
expanded.add(l.target);
added = true;
}
// Optional: Include upstream parents?
// if (!hasSource && hasTarget) { expanded.add(l.source); added = true; }
});
iterations++;
}
return expanded;
}
filterData() {
const serviceFilter = document.getElementById('service-filter').value;
const versionFilter = document.getElementById('version-filter').value;
const searchQuery = document.getElementById('search-input').value.toLowerCase();
const includeRelated = true;
// 1. Establish the "Base Context" (Service/Version Filter)
// These are the nodes that *strictly* match selected dropdowns.
// If "all" is selected, everything is valid context.
const baseContextNodes = this.allNodesData.filter(node => {
if (serviceFilter !== 'all' && node.containerName !== serviceFilter) return false;
if (versionFilter !== 'all' && node.version !== versionFilter) return false;
return true;
});
const baseContextIds = new Set(baseContextNodes.map(n => n.id));
// 2. Expand Context (Find dependencies of the base context)
// This creates the "Visible Universe" - everything relevant to the selected service/version.
// If we limited search strictly to baseContextIds, we couldn't find dependencies that are shown.
const visibleUniverseIds = this.getExpandedSet(baseContextIds, includeRelated);
let finalNodeIds = new Set();
// 3. Apply Search *within* the Visible Universe
if (searchQuery) {
// Find nodes in the universe that match the search query
const matchedInUniverse = [];
visibleUniverseIds.forEach(id => {
const node = this.allNodesData.find(n => n.id === id);
if (!node) return;
let matchFound = false;
// 1. Check ID
if (node.id.toLowerCase().includes(searchQuery)) matchFound = true;
// 2. Check Return Structure Only (User request)
if (!matchFound && node.methods) {
for (const method of node.methods) {
let rStruct = method.returnStructure;
if (rStruct && rStruct.toString().startsWith('REF:') && typeof GLOBAL_DEFINITIONS !== 'undefined') {
rStruct = GLOBAL_DEFINITIONS[rStruct] || rStruct;
}
if (rStruct && rStruct.toString().toLowerCase().includes(searchQuery)) {
matchFound = true;
break;
}
}
}
if (matchFound) {
matchedInUniverse.push(id);
}
});
// 4. Expand the Search Results (show their context)
// If I searched for a dependency, I want to see its connections too.
finalNodeIds = this.getExpandedSet(new Set(matchedInUniverse), includeRelated);
} else {
// No search, just show the universe
finalNodeIds = visibleUniverseIds;
}
this.nodes = this.allNodesData.filter(n => finalNodeIds.has(n.id));
const nodeIds = new Set(this.nodes.map(n => n.id));
this.links = this.allLinksData.filter(l => nodeIds.has(l.source) && nodeIds.has(l.target))
.map(l => ({
source: this.nodes.find(n => n.id === l.source),
target: this.nodes.find(n => n.id === l.target),
}));
// Check zoom level again as node set changed, but usually we just re-layout
this.computeLayout();
this.render();
const isFiltered = (serviceFilter !== 'all' || versionFilter !== 'all' || searchQuery.length > 0);
this.centerGraph(isFiltered);
}
computeLayout() {
// A simple Layered Graph Layout (DFS-based)
// 0. Pre-calculate dimensions for all nodes so we have accurate sizes for layout
this.calculateAllNodeDimensions();
// 1. Build Adjacency List & Incoming Counts
const adj = new Map();
const incomingCount = new Map();
this.nodes.forEach(n => {
adj.set(n.id, []);
incomingCount.set(n.id, 0);
});
this.links.forEach(l => {
adj.get(l.source.id).push(l.target);
incomingCount.set(l.target.id, (incomingCount.get(l.target.id) || 0) + 1);
});
// Sort children by name for deterministic traversal
adj.forEach(children => children.sort((a, b) => a.id.localeCompare(b.id)));
// 2. Assign Layers (Rank - X Coordinate)
// We use a "Longest Path" approach via Stack (DFS-ish)
const stack = this.nodes.filter(n => incomingCount.get(n.id) === 0);
// Sort roots for deterministic start
stack.sort((a, b) => a.id.localeCompare(b.id));
if (stack.length === 0 && this.nodes.length > 0) stack.push(this.nodes[0]);
const layers = new Map();
stack.forEach(n => layers.set(n.id, 0));
// Clone stack for loop to avoid mutation issues if we needed strictly separate passes
const rankStack = [...stack];
while (rankStack.length > 0) {
const node = rankStack.pop();
const layer = layers.get(node.id);
const children = adj.get(node.id);
children.forEach(child => {
const currentChildLayer = layers.get(child.id) || 0;
if (layer + 1 > currentChildLayer) {
layers.set(child.id, layer + 1);
// Re-push child to update its descendants if its layer changed
// This ensures "Longest Path"
rankStack.push(child);
}
});
}
this.nodes.forEach(node => {
if (!layers.has(node.id)) layers.set(node.id, 0);
});
// 3. Compute DFS Order (Vertical - Y Coordinate sorting)
// This ensures branches are kept together visually
const dfsOrder = new Map();
let sequence = 0;
const visited = new Set();
const performDFS = (node) => {
if (visited.has(node.id)) return;
visited.add(node.id);
dfsOrder.set(node.id, sequence++);
const children = adj.get(node.id);
children.forEach(child => performDFS(child));
};
// Start DFS from roots (and then any unvisited nodes for disconnected components)
const roots = this.nodes.filter(n => incomingCount.get(n.id) === 0)
.sort((a, b) => a.id.localeCompare(b.id));
roots.forEach(performDFS);
this.nodes.forEach(n => {
if (!visited.has(n.id)) performDFS(n);
});
// 4. Group & Position
const layerGroups = [];
layers.forEach((layer, nodeId) => {
if (!layerGroups[layer]) layerGroups[layer] = [];
const node = this.nodes.find(n => n.id === nodeId);
layerGroups[layer].push(node);
});
const COLUMN_GAP = 70;
let currentBoundaryX = 0;
layerGroups.forEach((nodesInLayer, layerIndex) => {
// Critical: Sort by DFS sequence, NOT name
nodesInLayer.sort((a, b) => {
const orderA = dfsOrder.get(a.id);
const orderB = dfsOrder.get(b.id);
return orderA - orderB;
});
let layerWidth = 0;
nodesInLayer.forEach(n => {
if (n.width > layerWidth) layerWidth = n.width;
});
const layerCenterX = currentBoundaryX + layerWidth;
let currentY = 0;
let totalHeight = 0;
nodesInLayer.forEach(n => totalHeight += n.height + 40);
totalHeight -= 40;
currentY = -totalHeight / 2;
nodesInLayer.forEach((node) => {
node.x = layerCenterX;
node.y = currentY + node.height / 2;
currentY += node.height + 40;
});
currentBoundaryX += layerWidth + COLUMN_GAP;
});
}
calculateAllNodeDimensions() {
this.nodes.forEach(node => {
node.width = this.getNodeWidth(node);
node.height = this.getNodeHeight(node);
});
}
resolveTypeNode(returnStructure) {
if (!returnStructure) return null;
// If it's a REF string, resolve it.
if (typeof returnStructure === 'string' && returnStructure.startsWith('REF:')) {
const refId = returnStructure;
if (typeof GLOBAL_DEFINITIONS !== 'undefined' && GLOBAL_DEFINITIONS[refId]) {
// Recursively resolve in case of deep references? Usually flat.
return this.resolveTypeNode(GLOBAL_DEFINITIONS[refId]);
}
return { kind: 'primitive', type: '(Reference not found)' };
}
// If it's already an object, return it.
if (typeof returnStructure === 'object') return returnStructure;
// If simple string (primitive fallback)
return { kind: 'primitive', type: returnStructure };
}
getTypeNodeDimensions(typeNode, pathPrefix, depth = 0) {
const resolved = this.resolveTypeNode(typeNode);
if (!resolved) return { width: 0, height: 0 };
const lineHeight = 20;
const indent = 15;
const charWidth = 9; // Approx
if (resolved.kind === 'primitive') {
return { width: resolved.type.length * charWidth, height: lineHeight };
}
if (resolved.kind === 'reference') {
// Should have been resolved? Or maybe explicit generic reference
return { width: (resolved.type.length + 20) * charWidth, height: lineHeight };
}
if (resolved.kind === 'promise') {
const innerDim = this.getTypeNodeDimensions(resolved.type, pathPrefix, depth);
// "Promise<" + inner + ">"
const wrapperWidth = ("Promise<".length + 1) * charWidth;
return { width: wrapperWidth + innerDim.width, height: innerDim.height };
}
if (resolved.kind === 'array') {
const dim = this.getTypeNodeDimensions(resolved.elementType, pathPrefix, depth);
return { width: dim.width + 20, height: dim.height }; // Simplified
}
if (resolved.kind === 'union') {
// Assume single line for now if simple, or multi-line?
// Let's assume union is displayed as "A | B" (primitive-like) for simplicity unless we want deep?
// Let's try to sum widths?
let w = 0;
resolved.types.forEach(t => w += this.getTypeNodeDimensions(t, pathPrefix, depth).width + 30);
return { width: w, height: lineHeight };
}
if (resolved.kind === 'object') {
const isExpanded = this.expandedReturns.has(pathPrefix);
const name = resolved.type || 'Object';
const summary = `${name} { ... }`;
const summaryWidth = (summary.length + 3) * charWidth;
if (!isExpanded) {
return { width: summaryWidth, height: lineHeight };
} else {
let totalHeight = lineHeight; // Header: "Name {"
let maxWidth = (name.length + 2) * charWidth;
if (resolved.properties) {
resolved.properties.forEach(prop => {
const propPath = `${pathPrefix}:${prop.name}`;
const dim = this.getTypeNodeDimensions(prop.type, propPath, depth + 1);
totalHeight += dim.height;
const propLineW = (indent * (depth + 1)) + ((prop.name.length + 2) * charWidth) + dim.width;
if (propLineW > maxWidth) maxWidth = propLineW;
});
}
totalHeight += lineHeight; // Footer "}"
return { width: maxWidth, height: totalHeight };
}
}
if (resolved.kind === 'enum') {
const isExpanded = this.expandedReturns.has(pathPrefix);
const name = resolved.type || 'Enum';
if (!isExpanded) return { width: (name.length + 5) * charWidth, height: lineHeight };
let h = lineHeight;
let w = (name.length + 5) * charWidth;
resolved.members.forEach(m => {
h += lineHeight;
const mw = (m.length + indent * (depth + 1)) * charWidth;
if (mw > w) w = mw;
});
h += lineHeight;
return { width: w, height: h };
}
// Default
return { width: 100, height: 20 };
}
getNodeHeight(node) {
const headerHeight = 80;
const padding = 15;
const baseHeight = headerHeight + padding;
const methodLineHeight = 26;
// Detail view constants
const detailPadding = 10;
const definitionLineHeight = 22;
const returnStructureLineHeight = 20;
if (!node.methods || node.methods.length === 0) {
return baseHeight + 10;
}
if (!node.showDetails) {
return baseHeight + 10 + (node.methods.length * methodLineHeight);
} else {
// Calculate expanded height
let totalMethodHeight = 0;
node.methods.forEach((method, methodIndex) => {
totalMethodHeight += methodLineHeight; // Name line
if (typeof method === 'object') {
// Definition is now inline, so no extra height added here
// totalMethodHeight += definitionLineHeight + 4;
// Return Structure
if (method.returnStructure) {
const rootPath = `${node.id}-${methodIndex}`;
const isExpanded = this.expandedReturns.has(rootPath);
// Always add summary line height (20)
// If expanded, add the full calculated height of the type node.
// Note: getTypeNodeDimensions returns total height including its own nestedness.
// If we display summary AND expanded content? verify render logic.
// render logic: if promise, it renders inline-ish.
// if expanded object: renders summary + properties.
// Let's use getTypeNodeDimensions directly.
const dims = this.getTypeNodeDimensions(method.returnStructure, rootPath, 0);
// Wait, getTypeNodeDimensions returns height of the *content*.
// Does it include the summary line?
// In 'object' case: if not expanded, returns summary height (20).
// If expanded, returns header + props + footer.
// So simply adding dims.height is correct.
totalMethodHeight += dims.height;
}
}
totalMethodHeight += 15; // Gap between methods
});
return baseHeight + Math.max(10, totalMethodHeight);
}
}
getNodeWidth(node) {
const titleWidth = (node.id.length * 15) + 40; // Approx
let maxContent = titleWidth;
const detailCharWidth = 8.5; // Slightly compressed monospace
if (node.methods) {
node.methods.forEach((m, methodIdx) => {
const methodName = m.name || m;
// Basic Width: "+ MethodName"
let methodWidth = (`+ ${methodName}`).length * detailCharWidth;
if (methodWidth > maxContent) maxContent = methodWidth;
// Only account for definition / returns if details are shown
if (node.showDetails && typeof m === 'object') {
// Check definition (signature) width
// Assuming it renders somewhat inline or we just want to ensure space for it if it were long
if (m.definition) {
const defWidth = (`+ ${methodName}${m.definition}`).length * detailCharWidth;
if (defWidth > maxContent) maxContent = defWidth;
}
if (m.returnStructure) {
const rootPath = `${node.id}-${methodIdx}`;
const dim = this.getTypeNodeDimensions(m.returnStructure, rootPath, 0);
const fullWidth = dim.width + 40; // padding
if (fullWidth > maxContent) maxContent = fullWidth;
}
}
});
}
return Math.max(220, maxContent + 30);
}
getEstimatedTextWidths(node) {
const titleCharWidth = 14;
const normalCharWidth = 10;
const titleLen = node.id.length * titleCharWidth;
const metaString = `${node.containerName}${node.version && node.version !== 'unknown' ? ' / ' + node.version : ''} `;
const metaLen = metaString.length * normalCharWidth;
return { titleLen, metaLen };
}
updateZoom(scaleChange, centerPoint) {
let newScale = this.scale * scaleChange;
newScale = Math.min(Math.max(0.01, newScale), 5); // Limit zoom levels
// If no center point provided (e.g. buttons), zoom to center of viewport
if (!centerPoint) {
centerPoint = { x: this.width / 2, y: this.height / 2 };
}
// Calculate new translation to keep centerPoint stationary
// Calculate new translation to keep centerPoint stationary
const scaleRatio = newScale / this.scale;
this.translateX = centerPoint.x - (centerPoint.x - this.translateX) * scaleRatio;
this.translateY = centerPoint.y - (centerPoint.y - this.translateY) * scaleRatio;
this.scale = newScale;
this.render();
}
centerGraph(isFiltered = false) {
if (this.nodes.length === 0) {
this.translateY = this.height / 2;
this.render();
return;
}
if (isFiltered) {
// Calculate Bounding Box of visible nodes
let minX = Infinity, maxX = -Infinity;
let minY = Infinity, maxY = -Infinity;
this.nodes.forEach(node => {
const w = node.width;
const h = node.height;
const left = node.x - w / 2;
const right = node.x + w / 2;
const top = node.y - h / 2;
const bottom = node.y + h / 2;
if (left < minX) minX = left;
if (right > maxX) maxX = right;
if (top < minY) minY = top;
if (bottom > maxY) maxY = bottom;
});
const midY = (minY + maxY) / 2;
// Align left edge to 40px padding
this.translateX = 40 - (minX * this.scale);