refactor: simplify WebSocket connection logic in DockerTerminal component

- Removed redundant checks for containerId before establishing WebSocket connection.
- Streamlined the connection setup and added the AttachAddon directly after the terminal is opened.
- Updated UI text to clarify the connection method.
This commit is contained in:
Mauricio Siu
2025-10-05 00:45:07 -06:00
parent 47a9bd9c86
commit aadb278e5f

View File

@@ -4,7 +4,6 @@ import { FitAddon } from "xterm-addon-fit";
import "@xterm/xterm/css/xterm.css";
import { AttachAddon } from "@xterm/addon-attach";
import { useTheme } from "next-themes";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
interface Props {
@@ -38,48 +37,30 @@ export const DockerTerminal: React.FC<Props> = ({
},
});
const addonFit = new FitAddon();
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}`;
const ws = new WebSocket(wsUrl);
const addonAttach = new AttachAddon(ws);
// @ts-ignore
term.open(termRef.current);
// @ts-ignore
term.loadAddon(addonFit);
term.loadAddon(addonAttach);
addonFit.fit();
// only connect if containerId is provided
if (
containerId &&
containerId !== "" &&
containerId !== "select-a-container"
) {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}`;
const ws = new WebSocket(wsUrl);
const addonAttach = new AttachAddon(ws);
term.loadAddon(addonAttach);
ws.onopen = () => {
setIsConnected(true);
};
ws.onclose = () => {
setIsConnected(false);
};
return () => {
ws.readyState === WebSocket.OPEN && ws.close();
};
}
return () => {
ws.readyState === WebSocket.OPEN && ws.close();
};
}, [containerId, activeWay, id]);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2 mt-4">
<Label>
Select shell to connect to <b>{isConnected ? containerId : "..."}</b>
</Label>
<span>
Select way to connect to <b>{containerId}</b>
</span>
<Tabs value={activeWay} onValueChange={setActiveWay}>
<TabsList>
<TabsTrigger value="bash">Bash</TabsTrigger>