Compare commits

..
3 Commits
Author SHA1 Message Date
SerinaNya 8c13af680a refactor(topology)!: rename node info revision
Replace the epoch/revision freshness tuple with nodeInfoRevision.

BREAKING CHANGE: topology API clients must use nodeInfoRevision;
nodeInfoFullRevision and nodeInfoFullRevisionEpoch are removed.
2026-08-31 01:13:34 +08:00
SerinaNya 0b705f9ba0 feat(topology): show extra routes in node details
Refresh selected node details when full metadata changes.
2026-08-28 23:13:49 +08:00
SerinaNya 89474b9e91 feat(dashboard)!: add routing table and split endpoint settings
- Add #/routing-table with one-second polling and route filters
- Separate auto-connect targets from local external endpoints
- Remove the obsolete interfaces navigation module

BREAKING CHANGE: #/interfaces is removed.
2026-08-27 23:19:39 +08:00
10 changed files with 530 additions and 184 deletions
+5 -2
View File
@@ -8,6 +8,7 @@ import { OverviewPage } from '@/pages/overview'
import { ConnectionsPage } from '@/pages/connections' import { ConnectionsPage } from '@/pages/connections'
import { SettingsPage } from '@/pages/settings' import { SettingsPage } from '@/pages/settings'
import { TopologyPage } from '@/pages/topology' import { TopologyPage } from '@/pages/topology'
import { RoutingTablePage } from '@/pages/routing-table'
import { useKlalbSSE } from '@/hooks/use-klalb-sse' import { useKlalbSSE } from '@/hooks/use-klalb-sse'
import { useHashRoute } from '@/hooks/use-hash-route' import { useHashRoute } from '@/hooks/use-hash-route'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -39,7 +40,6 @@ export function App() {
<AppSidebar <AppSidebar
currentTab={currentTab} currentTab={currentTab}
onSelectTab={navigate} onSelectTab={navigate}
onlineDevices={status?.onlineDevices}
linksCount={safeLinks.length} linksCount={safeLinks.length}
establishedLinksCount={establishedLinksCount} establishedLinksCount={establishedLinksCount}
isConnected={isConnected} isConnected={isConnected}
@@ -75,10 +75,13 @@ export function App() {
{currentTab === 'topology' && <TopologyPage />} {currentTab === 'topology' && <TopologyPage />}
{currentTab === 'routing-table' && <RoutingTablePage />}
{currentTab !== 'overview' && {currentTab !== 'overview' &&
currentTab !== 'connections' && currentTab !== 'connections' &&
currentTab !== 'settings' && currentTab !== 'settings' &&
currentTab !== 'topology' && ( currentTab !== 'topology' &&
currentTab !== 'routing-table' && (
<div className="flex flex-1 items-center justify-center p-8"> <div className="flex flex-1 items-center justify-center p-8">
<Card className="max-w-md text-center"> <Card className="max-w-md text-center">
<CardHeader> <CardHeader>
+2 -12
View File
@@ -3,7 +3,6 @@ import {
Network, Network,
GitFork, GitFork,
Share2, Share2,
Cpu,
Settings, Settings,
Activity, Activity,
Layers, Layers,
@@ -24,12 +23,11 @@ import {
} from '@/components/ui/sidebar' } from '@/components/ui/sidebar'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
export type NavTab = 'overview' | 'connections' | 'routes' | 'topology' | 'interfaces' | 'settings' export type NavTab = 'overview' | 'connections' | 'routing-table' | 'topology' | 'settings'
interface AppSidebarProps { interface AppSidebarProps {
currentTab: NavTab currentTab: NavTab
onSelectTab: (tab: NavTab) => void onSelectTab: (tab: NavTab) => void
onlineDevices?: number
linksCount?: number linksCount?: number
establishedLinksCount?: number establishedLinksCount?: number
isConnected?: boolean isConnected?: boolean
@@ -38,7 +36,6 @@ interface AppSidebarProps {
export function AppSidebar({ export function AppSidebar({
currentTab, currentTab,
onSelectTab, onSelectTab,
onlineDevices = 0,
linksCount = 0, linksCount = 0,
establishedLinksCount = 0, establishedLinksCount = 0,
isConnected = false, isConnected = false,
@@ -56,7 +53,7 @@ export function AppSidebar({
badge: linksCount > 0 ? `${establishedLinksCount}/${linksCount}` : undefined, badge: linksCount > 0 ? `${establishedLinksCount}/${linksCount}` : undefined,
}, },
{ {
id: 'routes' as NavTab, id: 'routing-table' as NavTab,
title: 'SRv6 路由表', title: 'SRv6 路由表',
icon: GitFork, icon: GitFork,
}, },
@@ -64,12 +61,6 @@ export function AppSidebar({
id: 'topology' as NavTab, id: 'topology' as NavTab,
title: '网络拓扑', title: '网络拓扑',
icon: Share2, icon: Share2,
badge: onlineDevices > 0 ? `${onlineDevices}` : undefined,
},
{
id: 'interfaces' as NavTab,
title: '网卡接口',
icon: Cpu,
}, },
{ {
id: 'settings' as NavTab, id: 'settings' as NavTab,
@@ -160,4 +151,3 @@ export function AppSidebar({
</Sidebar> </Sidebar>
) )
} }
+31 -1
View File
@@ -6,6 +6,7 @@ import {
Network, Network,
Clock3, Clock3,
FileText, FileText,
Route,
} from 'lucide-react' } from 'lucide-react'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -18,6 +19,7 @@ import {
SheetHeader, SheetHeader,
SheetTitle, SheetTitle,
} from '@/components/ui/sheet' } from '@/components/ui/sheet'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { formatNanoDelay } from '@/lib/format' import { formatNanoDelay } from '@/lib/format'
export interface SheetNodeInfo { export interface SheetNodeInfo {
@@ -45,6 +47,7 @@ interface NodeDetailSheetProps {
/** 设备描述(来自 /api/node-info 查询) */ /** 设备描述(来自 /api/node-info 查询) */
description?: string | null description?: string | null
descriptionLoading?: boolean descriptionLoading?: boolean
extraRoutes?: string[]
} }
export function NodeDetailSheet({ export function NodeDetailSheet({
@@ -56,6 +59,7 @@ export function NodeDetailSheet({
onCopy, onCopy,
description, description,
descriptionLoading, descriptionLoading,
extraRoutes = [],
}: NodeDetailSheetProps) { }: NodeDetailSheetProps) {
if (!node) return null if (!node) return null
@@ -91,7 +95,13 @@ export function NodeDetailSheet({
</div> </div>
</SheetHeader> </SheetHeader>
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"> <div className="flex flex-1 flex-col overflow-y-auto p-4">
<Tabs defaultValue="overview" className="min-h-0">
<TabsList className="w-full">
<TabsTrigger value="overview"></TabsTrigger>
<TabsTrigger value="routes"><Route className="size-3.5" /></TabsTrigger>
</TabsList>
<TabsContent value="overview" className="flex flex-col gap-4 pt-4">
{/* Device Description */} {/* Device Description */}
<div className="flex flex-col gap-1.5 rounded-lg border bg-muted/30 p-3"> <div className="flex flex-col gap-1.5 rounded-lg border bg-muted/30 p-3">
<span className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground"> <span className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
@@ -197,6 +207,26 @@ export function NodeDetailSheet({
<Gauge data-icon="inline-start" /> <Gauge data-icon="inline-start" />
Kperf Kperf
</Button> </Button>
</TabsContent>
<TabsContent value="routes" className="pt-4">
{descriptionLoading ? (
<div className="flex flex-col gap-1.5 py-8" aria-live="polite">
<Skeleton className="h-3.5 w-full" />
<Skeleton className="h-3.5 w-2/3" />
</div>
) : extraRoutes.length === 0 ? (
<p className="py-8 text-center text-xs text-muted-foreground"></p>
) : (
<ul className="flex flex-col gap-1.5" aria-label="额外路由列表">
{extraRoutes.map((route, index) => (
<li key={`${route}-${index}`}>
<code className="block select-text break-all rounded-md border bg-muted/30 px-2.5 py-2 font-mono text-xs text-foreground">{route}</code>
</li>
))}
</ul>
)}
</TabsContent>
</Tabs>
</div> </div>
</SheetContent> </SheetContent>
</Sheet> </Sheet>
+1 -2
View File
@@ -4,9 +4,8 @@ import type { NavTab } from '@/components/layout/app-sidebar'
const VALID_TABS: NavTab[] = [ const VALID_TABS: NavTab[] = [
'overview', 'overview',
'connections', 'connections',
'routes', 'routing-table',
'topology', 'topology',
'interfaces',
'settings', 'settings',
] ]
+47
View File
@@ -0,0 +1,47 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { RoutingTableItem } from '@/types/api'
const POLL_INTERVAL_MS = 1000
interface UseRoutingTableResult {
routingTable: RoutingTableItem[]
isLoading: boolean
error: string | null
refresh: () => void
}
export function useRoutingTable(): UseRoutingTableResult {
const [routingTable, setRoutingTable] = useState<RoutingTableItem[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const mountedRef = useRef(true)
const fetchRoutingTable = useCallback(async () => {
try {
const response = await fetch('/api/routing-table')
if (!response.ok) throw new Error(`路由接口异常 (${response.status})`)
const payload: unknown = await response.json()
if (!Array.isArray(payload)) throw new Error('路由接口返回格式异常')
if (!mountedRef.current) return
setRoutingTable(payload as RoutingTableItem[])
setError(null)
} catch (err: unknown) {
if (mountedRef.current) setError(err instanceof Error ? err.message : String(err))
} finally {
if (mountedRef.current) setIsLoading(false)
}
}, [])
useEffect(() => {
mountedRef.current = true
void fetchRoutingTable()
const timer = window.setInterval(() => void fetchRoutingTable(), POLL_INTERVAL_MS)
return () => {
mountedRef.current = false
window.clearInterval(timer)
}
}, [fetchRoutingTable])
const refresh = useCallback(() => void fetchRoutingTable(), [fetchRoutingTable])
return { routingTable, isLoading, error, refresh }
}
+12 -2
View File
@@ -14,6 +14,7 @@ export interface LayoutNode extends SimulationNodeDatum {
compressedAddress?: string compressedAddress?: string
isSelf: boolean isSelf: boolean
deviceName?: string deviceName?: string
nodeInfoRevision?: number
x: number x: number
y: number y: number
} }
@@ -117,7 +118,10 @@ export function useTopology(): UseTopologyResult {
const topoNodes: TopologyNode[] = Array.isArray(payload.nodes) const topoNodes: TopologyNode[] = Array.isArray(payload.nodes)
? payload.nodes.filter( ? payload.nodes.filter(
(n) => n && typeof n.id === 'string' && n.id !== '' (n) => n && typeof n.id === 'string' && n.id !== ''
) ).map((n) => ({
...n,
nodeInfoRevision: n.nodeInfoRevision ?? 0,
}))
: [] : []
const topoEdgesRaw: TopologyEdge[] = Array.isArray(payload.edges) const topoEdgesRaw: TopologyEdge[] = Array.isArray(payload.edges)
? payload.edges ? payload.edges
@@ -170,7 +174,13 @@ export function useTopology(): UseTopologyResult {
prev.length === topoNodes.length prev.length === topoNodes.length
? prev.map((n) => { ? prev.map((n) => {
const fresh = topoNodes.find((t) => t.id === n.id) const fresh = topoNodes.find((t) => t.id === n.id)
return fresh ? { ...n, deviceName: fresh.deviceName } : n return fresh
? {
...n,
deviceName: fresh.deviceName,
nodeInfoRevision: fresh.nodeInfoRevision,
}
: n
}) })
: prev : prev
) )
+285
View File
@@ -0,0 +1,285 @@
import { useMemo, useState } from "react"
import { Check, Copy, GitFork, RefreshCw, Search } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import { useRoutingTable } from "@/hooks/use-routing-table"
import type { RoutingTableItem } from "@/types/api"
type ProtocolFilter = "all" | "direct" | "klalb"
function protocolName(protocol: RoutingTableItem["protocol"]): string {
const value = String(protocol)
const normalized = value.toLowerCase()
if (normalized === "direct" || value === "0") return "Direct"
if (
normalized.includes("klalb") ||
normalized.includes("srv6") ||
value === "1"
)
return "KLALB SRv6"
return value
}
function protocolBadge(protocol: RoutingTableItem["protocol"]) {
const name = protocolName(protocol)
if (name === "Direct")
return (
<Badge
variant="secondary"
className="bg-blue-500/10 text-blue-600 dark:text-blue-400"
>
{name}
</Badge>
)
if (name === "KLALB SRv6")
return (
<Badge
variant="secondary"
className="bg-purple-500/10 text-purple-600 dark:text-purple-400"
>
{name}
</Badge>
)
return <Badge variant="outline">{name}</Badge>
}
export function RoutingTablePage() {
const { routingTable, isLoading, error, refresh } = useRoutingTable()
const [searchQuery, setSearchQuery] = useState("")
const [protocolFilter, setProtocolFilter] = useState<ProtocolFilter>("all")
const [copiedHop, setCopiedHop] = useState<string | null>(null)
const counts = useMemo(
() => ({
total: routingTable.length,
direct: routingTable.filter(
(route) => protocolName(route.protocol) === "Direct"
).length,
klalb: routingTable.filter(
(route) => protocolName(route.protocol) === "KLALB SRv6"
).length,
}),
[routingTable]
)
const filteredRoutingTable = useMemo(() => {
const query = searchQuery.trim().toLowerCase()
return routingTable.filter((route) => {
const matchesSearch =
!query ||
[
route.destination,
route.nexthop,
route.interface,
protocolName(route.protocol),
].some((value) => String(value).toLowerCase().includes(query))
const name = protocolName(route.protocol)
const matchesProtocol =
protocolFilter === "all" ||
(protocolFilter === "direct" && name === "Direct") ||
(protocolFilter === "klalb" && name === "KLALB SRv6")
return matchesSearch && matchesProtocol
})
}, [routingTable, searchQuery, protocolFilter])
const copyNextHop = async (nextHop: string) => {
try {
await navigator.clipboard.writeText(nextHop)
setCopiedHop(nextHop)
window.setTimeout(
() => setCopiedHop((current) => (current === nextHop ? null : current)),
1500
)
} catch {
setCopiedHop(null)
}
}
const filterOptions: { value: ProtocolFilter; label: string }[] = [
{ value: "all", label: "全部" },
{ value: "direct", label: "直连" },
{ value: "klalb", label: "KLALB SRv6" },
]
return (
<div className="flex flex-1 flex-col gap-5 p-6">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
<GitFork className="size-5" />
</div>
<div>
<h1 className="text-xl font-bold tracking-tight">SRv6 </h1>
<p className="text-xs text-muted-foreground">
IPv6
</p>
</div>
</div>
<div className="flex flex-wrap gap-2 sm:ml-13 lg:ml-0">
<Badge variant="outline"> {counts.total}</Badge>
<Badge
variant="secondary"
className="bg-blue-500/10 text-blue-600 dark:text-blue-400"
>
{counts.direct}
</Badge>
<Badge
variant="secondary"
className="bg-purple-500/10 text-purple-600 dark:text-purple-400"
>
KLALB SRv6 {counts.klalb}
</Badge>
</div>
</div>
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="relative w-full max-w-sm">
<Search className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="搜索目的地址、下一跳、接口或协议"
className="pl-8"
/>
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex items-center rounded-lg border bg-background p-0.5 shadow-2xs">
{filterOptions.map((option) => (
<Button
key={option.value}
variant={
protocolFilter === option.value ? "secondary" : "ghost"
}
size="sm"
onClick={() => setProtocolFilter(option.value)}
>
{option.label}
</Button>
))}
</div>
<Button
variant="outline"
size="sm"
onClick={refresh}
disabled={isLoading}
title="刷新路由表"
>
<RefreshCw
data-icon="inline-start"
className={isLoading ? "animate-spin" : ""}
/>
</Button>
</div>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription>
{error}
</AlertDescription>
</Alert>
)}
{isLoading && routingTable.length === 0 ? (
<div className="border-y py-12 text-center text-sm text-muted-foreground">
...
</div>
) : filteredRoutingTable.length === 0 ? (
<div className="border-y py-12 text-center">
<p className="text-sm font-medium"></p>
<p className="mt-1 text-xs text-muted-foreground">
</p>
</div>
) : (
<div className="overflow-hidden rounded-lg border bg-card shadow-2xs">
<Table>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredRoutingTable.map((route, index) => (
<TableRow
key={`${route.destination}-${route.nexthop}-${route.interface}-${index}`}
>
<TableCell className="font-mono text-xs font-medium">
{route.destination}
</TableCell>
<TableCell>{protocolBadge(route.protocol)}</TableCell>
<TableCell className="text-right font-mono text-xs">
{route.preference}
</TableCell>
<TableCell className="text-right font-mono text-xs">
{(route.cost / 1_000_000).toFixed(2)} ms
</TableCell>
<TableCell>
<Badge variant="outline" className="font-mono text-[10px]">
{route.flag}
</Badge>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<span className="font-mono text-xs">
{route.nexthop || "--"}
</span>
{route.nexthop && (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon-xs"
title="复制下一跳"
onClick={() => void copyNextHop(route.nexthop)}
/>
}
>
<>
{copiedHop === route.nexthop ? (
<Check
data-icon="inline-start"
className="text-emerald-500"
/>
) : (
<Copy data-icon="inline-start" />
)}
</>
</TooltipTrigger>
<TooltipContent></TooltipContent>
</Tooltip>
)}
</div>
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{route.interface || "--"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
)
}
+95 -125
View File
@@ -88,55 +88,6 @@ function toAddrString(item: unknown): string {
return String(item) return String(item)
} }
interface ConnectionItem {
id: string
address: string
autoConnect: boolean
}
function parseConnectionsFromConfig(config: KLALBControllerConfig | null): ConnectionItem[] {
if (!config) return []
const lineTable = (
Array.isArray(config.externalEndpoints)
? config.externalEndpoints
: Array.isArray(config.openConnections)
? config.openConnections
: Array.isArray(config.LineTable)
? config.LineTable
: []
).map(toAddrString)
const connectTable = (
Array.isArray(config.autoConnections)
? config.autoConnections
: Array.isArray(config.ConnectLineTable)
? config.ConnectLineTable
: []
).map(toAddrString)
const items: ConnectionItem[] = []
// openConnections (autoConnect: false)
lineTable.forEach((addr, index) => {
if (addr && addr.trim() !== '') {
items.push({
id: `open-${index}-${addr}`,
address: addr,
autoConnect: false,
})
}
})
// autoConnections (autoConnect: true)
connectTable.forEach((addr, index) => {
if (addr && addr.trim() !== '') {
items.push({
id: `auto-${index}-${addr}`,
address: addr,
autoConnect: true,
})
}
})
return items
}
function SettingsForm({ function SettingsForm({
initialConfig, initialConfig,
onSave, onSave,
@@ -163,8 +114,26 @@ function SettingsForm({
initialConfig.TUNName.trim() !== '') initialConfig.TUNName.trim() !== '')
) )
const [connections, setConnections] = useState<ConnectionItem[]>(() => const [autoConnections, setAutoConnections] = useState<string[]>(() =>
parseConnectionsFromConfig(initialConfig) (
Array.isArray(initialConfig.autoConnections)
? initialConfig.autoConnections
: Array.isArray(initialConfig.ConnectLineTable)
? initialConfig.ConnectLineTable
: []
).map(toAddrString)
)
const [externalEndpoints, setExternalEndpoints] = useState<string[]>(() =>
(
Array.isArray(initialConfig.externalEndpoints)
? initialConfig.externalEndpoints
: Array.isArray(initialConfig.openConnections)
? initialConfig.openConnections
: Array.isArray(initialConfig.LineTable)
? initialConfig.LineTable
: []
).map(toAddrString)
) )
const [ntpServers, setNtpServers] = useState<string[]>(() => const [ntpServers, setNtpServers] = useState<string[]>(() =>
@@ -196,14 +165,12 @@ function SettingsForm({
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault() e.preventDefault()
const cleanConnections = connections.filter((c) => c.address.trim() !== '') const updatedAutoConnections = autoConnections
// 互斥分离:选中自动连接的进 autoConnections,未选中的进 externalEndpoints .filter((address) => address.trim() !== '')
const updatedExternalEndpoints = cleanConnections .map((address) => address.trim())
.filter((c) => !c.autoConnect) const updatedExternalEndpoints = externalEndpoints
.map((c) => c.address.trim()) .filter((address) => address.trim() !== '')
const updatedAutoConnections = cleanConnections .map((address) => address.trim())
.filter((c) => c.autoConnect)
.map((c) => c.address.trim())
// 保存时同时携带新键名与历史别名,兼容新旧后端 // 保存时同时携带新键名与历史别名,兼容新旧后端
const denyQuery = const denyQuery =
@@ -248,34 +215,6 @@ function SettingsForm({
await onSave(updatedConfig as KLALBControllerConfig) await onSave(updatedConfig as KLALBControllerConfig)
} }
// --- Dynamic Connection Items Handlers ---
const addConnection = () => {
setConnections((prev) => [
...prev,
{
id: `conn-${Date.now()}`,
address: '',
autoConnect: true,
},
])
}
const updateConnection = (
index: number,
field: 'address' | 'autoConnect',
value: string | boolean
) => {
setConnections((prev) => {
const next = [...prev]
next[index] = { ...next[index], [field]: value }
return next
})
}
const removeConnection = (index: number) => {
setConnections((prev) => prev.filter((_, i) => i !== index))
}
// --- Generic Dynamic List Handlers --- // --- Generic Dynamic List Handlers ---
const addListItem = (setter: React.Dispatch<React.SetStateAction<string[]>>) => { const addListItem = (setter: React.Dispatch<React.SetStateAction<string[]>>) => {
setter((prev) => [...prev, '']) setter((prev) => [...prev, ''])
@@ -688,80 +627,111 @@ function SettingsForm({
{/* Tab 3: 连接与同步列表 (Lists) */} {/* Tab 3: 连接与同步列表 (Lists) */}
<TabsContent value="lists" className="m-0 flex flex-col gap-6"> <TabsContent value="lists" className="m-0 flex flex-col gap-6">
{/* 1. Connections List (with Auto Connect toggle) */} {/* 1. Automatic Connection Endpoints */}
<Card className="shadow-2xs"> <Card className="shadow-2xs">
<CardHeader className="flex flex-row items-center justify-between pb-3"> <CardHeader className="flex flex-row items-center justify-between pb-3">
<div> <div>
<CardTitle className="text-base"></CardTitle> <CardTitle className="text-base"></CardTitle>
<CardDescription> <CardDescription></CardDescription>
Socket
</CardDescription>
</div> </div>
<Button <Button
type="button" type="button"
size="sm" size="sm"
variant="outline" variant="outline"
onClick={addConnection} onClick={() => addListItem(setAutoConnections)}
> >
<Plus data-icon="inline-start" /> <Plus data-icon="inline-start" />
</Button> </Button>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<FieldGroup className="gap-3"> <FieldGroup className="gap-2">
{connections.length === 0 ? ( {autoConnections.length === 0 ? (
<div className="rounded-lg border border-dashed p-6 text-center text-xs text-muted-foreground"> <div className="rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground">
</div> </div>
) : ( ) : (
connections.map((item, idx) => ( autoConnections.map((endpoint, idx) => (
<div <div key={idx} className="flex items-center gap-2">
key={item.id}
className="flex flex-col gap-3 rounded-lg border bg-card p-3 shadow-2xs sm:flex-row sm:items-center sm:justify-between"
>
<div className="flex flex-1 items-center gap-2">
<Input <Input
className="flex-1 font-mono text-xs" className="flex-1 font-mono text-xs"
placeholder="tcp://kne01.yoyo250.fun:4565 或 udp://..." placeholder="tcp://kne01.yoyo250.fun:4565 或 udp://..."
value={item.address} value={endpoint}
onChange={(e) => onChange={(e) =>
updateConnection(idx, 'address', e.target.value) updateListItem(idx, e.target.value, setAutoConnections)
} }
/> />
</div>
<div className="flex shrink-0 items-center justify-end gap-4">
<Field orientation="horizontal" className="flex items-center gap-2">
<FieldLabel htmlFor={`auto-conn-${item.id}`} className="cursor-pointer text-xs text-muted-foreground">
</FieldLabel>
<Switch
id={`auto-conn-${item.id}`}
checked={item.autoConnect}
onCheckedChange={(checked) =>
updateConnection(idx, 'autoConnect', checked)
}
/>
</Field>
<Button <Button
type="button" type="button"
variant="ghost" variant="ghost"
size="icon-xs" size="icon-xs"
className="text-destructive hover:text-destructive" className="text-destructive hover:text-destructive"
onClick={() => removeConnection(idx)} onClick={() => removeListItem(idx, setAutoConnections)}
title="删除该连接" title="删除该端点"
> >
<Trash2 className="size-3.5" /> <Trash2 className="size-3.5" />
</Button> </Button>
</div> </div>
</div>
)) ))
)} )}
</FieldGroup> </FieldGroup>
</CardContent> </CardContent>
</Card> </Card>
{/* 2. NTP Server List */} {/* 2. Published External Endpoints */}
<Card className="shadow-2xs">
<CardHeader className="flex flex-row items-center justify-between pb-3">
<div>
<CardTitle className="text-base"></CardTitle>
<CardDescription>
访
</CardDescription>
</div>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => addListItem(setExternalEndpoints)}
>
<Plus data-icon="inline-start" />
</Button>
</CardHeader>
<CardContent>
<FieldGroup className="gap-2">
{externalEndpoints.length === 0 ? (
<div className="rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground">
</div>
) : (
externalEndpoints.map((endpoint, idx) => (
<div key={idx} className="flex items-center gap-2">
<Input
className="flex-1 font-mono text-xs"
placeholder="tcp://本机公网地址:4565 或 udp://..."
value={endpoint}
onChange={(e) =>
updateListItem(idx, e.target.value, setExternalEndpoints)
}
/>
<Button
type="button"
variant="ghost"
size="icon-xs"
className="text-destructive hover:text-destructive"
onClick={() => removeListItem(idx, setExternalEndpoints)}
title="删除该端点"
>
<Trash2 className="size-3.5" />
</Button>
</div>
))
)}
</FieldGroup>
</CardContent>
</Card>
{/* 3. NTP Server List */}
<Card className="shadow-2xs"> <Card className="shadow-2xs">
<CardHeader className="flex flex-row items-center justify-between pb-3"> <CardHeader className="flex flex-row items-center justify-between pb-3">
<div> <div>
+35 -19
View File
@@ -1,4 +1,4 @@
import { useState, useMemo, useCallback, useRef } from 'react' import { useState, useMemo, useCallback, useRef, useEffect } from 'react'
import { ReactFlowProvider } from '@xyflow/react' import { ReactFlowProvider } from '@xyflow/react'
import { import {
Share2, Share2,
@@ -28,6 +28,23 @@ export function TopologyPage() {
const [nodeInfo, setNodeInfo] = useState<NodeInfoDetail | null>(null) const [nodeInfo, setNodeInfo] = useState<NodeInfoDetail | null>(null)
const [nodeInfoLoading, setNodeInfoLoading] = useState(false) const [nodeInfoLoading, setNodeInfoLoading] = useState(false)
const nodeInfoSeqRef = useRef(0) const nodeInfoSeqRef = useRef(0)
const nodeInfoRevisionRef = useRef<number | null>(null)
const nodeInfoRevisionInitializedRef = useRef(false)
const fetchNodeInfo = useCallback((nodeId: string) => {
setNodeInfo(null)
setNodeInfoLoading(true)
const seq = ++nodeInfoSeqRef.current
fetch(`/api/node-info?address=${encodeURIComponent(nodeId)}`)
.then((res) => (res.ok ? res.json() : null))
.then((data: NodeInfoDetail | null) => {
if (seq === nodeInfoSeqRef.current && data) setNodeInfo(data)
})
.catch(() => {})
.finally(() => {
if (seq === nodeInfoSeqRef.current) setNodeInfoLoading(false)
})
}, [])
const handleCopy = useCallback((text: string) => { const handleCopy = useCallback((text: string) => {
navigator.clipboard.writeText(text) navigator.clipboard.writeText(text)
@@ -39,30 +56,18 @@ export function TopologyPage() {
setSelectedNodeId(nodeId) setSelectedNodeId(nodeId)
if (nodeId) { if (nodeId) {
setSheetOpen(true) setSheetOpen(true)
setNodeInfo(null) const selected = nodes.find((node) => node.id === nodeId)
setNodeInfoLoading(true) nodeInfoRevisionRef.current = selected?.nodeInfoRevision ?? 0
const seq = ++nodeInfoSeqRef.current nodeInfoRevisionInitializedRef.current = true
fetch(`/api/node-info?address=${encodeURIComponent(nodeId)}`) fetchNodeInfo(nodeId)
.then((res) => (res.ok ? res.json() : null))
.then((data: NodeInfoDetail | null) => {
// 防止乱序:仅当仍是当前选中节点时才应用结果
if (seq === nodeInfoSeqRef.current && data) {
setNodeInfo(data)
}
})
.catch(() => {})
.finally(() => {
if (seq === nodeInfoSeqRef.current) {
setNodeInfoLoading(false)
}
})
} else { } else {
setSheetOpen(false) setSheetOpen(false)
setNodeInfo(null) setNodeInfo(null)
setNodeInfoLoading(false) setNodeInfoLoading(false)
nodeInfoSeqRef.current++ nodeInfoSeqRef.current++
nodeInfoRevisionInitializedRef.current = false
} }
}, []) }, [fetchNodeInfo, nodes])
const handleNodeDragEnd = useCallback( const handleNodeDragEnd = useCallback(
(_id: string, _x: number, _y: number) => { (_id: string, _x: number, _y: number) => {
@@ -78,6 +83,16 @@ export function TopologyPage() {
[nodes, selectedNodeId] [nodes, selectedNodeId]
) )
useEffect(() => {
if (!selectedNode) return
const nodeInfoRevision = selectedNode.nodeInfoRevision ?? 0
if (!nodeInfoRevisionInitializedRef.current) return
if (nodeInfoRevisionRef.current !== nodeInfoRevision) {
nodeInfoRevisionRef.current = nodeInfoRevision
fetchNodeInfo(selectedNode.id)
}
}, [selectedNode, fetchNodeInfo])
// 邻居信息(基于边集合推导) // 邻居信息(基于边集合推导)
const neighbors = useMemo(() => { const neighbors = useMemo(() => {
if (!selectedNode) return [] if (!selectedNode) return []
@@ -203,6 +218,7 @@ export function TopologyPage() {
onCopy={handleCopy} onCopy={handleCopy}
description={nodeInfo?.deviceDescription ?? null} description={nodeInfo?.deviceDescription ?? null}
descriptionLoading={nodeInfoLoading} descriptionLoading={nodeInfoLoading}
extraRoutes={nodeInfo?.extraRoutes}
/> />
</div> </div>
) )
+3 -7
View File
@@ -64,7 +64,7 @@ export interface SSEEventData {
links: RemoteLinkItem[] links: RemoteLinkItem[]
} }
export interface RouteItemData { export interface RoutingTableItem {
destination: string destination: string
protocol: number protocol: number
preference: number preference: number
@@ -80,6 +80,7 @@ export interface TopologyNode {
compressedAddress?: string compressedAddress?: string
isSelf: boolean isSelf: boolean
deviceName?: string deviceName?: string
nodeInfoRevision?: number
} }
export interface TopologyEdge { export interface TopologyEdge {
@@ -101,12 +102,7 @@ export interface NodeInfoDetail {
deviceDescription: string deviceDescription: string
reachable?: boolean reachable?: boolean
openLines?: string[] openLines?: string[]
} extraRoutes?: string[]
export interface NetworkInterfaceInfo {
name: string
displayName: string
addresses: string[]
} }
export interface KLALBControllerConfig { export interface KLALBControllerConfig {