Spaces:
Running
Running
File size: 1,371 Bytes
a405934 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import { useEffect, useRef } from "react";
import { Terminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import "xterm/css/xterm.css";
export default function XTerm({ onData, output }) {
const termRef = useRef(null);
const fitAddon = new FitAddon();
useEffect(() => {
const term = new Terminal({
cursorBlink: true,
fontSize: 14,
theme: {
background: "#1e1e1e",
foreground: "#ffffff",
},
});
termRef.current = term;
term.loadAddon(fitAddon);
term.open(document.getElementById("terminal-container"));
fitAddon.fit();
term.onData((data) => {
// Echo user input (like real terminals)
term.write(data);
// When ENTER pressed, send full line to parent
if (data === "\r") {
const line = term._core.buffer.xtermBuffer.active.getLine(
term.buffer.active.cursorY
).translateToString().trim();
onData(line);
}
});
return () => term.dispose();
}, []);
// Print backend output into terminal
useEffect(() => {
if (output) {
termRef.current?.writeln("\r\n" + output);
}
}, [output]);
return (
<div
id="terminal-container"
style={{
width: "100%",
height: "180px",
background: "#1e1e1e",
borderTop: "1px solid #333",
}}
></div>
);
}
|