Files
Terminal-Website/public/js/terminal.js
2024-01-16 20:53:14 +01:00

112 lines
2.9 KiB
JavaScript

const hostname = `192.168.${Math.floor(Math.random()*100)}.${Math.floor(Math.random()*255)}`;
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll(".pathText").forEach((element)=> {
element.innerHTML = `guest@${hostname}`;
});
const terminalInput = document.getElementById("terminalInput");
terminalInput.addEventListener("input", function (e) {
resizeInput();
});
resizeInput()
terminalInput.addEventListener('blur', function(e) {
e.preventDefault();
setTimeout(() => {
terminalInput.focus();
}, 0);
}, false);
document.addEventListener('click', function(e) {
e.preventDefault();
setTimeout(() => {
terminalInput.focus();
}, 0);
}, false);
terminalInput.focus();
terminalInput.addEventListener("keydown", async function (e) {
if (e.key === "Enter"){
await sendCommand(e);
}
});
});
async function sendCommand(e){
const command = e.target.value;
e.target.value = "";
resizeInput();
console.log("COMMAND SENT: "+command);
try {
// Construct the URL with the command parameter in the query string
const url = "/execute?command=" + encodeURIComponent(command);
// Make a GET request using the fetch API
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
// Parse the JSON response
const files = await response.json();
// Handle the execution response
handleExecutionResponse(files);
} catch (error) {
console.error("Error:", error.message);
}
}
function resizeInput() {
const inputText = terminalInput.value;
const inputWidth = measureTextWidth(inputText);
const maxWidth = 300; // Set your desired maximum width
if (inputWidth <= maxWidth) {
terminalInput.style.width = inputWidth + "px";
} else {
terminalInput.style.width = maxWidth + "px";
terminalInput.value = inputText.slice(0, -1); // Remove the last character
}
}
function measureTextWidth(text) {
const nonBreakingSpace = '\u00A0';
const sanitizedText = text.replace(/ /g, nonBreakingSpace);
const fakeElement = document.createElement("div");
fakeElement.style.visibility = "hidden";
fakeElement.style.position = "absolute";
fakeElement.style.top = "0";
fakeElement.style.left = "0";
fakeElement.style.width = "auto";
fakeElement.style.fontFamily = "Source Code Pro";
fakeElement.style.fontSize = "16px";
fakeElement.style.whiteSpace = "nowrap";
fakeElement.innerHTML = sanitizedText;
document.body.appendChild(fakeElement);
const width = fakeElement.offsetWidth;
document.body.removeChild(fakeElement);
return width;
}
function handleExecutionResponse(response) {
console.log(response);
}