-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.js
2237 lines (1827 loc) · 99 KB
/
bst.js
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
/*
=============================================================
Author: Julian Manders-Jones
Date: October 2024
Project: Binary Search Tree Visualiser
Repo: https://github.com/iteacher/bstvisualiser
Description: an interactive tool designed for learners, educators, and developers interested in deepening their understanding of binary search trees. This app offers a dynamic approach to studying BSTs by enabling users to visually interact with and manipulate the tree structure.
© 2024 Julian Manders-Jones. All rights reserved.
This file is part of Binary Search Tree Visualiser.
MIT License
You may obtain a copy of the License at [Link to LICENSE file]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
=============================================================
*/
document.addEventListener('DOMContentLoaded', () => {
// === Configuration Variables ===
// let initialNodeRadius = window.innerHeight / 50;
// === DOM Elements ===
const treeLayer = document.getElementById('treeLayer');
const treeContainer = document.getElementById('treeContainer');
const treeSVG = document.getElementById('treeSVG');
const edgesGroup = document.getElementById('edges');
const nodesGroup = document.getElementById('nodes');
const comparisonBox = document.getElementById('comparisonBox');
const numbersList = document.getElementById('numbersList');
const nextButton = document.getElementById('nextButton');
const container = document.getElementById('traversalsContainer');
const zoomSlider = document.getElementById('zoomSlider');
const zoomSliderContainer = document.getElementById('zoomSliderContainer');
const traversalsPaneHandle = document.getElementById('traversalPaneHandle');
const randomizeButtonReset = document.getElementById('randomizeButton');
const createButton = document.getElementById('redrawButton');
const paneHandle = document.getElementById('paneHandle');
const leftPane = document.getElementById('leftPane');
const addButton = document.getElementById('addButton');
const randomizeButton = document.getElementById('randomizeButton');
const nodes = document.querySelectorAll('.svg-node');
const traversalNames = ["In-Order", "Post-Order", "Pre-Order"];
// === State Variables ===
let initialNodeRadius = window.innerWidth / 40;
let numbers = [];
let index = 0;
let currentStep = null;
let bst = null;
let currentScale = 1;
let translateX = 0;
let translateY = 0;
let isPanning = false;
let startX = 0;
let startY = 0;
let initialTranslateX = 0;
let initialTranslateY = 0;
let t_isDragging = false;
let t_startX, t_startY, t_initialX, t_initialY;
// Global variable to store the value of the node being deleted
let deletedNodeValue = null;
// === Node Class ===
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.parent = null;
this.x = 0;
this.y = 0;
this.svgElement = null;
this.textElement = null;
}
}
// === BST Class ===
class BST {
constructor(dataType) {
this.root = null;
this.dataType = dataType; // Store the selected data type
}
// Compare method remains unchanged
compare(a, b) {
if (this.dataType === 'integer' || this.dataType === 'double' || this.dataType === 'mixed') {
return a - b;
} else if (this.dataType === 'letter' || this.dataType === 'word') {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
}
getMaxDepth(node = this.root) {
if (node === null) return 0;
return 1 + Math.max(this.getMaxDepth(node.left), this.getMaxDepth(node.right));
}
assignPosition(node, minX, maxX, currentDepth, maxDepth) {
if (node === null) return;
const paddingTop = 30 + initialNodeRadius; // Adjust for larger nodes
const paddingBottom = 30 + initialNodeRadius; // Adjust for larger nodes
const totalAvailableHeight = treeLayer.clientHeight - paddingTop - paddingBottom;
const levels = maxDepth;
const verticalSpacing = totalAvailableHeight / (levels - 1 || 1);
// Calculate vertical position using the current depth
node.y = paddingTop + (currentDepth - 1) * verticalSpacing;
// Calculate horizontal position
node.x = (minX + maxX) / 2;
// Assign positions to left and right children
const minSpacing = 20; // Adjust as needed to prevent overlap
this.assignPosition(node.left, minX, node.x - minSpacing, currentDepth + 1, maxDepth);
this.assignPosition(node.right, node.x + minSpacing, maxX, currentDepth + 1, maxDepth);
}
insert(value) {
if (this.root === null) {
this.root = new Node(value);
return this.root;
}
let current = this.root;
let parent = null;
while (current !== null) {
parent = current;
const comparison = this.compare(value, current.value);
if (comparison < 0) {
current = current.left;
} else if (comparison > 0) {
current = current.right;
} else {
// Duplicate value, ignore
return null;
}
}
const newNode = new Node(value);
newNode.parent = parent;
if (this.compare(value, parent.value) < 0) {
parent.left = newNode;
} else {
parent.right = newNode;
}
return newNode;
}
// === New delete Method ===
delete(value) {
this.root = this._deleteRecursively(this.root, value);
}
_deleteRecursively(node, value) {
if (node === null) return null;
const comparison = this.compare(value, node.value);
if (comparison < 0) {
node.left = this._deleteRecursively(node.left, value);
if (node.left) node.left.parent = node;
} else if (comparison > 0) {
node.right = this._deleteRecursively(node.right, value);
if (node.right) node.right.parent = node;
} else {
// Node found
if (node.left === null && node.right === null) {
// No children
return null;
} else if (node.left === null) {
// One child (right)
node.right.parent = node.parent;
return node.right;
} else if (node.right === null) {
// One child (left)
node.left.parent = node.parent;
return node.left;
} else {
// Two children
const successor = this.minValueNode(node.right);
node.value = successor.value;
node.textElement.textContent = successor.value; // Update SVG text
node.right = this._deleteRecursively(node.right, successor.value);
if (node.right) node.right.parent = node;
}
}
return node;
}
// === New minValueNode Method ===
minValueNode(node) {
let current = node;
while (current.left !== null) {
current = current.left;
}
return current;
}
}
// === Helper Functions ===
function createEdge(parentNode, childNode) {
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute('x1', parentNode.x);
line.setAttribute('y1', parentNode.y);
line.setAttribute('x2', childNode.x);
line.setAttribute('y2', childNode.y);
line.setAttribute('stroke', 'white');
line.setAttribute('stroke-width', '2');
line.classList.add('svg-edge');
line.setAttribute('data-parent', parentNode.value);
line.setAttribute('data-child', childNode.value);
edgesGroup.appendChild(line);
}
function createNodeElement(node) {
// Ensure x and y are set
if (node.x === undefined || node.y === undefined) {
console.error(`Node coordinates not set for value: ${node.value}`);
return;
}
// Create SVG circle for the node
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', node.x);
circle.setAttribute('cy', node.y);
circle.setAttribute('r', initialNodeRadius);
circle.setAttribute('data-value', node.value);
circle.classList.add('svg-node');
nodesGroup.appendChild(circle);
node.svgElement = circle;
// Create SVG text for the node value
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', node.x);
text.setAttribute('y', node.y);
text.setAttribute('data-value', node.value);
text.classList.add('svg-text');
text.textContent = node.value;
nodesGroup.appendChild(text);
node.textElement = text;
// Add event listeners for hover effect
setupNodeEventListeners(node);
// Add click event listener for deletion
node.svgElement.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent triggering other click events
confirmDeletion(node);
});
setTimeout(() => {
circle.setAttribute('r', initialNodeRadius);
}, 100);
}
// === Control Functions ===
function parseNumbers() {
const input = document.getElementById('numbersInput').value;
const dataType = document.getElementById('dataTypeSelect').value;
let parsedNumbers = [];
switch(dataType) {
case 'integer':
parsedNumbers = input.split(',').map(num => parseInt(num.trim(), 10)).filter(num => !isNaN(num));
break;
case 'double':
parsedNumbers = input.split(',').map(num => parseFloat(num.trim())).filter(num => !isNaN(num));
break;
case 'letter':
parsedNumbers = input.split(',').map(item => item.trim()).filter(item => /^[A-Za-z]$/.test(item));
break;
case 'word':
parsedNumbers = input.split(',').map(item => item.trim()).filter(item => /^[A-Za-z]+$/.test(item));
break;
case 'mixed':
parsedNumbers = input.split(',').map(item => item.trim()).filter(item => /^[0-9]*\.?[0-9]+$/.test(item));
break;
default:
parsedNumbers = [];
}
// Remove duplicates
numbers = [...new Set(parsedNumbers)];
// Validation Feedback
const originalCount = input.split(',').length;
const parsedCount = numbers.length;
if (originalCount !== parsedCount) {
showStatus(`Some inputs were invalid or duplicates and have been ignored.`);
} else {
showStatus('All inputs are valid and have been added.');
}
}
function updateNumbersList(highlightIndex = null) {
//numbersList before clearing
// console.log("numbersList: receiving new list - ", numbers);
numbersList.innerHTML = '';
textarea.value = numbers.join(', '); // Update the textarea to reflect the current numbers array
for (let i = 0; i < numbers.length; i++) {
const numItem = document.createElement('div');
numItem.className = 'number-item';
numItem.id = `number-${i}`;
numItem.innerText = numbers[i];
// Set data-value attribute
numItem.setAttribute('data-value', numbers[i]);
if (i < index) {
// Number has been inserted
numItem.classList.add('inserted');
}
if (highlightIndex === i) {
numItem.classList.add('current');
}
// Add fade-in effect
numItem.classList.add('fade-in');
numbersList.appendChild(numItem);
}
// console.log("numbersList after clearing: ", numbers);
}
// Function to update button text while preserving SVG
function updateButtonText(button, newText) {
console.log("updateButtonText: ", button, newText);
const textNode = button.querySelector('span'); // Use a span for text
if (textNode) {
textNode.textContent = newText;
}
}
/**
* Resets the visualization.
* @param {boolean} shouldUpdateNumbersList - Determines whether to update the numbers list.
*/
function resetVisualization(shouldUpdateNumbersList = true) {
// Clear SVG
edgesGroup.innerHTML = '';
nodesGroup.innerHTML = '';
// Reset BST with the selected data type
const dataType = document.getElementById('dataTypeSelect').value;
bst = new BST(dataType);
index = 0;
currentStep = null;
// Run the simulation to determine expected depths
simulateInsertions();
// Reset UI
showStatus('Press Start');
updateButtonText(nextButton, 'Start');
nextButton.disabled = false;
// Reset Zoom and Pan
currentScale = 1;
translateX = 0;
translateY = 0;
applyTransform();
zoomSlider.value = '1';
if (shouldUpdateNumbersList) {
// Parse and update numbers
parseNumbers();
updateNumbersList();
}
}
// Flag to determine if manual resizing has been performed
let isManuallyResized = false;
// Modify the autoResize function to respect manual resizing
function autoResize() {
if (isManuallyResized) return; // Do not auto-resize if manually resized
const textarea = document.getElementById('numbersInput');
textarea.style.height = 'auto'; // Reset the height
textarea.style.height = textarea.scrollHeight + '1em'; // Set to scrollHeight
}
// Attach the autoResize function to the input event for real-time resizing
//textarea.addEventListener('input', autoResize);
// Attach the autoResize function to the input event for real-time resizing
const textarea = document.getElementById('numbersInput');
textarea.addEventListener('input', autoResize);
// Modify the randomizeNumbers function to call autoResize after updating the textarea
function randomizeNumbers() {
const dataType = document.getElementById('dataTypeSelect').value;
const numCount = Math.floor(Math.random() * (12 - 6 + 1)) + 6; // Generate between 6 to 12 items
const uniqueValues = new Set();
while (uniqueValues.size < numCount) {
let value;
switch(dataType) {
case 'integer':
// Generate random integers between -100 and 100
value = Math.floor(Math.random() * 201) - 100;
break;
case 'double':
// Generate random doubles between -100.00 and 100.00 with two decimal places
value = parseFloat((Math.random() * 200 - 100).toFixed(2));
break;
case 'letter':
// Generate random uppercase letters A-Z
value = String.fromCharCode(65 + Math.floor(Math.random() * 26));
break;
case 'word':
// Generate random short words (less than 5 characters)
value = generateRandomWord();
break;
case 'mixed':
// Randomly choose between generating an integer or a double
if (Math.random() < 0.5) {
value = Math.floor(Math.random() * 201) - 100;
} else {
value = parseFloat((Math.random() * 200 - 100).toFixed(2));
}
break;
default:
value = null;
}
// Add the generated value to the set if it's valid
if (value !== null) {
uniqueValues.add(value);
}
}
// Convert the set to an array
numbers = Array.from(uniqueValues);
// Update the textarea with the new list
textarea.value = numbers.join(', ');
// Call autoResize to adjust the height based on new content
autoResize();
// Reset the visualization with the new list
resetVisualization();
}
function stepForward() {
console.log("stepForward: ", nextButton.innerText);
// If button says "Restart", reset the visualization
if (nextButton.innerText === 'Restart') {
resetVisualization();
return;
}
// If button says "Start", reset and start anew
if (nextButton.innerText === 'Start') {
resetVisualization(false); // Don't update numbers list
updateButtonText(nextButton, 'Next');
}
// Proceed with insertion steps
if (index >= numbers.length) {
showStatus("All values have been inserted.");
updateButtonText(nextButton, 'Restart');
return;
}
let value = numbers[index];
if (!currentStep) {
// Starting a new insertion
updateNumbersList(index);
currentStep = {
value: value,
node: bst.root
};
if (bst.root === null) {
// Insert root node
let newNode = bst.insert(value);
if (newNode) {
// Assign precomputed positions
const pos = expectedPositions[String(value)];
newNode.x = pos.x;
newNode.y = pos.y;
// Create SVG elements for the new node
createNodeElement(newNode);
showStatus(`Root node placed: ${value}`);
index++;
currentStep = null;
updateNumbersList();
}
} else {
// Highlight root node for comparison
highlightNode(bst.root, 'highlighted');
showStatus(`Comparing: ${value} with ${bst.root.value}`);
}
} else {
let currentNode = currentStep.node;
const comparison = bst.compare(currentStep.value, currentNode.value);
if (comparison < 0) {
if (currentNode.left === null) {
// Insert to the left
let newNode = bst.insert(currentStep.value);
if (newNode) {
// Assign precomputed positions
const pos = expectedPositions[String(newNode.value)];
newNode.x = pos.x;
newNode.y = pos.y;
// Create SVG elements for the new node
createNodeElement(newNode);
// Create edge between parent and new node
createEdge(currentNode, newNode);
highlightNode(newNode, 'new-node');
showStatus(`Inserted ${currentStep.value} to the left of ${currentNode.value}`);
unhighlightNode(currentNode, 'highlighted');
index++;
currentStep = null;
updateNumbersList();
}
} else {
// Move to left child
unhighlightNode(currentNode, 'highlighted');
currentStep.node = currentNode.left;
showStatus(`Moving left to compare with ${currentStep.node.value}`);
highlightNode(currentStep.node, 'highlighted');
}
} else if (comparison > 0) {
if (currentNode.right === null) {
// Insert to the right
let newNode = bst.insert(currentStep.value);
if (newNode) {
// Assign precomputed positions
const pos = expectedPositions[String(newNode.value)];
newNode.x = pos.x;
newNode.y = pos.y;
// Create SVG elements for the new node
createNodeElement(newNode);
// Create edge between parent and new node
createEdge(currentNode, newNode);
highlightNode(newNode, 'new-node');
showStatus(`Inserted ${currentStep.value} to the right of ${currentNode.value}`);
unhighlightNode(currentNode, 'highlighted');
index++;
currentStep = null;
updateNumbersList();
}
} else {
// Move to right child
unhighlightNode(currentNode, 'highlighted');
currentStep.node = currentNode.right;
showStatus(`Moving right to compare with ${currentStep.node.value}`);
highlightNode(currentStep.node, 'highlighted');
}
} else {
// Duplicate detected
showStatus(`Duplicate value ${currentStep.value} ignored.`);
unhighlightNode(currentNode, 'highlighted');
index++;
currentStep = null;
updateNumbersList();
}
}
if (index >= numbers.length && !currentStep) {
showStatus("All values have been inserted.");
updateButtonText(nextButton, 'Restart');
}
}
function setZoom(value) {
currentScale = parseFloat(value);
currentScale = Math.min(Math.max(currentScale, 0.5), 2); // Ensure scale is within bounds
applyTransform();
}
function applyTransform() {
treeContainer.style.transform = `translate(${translateX}px, ${translateY}px) scale(${currentScale})`;
}
// === Panning Functions ===
function enablePanning() {
treeLayer.addEventListener('mousedown', (e) => {
isPanning = true;
startX = e.clientX;
startY = e.clientY;
initialTranslateX = translateX;
initialTranslateY = translateY;
treeLayer.style.cursor = 'grabbing';
});
window.addEventListener('mousemove', (e) => {
if (!isPanning) return;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
translateX = initialTranslateX + deltaX;
translateY = initialTranslateY + deltaY;
applyTransform();
});
window.addEventListener('mouseup', () => {
if (isPanning) {
isPanning = false;
treeLayer.style.cursor = 'grab';
}
});
}
// === Touch Events for Panning and Zooming ===
function enableTouchGestures() {
let touchStartDistance = 0;
let initialScaleTouch = currentScale;
let initialTranslateTouch = { x: 0, y: 0 };
treeLayer.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
// Single finger touch for panning
isPanning = true;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
initialTranslateX = translateX;
initialTranslateY = translateY;
} else if (e.touches.length === 2) {
// Two fingers touch for zooming
isPanning = false;
touchStartDistance = getDistance(e.touches[0], e.touches[1]);
initialScaleTouch = currentScale;
initialTranslateTouch.x = translateX;
initialTranslateTouch.y = translateY;
}
});
treeLayer.addEventListener('touchmove', (e) => {
e.preventDefault();
if (e.touches.length === 1 && isPanning) {
const deltaX = e.touches[0].clientX - startX;
const deltaY = e.touches[0].clientY - startY;
translateX = initialTranslateX + deltaX;
translateY = initialTranslateY + deltaY;
applyTransform();
} else if (e.touches.length === 2) {
const currentDistance = getDistance(e.touches[0], e.touches[1]);
const scaleFactor = currentDistance / touchStartDistance;
currentScale = initialScaleTouch * scaleFactor;
currentScale = Math.min(Math.max(currentScale, 0.5), 2); // Clamp between 0.5 and 2
applyTransform();
zoomSlider.value = currentScale;
}
});
treeLayer.addEventListener('touchend', (e) => {
if (e.touches.length < 2) {
touchStartDistance = 0;
}
if (e.touches.length === 0) {
isPanning = false;
}
});
}
function getDistance(touch1, touch2) {
const dx = touch2.clientX - touch1.clientX;
const dy = touch2.clientY - touch1.clientY;
return Math.sqrt(dx * dx + dy * dy);
}
// === Event Listeners ===
addButton.addEventListener('click', () => {
resetVisualization();
});
randomizeButton.addEventListener('click', () => {
randomizeNumbers();
});
nextButton.addEventListener('click', () => {
stepForward();
});
// Zoom Slider
zoomSlider.addEventListener('input', (e) => {
setZoom(e.target.value);
});
// Event Listener for the handle click
traversalsPaneHandle.addEventListener('click', () => {
container.classList.toggle('open');
});
// Event Listener for the handle click
paneHandle.addEventListener('click', () => {
leftPane.classList.toggle('open');
});
// Redraw Button Event Listener
const redrawButton = document.getElementById('redrawButton');
redrawButton.addEventListener('click', () => {
redrawButton.disabled = true; // Prevent multiple clicks during the process
const totalDelay = clearNumbersList(); // Start the removal animation
setTimeout(() => {
resetVisualization(false); // Don't reset numbers list
// Insert nodes into the BST
insertNodesintoBST();
// Parse and update numbers
parseNumbers();
updateNumbersList();
showStatus("All inputs have been added.");
redrawButton.disabled = false; // Re-enable the button after completion
}, totalDelay); // Wait until all items have been removed
});
// Initialize Panning and Touch Gestures
enablePanning();
enableTouchGestures();
//when i change datatTypeSelect it calls initializeDemo
const dataTypeSelect = document.getElementById('dataTypeSelect');
dataTypeSelect.addEventListener('change', initializeDemo);
// === Initialization ===
function initializeDemo() {
// Get the selected data type from the dropdown
const dataType = document.getElementById('dataTypeSelect').value;
// Define balanced and duplicate-free lists for each data type
if (dataType === 'integer') {
numbers = [
77, 37, 150, 22, 70, 124, 175,
15, 30, 50, 75, 100, 126, 170,
180, 14, 20, 25, 36, 45, 69,
71, 76, 90, 123, 125, 127, 169,
171, 179, 181
];
} else if (dataType === 'double') {
numbers = [
77.5, 37.2, 150.1, 22.8, 70.6, 124.3, 175.4,
15.9, 30.7, 50.2, 75.5, 100.4, 126.6, 170.8,
180.3, 14.1, 20.5, 25.2, 36.4, 45.7, 69.9,
71.3, 76.6, 90.8, 123.5, 125.7, 127.9, 169.2,
171.4, 179.6, 181.8
];
} else if (dataType === 'letter') {
numbers = [
'N', 'G', 'D', 'B', 'F', 'K', 'I', 'M', 'T', 'Q', 'O', 'R',
'W', 'U', 'X'
];
} else if (dataType === 'word') {
numbers = [
'fox', 'can', 'bag', 'ant', 'ace', 'art', 'bed',
'bat', 'bug', 'dog', 'cow', 'cat', 'day', 'eat',
'ear', 'egg', 'man', 'jam', 'hat', 'fun', 'ice',
'kid', 'jar', 'leg', 'rat', 'owl', 'net', 'pig',
'toy', 'sun', 'zip'
];
} else if (dataType === 'mixed') {
numbers = [
77, 37.5, 150, 22.8, 70, 124.3, 175,
15.9, 30, 50.2, 75, 100.4, 126, 170.8,
180, 14.1, 20, 25.2, 36.4, 45, 69.9,
71, 76.6, 90.8, 123.5, 125.7, 127.9, 169,
171.4, 179.6, 181
];
}
// Update the textarea with the new list
textarea.value = numbers.join(', ');
// Call autoResize to adjust the height based on content
autoResize();
// Reset the visualization with the new list
resetVisualization();
updateNumbersList();
}
// Initialize the demo
initializeDemo();
// Adjust the tree layer on window resize
window.addEventListener('resize', () => {
if (bst.root !== null) {
// Recalculate positions using expected depths
bst.assignPosition(bst.root, 50, treeLayer.clientWidth - 50, 1, bst.getMaxDepth());
// Update positions of SVG elements
updateSVGElements();
}
});
function clearNumbersList() {
// Assuming numbersList is the DOM element containing the list of numbers
numbersList.innerHTML = ''; // Clear the list
// Optionally, return a delay if you have animations
return 0; // No delay by default
}
function updateSVGElements() {
// Update positions of edges
edgesGroup.querySelectorAll('.svg-edge').forEach(line => {
const parentValue = line.getAttribute('data-parent');
const childValue = line.getAttribute('data-child');
const parentNode = findNodeByValue(bst.root, parentValue);
const childNode = findNodeByValue(bst.root, childValue);
if (parentNode && childNode) {
line.setAttribute('x1', parentNode.x);
line.setAttribute('y1', parentNode.y);
line.setAttribute('x2', childNode.x);
line.setAttribute('y2', childNode.y);
}
});
// Update positions of nodes
nodesGroup.querySelectorAll('.svg-node').forEach(circle => {
const value = circle.getAttribute('data-value');
const node = findNodeByValue(bst.root, value);
if (node) {
circle.setAttribute('cx', node.x);
circle.setAttribute('cy', node.y);
}
});
// Update positions of texts
nodesGroup.querySelectorAll('.svg-text').forEach(text => {
const value = text.getAttribute('data-value');
const node = findNodeByValue(bst.root, value);
if (node) {
text.setAttribute('x', node.x);
text.setAttribute('y', node.y + 5); // Adjust for vertical centering
}
});
}
function parseTreeAndHideEdges(node) {
if (node === null) return true;
const leftHidden = parseTreeAndHideEdges(node.left);
const rightHidden = parseTreeAndHideEdges(node.right);
if (leftHidden && rightHidden && node.svgElement.classList.contains('node-greyed-out')) {
hideSubtreeEdges(node);
return true;
}
return false;
}
function hideSubtreeEdges(node) {
if (node === null) return;
// Hide edges connected to this node
const edges = document.querySelectorAll(`line[data-parent="${node.value}"], line[data-child="${node.value}"]`);
edges.forEach(edge => edge.classList.add('hidden-edge'));
// Recursively hide edges for left and right children
hideSubtreeEdges(node.left);
hideSubtreeEdges(node.right);
}
function showAllEdges() {
const edges = document.querySelectorAll('line');
edges.forEach(edge => edge.classList.remove('hidden-edge'));
}
function clearTraversalTimeouts() {
traversalTimeouts.forEach(timeout => clearTimeout(timeout));
traversalTimeouts = [];
}
traversalNames.forEach(name => {
const box = document.createElement('div');
box.className = 'traversalBox';
const button = document.createElement('button');
button.textContent = name;
button.className = 'button-style';
button.dataset.isStarted = 'false'; // Initialize state as not started
// Event Listener for Traversal Buttons
button.addEventListener('click', function() {
const isStarted = this.dataset.isStarted === 'true';
if (!isStarted) {
// First Click: Start Traversal
traverseSortedTree(name, box.querySelector('.traversalList'));
this.textContent = 'Cancel'; // Change button text to 'Cancel'
this.dataset.isStarted = 'true'; // Update state
// Disable Other Buttons
const buttons = document.querySelectorAll('.button-style');
buttons.forEach(btn => {
if (btn !== this) btn.disabled = true;
});
// console.log(`Traversal "${name}" started.`);
} else {
// Second Click: Stop Traversal and Reset
clearTraversalTimeouts(); // Stop ongoing traversals
redrawTree(); // Redraw the tree visualization
this.textContent = name; // Reset button text to original
this.dataset.isStarted = 'false'; // Update state
// Enable All Buttons
const buttons = document.querySelectorAll('.button-style');
buttons.forEach(btn => btn.disabled = false);
// console.log(`Traversal "${name}" canceled.`);
}
});
const list = document.createElement('div');
list.className = 'traversalList';
box.appendChild(button);
box.appendChild(list);
container.appendChild(box);
});
document.addEventListener('mousemove', (e) => {
if (!t_isDragging) return;
const dx = e.clientX - t_startX;
const dy = e.clientY - t_startY;
let newX = t_initialX + dx;
let newY = t_initialY + dy;
// Constrain within treeSVG boundaries
const maxX = treeSVG.clientWidth ;
const maxY = treeSVG.clientHeight - 250;
newX = Math.max(0, Math.min(newX, maxX));
newY = Math.max(0, Math.min(newY, maxY));
container.style.left = `${newX}px`;
container.style.top = `${newY}px`;
});
document.addEventListener('mouseup', () => {
t_isDragging = false;
document.body.style.userSelect = ''; // Re-enable text selection
});
// Optional: Add touch support for mobile devices
container.addEventListener('touchstart', (e) => {
t_isDragging = true;