81 lines
1.8 KiB
TypeScript
Raw Normal View History

"use client";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "./xterm.css";
import { useEffect, useRef, useState } from "react";
import { Socket } from "socket.io-client";
import { Loader2 } from "lucide-react";
export default function EditorTerminal({
socket,
term,
setTerm,
}: {
socket: Socket;
term: Terminal | null;
setTerm: (term: Terminal) => void;
}) {
const terminalRef = useRef(null);
2024-04-28 20:06:47 -04:00
useEffect(() => {
if (!terminalRef.current) return;
2024-04-28 20:06:47 -04:00
const terminal = new Terminal({
2024-04-29 21:36:33 -04:00
cursorBlink: true,
theme: {
background: "#262626",
},
2024-05-02 15:25:24 -07:00
fontFamily: "var(--font-geist-mono)",
fontSize: 14,
});
2024-04-28 20:06:47 -04:00
setTerm(terminal);
2024-04-28 20:06:47 -04:00
return () => {
if (terminal) terminal.dispose();
};
}, []);
2024-04-28 20:06:47 -04:00
useEffect(() => {
if (!term) return;
2024-04-28 20:06:47 -04:00
// const onTerminalResponse = (response: { data: string }) => {
// const res = response.data;
// term.write(res);
// };
2024-04-28 20:06:47 -04:00
if (terminalRef.current) {
// socket.on("terminalResponse", onTerminalResponse);
2024-04-28 20:06:47 -04:00
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(terminalRef.current);
fitAddon.fit();
setTerm(term);
2024-04-28 20:06:47 -04:00
}
const disposable = term.onData((data) => {
console.log("sending data", data);
socket.emit("terminalData", "testId", data);
});
2024-04-28 20:06:47 -04:00
// socket.emit("terminalData", "\n");
2024-04-28 20:06:47 -04:00
return () => {
disposable.dispose();
};
}, [term, terminalRef.current]);
2024-04-28 20:06:47 -04:00
2024-04-30 22:48:36 -04:00
return (
2024-05-02 15:25:24 -07:00
<div ref={terminalRef} className="w-full h-full text-left">
2024-04-30 22:48:36 -04:00
{term === null ? (
<div className="flex items-center text-muted-foreground p-2">
<Loader2 className="animate-spin mr-2 h-4 w-4" />
<span>Connecting to terminal...</span>
</div>
) : null}
</div>
);
2024-04-28 20:06:47 -04:00
}