Update terminal-panel.tsx

This commit is contained in:
MacRimi
2025-11-21 19:25:23 +01:00
parent e26956dbe8
commit 50e3b8e7d4

View File

@@ -1,20 +1,11 @@
"use client" "use client"
import type React from "react" import type React from "react"
import { useEffect, useRef } from "react" import { useEffect, useRef, useState } from "react"
import { API_PORT } from "@/lib/api-config" import { API_PORT } from "@/lib/api-config"
let Terminal: any
let FitAddon: any
if (typeof window !== "undefined") {
Terminal = require("xterm").Terminal
FitAddon = require("xterm-addon-fit").FitAddon
require("xterm/css/xterm.css")
}
type TerminalPanelProps = { type TerminalPanelProps = {
websocketUrl?: string // Custom WebSocket URL if needed websocketUrl?: string
} }
function getWebSocketUrl(): string { function getWebSocketUrl(): string {
@@ -25,14 +16,11 @@ function getWebSocketUrl(): string {
const { protocol, hostname, port } = window.location const { protocol, hostname, port } = window.location
const isStandardPort = port === "" || port === "80" || port === "443" const isStandardPort = port === "" || port === "80" || port === "443"
// Use wss:// for https, ws:// for http
const wsProtocol = protocol === "https:" ? "wss:" : "ws:" const wsProtocol = protocol === "https:" ? "wss:" : "ws:"
if (isStandardPort) { if (isStandardPort) {
// Behind proxy - use current host
return `${wsProtocol}//${hostname}/ws/terminal` return `${wsProtocol}//${hostname}/ws/terminal`
} else { } else {
// Direct access - use API port
return `${wsProtocol}//${hostname}:${API_PORT}/ws/terminal` return `${wsProtocol}//${hostname}:${API_PORT}/ws/terminal`
} }
} }
@@ -42,12 +30,20 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
const termRef = useRef<any>(null) const termRef = useRef<any>(null)
const fitAddonRef = useRef<any>(null) const fitAddonRef = useRef<any>(null)
const wsRef = useRef<WebSocket | null>(null) const wsRef = useRef<WebSocket | null>(null)
// For touch gestures
const touchStartRef = useRef<{ x: number; y: number; time: number } | null>(null) const touchStartRef = useRef<{ x: number; y: number; time: number } | null>(null)
const [xtermLoaded, setXtermLoaded] = useState(false)
useEffect(() => { useEffect(() => {
if (!containerRef.current || !Terminal || !FitAddon) return if (typeof window === "undefined") return
Promise.all([
import("xterm").then((mod) => mod.Terminal),
import("xterm-addon-fit").then((mod) => mod.FitAddon),
import("xterm/css/xterm.css"),
])
.then(([Terminal, FitAddon]) => {
if (!containerRef.current) return
console.log("[v0] TerminalPanel: Initializing terminal") console.log("[v0] TerminalPanel: Initializing terminal")
@@ -67,6 +63,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
termRef.current = term termRef.current = term
fitAddonRef.current = fitAddon fitAddonRef.current = fitAddon
setXtermLoaded(true)
const wsUrl = websocketUrl || getWebSocketUrl() const wsUrl = websocketUrl || getWebSocketUrl()
console.log("[v0] TerminalPanel: Connecting to WebSocket:", wsUrl) console.log("[v0] TerminalPanel: Connecting to WebSocket:", wsUrl)
@@ -93,14 +90,12 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
term.writeln("\r\n\x1b[33m[INFO] Connection closed\x1b[0m") term.writeln("\r\n\x1b[33m[INFO] Connection closed\x1b[0m")
} }
// Send user input to backend
term.onData((data) => { term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) { if (ws.readyState === WebSocket.OPEN) {
ws.send(data) ws.send(data)
} }
}) })
// Re-adjust terminal size on window resize
const handleResize = () => { const handleResize = () => {
try { try {
fitAddon.fit() fitAddon.fit()
@@ -116,6 +111,10 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
ws.close() ws.close()
term.dispose() term.dispose()
} }
})
.catch((error) => {
console.error("[v0] TerminalPanel: Failed to load xterm:", error)
})
}, [websocketUrl]) }, [websocketUrl])
const sendSequence = (seq: string) => { const sendSequence = (seq: string) => {
@@ -149,7 +148,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
sendSequence("\r") sendSequence("\r")
break break
case "CTRL_C": case "CTRL_C":
sendSequence("\x03") // Ctrl+C sendSequence("\x03")
break break
default: default:
break break
@@ -174,26 +173,24 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
const dy = touch.clientY - start.y const dy = touch.clientY - start.y
const dt = Date.now() - start.time const dt = Date.now() - start.time
const minDistance = 30 // Minimum pixels for swipe detection const minDistance = 30
const maxTime = 1000 // Maximum time in milliseconds const maxTime = 1000
touchStartRef.current = null touchStartRef.current = null
if (dt > maxTime) return // Gesture too slow, ignore if (dt > maxTime) return
if (Math.abs(dx) < minDistance && Math.abs(dy) < minDistance) { if (Math.abs(dx) < minDistance && Math.abs(dy) < minDistance) {
return // Movement too small, ignore return
} }
if (Math.abs(dx) > Math.abs(dy)) { if (Math.abs(dx) > Math.abs(dy)) {
// Horizontal swipe
if (dx > 0) { if (dx > 0) {
handleKeyButton("RIGHT") handleKeyButton("RIGHT")
} else { } else {
handleKeyButton("LEFT") handleKeyButton("LEFT")
} }
} else { } else {
// Vertical swipe
if (dy > 0) { if (dy > 0) {
handleKeyButton("DOWN") handleKeyButton("DOWN")
} else { } else {
@@ -204,15 +201,17 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
return ( return (
<div className="flex flex-col h-full w-full"> <div className="flex flex-col h-full w-full">
{/* Terminal display */}
<div <div
ref={containerRef} ref={containerRef}
className="flex-1 bg-black rounded-t-md overflow-hidden" className="flex-1 bg-black rounded-t-md overflow-hidden"
onTouchStart={handleTouchStart} onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd} onTouchEnd={handleTouchEnd}
/> >
{!xtermLoaded && (
<div className="flex items-center justify-center h-full text-zinc-400">Initializing terminal...</div>
)}
</div>
{/* Touch keyboard bar for mobile/tablet */}
<div className="flex flex-wrap gap-2 justify-center items-center px-2 py-2 bg-zinc-900 text-sm rounded-b-md"> <div className="flex flex-wrap gap-2 justify-center items-center px-2 py-2 bg-zinc-900 text-sm rounded-b-md">
<TouchKey label="ESC" onClick={() => handleKeyButton("ESC")} /> <TouchKey label="ESC" onClick={() => handleKeyButton("ESC")} />
<TouchKey label="TAB" onClick={() => handleKeyButton("TAB")} /> <TouchKey label="TAB" onClick={() => handleKeyButton("TAB")} />
@@ -227,7 +226,6 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl }) =>
) )
} }
// Reusable button component for touch keyboard
type TouchKeyProps = { type TouchKeyProps = {
label: string label: string
onClick: () => void onClick: () => void