async print to console

This commit is contained in:
Baipyrus 2023-01-18 08:02:41 +01:00
parent 16057b4a18
commit cd1de28b66
3 changed files with 102 additions and 59 deletions

View File

@ -18,7 +18,7 @@
██████╔╝██║ ██║██║██║ ██║ ██║ ██║██╗╚██████╔╝███████║
╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚══════╝
</pre>
root@baipyr.us:~#
<a>root@baipyr.us:~# </a>
<a id="current"></a>
<input type="text" id="input">
</div>

View File

@ -16,7 +16,6 @@ function cmd_about() {
function cmd_clear() {
// Clear terminal by reloading page
window.location.reload();
return "";
}
function cmd_history() {
@ -77,29 +76,46 @@ function cmd_nick(input) {
name: user.name,
id: user.id
})
}).then(res => {});
return `Applied name '${user.name}'.`;
}).then(res => {
if (res.status === 200) {
user.connected = true;
return res.json();
}
}).then(res => {
if (res === undefined)
return;
if (res)
outputText({output: `Applied name '${user.name}'.`});
else {
outputText({output: `Name '${user.name}' is already taken!.`});
user.name = "";
}
});
return null;
}
async function cmd_msg(input) {
function cmd_msg(input) {
if (input === undefined)
return "No message given!";
return "No username given!";
if (!user.connected)
return "You are not connected!";
const res = await fetch('/message', {
const username = input[0];
pretext = `Chat (${username})> `;
chatMode = `msg ${username}`;
fetch('/chatInit', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: input.join(' '),
name: username,
id: user.id
})
});
if (res.status === 200) {
const { message } = await res.json();
return message;
} else
return "Server returned status " + res.status;
}).then(res => {});
}
function cmd_exit() {
if (chatMode.split(' ')[0] !== "default")
chatMode = "default";
}

View File

@ -25,12 +25,12 @@ fetch('/connect').then(res => {
user.id = id;
});
const user = { id: "", name: "", history: [], connected: false };
let chatMode = "default";
let pretext = "root@baipyr.us:~# ";
// Initiating variables
const length = pretext.length+1;
let startPosition = length;
let cursorPosition = 0;
let cursorYOffset = 7;
let history = { index: 0, list: [] };
@ -71,7 +71,7 @@ document.addEventListener("selectionchange", e => {
}
});
document.addEventListener("keydown", async e => {
document.addEventListener("keydown", e => {
const text = textCur.textContent;
switch (e.key) {
case "Backspace":
@ -113,38 +113,7 @@ document.addEventListener("keydown", async e => {
break;
case "Enter":
// Befehl absenden / Zeilenumbruch
tbDiv.removeChild(textIn);
tbDiv.removeChild(textCur);
const inputSet = new Set(text.split(''));
if (text !== "" || inputSet.has(" ") && inputSet.size === 1) {
history.list.push(text);
history.index = history.list.length;
}
// Fix current input to page
tbDiv.appendChild(createText(text));
tbDiv.innerHTML += `<br>`;
// Run command and return output
let commandOutput = await runCommand(text);
if (commandOutput !== "") {
// If output is given, display it as text with formatting
tbDiv.append(createText(commandOutput, false))
tbDiv.innerHTML += `<br>`;
// Offset cursor by at least one line, and as many more as there are line breaks
cursorYOffset += commandOutput.split("<br>").length;
}
// Add new pretext to terminal
tbDiv.innerHTML += pretext;
// Add elements on top of div
tbDiv.appendChild(textCur);
tbDiv.appendChild(textIn);
// Reset variables
textCur.textContent = "";
cursorPosition = 0;
cursorYOffset++;
updateCursor();
outputText({user: text});
break;
case "ArrowUp":
// Einen Befehl zurück in der History
@ -174,6 +143,46 @@ document.addEventListener("keydown", async e => {
}
});
function outputText(params) {
const { user, output } = params;
tbDiv.removeChild(textIn);
tbDiv.removeChild(textCur);
if (user !== undefined) {
const inputSet = new Set(user.split(''));
if (user !== "" || inputSet.has(" ") && inputSet.size === 1) {
history.list.push(user);
history.index = history.list.length;
}
// Fix current input to page
tbDiv.appendChild(createText(user));
tbDiv.innerHTML += `<br>`;
cursorYOffset++;
}
// Run command and return output
let commandOutput = (output === undefined && user !== undefined) ? runCommand(user) : output;
if (commandOutput !== "" && commandOutput !== null) {
// If output is given, display it as text with formatting
tbDiv.append(createText(commandOutput, false))
tbDiv.innerHTML += `<br>`;
// Offset cursor by at least one line, and as many more as there are line breaks
cursorYOffset += commandOutput.split("<br>").length;
}
// Add new pretext to terminal
if (commandOutput !== null)
tbDiv.innerHTML += pretext;
// Add elements on top of div
tbDiv.appendChild(textCur);
tbDiv.appendChild(textIn);
// Reset variables
textCur.textContent = "";
cursorPosition = 0;
updateCursor();
}
// Create an 'a' element with input string as its contents
function createText(str, safe=true) {
const link = document.createElement("a");
@ -189,11 +198,33 @@ function createText(str, safe=true) {
}
// Run input as command if possible
async function runCommand(input) {
function runCommand(input) {
// Return on no input
if (input === "")
return "";
const modeSplit = chatMode.split(' ');
switch (modeSplit[0]) {
case "msg":
// Direct message
fetch('/message', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: user.id,
message: input,
name: modeSplit[1]
})
}).then(res => {});
return "";
// case "chat":
// // Global messages
// break;
}
let output = "";
const lowerIn = input.toLowerCase();
@ -206,18 +237,12 @@ async function runCommand(input) {
const lowerNm = name.toLowerCase();
// If command is called without parameters
if (lowerIn === lowerNm) {
if (window[func].constructor.name === "AsnycFunction")
output = await window[func]();
else
output = window[func]();
break;
// If command is called with parameters
} else if (lowerIn.startsWith(lowerNm + " ")) {
// Parameters always follow the command name after first space
const params = input.split(" ").filter((e,i)=>i!==0);
if (window[func].constructor.name === "AsnycFunction")
output = await window[func](params);
else
output = window[func](params);
break;
}
@ -225,8 +250,10 @@ async function runCommand(input) {
}
// Standard output:
if (output === "" && !lowerIn.startsWith("clear"))
if (output === "")
output = `${input.split(" ")[0]}: command not found`;
if (output === undefined)
output = "";
// Return command output
return output;
@ -235,7 +262,7 @@ async function runCommand(input) {
// Update cursor position based on coordinates
function updateCursor() {
let cursor = document.getElementById("cursor");
cursor.style.transform = `translate(${startPosition+cursorPosition-1}ch, ${2.222*cursorYOffset-0.4}ch)`;
cursor.style.transform = `translate(${pretext.length+cursorPosition}ch, ${2.222*cursorYOffset-0.4}ch)`;
}
// Toggle cursor visibility