Fix ts configuration and missing fragment in server route after terminal removal

This commit is contained in:
Bot
2026-04-16 12:14:30 +08:00
parent a4dc173fcc
commit 8733070cf1
5 changed files with 78 additions and 363 deletions
-9
View File
@@ -1,9 +0,0 @@
import { ModelCreateTerminalResponse } from "@/types"
import { FetcherMethod, fetcher } from "./api"
export const createTerminal = async (id: number): Promise<ModelCreateTerminalResponse> => {
return fetcher<ModelCreateTerminalResponse>(FetcherMethod.POST, "/api/v1/terminal", {
server_id: id,
})
}
-206
View File
@@ -1,206 +0,0 @@
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import useTerminal from "@/hooks/useTerminal"
import { sleep } from "@/lib/utils"
import { AttachAddon } from "@xterm/addon-attach"
import { FitAddon } from "@xterm/addon-fit"
import { Terminal } from "@xterm/xterm"
import "@xterm/xterm/css/xterm.css"
import { Terminal as TerminalIcon } from "lucide-react"
import { JSX, forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useParams } from "react-router-dom"
import { toast } from "sonner"
import { FMCard } from "./fm"
import { Button } from "./ui/button"
import { IconButton } from "./xui/icon-button"
interface XtermProps {
wsUrl: string
setClose: React.Dispatch<React.SetStateAction<boolean>>
}
const XtermComponent = forwardRef<HTMLDivElement, XtermProps & JSX.IntrinsicElements["div"]>(
({ wsUrl, setClose, ...props }, ref) => {
const terminalIdRef = useRef<HTMLDivElement>(null)
const terminalRef = useRef<Terminal | null>(null)
const wsRef = useRef<WebSocket | null>(null)
useImperativeHandle(ref, () => {
return {
...terminalIdRef.current!,
async requestFullscreen() {
await terminalIdRef.current?.requestFullscreen()
},
}
}, [])
useEffect(() => {
return () => {
wsRef.current?.close()
terminalRef.current?.dispose()
}
}, [])
useEffect(() => {
terminalRef.current = new Terminal({
cursorBlink: true,
fontSize: 16,
})
const url = new URL(wsUrl, window.location.origin)
url.protocol = url.protocol.replace("http", "ws")
const ws = new WebSocket(url)
wsRef.current = ws
ws.binaryType = "arraybuffer"
ws.onopen = () => {
onResize()
}
ws.onclose = () => {
terminalRef.current?.dispose()
setClose(true)
}
ws.onerror = (e) => {
console.error(e)
toast("Websocket error", {
description: "View console for details.",
})
}
}, [wsUrl])
const fitAddon = useRef(new FitAddon()).current
const sendResize = useRef(false)
const doResize = () => {
if (!terminalIdRef.current) return
fitAddon.fit()
const dimensions = fitAddon.proposeDimensions()
if (dimensions) {
const prefix = new Int8Array([1])
const resizeMessage = new TextEncoder().encode(
JSON.stringify({
Rows: dimensions.rows,
Cols: dimensions.cols,
}),
)
const msg = new Int8Array(prefix.length + resizeMessage.length)
msg.set(prefix)
msg.set(resizeMessage, prefix.length)
wsRef.current?.send(msg)
}
}
const onResize = async () => {
if (sendResize.current) return
sendResize.current = true
try {
await sleep(1500)
doResize()
} catch (error) {
console.error("resize error", error)
} finally {
sendResize.current = false
}
}
useEffect(() => {
if (!wsRef.current || !terminalIdRef.current || !terminalRef.current) return
const attachAddon = new AttachAddon(wsRef.current)
terminalRef.current.loadAddon(attachAddon)
terminalRef.current.loadAddon(fitAddon)
terminalRef.current.open(terminalIdRef.current)
window.addEventListener("resize", onResize)
return () => {
window.removeEventListener("resize", onResize)
if (wsRef.current) {
wsRef.current.close()
}
}
}, [wsRef.current, terminalRef.current, terminalIdRef.current])
return <div ref={terminalIdRef} {...props} />
},
)
export const TerminalPage = () => {
const { id } = useParams<{ id: string }>()
const [open, setOpen] = useState(false)
const terminal = useTerminal(id ? parseInt(id) : undefined)
const terminalIdRef = useRef<HTMLDivElement>(null)
return (
<div className="px-8">
<div className="flex mt-6 mb-4">
<h1 className="flex-1 text-3xl font-bold tracking-tight">{`Terminal (${id})`}</h1>
<div className="flex ml-auto self-end sm:self-auto gap-2 flex-wrap shrink-0">
<IconButton
icon="expand"
onClick={async () => {
await terminalIdRef.current?.requestFullscreen()
}}
/>
<FMCard id={id} />
</div>
</div>
{terminal?.session_id ? (
<XtermComponent
ref={terminalIdRef}
className="max-h-[60%] mb-5 overflow-auto"
wsUrl={`/api/v1/ws/terminal/${terminal?.session_id}`}
setClose={setOpen}
/>
) : (
<p>The server does not exist, or have not been connected yet.</p>
)}
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogContent className="sm:max-w-lg">
<AlertDialogHeader>
<AlertDialogTitle>Session completed</AlertDialogTitle>
<AlertDialogDescription>
You may close this window now.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction asChild>
<Button onClick={window.close}>Close</Button>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export const TerminalButton = ({ id, menuItem = false }: { id: number; menuItem?: boolean }) => {
const { t } = useTranslation()
const handleOpenNewTab = () => {
window.open(`/dashboard/terminal/${id}`, "_blank")
}
if (menuItem) {
return (
<button
type="button"
onClick={handleOpenNewTab}
className="flex w-full items-center text-sm px-2 py-2 hover:bg-accent hover:text-accent-foreground"
>
<TerminalIcon className="h-4 w-4 mr-2" />
<span>{t("Terminal")}</span>
</button>
)
}
return <IconButton variant="outline" icon="terminal" onClick={handleOpenNewTab} />
}
-23
View File
@@ -1,23 +0,0 @@
import { createTerminal } from "@/api/terminal"
import { ModelCreateTerminalResponse } from "@/types"
import { useEffect, useState } from "react"
export default function useTerminal(serverId?: number) {
const [terminal, setTerminal] = useState<ModelCreateTerminalResponse | null>(null)
async function fetchTerminal() {
try {
const response = await createTerminal(serverId!)
setTerminal(response)
} catch (error) {
console.error("Failed to fetch terminal:", error)
}
}
useEffect(() => {
if (!serverId) return
fetchTerminal()
}, [serverId])
return terminal
}
+23 -34
View File
@@ -1,31 +1,27 @@
// NOTE: Do not modify the import order unless absolutely necessary.
import { createRoot } from "react-dom/client"
import { RouterProvider, createBrowserRouter } from "react-router-dom"
import "./index.css"
import "./lib/i18n"
import ErrorPage from "./error-page"
import { AuthProvider } from "./hooks/useAuth"
import { NotificationProvider } from "./hooks/useNotfication"
import { ServerProvider } from "./hooks/useServer"
import Root from "./routes/root"
import ErrorPage from "./error-page"
import ProtectedRoute from "./routes/protect"
import CronPage from "./routes/cron"
import LoginPage from "./routes/login"
import ServerPage from "./routes/server"
import ServicePage from "./routes/service"
import { TerminalPage } from "./components/terminal"
import DDNSPage from "./routes/ddns"
import NATPage from "./routes/nat"
import NotificationGroupPage from "./routes/notification-group"
import ServerGroupPage from "./routes/server-group"
import "./index.css"
import "./lib/i18n"
import AlertRulePage from "./routes/alert-rule"
import CronPage from "./routes/cron"
import DDNSPage from "./routes/ddns"
import LoginPage from "./routes/login"
import NATPage from "./routes/nat"
import NotificationPage from "./routes/notification"
import NotificationGroupPage from "./routes/notification-group"
import OnlineUserPage from "./routes/online-user"
import ProfilePage from "./routes/profile"
import ProtectedRoute from "./routes/protect"
import Root from "./routes/root"
import ServerPage from "./routes/server"
import ServerGroupPage from "./routes/server-group"
import ServicePage from "./routes/service"
import SettingsPage from "./routes/settings"
import UserPage from "./routes/user"
import WAFPage from "./routes/waf"
@@ -74,6 +70,14 @@ const router = createBrowserRouter([
</ServerProvider>
),
},
{
path: "/dashboard/notification",
element: (
<NotificationProvider withNotifierGroup>
<NotificationPage />
</NotificationProvider>
),
},
{
path: "/dashboard/alert-rule",
element: (
@@ -106,18 +110,7 @@ const router = createBrowserRouter([
</NotificationProvider>
),
},
{
path: "/dashboard/terminal/:id",
element: <TerminalPage />,
},
{
path: "/dashboard/notification",
element: (
<NotificationProvider withNotifierGroup>
<NotificationPage />
</NotificationProvider>
),
},
{
path: "/dashboard/profile",
element: (
@@ -128,11 +121,7 @@ const router = createBrowserRouter([
},
{
path: "/dashboard/settings",
element: (
<NotificationProvider withNotifierGroup>
<SettingsPage />
</NotificationProvider>
),
element: <SettingsPage />,
},
{
path: "/dashboard/settings/user",
+15 -51
View File
@@ -10,12 +10,6 @@ import { ServerCard } from "@/components/server"
import { ServerConfigCard } from "@/components/server-config"
import { ServerConfigCardBatch } from "@/components/server-config-batch"
import { Checkbox } from "@/components/ui/checkbox"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Table,
TableBody,
@@ -36,10 +30,7 @@ import useSWR from "swr"
export default function ServerPage() {
const { t } = useTranslation()
const { data, mutate, error, isLoading } = useSWR<Server[]>("/api/v1/server", swrFetcher, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
})
const { data, mutate, error, isLoading } = useSWR<Server[]>("/api/v1/server", swrFetcher)
const { serverGroups } = useServer()
useEffect(() => {
@@ -93,7 +84,7 @@ export default function ServerPage() {
accessorFn: (row) => {
return (
serverGroups
?.filter((sg) => sg.servers?.includes(row.id))
?.filter((sg) => sg.servers?.includes(row.id!))
.map((sg) => sg.group.id) || []
)
},
@@ -113,7 +104,7 @@ export default function ServerPage() {
{
header: t("Version"),
accessorKey: "host.version",
accessorFn: (row) => row.host.version || t("Unknown"),
accessorFn: (row) => row.host?.version || t("Unknown"),
},
{
header: t("EnableDDNS"),
@@ -149,30 +140,11 @@ export default function ServerPage() {
return (
<ActionButtonGroup
className="flex gap-2"
delete={{ fn: deleteServer, id: s.id, mutate: mutate }}
delete={{ fn: deleteServer, id: s.id!, mutate: mutate }}
>
<>
<ServerCard mutate={mutate} data={s} />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
icon="more"
variant="outline"
aria-label="More actions"
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<TerminalButton id={s.id} menuItem />
</DropdownMenuItem>
<DropdownMenuItem asChild>
<ServerConfigCard sid={s.id} variant="ghost" menuItem />
</DropdownMenuItem>
<DropdownMenuItem asChild>
<InstallCommandsMenu uuid={s.uuid} menuItem />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ServerConfigCard sid={s.id!} variant="outline" />
</>
</ActionButtonGroup>
)
@@ -193,11 +165,11 @@ export default function ServerPage() {
const selectedRows = table.getSelectedRowModel().rows
return (
<div className="px-3 max-w-7xl mx-auto">
<div className="flex flex-col sm:flex-row sm:items-center justify-between w-full gap-3 mt-6 mb-4">
<div className="px-3">
<div className="flex mt-6 mb-4">
<h1 className="text-3xl font-bold tracking-tight">{t("Server")}</h1>
<HeaderButtonGroup
className="flex gap-2 flex-wrap shrink-0"
className="flex-2 flex ml-auto gap-2"
delete={{
fn: deleteServer,
id: selectedRows.map((r) => r.original.id).filter(Boolean) as number[],
@@ -207,7 +179,7 @@ export default function ServerPage() {
<IconButton
icon="update"
onClick={async () => {
const id = selectedRows.map((r) => r.original.id)
const id = selectedRows.map((r) => r.original.id) as number[]
if (id.length < 1) {
toast(t("Error"), {
description: t("Results.SelectAtLeastOneServer"),
@@ -240,17 +212,16 @@ export default function ServerPage() {
})
}}
/>
<BatchMoveServerIcon serverIds={selectedRows.map((r) => r.original.id)} />
<BatchMoveServerIcon serverIds={selectedRows.map((r) => r.original.id) as number[]} />
<ServerConfigCardBatch
sid={selectedRows.map((r) => r.original.id)}
sid={selectedRows.map((r) => r.original.id) as number[]}
className="shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] bg-yellow-600 text-white hover:bg-yellow-500 dark:hover:bg-yellow-700 rounded-lg"
/>
<InstallCommandsMenu className="shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] bg-blue-700 text-white hover:bg-blue-600 dark:hover:bg-blue-800 rounded-lg" />
</HeaderButtonGroup>
</div>
<div className="rounded-md border overflow-x-auto">
<Table className="min-w-[960px]">
<TableHeader className="sticky top-0 bg-background z-10">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
@@ -277,16 +248,10 @@ export default function ServerPage() {
</TableRow>
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="text-xsm">
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
@@ -301,6 +266,5 @@ export default function ServerPage() {
</TableBody>
</Table>
</div>
</div>
)
}