"use client"; import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import { createRconServer, deleteRconServer, setRconServerEnabled, testSavedRconServer, updateRconServer, } from "@/app/admin/(console)/rcon/actions"; import { AdminModalForm } from "@/components/admin-modal-form"; import { rconSuggestions, type RconSuggestion } from "@/lib/rcon-help"; import { useRconSession } from "./use-rcon-session"; import { GearBuilder } from "./gear-builder"; const MAX_COMMAND_HISTORY = 50; const MAX_TRANSCRIPT_EXCHANGES = 50; type TranscriptExchange = { id: number; serverName: string; command: string; status: "pending" | "success" | "error"; message: string; }; export type RconServerOption = { id: string; name: string; host: string; port: number; enabled: boolean; }; export type RconTerminalNotice = { status: "success" | "error"; message: string; }; export function RconConsole({ notice, servers, }: { notice?: RconTerminalNotice; servers: RconServerOption[]; }) { const [selectedId, setSelectedId] = useState(servers[0]?.id ?? ""); const [command, setCommand] = useState(""); const [suggestionsOpen, setSuggestionsOpen] = useState(false); const [activeSuggestion, setActiveSuggestion] = useState(0); const [history, setHistory] = useState([]); const [historyIndex, setHistoryIndex] = useState(null); const [transcript, setTranscript] = useState([]); const draftRef = useRef(""); const inputRef = useRef(null); const nextExchangeIdRef = useRef(0); const pendingExchangeIdRef = useRef(null); const transcriptRef = useRef(null); const selected = servers.find((server) => server.id === selectedId) ?? servers[0]; const help = useRconSession(selected, command); const { state, action, pending } = help; const suggestions = selected?.enabled && !pending && suggestionsOpen ? rconSuggestions(command, help.catalog?.commands ?? [], help.usage?.text) : []; const suggestionIndex = Math.min(activeSuggestion, Math.max(0, suggestions.length - 1)); function acceptSuggestion(suggestion: RconSuggestion) { setCommand(suggestion.value); setSuggestionsOpen(false); setHistoryIndex(null); inputRef.current?.focus(); } useEffect(() => { inputRef.current?.focus(); }, [selectedId]); useEffect(() => { if (suggestions.length) document.getElementById(`rcon-suggestion-${suggestionIndex}`)?.scrollIntoView?.({ block: "nearest" }); }, [suggestionIndex, suggestions.length]); useEffect(() => { if (!pending && state.status !== "idle") inputRef.current?.focus(); }, [pending, state.status]); useEffect(() => { const exchangeId = pendingExchangeIdRef.current; if (exchangeId === null || state.status === "idle") return; const resultStatus: TranscriptExchange["status"] = state.status === "error" ? "error" : "success"; setTranscript((current) => current.map((exchange) => exchange.id === exchangeId ? { ...exchange, status: resultStatus, message: state.message } : exchange)); pendingExchangeIdRef.current = null; }, [state]); useEffect(() => { if (transcriptRef.current) transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight; }, [transcript]); function navigateHistory(direction: "older" | "newer") { if (!history.length) return; if (direction === "older") { const nextIndex = historyIndex === null ? history.length - 1 : Math.max(0, historyIndex - 1); if (historyIndex === null) draftRef.current = command; setHistoryIndex(nextIndex); setCommand(history[nextIndex]!); return; } if (historyIndex === null) return; if (historyIndex < history.length - 1) { const nextIndex = historyIndex + 1; setHistoryIndex(nextIndex); setCommand(history[nextIndex]!); } else { setHistoryIndex(null); setCommand(draftRef.current); } } function rememberSubmittedCommand() { help.stopHelp(); setSuggestionsOpen(false); const submitted = command.trim(); if (!submitted || !selected) return; const exchangeId = ++nextExchangeIdRef.current; pendingExchangeIdRef.current = exchangeId; const exchange: TranscriptExchange = { id: exchangeId, serverName: selected.name, command: submitted, status: "pending", message: "Command in progress…", }; setTranscript((current) => [...current, exchange].slice(-MAX_TRANSCRIPT_EXCHANGES)); setHistory((current) => [...current, submitted].slice(-MAX_COMMAND_HISTORY)); setHistoryIndex(null); draftRef.current = ""; setCommand(""); } return (
{servers.length ? ( ) : ( no-target )} {selected && {selected.host}:{selected.port}}
Command history {selected && ( <>
)}
{notice && (

{notice.status === "error" ? "Connection error" : "Connection update"}

{notice.message}

)} {!transcript.length && }
{transcript.map((exchange) => (

server://{exchange.serverName} $ {exchange.command}

{exchange.status === "pending" ?

Command in progress…

:
{exchange.message}
}
))}

{help.loading ? "Reading server help…" : help.message}

{help.usage && (

Server usage hint

{help.usage.text ?? (help.usage.failed ? "Usage unavailable. Refresh commands to retry." : "No usage supplied by server help.")}
)} {suggestions.length > 0 && (

↑↓ Select · Tab / Enter Insert · Esc Dismiss

    {suggestions.map((suggestion, index) => (
  • acceptSuggestion(suggestion)} onMouseDown={(event) => event.preventDefault()} role="option"> {suggestion.label}{" "}{suggestion.description}
  • ))}
)}
0} role="combobox" autoComplete="off" autoFocus className="min-w-0 flex-1 bg-transparent px-1 py-2 font-mono text-sm outline-none placeholder:text-muted focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50" disabled={!selected?.enabled || pending} id="rcon-command" key={selected?.id ?? "no-server"} maxLength={1024} name="command" onSelect={(event) => { const input = event.currentTarget; if (input.selectionStart !== input.value.length || input.selectionEnd !== input.value.length) setSuggestionsOpen(false); }} onBlur={() => setSuggestionsOpen(false)} onChange={(event) => { setCommand(event.target.value); setSuggestionsOpen(true); setActiveSuggestion(0); }} onKeyDown={(event) => { if (event.nativeEvent.isComposing) return; if (event.key === "Escape") { setSuggestionsOpen(false); return; } if (suggestions.length) { if (event.key === "ArrowUp" || event.key === "ArrowDown") { event.preventDefault(); setActiveSuggestion((suggestionIndex + (event.key === "ArrowUp" ? -1 : 1) + suggestions.length) % suggestions.length); return; } if ((event.key === "Tab" && !event.shiftKey) || event.key === "Enter") { event.preventDefault(); acceptSuggestion(suggestions[suggestionIndex]!); return; } } if (event.key === "ArrowUp" || event.key === "ArrowDown") { event.preventDefault(); navigateHistory(event.key === "ArrowUp" ? "older" : "newer"); } }} placeholder={selected ? (selected.enabled ? "list" : "Enable this connection to run commands") : "Add a connection to begin"} ref={inputRef} required spellCheck={false} value={command} />
); } function TerminalIdle({ selected }: { selected?: RconServerOption }) { if (!selected) return <>

Ready

No connections configured. Use Add to create a server connection.

; if (!selected.enabled) return <>

Disabled — {selected.name}

Enable this connection before testing commands.

; return <>

Ready — {selected.name}

Awaiting command

; } function HeaderButton({ label }: { label: string }) { return ; } function ConnectionModal({ mode, server, }: { mode: "add" | "edit"; server?: RconServerOption; }) { const editing = mode === "edit" ? server : undefined; return (
{editing && }
); } function ConnectionFields({ defaults, prefix, }: { defaults?: { name: string; host: string; port: number }; prefix: string; }) { const fieldClass = "mt-2 block w-full border border-line bg-canvas px-4 py-3 font-mono text-sm outline-none focus:border-accent"; return ( <> ); }