TerminalHomepage/js/main.js

111 lines
3.7 KiB
JavaScript

const pretext = "root@baipyr.us:~# ";
let startPosition = 0;
let cursorPosition = 0;
let cursorYOffset = 0;
document.addEventListener("keypress", e=>{
if ((e.key == "Enter") || (e.code == "KeyV" && e.ctrlKey))
return;
let textbox = document.getElementById("input");
const index = cursorPosition - startPosition;
if (e.key == ' ' && (textbox.innerText[index-1] == ' ' || cursorPosition == startPosition))
return;
if (index <= textbox.innerText.length-1) {
const text = textbox.innerText;
const a = text.substring(0, index);
const b = text.substring(index, text.length);
textbox.innerText = a + e.key + b;
} else
textbox.innerText += e.key;
cursorPosition++;
updateCursor();
});
document.addEventListener("keydown", e=>{
let textbox = document.getElementById("input");
const index = cursorPosition - startPosition;
const text = textbox.innerText;
switch (e.key) {
case "Backspace":
// Ein Zeichen nach links löschen
if (index == 0)
return;
if (index <= textbox.innerText.length-1) {
const a = text.substring(0, index-1);
const b = text.substring(index, text.length);
textbox.innerText=a+b;
} else
textbox.innerText = text.substring(0,text.length-1);
cursorPosition--;
updateCursor();
break;
case "ArrowLeft":
// Ein Zeichen nach links
if (cursorPosition > startPosition) {
cursorPosition--;
updateCursor();
}
break;
case "ArrowRight":
// Ein Zeichen nach reckts
if (index < textbox.innerText.length) {
cursorPosition++;
updateCursor();
}
break;
case "Delete":
// Ein Zeichen nach rechts löschen
if (index == 0 || index >= textbox.innerText.length)
return;
const a = text.substring(0, index);
const b = text.substring(index+1, text.length);
textbox.innerText=a+b;
break;
case "Enter":
// Befehl absenden / Zeilenumbruch
const parent = document.getElementById("textbox");
parent.removeChild(textbox);
// Run command and return output???
const commandOutput = "";
parent.innerHTML += '<a style="color: lightgrey;">' + text + '</a><br>' + commandOutput + pretext;
textbox.innerText = "";
parent.appendChild(textbox);
cursorPosition = startPosition;
cursorYOffset++;
updateCursor();
break;
case "ArrowUp":
// Einen Befehl zurück in der History
break;
case "ArrowDown":
// Einen Befehl nach vorne in der History
break;
case "Tab":
// Autocomplete
break;
}
});
function updateCursor() {
let cursor = document.getElementById("cursor");
const transform = `translate(${cursorPosition}ch,${cursorYOffset}em)`;
cursor.style.transform = transform;
}
function preload() {
let cursor = document.getElementById("cursor");
let textbox = document.getElementById("textbox");
textbox.innerHTML = pretext+textbox.innerHTML;
const length = textbox.innerText.length+1;
const transform = `translate(${length}ch)`;
cursor.style.transform = transform;
startPosition = length;
cursorPosition = length;
}
setInterval(()=>{
let cursor = document.getElementById("cursor");
cursor.style.opacity = (cursor.style.opacity=="1")?"0":"1";
},1000);