import { Stack } from './stack.js';
// Function to executed when the web page is loaded
onload = function () {
// Store the required HTML elements
const textbox = document.getElementById('comment');
const undo = document.getElementById('undo');
const clear = document.getElementById('clear');
const temptext = document.getElementById('temptext');
// Initialize the variables
textbox.value = "";
let text = "";
let stack = new Stack();
// Attach a click event listener to the button to clear the text editor
clear.onclick = function () {
stack.clear(); // Call the clear() function from the Stack class
text = ""; // Set the text to empty string
textbox.value = ""; // Set the value of the text box to empty string
temptext.innerHTML = "Sequence of operations will be shown here !"; // Set the message displaying the operation performed
};
// Attach an input event listener to the text box to insert data to the stack
// when the user enters text and removes the text by pressing the backspace key
textbox.oninput = function(event){
switch(event.inputType){
// Case when the character is inserted in the text box
case "insertText":
stack.push(0, event.data); // Store the operation type and the data in the stack
break;
// Case when the character is removed from the text box
case "deleteContentBackward":
stack.push(1, text[text.length - 1]); // Store the operation type and the last character removed from the text editor in the stack
break;
}
// Set the message on the right side of the web page to display the data in the stack
temptext.innerHTML = "Stack data: Operation " + stack.top() + "<br>" + temptext.innerHTML;
// Store the current text data in the text box
text = textbox.value;
};
// Attach a click event listener to button to perform the undo operation
undo.onclick = function () {
// Remove the top element from the stack
let operation = stack.pop();
// Check if the stack is not empty since the pop() function returns -1 as operation type if the stack is empty
if(operation[0] !== -1){
// Set the message to display the undo operation performed
temptext.innerHTML = "Performing undo operation<br>"+temptext.innerHTML;
// Check if the operation type was insert
if(operation[0] === 0){
// Store the length of the string
let len = operation[1].length;
// Update the text box value
textbox.value = textbox.value.substring(0,textbox.value.length-len);
}
// If the operation type was delete
else{
// Update the text value
textbox.value += operation[1];
}
// Update the variable to store the current text in the text box
text = textbox.value;
}
};
};