feat: add connections page, rename dashboard page to overview

This commit is contained in:
2026-08-23 20:01:41 +08:00
parent ba65c43183
commit e3f575096b
11 changed files with 1416 additions and 34 deletions
+42 -12
View File
@@ -1,24 +1,44 @@
import { useState } from 'react'
import { useMemo } from 'react'
import { SidebarProvider, SidebarInset } from '@/components/ui/sidebar'
import { TooltipProvider } from '@/components/ui/tooltip'
import { AppSidebar, type NavTab } from '@/components/layout/app-sidebar'
import { AppSidebar } from '@/components/layout/app-sidebar'
import { AppHeader } from '@/components/layout/app-header'
import { DashboardPage } from '@/pages/dashboard'
import { OverviewPage } from '@/pages/overview'
import { ConnectionsPage } from '@/pages/connections'
import { useKlalbSSE } from '@/hooks/use-klalb-sse'
import { useHashRoute } from '@/hooks/use-hash-route'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
export function App() {
const [currentTab, setCurrentTab] = useState<NavTab>('dashboard')
const { status, links, isConnected, reconnectAll, refreshStatus } = useKlalbSSE()
const { currentTab, navigate } = useHashRoute()
const {
status,
links,
isConnected,
reconnectAll,
refreshStatus,
addLink,
removeLink,
executeLinkAction,
} = useKlalbSSE()
const safeLinks = Array.isArray(links) ? links : []
const establishedLinksCount = useMemo(() => {
return safeLinks.filter(
(l) => l && (l.stateCode === 2 || (l.state && l.state.toLowerCase().includes('up')) || l.state === 'ESTABLISHED')
).length
}, [safeLinks])
return (
<TooltipProvider>
<SidebarProvider>
<AppSidebar
currentTab={currentTab}
onSelectTab={setCurrentTab}
onSelectTab={navigate}
onlineDevices={status?.onlineDevices}
linksCount={links.length}
linksCount={safeLinks.length}
establishedLinksCount={establishedLinksCount}
isConnected={isConnected}
/>
<SidebarInset className="flex flex-col">
@@ -30,15 +50,25 @@ export function App() {
/>
<main className="flex flex-1 flex-col overflow-y-auto">
{currentTab === 'dashboard' && (
<DashboardPage
{currentTab === 'overview' && (
<OverviewPage
status={status}
links={links}
links={safeLinks}
isConnected={isConnected}
/>
)}
{currentTab !== 'dashboard' && (
{currentTab === 'connections' && (
<ConnectionsPage
links={safeLinks}
isConnected={isConnected}
onAddLink={addLink}
onRemoveLink={removeLink}
onLinkAction={executeLinkAction}
/>
)}
{currentTab !== 'overview' && currentTab !== 'connections' && (
<div className="flex flex-1 items-center justify-center p-8">
<Card className="max-w-md text-center">
<CardHeader>
@@ -46,7 +76,7 @@ export function App() {
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
</p>
</CardContent>
</Card>
@@ -0,0 +1,82 @@
import {
MoreVertical,
RotateCcw,
Unplug,
Trash2,
Copy,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import type { RemoteLinkItem } from '@/types/api'
interface ConnectionActionMenuProps {
link: RemoteLinkItem
onLinkAction: (
address: string,
action: 'reconnect' | 'disconnect' | 'remove'
) => Promise<{ success: boolean; message?: string }>
onRemoveLink: (address: string) => Promise<{ success: boolean; message?: string }>
onCopyText: (text: string) => void
}
export function ConnectionActionMenu({
link,
onLinkAction,
onRemoveLink,
onCopyText,
}: ConnectionActionMenuProps) {
const targetAddress = link.socketAddress || link.name
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="ghost" size="icon-xs" className="text-muted-foreground">
<MoreVertical className="size-4" />
</Button>
}
/>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => onLinkAction(link.name, 'reconnect')}
>
<RotateCcw data-icon="inline-start" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => onLinkAction(link.name, 'disconnect')}
>
<Unplug data-icon="inline-start" />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => onCopyText(targetAddress)}
>
<Copy data-icon="inline-start" />
Socket
</DropdownMenuItem>
{link.vaddr && (
<DropdownMenuItem onClick={() => onCopyText(link.vaddr!)}>
<Copy data-icon="inline-start" />
SID
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() => onRemoveLink(targetAddress)}
>
<Trash2 data-icon="inline-start" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
+8 -6
View File
@@ -24,13 +24,14 @@ import {
} from '@/components/ui/sidebar'
import { Badge } from '@/components/ui/badge'
export type NavTab = 'dashboard' | 'links' | 'routes' | 'topology' | 'interfaces' | 'settings'
export type NavTab = 'overview' | 'connections' | 'routes' | 'topology' | 'interfaces' | 'settings'
interface AppSidebarProps {
currentTab: NavTab
onSelectTab: (tab: NavTab) => void
onlineDevices?: number
linksCount?: number
establishedLinksCount?: number
isConnected?: boolean
}
@@ -39,20 +40,21 @@ export function AppSidebar({
onSelectTab,
onlineDevices = 0,
linksCount = 0,
establishedLinksCount = 0,
isConnected = false,
}: AppSidebarProps) {
const navItems = [
{
id: 'dashboard' as NavTab,
title: '仪表盘总览',
id: 'overview' as NavTab,
title: '总览',
icon: LayoutDashboard,
badge: isConnected ? 'Live' : undefined,
},
{
id: 'links' as NavTab,
title: '线路与链路',
id: 'connections' as NavTab,
title: '连接',
icon: Network,
badge: linksCount > 0 ? `${linksCount}` : undefined,
badge: linksCount > 0 ? `${establishedLinksCount}/${linksCount}` : undefined,
},
{
id: 'routes' as NavTab,
+158
View File
@@ -0,0 +1,158 @@
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
+268
View File
@@ -0,0 +1,268 @@
"use client"
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import { cn } from "@/lib/utils"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
align = "start",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
className="isolate z-50 outline-none"
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuLabel({
className,
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.GroupLabel
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.SubmenuTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
}
function DropdownMenuSubContent({
align = "start",
alignOffset = -3,
side = "right",
sideOffset = 0,
className,
...props
}: React.ComponentProps<typeof DropdownMenuContent>) {
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
return (
<MenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
}
function DropdownMenuSeparator({
className,
...props
}: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+114
View File
@@ -0,0 +1,114 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+59
View File
@@ -0,0 +1,59 @@
import { useState, useEffect, useCallback } from 'react'
import type { NavTab } from '@/components/layout/app-sidebar'
const VALID_TABS: NavTab[] = [
'overview',
'connections',
'routes',
'topology',
'interfaces',
'settings',
]
function getTabFromHash(hash: string): NavTab {
const cleanHash = hash.replace(/^#\/?/, '').trim().toLowerCase()
if (!cleanHash || cleanHash === '') {
return 'overview'
}
// 向后兼容旧的 dashboard hash
if (cleanHash === 'dashboard') {
return 'overview'
}
const matchingTab = VALID_TABS.find((tab) => tab === cleanHash)
return matchingTab || 'overview'
}
export function useHashRoute() {
const [currentTab, setCurrentTabState] = useState<NavTab>(() =>
getTabFromHash(window.location.hash)
)
useEffect(() => {
const handleHashChange = () => {
const newTab = getTabFromHash(window.location.hash)
setCurrentTabState(newTab)
}
// If current hash is empty, initialize with #/overview
if (!window.location.hash || window.location.hash === '#' || window.location.hash === '#/') {
window.location.hash = '#/overview'
} else if (window.location.hash === '#/dashboard') {
window.location.hash = '#/overview'
}
window.addEventListener('hashchange', handleHashChange)
return () => {
window.removeEventListener('hashchange', handleHashChange)
}
}, [])
const navigate = useCallback((tab: NavTab) => {
window.location.hash = `#/${tab}`
setCurrentTabState(tab)
}, [])
return {
currentTab,
navigate,
}
}
+90 -6
View File
@@ -8,6 +8,12 @@ interface UseKlalbSSEResult {
error: string | null
reconnectAll: () => Promise<boolean>
refreshStatus: () => Promise<void>
addLink: (address: string) => Promise<{ success: boolean; message?: string }>
removeLink: (address: string) => Promise<{ success: boolean; message?: string }>
executeLinkAction: (
address: string,
action: 'reconnect' | 'disconnect' | 'remove'
) => Promise<{ success: boolean; message?: string }>
}
export function useKlalbSSE(): UseKlalbSSEResult {
@@ -20,14 +26,21 @@ export function useKlalbSSE(): UseKlalbSSEResult {
const refreshStatus = useCallback(async () => {
try {
const res = await fetch('/api/status')
if (res.ok) {
const data = (await res.json()) as SystemStatus
const [statusRes, linksRes] = await Promise.all([
fetch('/api/status'),
fetch('/api/links'),
])
if (statusRes.ok) {
const data = (await statusRes.json()) as SystemStatus
setStatus(data)
setError(null)
}
if (linksRes.ok) {
const linksData = await linksRes.json()
setLinks(Array.isArray(linksData) ? linksData : [])
}
setError(null)
} catch (err) {
console.warn('Failed to fetch status fallback:', err)
console.warn('Failed to fetch status/links fallback:', err)
}
}, [])
@@ -41,6 +54,74 @@ export function useKlalbSSE(): UseKlalbSSEResult {
}
}, [])
const addLink = useCallback(
async (address: string): Promise<{ success: boolean; message?: string }> => {
try {
const res = await fetch('/api/links', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address: address.trim() }),
})
const data = await res.json()
if (res.ok && data.success) {
refreshStatus()
return { success: true }
}
return { success: false, message: data.error || '添加连接失败' }
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err)
return { success: false, message: msg }
}
},
[refreshStatus]
)
const removeLink = useCallback(
async (address: string): Promise<{ success: boolean; message?: string }> => {
try {
const res = await fetch(
`/api/links?address=${encodeURIComponent(address.trim())}`,
{ method: 'DELETE' }
)
const data = await res.json()
if (res.ok && data.success) {
refreshStatus()
return { success: true }
}
return { success: false, message: data.error || '移除连接失败' }
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err)
return { success: false, message: msg }
}
},
[refreshStatus]
)
const executeLinkAction = useCallback(
async (
address: string,
action: 'reconnect' | 'disconnect' | 'remove'
): Promise<{ success: boolean; message?: string }> => {
try {
const res = await fetch('/api/links/action', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address, action }),
})
const data = await res.json()
if (res.ok && data.success) {
refreshStatus()
return { success: true }
}
return { success: false, message: data.error || `执行 ${action} 失败` }
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err)
return { success: false, message: msg }
}
},
[refreshStatus]
)
useEffect(() => {
let isUnmounted = false
@@ -65,7 +146,7 @@ export function useKlalbSSE(): UseKlalbSSEResult {
if (data.status) {
setStatus(data.status)
}
if (data.links) {
if (Array.isArray(data.links)) {
setLinks(data.links)
}
setIsConnected(true)
@@ -124,5 +205,8 @@ export function useKlalbSSE(): UseKlalbSSEResult {
error,
reconnectAll,
refreshStatus,
addLink,
removeLink,
executeLinkAction,
}
}
+4 -1
View File
@@ -29,7 +29,10 @@ export function formatPPS(pps?: number): string {
* @param nanoDelay 纳秒 (ns)
*/
export function formatNanoDelay(nanoDelay?: number): string {
if (nanoDelay === undefined || nanoDelay === null || isNaN(nanoDelay) || nanoDelay <= 0) {
if (nanoDelay === undefined || nanoDelay === null || isNaN(nanoDelay)) {
return 'NaN'
}
if (nanoDelay <= 0) {
return '0 ns'
}
if (nanoDelay >= 1_000_000_000) {
+584
View File
@@ -0,0 +1,584 @@
import { ConnectionActionMenu } from '@/components/connections/connection-action-menu'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
formatBytes,
formatNanoDelay,
formatPPS,
formatSpeed,
} from '@/lib/format'
import type { RemoteLinkItem } from '@/types/api'
import {
ArrowDown,
ArrowUp,
Check,
ChevronsLeftRightEllipsis,
Copy,
LayoutGrid,
List,
Network,
Plus,
Search,
Plug,
Unplug
} from "lucide-react"
import { useMemo, useState } from 'react'
interface ConnectionsPageProps {
links: RemoteLinkItem[]
isConnected: boolean
onAddLink: (address: string) => Promise<{ success: boolean; message?: string }>
onRemoveLink: (address: string) => Promise<{ success: boolean; message?: string }>
onLinkAction: (
address: string,
action: 'reconnect' | 'disconnect' | 'remove'
) => Promise<{ success: boolean; message?: string }>
}
export function ConnectionsPage({
links,
onAddLink,
onRemoveLink,
onLinkAction,
}: ConnectionsPageProps) {
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid')
const [searchQuery, setSearchQuery] = useState('')
const [statusFilter, setStatusFilter] = useState<'all' | 'up' | 'down'>('all')
// Add Dialog State
const [isAddOpen, setIsAddOpen] = useState(false)
const [newAddress, setNewAddress] = useState('')
const [addError, setAddError] = useState<string | null>(null)
const [isSubmitting, setIsSubmitting] = useState(false)
// Copy Feedback state
const [copiedAddress, setCopiedAddress] = useState<string | null>(null)
const copyText = (text: string) => {
navigator.clipboard.writeText(text)
setCopiedAddress(text)
setTimeout(() => setCopiedAddress(null), 2000)
}
// Summary calculations
const stats = useMemo(() => {
const total = links.length
const up = links.filter((l) => l.stateCode === 2 || l.state.toLowerCase().includes('up') || l.state === 'ESTABLISHED').length
const down = total - up
const totalUpSpeed = links.reduce((acc, l) => acc + (l.upSpeed || 0), 0)
const totalDownSpeed = links.reduce((acc, l) => acc + (l.downSpeed || 0), 0)
return { total, up, down, totalUpSpeed, totalDownSpeed }
}, [links])
// Filtered links
const filteredLinks = useMemo(() => {
return links.filter((link) => {
const matchSearch =
searchQuery === '' ||
link.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
(link.socketAddress &&
link.socketAddress.toLowerCase().includes(searchQuery.toLowerCase())) ||
(link.vaddr &&
link.vaddr.toLowerCase().includes(searchQuery.toLowerCase()))
const isLinkUp =
link.stateCode === 2 ||
link.state.toLowerCase().includes('up') ||
link.state === 'ESTABLISHED'
if (statusFilter === 'up') return matchSearch && isLinkUp
if (statusFilter === 'down') return matchSearch && !isLinkUp
return matchSearch
})
}, [links, searchQuery, statusFilter])
const handleAddSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!newAddress.trim()) {
setAddError('请输入远程连接 Socket 地址')
return
}
setIsSubmitting(true)
setAddError(null)
const res = await onAddLink(newAddress.trim())
setIsSubmitting(false)
if (res.success) {
setNewAddress('')
setIsAddOpen(false)
} else {
setAddError(res.message || '添加连接失败')
}
}
const getProtocolBadge = (address?: string) => {
if (!address) return <Badge variant="outline">TCP</Badge>
const lower = address.toLowerCase()
if (lower.startsWith('udp://')) {
return <Badge variant="secondary" className="bg-purple-500/10 text-purple-600 dark:text-purple-400 font-mono text-[10px]">UDP</Badge>
}
if (lower.startsWith('kltp://')) {
return <Badge variant="secondary" className="bg-amber-500/10 text-amber-600 dark:text-amber-400 font-mono text-[10px]">KLTP</Badge>
}
return <Badge variant="secondary" className="bg-blue-500/10 text-blue-600 dark:text-blue-400 font-mono text-[10px]">TCP</Badge>
}
return (
<div className="flex flex-1 flex-col gap-6 p-6">
{/* 1. Top Summary Banner */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card className="shadow-2xs">
<CardContent className="flex items-center justify-between p-4">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground"></span>
<span className="font-mono text-2xl font-bold">
{stats.total}
</span>
</div>
<div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
<Network className="size-5" />
</div>
</CardContent>
</Card>
<Card className="shadow-2xs">
<CardContent className="flex items-center justify-between p-4">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground"></span>
<span className="font-mono text-2xl font-bold text-emerald-600 dark:text-emerald-400">
{stats.up}
</span>
</div>
<div className="flex size-10 items-center justify-center rounded-xl bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
<Plug className="size-5" />
</div>
</CardContent>
</Card>
<Card className="shadow-2xs">
<CardContent className="flex items-center justify-between p-4">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground">/</span>
<span className="font-mono text-2xl font-bold text-rose-500">
{stats.down}
</span>
</div>
<div className="flex size-10 items-center justify-center rounded-xl bg-rose-500/10 text-rose-500">
<Unplug className="size-5" />
</div>
</CardContent>
</Card>
<Card className="shadow-2xs">
<CardContent className="flex items-center justify-between p-4">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground">
</span>
<div className="flex items-center gap-2 font-mono text-sm font-bold">
<span className="text-rose-500">
{formatSpeed(stats.totalUpSpeed, 1)}
</span>
<span className="text-emerald-500">
{formatSpeed(stats.totalDownSpeed, 1)}
</span>
</div>
</div>
<div className="flex size-10 items-center justify-center rounded-xl bg-blue-500/10 text-blue-500">
<ArrowUp className="size-5" />
</div>
</CardContent>
</Card>
</div>
{/* 2. Control Toolbar */}
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="flex flex-1 flex-wrap items-center gap-2">
{/* Search bar */}
<div className="relative w-full max-w-xs">
<Search className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="搜索 Socket / SID ..."
className="pl-8"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
{/* Status filter toggle */}
<div className="flex items-center rounded-lg border bg-background p-0.5 text-xs shadow-2xs">
<button
onClick={() => setStatusFilter("all")}
className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
statusFilter === "all"
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:text-foreground"
}`}
>
({stats.total})
</button>
<button
onClick={() => setStatusFilter("up")}
className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
statusFilter === "up"
? "bg-emerald-600 text-white"
: "text-muted-foreground hover:text-foreground"
}`}
>
线 ({stats.up})
</button>
<button
onClick={() => setStatusFilter("down")}
className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
statusFilter === "down"
? "bg-rose-600 text-white"
: "text-muted-foreground hover:text-foreground"
}`}
>
线 ({stats.down})
</button>
</div>
</div>
{/* Action buttons & View mode switch */}
<div className="flex items-center gap-2">
<div className="flex items-center rounded-lg border bg-background p-0.5 shadow-2xs">
<Button
variant={viewMode === "grid" ? "secondary" : "ghost"}
size="icon-xs"
onClick={() => setViewMode("grid")}
title="卡片网格视图"
>
<LayoutGrid className="size-3.5" />
</Button>
<Button
variant={viewMode === "table" ? "secondary" : "ghost"}
size="icon-xs"
onClick={() => setViewMode("table")}
title="表格视图"
>
<List className="size-3.5" />
</Button>
</div>
{/* Add Connection Dialog */}
<Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
<DialogTrigger
render={
<Button size="sm">
<Plus data-icon="inline-start" />
</Button>
}
/>
<DialogContent className="sm:max-w-md">
<form onSubmit={handleAddSubmit}>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
Socket
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4 py-4">
<div className="flex flex-col gap-2">
<label className="text-xs font-medium">
Socket URI
</label>
<Input
placeholder="tcp://... 或 udp://... 或 kltp://..."
value={newAddress}
onChange={(e) => setNewAddress(e.target.value)}
autoFocus
/>
<span className="text-[11px] text-muted-foreground">
<code>tcp://ip:port</code>、
<code>udp://ip:port</code>、<code>kltp://ip:port</code>
</span>
</div>
{addError && (
<div className="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">
{addError}
</div>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setIsAddOpen(false)}
>
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "添加中..." : "确认添加"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</div>
</div>
{/* 3. Main Content: Grid or Table View */}
{filteredLinks.length === 0 ? (
<Card className="flex flex-col items-center justify-center p-12 text-center shadow-2xs">
<div className="mb-3 flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
<Network className="size-6" />
</div>
<CardTitle className="text-base font-semibold">
</CardTitle>
<p className="mt-1 max-w-sm text-xs text-muted-foreground">
</p>
</Card>
) : viewMode === "grid" ? (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
{filteredLinks.map((link) => {
const isUp =
link.stateCode === 2 ||
link.state.toLowerCase().includes("up") ||
link.state === "ESTABLISHED"
const isUnstable =
link.stateCode === 1 ||
link.state.toLowerCase().includes("unstable")
return (
<Card
key={link.name}
className="flex flex-col justify-between shadow-2xs transition-colors hover:border-primary/40"
>
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<span
className={`size-2.5 shrink-0 rounded-full ${
isUp
? "animate-pulse bg-emerald-500"
: isUnstable
? "bg-amber-500"
: "bg-rose-500"
}`}
/>
<div className="flex min-w-0 flex-col gap-0.5">
<div className="flex items-center gap-1.5">
{getProtocolBadge(link.socketAddress || link.name)}
<span
className="truncate font-mono text-sm font-semibold text-foreground"
title={link.socketAddress || link.name}
>
{link.socketAddress || link.name}
</span>
</div>
</div>
</div>
{/* Actions dropdown component */}
<ConnectionActionMenu
link={link}
onLinkAction={onLinkAction}
onRemoveLink={onRemoveLink}
onCopyText={copyText}
/>
</div>
</CardHeader>
<CardContent className="flex flex-col gap-3.5 text-xs">
{/* Remote Virtual IPv6 Address */}
<div className="flex items-center justify-between gap-1.5 rounded-lg border bg-background/60 px-2.5 py-1.5">
<div className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
<ChevronsLeftRightEllipsis className="size-3.5 shrink-0" />
<span className="truncate"> SID:</span>
</div>
{link.vaddr ? (
<div className="flex items-center gap-1">
<span
className="max-w-[170px] truncate font-mono font-medium text-foreground"
title={link.vaddr}
>
{link.vaddr}
</span>
<Button
variant="ghost"
size="icon-xs"
className="size-4"
onClick={() => copyText(link.vaddr!)}
>
{copiedAddress === link.vaddr ? (
<Check className="size-3 text-emerald-500" />
) : (
<Copy className="size-3" />
)}
</Button>
</div>
) : (
<span className="text-muted-foreground italic">
</span>
)}
</div>
{/* Realtime Throughput & PPS */}
<div className="grid grid-cols-2 gap-2">
<div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2">
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
<span className="flex items-center gap-1 text-rose-500">
<ArrowUp className="size-3" />
</span>
<span>{formatPPS(link.upPPS)}</span>
</div>
<span className="font-mono text-sm font-bold text-foreground">
{formatSpeed(link.upSpeed)}
</span>
</div>
<div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2">
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
<span className="flex items-center gap-1 text-emerald-500">
<ArrowDown className="size-3" />
</span>
<span>{formatPPS(link.downPPS)}</span>
</div>
<span className="font-mono text-sm font-bold text-foreground">
{formatSpeed(link.downSpeed)}
</span>
</div>
</div>
{/* Delay & Jitter */}
<div className="flex flex-col gap-1 rounded-lg border bg-muted/30 p-2 text-[11px] text-muted-foreground">
<div className="flex items-center justify-between">
<span> (/):</span>
<span className="font-mono font-semibold text-foreground">
{isUp
? `${formatNanoDelay(link.upDelay)} / ${formatNanoDelay(link.downDelay)}`
: "NaN / NaN"}
</span>
</div>
<div className="flex items-center justify-between">
<span> (Jitter):</span>
<span className="font-mono text-foreground">
{isUp ? formatNanoDelay(link.upJitter) : "NaN"}
</span>
</div>
<div className="flex items-center justify-between">
<span> (/):</span>
<span className="font-mono text-foreground">
{formatBytes(link.upTraffic, 1)} /{" "}
{formatBytes(link.downTraffic, 1)}
</span>
</div>
</div>
</CardContent>
</Card>
)
})}
</div>
) : (
/* Table View */
<Card className="overflow-hidden shadow-2xs">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12 text-center"></TableHead>
<TableHead>Socket </TableHead>
<TableHead> SID (IPv6)</TableHead>
<TableHead className="text-right"> ()</TableHead>
<TableHead className="text-right"> ()</TableHead>
<TableHead className="text-right"></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead className="w-24 text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredLinks.map((link) => {
const isUp =
link.stateCode === 2 ||
link.state.toLowerCase().includes("up") ||
link.state === "ESTABLISHED"
return (
<TableRow key={link.name}>
<TableCell className="text-center">
<span
className={`inline-block size-2 rounded-full ${
isUp ? "bg-emerald-500" : "bg-rose-500"
}`}
title={link.state}
/>
</TableCell>
<TableCell>
<div className="flex items-center gap-1.5 font-mono text-xs font-semibold">
{getProtocolBadge(link.socketAddress || link.name)}
<span>{link.socketAddress || link.name}</span>
</div>
</TableCell>
<TableCell>
<span className="font-mono text-xs text-muted-foreground">
{link.vaddr || "--"}
</span>
</TableCell>
<TableCell className="text-right font-mono text-xs">
<span className="font-semibold text-rose-500">
{formatSpeed(link.upSpeed)}
</span>
<span className="ml-1 text-[10px] text-muted-foreground">
({formatPPS(link.upPPS)})
</span>
</TableCell>
<TableCell className="text-right font-mono text-xs">
<span className="font-semibold text-emerald-500">
{formatSpeed(link.downSpeed)}
</span>
<span className="ml-1 text-[10px] text-muted-foreground">
({formatPPS(link.downPPS)})
</span>
</TableCell>
<TableCell className="text-right font-mono text-xs">
{isUp ? formatNanoDelay(link.upDelay) : "NaN"}
</TableCell>
<TableCell className="text-right font-mono text-xs text-muted-foreground">
{formatBytes(
(link.upTraffic || 0) + (link.downTraffic || 0)
)}
</TableCell>
<TableCell className="text-center">
<ConnectionActionMenu
link={link}
onLinkAction={onLinkAction}
onRemoveLink={onRemoveLink}
onCopyText={copyText}
/>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
)}
</div>
)
}
@@ -34,13 +34,13 @@ import {
} from '@/lib/format'
import type { SystemStatus, RemoteLinkItem } from '@/types/api'
interface DashboardPageProps {
interface OverviewPageProps {
status: SystemStatus | null
links: RemoteLinkItem[]
isConnected: boolean
}
export function DashboardPage({ status, links, isConnected }: DashboardPageProps) {
export function OverviewPage({ status, links, isConnected }: OverviewPageProps) {
const [copied, setCopied] = useState(false)
const copyToClipboard = (text?: string) => {
@@ -145,14 +145,12 @@ export function DashboardPage({ status, links, isConnected }: DashboardPageProps
</div>
<div className="flex flex-col gap-0.5 rounded-xl border bg-background/60 px-3 py-1.5 shadow-2xs">
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Zap className="size-3.5" />
<span>线</span>
</div>
<span className="font-mono text-sm font-bold text-foreground">
{establishedLinks} <span className="text-xs font-normal text-muted-foreground">/ {totalLinks}</span>
</span>
<Zap className="size-3.5 text-muted-foreground" />
<span>线</span>
</div>
<span className="font-mono text-sm font-bold text-foreground">
{establishedLinks} <span className="text-xs font-normal text-muted-foreground">/ {totalLinks}</span>
</span>
</div>
</div>
</div>