document.addEventListener("DOMContentLoaded", function () { const input = document.getElementById("command-input"); // We assume your normal terminal UI is in the element with id "terminal". const normalTerminal = document.getElementById("terminal"); let interactiveWS = null; let interactiveMode = false; const ansi_up = new AnsiUp; // Listen for the "start-interactive" command in normal mode. input.addEventListener("keydown", function (event) { if (!interactiveMode && event.key === "Enter") { const command = input.value.trim(); if (command === "start-interactive") { startInteractiveSession(); input.value = ""; event.preventDefault(); return; } // Otherwise, your normal HTTP submission… } }); function startInteractiveSession() { // Hide the normal terminal and input. normalTerminal.style.display = "none"; input.style.display = "none"; // Create a new container for xterm.js. const xtermContainer = document.createElement("div"); xtermContainer.id = "xterm-container"; xtermContainer.style.width = "100%"; xtermContainer.style.height = "100vh"; // Optionally set additional styling (e.g. background color). document.body.appendChild(xtermContainer); // Initialize xterm.js Terminal. const term = new Terminal({ cursorBlink: true, scrollback: 1000, theme: { background: "#222", foreground: "#eee" } }); const fitAddon = new FitAddon.FitAddon(); term.loadAddon(fitAddon); term.open(xtermContainer); fitAddon.fit(); term.focus(); // Establish the WebSocket connection. interactiveWS = new WebSocket("ws://" + location.host + "/terminal"); interactiveWS.binaryType = "arraybuffer"; interactiveWS.onmessage = function (event) { const text = new TextDecoder("utf-8").decode(event.data); term.write(text); }; interactiveWS.onclose = function () { interactiveMode = false; term.write("\r\n--- Interactive session ended ---\r\n"); // Remove the xterm container. if (xtermContainer.parentNode) { xtermContainer.parentNode.removeChild(xtermContainer); } // Restore the normal terminal UI. normalTerminal.style.display = "block"; input.style.display = "block"; input.focus(); }; interactiveWS.onerror = function (err) { term.write("\r\n--- Error in interactive session ---\r\n"); console.error("Interactive WS error:", err); interactiveMode = false; if (xtermContainer.parentNode) { xtermContainer.parentNode.removeChild(xtermContainer); } normalTerminal.style.display = "block"; input.style.display = "block"; }; // When the user types in xterm, send the data to the server. term.onData(function (data) { // If the user presses Ctrl+D (ASCII 4), exit the session. if (data === "\x04") { term.write("\r\n--- Exiting interactive session ---\r\n"); interactiveWS.close(); } else { interactiveWS.send(data); } }); interactiveMode = true; } });