87 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-04-28 20:06:47 -04:00
"use client"
import { Terminal } from "@xterm/xterm"
import { FitAddon } from "@xterm/addon-fit"
2024-04-29 21:36:33 -04:00
import "./xterm.css"
2024-04-28 20:06:47 -04:00
import { useEffect, useRef, useState } from "react"
import { Socket } from "socket.io-client"
2024-04-30 22:48:36 -04:00
import { Loader2 } from "lucide-react"
2024-04-28 20:06:47 -04:00
export default function EditorTerminal({ socket }: { socket: Socket }) {
const terminalRef = useRef(null)
const [term, setTerm] = useState<Terminal | null>(null)
useEffect(() => {
if (!terminalRef.current) return
const terminal = new Terminal({
2024-04-29 21:36:33 -04:00
cursorBlink: true,
theme: {
background: "#262626",
},
2024-04-28 20:06:47 -04:00
})
setTerm(terminal)
return () => {
if (terminal) terminal.dispose()
}
}, [])
useEffect(() => {
if (!term) return
const onConnect = () => {
2024-05-02 00:00:35 -07:00
console.log("Connected to server", socket.connected)
2024-04-28 20:06:47 -04:00
setTimeout(() => {
socket.emit("createTerminal", { id: "testId" })
2024-05-02 00:00:35 -07:00
}, 2000)
2024-04-28 20:06:47 -04:00
}
2024-04-29 02:19:27 -04:00
const onTerminalResponse = (response: { data: string }) => {
// const res = Buffer.from(response.data, "base64").toString("utf-8")
const res = response.data
term.write(res)
2024-04-28 20:06:47 -04:00
}
socket.on("connect", onConnect)
if (terminalRef.current) {
socket.on("terminalResponse", onTerminalResponse)
const fitAddon = new FitAddon()
term.loadAddon(fitAddon)
term.open(terminalRef.current)
fitAddon.fit()
setTerm(term)
}
const disposable = term.onData((data) => {
console.log("sending data", data)
2024-04-29 02:19:27 -04:00
socket.emit("terminalData", "testId", data)
2024-04-28 20:06:47 -04:00
})
2024-04-29 02:19:27 -04:00
socket.emit("terminalData", "\n")
2024-04-28 20:06:47 -04:00
return () => {
socket.off("connect", onConnect)
socket.off("terminalResponse", onTerminalResponse)
disposable.dispose()
}
}, [term, terminalRef.current])
2024-04-30 22:48:36 -04:00
return (
<div
ref={terminalRef}
className="w-full font-mono text-sm h-full text-left"
>
{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
}