fix: added terminal response handling

This commit is contained in:
Akhilesh Rangani 2024-07-23 20:17:50 -04:00
parent 051bf1164a
commit 74a4352323
3 changed files with 21 additions and 18 deletions

View File

@ -38,26 +38,15 @@ export default function Terminals() {
createNewTerminal(); createNewTerminal();
}; };
const handleCloseTerminal = (termId: string) => {
closeTerminal(termId);
if (activeTerminalId === termId) {
const remainingTerminals = terminals.filter(t => t.id !== termId);
if (remainingTerminals.length > 0) {
setActiveTerminalId(remainingTerminals[0].id);
} else {
setActiveTerminalId("");
}
}
};
return ( return (
<> <>
<div className="h-10 w-full overflow-auto flex gap-2 shrink-0 tab-scroll"> <div className="h-10 w-full overflow-auto flex gap-2 shrink-0 tab-scroll">
{terminals.map((term) => ( {terminals.map((term) => (
<Tab <Tab
key={term.id} key={term.id}
creating={creatingTerminal}
onClick={() => setActiveTerminalId(term.id)} onClick={() => setActiveTerminalId(term.id)}
onClose={() => handleCloseTerminal(term.id)} onClose={() => closeTerminal(term.id)}
selected={activeTerminalId === term.id} selected={activeTerminalId === term.id}
> >
<SquareTerminal className="w-4 h-4 mr-2" /> <SquareTerminal className="w-4 h-4 mr-2" />
@ -88,10 +77,10 @@ export default function Terminals() {
term={term.terminal} term={term.terminal}
setTerm={(t: Terminal) => { setTerm={(t: Terminal) => {
setTerminals((prev) => setTerminals((prev) =>
prev.map((prevTerm) => prev.map((term) =>
prevTerm.id === term.id term.id === activeTerminalId
? { ...prevTerm, terminal: t } ? { ...term, terminal: t }
: prevTerm : term
) )
); );
}} }}

View File

@ -74,6 +74,20 @@ export default function EditorTerminal({
}; };
}, [term, terminalRef.current]); }, [term, terminalRef.current]);
useEffect(() => {
if (!term) return;
const handleTerminalResponse = (response: { id: string; data: string }) => {
if (response.id === id) {
term.write(response.data);
}
};
socket.on("terminalResponse", handleTerminalResponse);
return () => {
socket.off("terminalResponse", handleTerminalResponse);
};
}, [term, id, socket]);
return ( return (
<> <>
<div <div

View File

@ -3,7 +3,7 @@
import React, { createContext, useContext, useState, useEffect } from 'react'; import React, { createContext, useContext, useState, useEffect } from 'react';
import { io, Socket } from 'socket.io-client'; import { io, Socket } from 'socket.io-client';
import { Terminal } from '@xterm/xterm'; import { Terminal } from '@xterm/xterm';
import { createTerminal as createTerminalHelper, closeTerminal as closeTerminalHelper } from '@/lib/terminal'; // Adjust the import path as necessary import { createTerminal as createTerminalHelper, closeTerminal as closeTerminalHelper } from '@/lib/terminal';
interface TerminalContextType { interface TerminalContextType {
socket: Socket | null; socket: Socket | null;