forked from srl-labs/vscode-containerlab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.js
More file actions
5235 lines (4514 loc) · 220 KB
/
dev.js
File metadata and controls
5235 lines (4514 loc) · 220 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
document.addEventListener("DOMContentLoaded", async function () {
// vertical layout
function initializeResizingLogic() {
// Get elements with checks
const divider = document.getElementById('divider');
const dataDisplay = document.getElementById('data-display');
const rootDiv = document.getElementById('root-div');
const togglePanelButtonExpand = document.getElementById('toggle-panel-data-display-expand');
const togglePanelButtonCollapse = document.getElementById('toggle-panel-data-display-collapse');
// Check for required elements
if (!divider || !dataDisplay || !rootDiv || !togglePanelButtonExpand) {
console.warn('One or more required elements for resizing logic are missing. Initialization aborted.');
return;
}
let isDragging = false;
let resizeTimeout;
// Debounce function
function debounce(func, delay) {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(func, delay);
}
// Function to animate cy.fit()
function animateFit() {
if (typeof cy.animate === 'function') {
cy.animate({
fit: {
padding: 10, // Add padding around the graph
},
duration: 500, // Animation duration in milliseconds
});
} else {
console.warn('Cytoscape instance does not support animate. Skipping animation.');
}
}
// Handle dragging
divider.addEventListener('mousedown', () => {
isDragging = true;
document.body.style.cursor = 'ew-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const screenWidth = window.innerWidth;
const offsetX = e.clientX; // divider’s X from the LEFT
const minWidth = 5; // Minimum width in pixels for data-display
const maxWidth = screenWidth * 1; // Maximum width in pixels for data-display
// dataDisplayWidth is from divider to right edge:
const dataDisplayWidth = screenWidth - offsetX;
if (dataDisplayWidth >= minWidth && dataDisplayWidth <= maxWidth) {
// The rest (from left edge to divider) is rootDivWidth
const rootDivWidth = offsetX;
// Convert to percentage
const rootDivPercent = (rootDivWidth / screenWidth) * 100;
const dataDisplayPercent = (dataDisplayWidth / screenWidth) * 100;
// Position the divider at the same left as rootDiv’s right edge
divider.style.left = rootDivPercent + '%';
// rootDiv occupies the left portion
rootDiv.style.width = rootDivPercent + '%';
// dataDisplay starts where rootDiv ends
dataDisplay.style.left = rootDivPercent + '%';
dataDisplay.style.width = dataDisplayPercent + '%';
// Add or remove transparency
if ((dataDisplayWidth / rootDivWidth) * 100 > 60) {
dataDisplay.classList.add('transparent');
} else {
dataDisplay.classList.remove('transparent');
// Debounce the animation
debounce(() => {
console.info('Fitting Cytoscape to new size with animation');
animateFit();
}, 500); // Delay of 500ms
}
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
document.body.style.cursor = 'default';
});
// Toggle panel visibility
togglePanelButtonExpand.addEventListener('click', () => {
// rootDiv gets ~7%; dataDisplay gets ~93%
// rootDiv.style.width = '27%';
divider.style.left = '7%';
dataDisplay.style.left = '7%';
dataDisplay.style.width = '93%';
dataDisplay.classList.add('transparent');
});
// Toggle panel visibility
togglePanelButtonCollapse.addEventListener('click', () => {
// rootDiv gets ~98.5%; dataDisplay ~1.5%
rootDiv.style.width = '98.5%';
divider.style.left = '98.5%';
dataDisplay.style.left = '98.5%';
dataDisplay.style.width = '1.5%';
dataDisplay.classList.remove('transparent');
console.info('togglePanelButtonExpand - dataDisplay.style.width: ', dataDisplay.style.width);
console.info('togglePanelButtonExpand - rootDiv.style.width: ', rootDiv.style.width);
console.info('togglePanelButtonExpand - divider.style.left: ', divider.style.left);
// Animate fit after toggling
debounce(() => {
console.info('Fitting Cytoscape to new size with animation');
animateFit();
}, 500); // Delay of 500ms
});
}
if (isVscodeDeployment) {
// aarafat-tag: vs-code
initUptime();
}
// Call the function during initialization
initializeResizingLogic(cy);
detectColorScheme()
await changeTitle()
initializeDropdownTopoViewerRoleListeners();
initializeDropdownListeners();
initViewportDrawerClabEditoCheckboxToggle()
// initViewportDrawerGeoMapCheckboxToggle()
// insertAndColorSvg("nokia-logo", "white")
// Reusable function to initialize a WebSocket connection
function initializeWebSocket(url, onMessageCallback) {
const protocol = location.protocol === "https:" ? "wss://" : "ws://";
const socket = new WebSocket(protocol + location.host + url);
socket.onopen = () => {
console.info(`Successfully connected WebSocket to ${url}`);
if (socket.readyState === WebSocket.OPEN) {
socket.send(`Hi From the WebSocketClient-${url}`);
}
};
socket.onclose = (event) => {
console.info(`Socket to ${url} closed: `, event);
socket.send("Client Closed!");
};
socket.onerror = (error) => {
console.info(`Socket to ${url} error: `, error);
};
socket.onmessage = onMessageCallback;
return socket;
}
if (!isVscodeDeployment) {
// deploymenType !vs-code
// WebSocket for uptime
const socketUptime = initializeWebSocket("/uptime", async (msgUptime) => {
environments = await getEnvironments();
globalLabName = environments["clab-name"]
deploymentType = environments["deploymentType"]
console.info("initializeWebSocket - getEnvironments", environments)
console.info("initializeWebSocket - globalLabName", environments["clab-name"])
const string01 = "containerlab: " + globalLabName;
const string02 = " ::: Uptime: " + msgUptime.data;
const ClabSubtitle = document.getElementById("ClabSubtitle");
const messageBody = string01 + string02;
ClabSubtitle.innerText = messageBody;
console.info(ClabSubtitle.innerText);
});
// WebSocket for ContainerNodeStatus
const socketContainerNodeStatusInitial = initializeWebSocket(
"/containerNodeStatus",
(msgContainerNodeStatus) => {
try {
const {
Names,
Status,
State
} = JSON.parse(msgContainerNodeStatus.data);
setNodeContainerStatus(Names, Status);
console.info(JSON.parse(msgContainerNodeStatus.data));
const IPAddress = JSON.parse(msgContainerNodeStatus.data).Networks.Networks.clab.IPAddress;
const GlobalIPv6Address = JSON.parse(msgContainerNodeStatus.data).Networks.Networks.clab.GlobalIPv6Address
setNodeDataWithContainerAttribute(Names, Status, State, IPAddress, GlobalIPv6Address);
} catch (error) {
console.error("Error parsing JSON:", error);
}
},
);
}
// deploymenType vs-code
async function initUptime() {
environments = await getEnvironments();
globalLabName = environments["clab-name"]
deploymentType = environments["deploymentType"]
console.info("initializeWebSocket - getEnvironments", environments)
console.info("initializeWebSocket - globalLabName", environments["clab-name"])
const string01 = "topology: " + globalLabName;
// const string02 = " ::: Uptime: " + "msgUptime.data";
const string02 = "";
const ClabSubtitle = document.getElementById("ClabSubtitle");
const messageBody = string01 + string02;
ClabSubtitle.innerText = messageBody;
console.info(ClabSubtitle.innerText);
}
// helper functions for cytoscapePopper
function popperFactory(ref, content, opts) {
const popperOptions = {
middleware: [
FloatingUIDOM.flip(),
FloatingUIDOM.shift({
limiter: FloatingUIDOM.limitShift()
})
],
...opts,
};
function update() {
FloatingUIDOM.computePosition(ref, content, popperOptions).then(({
x,
y
}) => {
Object.assign(content.style, {
left: `${x}px`,
top: `${y}px`,
});
});
}
update();
return {
update
};
}
// init cytoscapePopper
cytoscape.use(cytoscapePopper(popperFactory));
// Instantiate Cytoscape.js
cy = cytoscape({
container: document.getElementById("cy"),
elements: [],
style: [{
selector: "node",
style: {
"background-color": "#3498db",
label: "data(label)",
},
},],
boxSelectionEnabled: true,
wheelSensitivity: 0.2,
selectionType: 'additive' // Allow additive selection
});
// Listen for selection events
cy.on('select', 'node', (event) => {
const selectedNodes = cy.$('node:selected');
// Dynamically style selected nodes
selectedNodes.style({
'border-width': 2,
'border-color': '#ff0000'
});
console.info('Selected nodes:', selectedNodes.map(n => n.id()));
});
// Optionally, reset the style when nodes are unselected
cy.on('unselect', 'node', (event) => {
// Clear inline styles for all nodes
loadCytoStyle(cy);
console.info('Remaining selected nodes:', cy.$('node:selected').map(n => n.id()));
});
// Optionally, reset the style when edges are unselected
cy.on('unselect', 'edge', (event) => {
// Clear inline styles for all nodes
loadCytoStyle(cy);
console.info('Remaining selected nodes:', cy.$('node:selected').map(n => n.id()));
});
// Programmatic selection of nodes
setTimeout(() => {
cy.$('#node1, #node2').select(); // Select node1 and node2 after 2 seconds
console.info('Programmatic selection: node1 and node2');
}, 2000);
// Helper function to check if a node is inside a parent
function isNodeInsideParent(node, parent) {
const parentBox = parent.boundingBox();
const nodePos = node.position();
return (
nodePos.x >= parentBox.x1 &&
nodePos.x <= parentBox.x2 &&
nodePos.y >= parentBox.y1 &&
nodePos.y <= parentBox.y2
);
}
// Drag-and-Drop logic
cy.on('dragfree', 'node', (event) => {
// Assuming the checkbox is always true in your test
const isViewportDrawerClabEditorCheckboxChecked = true;
if (isViewportDrawerClabEditorCheckboxChecked) {
const draggedNode = event.target;
// Check all parent nodes to see if the dragged node is inside one
let assignedParent = null;
cy.nodes(':parent').forEach((parent) => {
if (isNodeInsideParent(draggedNode, parent)) {
assignedParent = parent;
}
});
// console.log(`assignedParent id: ${assignedParent.id()}, assignedParentChildren: ${assignedParent.children()}` )
if (assignedParent) {
// If dragged inside a parent, reassign the node to that parent
draggedNode.move({
parent: assignedParent.id()
});
console.info(`${draggedNode.id()} became a child of ${assignedParent.id()}`);
// Get the dummy child node using your naming convention
// const dummyChild = cy.getElementById(`${assignedParent.id()}:dummyChild`);
// Get the dummy child node using topoViewerRole
const dummyChild = assignedParent.children('[topoViewerRole = "dummyChild"]');
console.log(`assignedParent id: ${assignedParent.id()}, assignedParentChildren: ${assignedParent.children()}, assignedParentDoummyChild: ${dummyChild.id()}`)
// Only proceed if the dummy child exists
if (dummyChild.length > 0) {
// Get all children of the parent except the dummy child
const realChildren = assignedParent.children().not(dummyChild);
console.log("realChildren: ", realChildren);
// If there is at least one non-dummy child, remove the dummy
if (realChildren.length > 0) {
dummyChild.remove();
console.log("Dummy child removed");
} else {
console.log("No real children present, dummy child remains");
}
}
}
// Select all parent nodes where data.topoViewerRole equals "group"
var parentNodes = cy.nodes('[topoViewerRole = "group"]');
// Iterate over each matching parent node and remove it if it has no children
parentNodes.forEach(function (parentNode) {
if (parentNode.children().empty()) { // Checks if there are no child nodes
parentNode.remove();
}
});
// To release the node from the parent, alt + shift + click on the node.
}
// console.log(`AFTER assignedParent id: ${assignedParent.id()}, assignedParentChildren: ${assignedParent.children()}` )
});
// Initialize edgehandles with configuration
const eh = cy.edgehandles({
// Enable preview of edge before finalizing
preview: false,
hoverDelay: 50, // time spent hovering over a target node before it is considered selected
snap: false, // when enabled, the edge can be drawn by just moving close to a target node (can be confusing on compound graphs)
snapThreshold: 10, // the target node must be less than or equal to this many pixels away from the cursor/finger
snapFrequency: 150, // the number of times per second (Hz) that snap checks done (lower is less expensive)
noEdgeEventsInDraw: false, // set events:no to edges during draws, prevents mouseouts on compounds
disableBrowserGestures: false, // during an edge drawing gesture, disable browser gestures such as two-finger trackpad swipe and pinch-to-zoom
canConnect: function (sourceNode, targetNode) {
// whether an edge can be created between source and target
return !sourceNode.same(targetNode) && !sourceNode.isParent() && !targetNode.isParent();
},
edgeParams: function (sourceNode, targetNode) {
// for edges between the specified source and target
// return element object to be passed to cy.add() for edge
return {};
},
});
// Enable edgehandles functionality
eh.enable();
let isEdgeHandlerActive = false; // Flag to track if edge handler is active
cy.on('ehcomplete', async (event, sourceNode, targetNode, addedEdge) => {
console.info(`Edge created from ${sourceNode.id()} to ${targetNode.id()}`);
console.info("Added edge:", addedEdge);
// Reset the edge handler flag after a short delay
setTimeout(() => {
isEdgeHandlerActive = false;
}, 100); // Adjust delay as needed
// Get the ID of the added edge
const edgeId = addedEdge.id(); // Extracts the edge ID
// Helper function to get the next available endpoint with pattern detection
function getNextEndpoint(nodeId) {
// Get all edges connected to the node, both as source and target
const edges = cy.edges(`[source = "${nodeId}"], [target = "${nodeId}"]`);
const e1Pattern = /^e1-(\d+)$/;
const ethPattern = /^eth(\d+)$/;
let usedNumbers = new Set();
let selectedPattern = null; // Determine the pattern based on existing endpoints
edges.forEach(edge => {
// Check both sourceEndpoint and targetEndpoint for the connected node
['sourceEndpoint', 'targetEndpoint'].forEach(key => {
const endpoint = edge.data(key);
// Skip if the endpoint is not associated with the current node
const isNodeEndpoint = (edge.data('source') === nodeId && key === 'sourceEndpoint') ||
(edge.data('target') === nodeId && key === 'targetEndpoint');
if (!endpoint || !isNodeEndpoint) return;
let match = endpoint.match(e1Pattern);
if (match) {
// Endpoint matches e1- pattern
const endpointNum = parseInt(match[1], 10);
usedNumbers.add(endpointNum);
if (!selectedPattern) selectedPattern = e1Pattern;
} else {
match = endpoint.match(ethPattern);
if (match) {
// Endpoint matches eth pattern
const endpointNum = parseInt(match[1], 10);
usedNumbers.add(endpointNum);
if (!selectedPattern) selectedPattern = ethPattern;
}
}
});
});
// If no pattern was detected, default to e1Pattern
if (!selectedPattern) {
selectedPattern = e1Pattern;
}
// Find the smallest unused number
let endpointNum = 1;
while (usedNumbers.has(endpointNum)) {
endpointNum++;
}
// Return the new endpoint formatted according to the pattern
return selectedPattern === e1Pattern ?
`e1-${endpointNum}` :
`eth${endpointNum}`;
}
// Calculate next available source and target endpoints
const sourceEndpoint = getNextEndpoint(sourceNode.id(), true);
const targetEndpoint = getNextEndpoint(targetNode.id(), false);
// Add calculated endpoints to the edge data
addedEdge.data('sourceEndpoint', sourceEndpoint);
addedEdge.data('targetEndpoint', targetEndpoint);
// Add editor flag to the edge data
addedEdge.data('editor', 'true');
await showPanelContainerlabEditor(event)
// Save the edge element to file in the server CY and Yaml
await saveEdgeToEditorToFile(edgeId, sourceNode, sourceEndpoint, targetNode, targetEndpoint);
});
loadCytoStyle(cy);
// Enable grid guide extension
cy.gridGuide({
// On/Off Modules
snapToGridOnRelease: true,
snapToGridDuringDrag: false,
snapToAlignmentLocationOnRelease: true,
snapToAlignmentLocationDuringDrag: false,
distributionGuidelines: false,
geometricGuideline: false,
initPosAlignment: false,
centerToEdgeAlignment: false,
resize: false,
parentPadding: false,
drawGrid: false,
// General
gridSpacing: 10,
snapToGridCenter: true,
// Draw Grid
zoomDash: true,
panGrid: true,
gridStackOrder: -1,
gridColor: '#dedede',
lineWidth: 1.0,
// Guidelines
guidelinesStackOrder: 4,
guidelinesTolerance: 2.00,
guidelinesStyle: {
strokeStyle: "#8b7d6b",
geometricGuidelineRange: 400,
range: 100,
minDistRange: 10,
distGuidelineOffset: 10,
horizontalDistColor: "#ff0000",
verticalDistColor: "#00ff00",
initPosAlignmentColor: "#0000ff",
lineDash: [0, 0],
horizontalDistLine: [0, 0],
verticalDistLine: [0, 0],
initPosAlignmentLine: [0, 0],
},
// Parent Padding
parentSpacing: -1
});
// * Fetches data from the JSON file, processes it, and loads it into the Cytoscape instance.
// * This integrated function appends a timestamp to bypass caching, fetches the JSON data,
// * processes the data with `assignMissingLatLng()`, clears existing elements, adds the new ones,
// * applies the "cola" layout, removes specific nodes, and sets up expand/collapse functionality.
fetchAndLoadData()
// Instantiate hover text element
const hoverText = document.createElement("box");
hoverText.classList.add(
"hover-text",
"is-hidden",
"box",
"has-text-weight-normal",
"is-warning",
"is-smallest",
);
hoverText.textContent = "Launch CloudShell.";
document.body.appendChild(hoverText);
var shiftKeyDown = false;
// Detect when Shift is pressed or released
document.addEventListener('keydown', (event) => {
if (event.key === 'Shift') {
shiftKeyDown = true;
}
});
document.addEventListener('keyup', (event) => {
if (event.key === 'Shift') {
shiftKeyDown = false;
}
});
var altKeyDown = false;
// Detect when Alt is pressed or released
document.addEventListener('keydown', (event) => {
if (event.key === 'Alt') {
altKeyDown = true;
}
});
document.addEventListener('keyup', (event) => {
if (event.key === 'Alt') {
altKeyDown = false;
}
});
var ctrlKeyDown = false;
// Detect when Control is pressed or released
document.addEventListener('keydown', (event) => {
if (event.key === 'Control') {
ctrlKeyDown = true;
}
});
document.addEventListener('keyup', (event) => {
if (event.key === 'Control') {
ctrlKeyDown = false;
}
});
// Toggle the Panel(s) when clicking on the cy container
document.getElementById("cy").addEventListener("click", async function (event) {
console.info("cy container clicked init");
console.info("isPanel01Cy: ", isPanel01Cy);
console.info("nodeClicked: ", nodeClicked);
console.info("edgeClicked: ", edgeClicked);
// This code will be executed when you click anywhere in the Cytoscape container
// You can add logic specific to the container here
if (!nodeClicked && !edgeClicked) {
console.info("!nodeClicked -- !edgeClicked");
if (!isPanel01Cy) {
console.info("!isPanel01Cy: ");
// Remove all Overlayed Panel
// Get all elements with the class "panel-overlay"
var panelOverlays = document.getElementsByClassName("panel-overlay");
console.info("panelOverlays: ", panelOverlays);
// Loop through each element and set its display to 'none'
for (var i = 0; i < panelOverlays.length; i++) {
console.info
panelOverlays[i].style.display = "none";
}
var viewportDrawer = document.getElementsByClassName("viewport-drawer");
// Loop through each element and set its display to 'none'
for (var i = 0; i < viewportDrawer.length; i++) {
viewportDrawer[i].style.display = "none";
}
// display none each ViewPortDrawer Element, the ViewPortDrawer is created during DOM loading and styled as display node initially
var ViewPortDrawerElements =
document.getElementsByClassName("ViewPortDrawer");
var ViewPortDrawerArray = Array.from(ViewPortDrawerElements);
ViewPortDrawerArray.forEach(function (element) {
element.style.display = "none";
});
} else {
removeElementById("Panel-01");
appendMessage(`"try to remove panel01-Cy"`);
}
}
nodeClicked = false;
edgeClicked = false;
});
// Listen for tap or click on the Cytoscape canvas
// editor mode true - Shift + click/tap to add a new node
cy.on('click', async (event) => {
// Usage: Initialize the listener and get a live checker function
const isViewportDrawerClabEditorCheckboxChecked = setupCheckboxListener('#viewport-drawer-clab-editor-content-01 .checkbox-input');
if (event.target === cy && shiftKeyDown && isViewportDrawerClabEditorCheckboxChecked) { // Ensures Shift + click/tap and the isViewportDrawerClabEditorCheckboxChecked
const pos = event.position;
const newNodeId = 'nodeId-' + (cy.nodes().length + 1);
// Add the new node to the graph
cy.add({
group: 'nodes',
data: {
"id": newNodeId,
"editor": "true",
"weight": "30",
"name": newNodeId,
"parent": "",
"topoViewerRole": "pe",
"sourceEndpoint": "",
"targetEndpoint": "",
"containerDockerExtraAttribute": {
"state": "",
"status": "",
},
"extraData": {
"kind": "container",
"longname": "",
"image": "",
"mgmtIpv4Address": "",
},
},
position: {
x: pos.x,
y: pos.y
}
});
var cyNode = cy.$id(newNodeId); // Get cytoscpe node object id
await showPanelContainerlabEditor(event)
// sleep (1000)
await showPanelNodeEditor(cyNode)
// sleep (100)
await saveNodeToEditorToFile()
} else {
loadCytoStyle(cy)
}
});
cy.on("click", "node", async function (event) {
const node = event.target;
nodeClicked = true;
console.info("Node clicked:", node.id());
console.info("isPanel01Cy:", isPanel01Cy);
console.info("nodeClicked:", nodeClicked);
console.info("edgeClicked:", edgeClicked);
console.info("isEdgeHandlerActive:", isEdgeHandlerActive);
// Fetch environments and log details
const environments = await getEnvironments(event);
console.info("Environments:", environments);
cytoTopologyJson = environments["EnvCyTopoJsonBytes"]
clabServerAddress = environments["clab-server-address"]
// Ignore the click event if edge handler is active
if (isEdgeHandlerActive) {
return;
}
const originalEvent = event.originalEvent;
const extraData = node.data("extraData");
const isNodeInEditMode = node.data("editor") === "true";
const checkboxChecked = setupCheckboxListener('#viewport-drawer-clab-editor-content-01 .checkbox-input');
globalSelectedNode = extraData.longname;
if (checkboxChecked) {
// Handle node modification actions based on keyboard modifiers
switch (true) {
case originalEvent.ctrlKey && node.isChild():
console.info(`Orphaning node: ${node.id()} from parent: ${node.parent().id()}`);
node.move({ parent: null });
break;
case originalEvent.shiftKey:
console.info("Starting edge creation from node:", extraData.longname);
isEdgeHandlerActive = true;
eh.start(node);
showPanelNodeEditor(node);
break;
case originalEvent.altKey && isNodeInEditMode:
console.info("Deleting node:", extraData.longname);
deleteNodeToEditorToFile(node);
break;
}
}
// Handle actions for editor nodes
if (isNodeInEditMode) {
showPanelNodeEditor(node);
} else {
// Handle actions for non-editor nodes
switch (true) {
case originalEvent.ctrlKey: { // Ctrl + Click to connect to SSH
console.info("Connecting to SSH for node:", extraData.longname);
globalSelectedNode = extraData.longname;
nodeActionConnectToSSH(event);
break;
}
case originalEvent.shiftKey && node.parent().empty() && !node.isParent(): { // Shift + Click to create a new parent
console.info("Creating a new parent node");
createNewParent({ nodeToReparent: node, createDummyChild: false });
break;
}
// case originalEvent.shiftKey && node.isParent(): // Shift + Click to edit an existing parent
case node.isParent(): // Shift + Click to edit an existing parent
{
console.info("Editing existing parent node");
const currentParentId = node.id(); // Get the current parent ID
const nodeEditorParentPanel = document.getElementById("panel-node-editor-parent");
if (nodeEditorParentPanel) {
nodeEditorParentPanel.style.display = "block";
document.getElementById("panel-node-editor-parent-graph-group-id").textContent = currentParentId;
document.getElementById("panel-node-editor-parent-graph-group").value = currentParentId.split(":")[0];
document.getElementById("panel-node-editor-parent-graph-level").value = currentParentId.split(":")[1];
}
}
break;
case originalEvent.altKey && node.parent() && !node.isParent(): { // Alt + Click to orphaning a child node
console.info("Orphaning child node");
console.info("node data: ", node.data("topoViewerRole"));
orphaningNode(node)
if (node.data("topoViewerRole") == "dummyChild") {
node.remove()
}
break;
}
case (node.data("topoViewerRole") == "textbox"): {
break;
}
case (node.data("topoViewerRole") == "dummyChild"): {
break;
}
case !originalEvent.altKey && !originalEvent.ctrlKey && !node.isParent(): {
// Toggle panel-node display and update content
const panelOverlays = document.getElementsByClassName("panel-overlay");
Array.from(panelOverlays).forEach(panel => panel.style.display = "none");
const panelNode = document.getElementById("panel-node");
panelNode.style.display = (panelNode.style.display === "none") ? "block" : "none";
document.getElementById("panel-node-name").textContent = extraData.longname;
document.getElementById("panel-node-kind").textContent = extraData.kind;
document.getElementById("panel-node-mgmtipv4").textContent = extraData.mgmtIpv4Address;
document.getElementById("panel-node-mgmtipv6").textContent = extraData.mgmtIpv6Address;
document.getElementById("panel-node-fqdn").textContent = extraData.fqdn;
document.getElementById("panel-node-topoviewerrole").textContent = node.data("topoViewerRole");
document.getElementById("panel-node-state").textContent = extraData.state;
document.getElementById("panel-node-image").textContent = extraData.image;
globalSelectedNode = extraData.longname;
console.info("Global selected node:", globalSelectedNode);
appendMessage(`isPanel01Cy: ${isPanel01Cy}`);
appendMessage(`nodeClicked: ${nodeClicked}`);
break;
}
default:
break;
}
}
});
// Click event listener for edges
cy.on("click", "edge", async function (event) {
console.info("edge clicked init");
console.info("isPanel01Cy: ", isPanel01Cy);
console.info("nodeClicked: ", nodeClicked);
console.info("edgeClicked: ", edgeClicked);
// Remove all Overlayed Panel
// Get all elements with the class "panel-overlay"
var panelOverlays = document.getElementsByClassName("panel-overlay");
// Loop through each element and set its display to 'none'
for (var i = 0; i < panelOverlays.length; i++) {
panelOverlays[i].style.display = "none";
}
// This code will be executed when you click on a node
// You can add logic specific to nodes here
const clickedEdge = event.target;
console.log("clickedEdge:", clickedEdge)
console.log("clickedEdge.data:", clickedEdge.data)
console.log("clickedEdge.data.source:", clickedEdge.data("source"))
console.log("clickedEdge.data.target:", clickedEdge.data("target"))
edgeClicked = true;
console.info("edge clicked after");
console.info("isPanel01Cy: ", isPanel01Cy);
console.info("nodeClicked: ", nodeClicked);
console.info("edgeClicked: ", edgeClicked);
const defaultEdgeColor = "#969799";
console.info(defaultEdgeColor);
// Change the color of the clicked edge (for example, to blue)
if (clickedEdge.data("editor") === "true") {
clickedEdge.style("line-color", "#32CD32");
} else {
clickedEdge.style("line-color", "#0043BF");
}
// Revert the color of other edges that were not clicked (e.g., back to their default color)
cy.edges().forEach(function (edge) {
if (edge !== clickedEdge) {
edge.style("line-color", defaultEdgeColor);
}
});
// Assign middle labels
assignMiddleLabels(clickedEdge);
// Usage: Initialize the listener and get a live checker function
const isViewportDrawerClabEditorCheckboxChecked = setupCheckboxListener('#viewport-drawer-clab-editor-content-01 .checkbox-input');
if (event.originalEvent.altKey && isViewportDrawerClabEditorCheckboxChecked && clickedEdge.data("editor") === "true") {
console.info("Alt + Click is enabled");
console.info("deleted Edge: ", clickedEdge.data("source"), clickedEdge.data("target"));
deleteEdgeToEditorToFile(clickedEdge)
}
if (event.originalEvent.altKey && isViewportDrawerClabEditorCheckboxChecked && clickedEdge.data("editor") !== "true") {
console.info("Alt + Click is enabled");
bulmaToast.toast({
message: `Hey there, that link’s locked down read-only, so no deleting it. 😎👊`,
type: "is-warning is-size-6 p-3",
duration: 4000,
position: "top-center",
closeOnClick: true,
});
}
if (clickedEdge.data("editor") !== "true") {
// set selected edge-id to global variable
globalSelectedEdge = clickedEdge.data("id")
console.log(`"edgeClicked: " ${globalSelectedEdge}`);
appendMessage(`"edgeClicked: " ${edgeClicked}`);
console.log("clickedEdge.data.source 2nd:", clickedEdge.data("source"))
console.log("clickedEdge.data.target 2nd:", clickedEdge.data("target"))
document.getElementById("panel-link").style.display = "none";
if (document.getElementById("panel-link").style.display === "none") {
document.getElementById("panel-link").style.display = "block";
} else {
document.getElementById("panel-link").style.display = "none";
}
document.getElementById("panel-link-name").innerHTML = `┌ ${clickedEdge.data("source")} :: ${clickedEdge.data("sourceEndpoint")}<br>└ ${clickedEdge.data("target")} :: ${clickedEdge.data("targetEndpoint")}`
document.getElementById("panel-link-endpoint-a-name").textContent = `${clickedEdge.data("source")} :: ${clickedEdge.data("sourceEndpoint")}`
// document.getElementById("panel-link-endpoint-a-mac-address").textContent = "getting the MAC address"
document.getElementById("panel-link-endpoint-b-name").textContent = `${clickedEdge.data("target")} :: ${clickedEdge.data("targetEndpoint")}`
// document.getElementById("panel-link-endpoint-b-mac-address").textContent = "getting the MAC address"
document.getElementById("endpoint-a-edgeshark").textContent = `Edgeshark :: ${clickedEdge.data("source")} :: ${clickedEdge.data("sourceEndpoint")}`
document.getElementById("endpoint-b-edgeshark").textContent = `Edgeshark :: ${clickedEdge.data("target")} :: ${clickedEdge.data("targetEndpoint")}`
//render sourceSubInterfaces
let clabSourceSubInterfacesClabData
if (isVscodeDeployment) {
try {
console.log("########################################################### source subInt")
const response = await sendMessageToVscodeEndpointPost("clab-link-subinterfaces", {
nodeName: clickedEdge.data("extraData").clabSourceLongName,
interfaceName: clickedEdge.data("extraData").clabSourcePort
});
clabSourceSubInterfacesClabData = response.map(item => item.name); // Output: ["e1-1-1", "e1-1-2"]
console.log("Source SubInterface list:", clabSourceSubInterfacesClabData);
if (Array.isArray(clabSourceSubInterfacesClabData) && clabSourceSubInterfacesClabData.length > 0) {
// Map sub-interfaces with prefix
const sourceSubInterfaces = clabSourceSubInterfacesClabData
// Render sub-interfaces
renderSubInterfaces(sourceSubInterfaces, 'endpoint-a-top', 'endpoint-a-bottom', nodeName);
} else if (Array.isArray(clabSourceSubInterfacesClabData)) {
console.info("No sub-interfaces found. The input data array is empty.");
renderSubInterfaces(null, 'endpoint-a-top', 'endpoint-a-bottom', nodeName);
} else {
console.info("No sub-interfaces found. The input data is null, undefined, or not an array.");
renderSubInterfaces(null, 'endpoint-a-top', 'endpoint-a-bottom', nodeName);
}
} catch (error) {
console.error("Failed to get SubInterface list:", error);
}
} else {