feat(topology): add network topology page; tighten config save check
- Interactive SRv6 topology canvas (@xyflow/react + d3-force auto-layout), custom nodes/edges, detail sheet, search and relayout controls - Strict success-flag validation on /api/config save responses
This commit is contained in:
+5
-1
@@ -7,6 +7,7 @@ import { AppHeader } from '@/components/layout/app-header'
|
||||
import { OverviewPage } from '@/pages/overview'
|
||||
import { ConnectionsPage } from '@/pages/connections'
|
||||
import { SettingsPage } from '@/pages/settings'
|
||||
import { TopologyPage } from '@/pages/topology'
|
||||
import { useKlalbSSE } from '@/hooks/use-klalb-sse'
|
||||
import { useHashRoute } from '@/hooks/use-hash-route'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -72,9 +73,12 @@ export function App() {
|
||||
|
||||
{currentTab === 'settings' && <SettingsPage />}
|
||||
|
||||
{currentTab === 'topology' && <TopologyPage />}
|
||||
|
||||
{currentTab !== 'overview' &&
|
||||
currentTab !== 'connections' &&
|
||||
currentTab !== 'settings' && (
|
||||
currentTab !== 'settings' &&
|
||||
currentTab !== 'topology' && (
|
||||
<div className="flex flex-1 items-center justify-center p-8">
|
||||
<Card className="max-w-md text-center">
|
||||
<CardHeader>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { memo } from 'react'
|
||||
import { Handle, Position, type NodeProps, type Node } from '@xyflow/react'
|
||||
import { Server, Copy, Check } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface DeviceNodeData {
|
||||
address: string
|
||||
compressedAddress?: string
|
||||
isSelf: boolean
|
||||
deviceName?: string
|
||||
onCopy?: (text: string) => void
|
||||
copiedId?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type DeviceNodeType = Node<DeviceNodeData, 'device'>
|
||||
|
||||
function DeviceNodeComponent({ data, selected }: NodeProps<Node<DeviceNodeData>>) {
|
||||
const { deviceName, compressedAddress, address, isSelf, onCopy, copiedId } = data
|
||||
const isCopied = copiedId === address
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative flex min-w-44 cursor-pointer flex-col gap-1 rounded-xl border bg-card px-3 py-2.5 shadow-sm transition-all',
|
||||
'hover:border-primary/50 hover:shadow-md',
|
||||
selected && 'border-primary ring-2 ring-primary/30',
|
||||
isSelf &&
|
||||
'border-primary/60 bg-linear-to-br from-primary/5 via-card to-card'
|
||||
)}
|
||||
>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
className="!h-2 !w-2 !border-none !bg-transparent"
|
||||
isConnectable={false}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-7 shrink-0 items-center justify-center rounded-lg',
|
||||
isSelf ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<Server className="size-4" />
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-col leading-tight">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="max-w-36 truncate text-xs font-semibold text-foreground">
|
||||
{deviceName || '未命名节点'}
|
||||
</span>
|
||||
{isSelf && (
|
||||
<span className="shrink-0 rounded-full bg-primary/15 px-1.5 py-px text-[9px] font-bold uppercase tracking-wide text-primary">
|
||||
本机
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onCopy?.(address)
|
||||
}}
|
||||
className="flex items-center gap-0.5 font-mono text-[10px] text-muted-foreground hover:text-foreground"
|
||||
title="点击复制完整地址"
|
||||
>
|
||||
<span className="max-w-32 truncate">{compressedAddress || address}</span>
|
||||
{isCopied ? (
|
||||
<Check className="size-2.5 shrink-0 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="size-2.5 shrink-0 opacity-40 group-hover:opacity-100" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isSelf && (
|
||||
<span className="absolute -top-1 -right-1 flex size-3">
|
||||
<span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-400 opacity-60" />
|
||||
<span className="relative inline-flex size-3 rounded-full border-2 border-card bg-emerald-500" />
|
||||
</span>
|
||||
)}
|
||||
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
className="!h-2 !w-2 !border-none !bg-transparent"
|
||||
isConnectable={false}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const DeviceNode = memo(DeviceNodeComponent)
|
||||
@@ -0,0 +1,94 @@
|
||||
import { memo } from 'react'
|
||||
import {
|
||||
BaseEdge,
|
||||
EdgeLabelRenderer,
|
||||
getSmoothStepPath,
|
||||
useReactFlow,
|
||||
type EdgeProps,
|
||||
type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { formatNanoDelay } from '@/lib/format'
|
||||
|
||||
export interface LinkEdgeData {
|
||||
delay: number
|
||||
cost: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type LinkEdgeType = Edge<LinkEdgeData, 'link'>
|
||||
|
||||
function delayColor(delayNs: number): { stroke: string; badge: string } {
|
||||
const ms = delayNs / 1_000_000
|
||||
if (delayNs <= 0 || !Number.isFinite(delayNs)) {
|
||||
return { stroke: 'hsl(var(--muted-foreground))', badge: 'bg-muted text-muted-foreground' }
|
||||
}
|
||||
if (ms < 1) {
|
||||
return { stroke: '#10b981', badge: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400' }
|
||||
}
|
||||
if (ms < 20) {
|
||||
return { stroke: '#f59e0b', badge: 'bg-amber-500/15 text-amber-600 dark:text-amber-400' }
|
||||
}
|
||||
return { stroke: '#f43f5e', badge: 'bg-rose-500/15 text-rose-600 dark:text-rose-400' }
|
||||
}
|
||||
|
||||
function LinkEdgeComponent({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
sourcePosition,
|
||||
targetPosition,
|
||||
data,
|
||||
selected,
|
||||
}: EdgeProps<LinkEdgeType>) {
|
||||
const { setEdges } = useReactFlow()
|
||||
const [edgePath, labelX, labelY] = getSmoothStepPath({
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
borderRadius: 16,
|
||||
})
|
||||
|
||||
const delay = data?.delay ?? 0
|
||||
const { stroke, badge } = delayColor(delay)
|
||||
const showLabel = delay > 0 && Number.isFinite(delay)
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
style={{
|
||||
strokeWidth: selected ? 2.5 : 1.75,
|
||||
stroke,
|
||||
opacity: selected ? 1 : 0.85,
|
||||
}}
|
||||
/>
|
||||
{showLabel && (
|
||||
<EdgeLabelRenderer>
|
||||
<div
|
||||
style={{
|
||||
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
|
||||
}}
|
||||
className="pointer-events-none absolute"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEdges((eds) => eds.filter((e) => e.id !== id))}
|
||||
className={`pointer-events-auto cursor-pointer rounded-md border border-border/60 px-1.5 py-px font-mono text-[10px] font-semibold tabular-nums shadow-2xs backdrop-blur-xs transition-opacity hover:opacity-70 ${badge}`}
|
||||
title="点击隐藏该链路"
|
||||
>
|
||||
{formatNanoDelay(delay)}
|
||||
</button>
|
||||
</div>
|
||||
</EdgeLabelRenderer>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const LinkEdge = memo(LinkEdgeComponent)
|
||||
@@ -0,0 +1,179 @@
|
||||
import {
|
||||
Server,
|
||||
Copy,
|
||||
Check,
|
||||
Gauge,
|
||||
Network,
|
||||
Clock3,
|
||||
} from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import { formatNanoDelay } from '@/lib/format'
|
||||
|
||||
export interface SheetNodeInfo {
|
||||
id: string
|
||||
address: string
|
||||
compressedAddress?: string
|
||||
isSelf: boolean
|
||||
deviceName?: string
|
||||
}
|
||||
|
||||
export interface SheetNeighborInfo {
|
||||
address: string
|
||||
deviceName?: string
|
||||
delay: number
|
||||
cost: number
|
||||
}
|
||||
|
||||
interface NodeDetailSheetProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
node: SheetNodeInfo | null
|
||||
neighbors: SheetNeighborInfo[]
|
||||
copiedId: string | null
|
||||
onCopy: (text: string) => void
|
||||
}
|
||||
|
||||
export function NodeDetailSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
node,
|
||||
neighbors,
|
||||
copiedId,
|
||||
onCopy,
|
||||
}: NodeDetailSheetProps) {
|
||||
if (!node) return null
|
||||
|
||||
const isCopied = copiedId === node.address
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent side="right" className="w-full gap-0 sm:max-w-sm">
|
||||
<SheetHeader className="border-b">
|
||||
<div className="flex items-center gap-2.5 pt-4">
|
||||
<div
|
||||
className={`flex size-9 shrink-0 items-center justify-center rounded-lg ${
|
||||
node.isSelf
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
<Server className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<SheetTitle className="flex items-center gap-2 truncate">
|
||||
{node.deviceName || '未命名节点'}
|
||||
{node.isSelf && (
|
||||
<Badge variant="default" className="px-1.5 py-0 text-[10px]">
|
||||
本机
|
||||
</Badge>
|
||||
)}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="truncate font-mono text-xs">
|
||||
{node.compressedAddress || node.address}
|
||||
</SheetDescription>
|
||||
</div>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
|
||||
{/* Full Address */}
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
完整 SRv6 地址 (SID)
|
||||
</span>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<code className="break-all font-mono text-xs font-semibold text-foreground select-all">
|
||||
{node.address}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="shrink-0"
|
||||
onClick={() => onCopy(node.address)}
|
||||
title="复制完整地址"
|
||||
>
|
||||
{isCopied ? (
|
||||
<Check className="size-3.5 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2.5">
|
||||
<div className="flex items-center gap-1 text-[11px] text-muted-foreground">
|
||||
<Network className="size-3" />
|
||||
邻居数量
|
||||
</div>
|
||||
<span className="font-mono text-lg font-bold">{neighbors.length}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2.5">
|
||||
<div className="flex items-center gap-1 text-[11px] text-muted-foreground">
|
||||
<Gauge className="size-3" />
|
||||
平均时延
|
||||
</div>
|
||||
<span className="font-mono text-lg font-bold">
|
||||
{neighbors.length > 0
|
||||
? formatNanoDelay(
|
||||
neighbors.reduce((acc, n) => acc + n.delay, 0) / neighbors.length
|
||||
)
|
||||
: '--'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Neighbor list */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs font-semibold text-muted-foreground">邻居链路</span>
|
||||
{neighbors.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground">
|
||||
暂无可达邻居节点
|
||||
</div>
|
||||
) : (
|
||||
neighbors.map((nb) => (
|
||||
<div
|
||||
key={nb.address}
|
||||
className="flex items-center justify-between gap-2 rounded-lg border bg-card px-2.5 py-2"
|
||||
>
|
||||
<div className="flex min-w-0 flex-col leading-tight">
|
||||
<span className="truncate text-xs font-medium text-foreground">
|
||||
{nb.deviceName || '未命名节点'}
|
||||
</span>
|
||||
<span className="truncate font-mono text-[10px] text-muted-foreground">
|
||||
{nb.address}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 font-mono text-[11px] font-semibold">
|
||||
<Clock3 className="size-3" />
|
||||
{formatNanoDelay(nb.delay)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Reserved for Kperf speed test */}
|
||||
<Button variant="outline" size="sm" disabled title="测速功能即将接入">
|
||||
<Gauge data-icon="inline-start" />
|
||||
发起 Kperf 测速(即将支持)
|
||||
</Button>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import {
|
||||
ReactFlow,
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
Controls,
|
||||
MiniMap,
|
||||
type Node,
|
||||
type Edge,
|
||||
type NodeMouseHandler,
|
||||
type OnNodesChange,
|
||||
} from '@xyflow/react'
|
||||
import '@xyflow/react/dist/style.css'
|
||||
import { DeviceNode, type DeviceNodeData } from './device-node'
|
||||
import { LinkEdge, type LinkEdgeData } from './link-edge'
|
||||
import type { LayoutEdge, LayoutNode } from '@/hooks/use-topology'
|
||||
|
||||
const nodeTypes = { device: DeviceNode }
|
||||
const edgeTypes = { link: LinkEdge }
|
||||
|
||||
interface TopologyCanvasProps {
|
||||
nodes: LayoutNode[]
|
||||
edges: LayoutEdge[]
|
||||
searchQuery: string
|
||||
copiedId: string | null
|
||||
onCopy: (text: string) => void
|
||||
/** 用户拖拽结束后的位置回写(id -> 坐标),用于轮询刷新时保持位置 */
|
||||
onNodeDragEnd?: (id: string, x: number, y: number) => void
|
||||
onNodeSelect: (nodeId: string | null) => void
|
||||
}
|
||||
|
||||
function matchesSearch(node: LayoutNode, query: string): boolean {
|
||||
if (!query.trim()) return true
|
||||
const q = query.toLowerCase()
|
||||
return (
|
||||
(node.deviceName ?? '').toLowerCase().includes(q) ||
|
||||
node.address.toLowerCase().includes(q) ||
|
||||
(node.compressedAddress ?? '').toLowerCase().includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
export function TopologyCanvas({
|
||||
nodes: layoutNodes,
|
||||
edges: layoutEdges,
|
||||
searchQuery,
|
||||
copiedId,
|
||||
onCopy,
|
||||
onNodeDragEnd,
|
||||
onNodeSelect,
|
||||
}: TopologyCanvasProps) {
|
||||
// 完全受控渲染:由外部数据纯派生,无内部镜像状态
|
||||
const flowNodes = useMemo<Node<DeviceNodeData>[]>(
|
||||
() =>
|
||||
layoutNodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: 'device' as const,
|
||||
position: { x: n.x, y: n.y },
|
||||
data: {
|
||||
address: n.address,
|
||||
compressedAddress: n.compressedAddress,
|
||||
isSelf: n.isSelf,
|
||||
deviceName: n.deviceName,
|
||||
copiedId,
|
||||
onCopy,
|
||||
},
|
||||
style: matchesSearch(n, searchQuery) ? undefined : { opacity: 0.25 },
|
||||
})),
|
||||
[layoutNodes, searchQuery, copiedId, onCopy]
|
||||
)
|
||||
|
||||
const flowEdges = useMemo<Edge<LinkEdgeData>[]>(
|
||||
() =>
|
||||
layoutEdges.map((e) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
type: 'link' as const,
|
||||
data: { delay: e.delay, cost: e.cost },
|
||||
})),
|
||||
[layoutEdges]
|
||||
)
|
||||
|
||||
// 拖拽过程中仅更新受控坐标(position 变更);其余变更类型忽略
|
||||
const onNodesChange: OnNodesChange<Node<DeviceNodeData>> = useCallback(
|
||||
(changes) => {
|
||||
if (!onNodeDragEnd) return
|
||||
for (const change of changes) {
|
||||
if (
|
||||
change.type === 'position' &&
|
||||
change.position &&
|
||||
!change.dragging
|
||||
) {
|
||||
onNodeDragEnd(change.id, change.position.x, change.position.y)
|
||||
}
|
||||
}
|
||||
},
|
||||
[onNodeDragEnd]
|
||||
)
|
||||
|
||||
const handleNodeClick: NodeMouseHandler<Node<DeviceNodeData>> = useCallback(
|
||||
(_, node) => {
|
||||
onNodeSelect(node.id)
|
||||
},
|
||||
[onNodeSelect]
|
||||
)
|
||||
|
||||
const handlePaneClick = useCallback(() => {
|
||||
onNodeSelect(null)
|
||||
}, [onNodeSelect])
|
||||
|
||||
return (
|
||||
<ReactFlow
|
||||
nodes={flowNodes}
|
||||
edges={flowEdges}
|
||||
onNodesChange={onNodesChange}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
onNodeClick={handleNodeClick}
|
||||
onPaneClick={handlePaneClick}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.2, maxZoom: 1.25 }}
|
||||
minZoom={0.15}
|
||||
maxZoom={2.5}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
nodesConnectable={false}
|
||||
deleteKeyCode={null}
|
||||
colorMode="system"
|
||||
>
|
||||
<Background variant={BackgroundVariant.Dots} gap={22} size={1.4} />
|
||||
<Controls showInteractive={false} position="bottom-left" />
|
||||
<MiniMap pannable zoomable className="!hidden sm:!block" />
|
||||
</ReactFlow>
|
||||
)
|
||||
}
|
||||
@@ -49,13 +49,13 @@ export function useKlalbConfig(): UseKlalbConfigResult {
|
||||
body: JSON.stringify(newConfig),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (res.ok && (data.success || data.success === undefined)) {
|
||||
if (res.ok && data.success === true) {
|
||||
setConfig(newConfig)
|
||||
setSaveSuccess(true)
|
||||
setTimeout(() => setSaveSuccess(false), 3000)
|
||||
return { success: true }
|
||||
}
|
||||
const errMsg = data.error || data.message || '保存配置失败'
|
||||
const errMsg = data.error || '保存配置失败'
|
||||
setError(errMsg)
|
||||
return { success: false, message: errMsg }
|
||||
} catch (err: unknown) {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import {
|
||||
forceSimulation,
|
||||
forceLink,
|
||||
forceManyBody,
|
||||
forceCenter,
|
||||
type SimulationNodeDatum,
|
||||
} from 'd3-force'
|
||||
import type { TopologyNode, TopologyEdge, TopologyData } from '@/types/api'
|
||||
|
||||
export interface LayoutNode extends SimulationNodeDatum {
|
||||
id: string
|
||||
address: string
|
||||
compressedAddress?: string
|
||||
isSelf: boolean
|
||||
deviceName?: string
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface LayoutEdge {
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
delay: number
|
||||
cost: number
|
||||
}
|
||||
|
||||
interface UseTopologyResult {
|
||||
nodes: LayoutNode[]
|
||||
edges: LayoutEdge[]
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
relayout: () => void
|
||||
}
|
||||
|
||||
const POLL_INTERVAL_MS = 1000
|
||||
|
||||
function structureSignature(nodes: TopologyNode[], edges: TopologyEdge[]): string {
|
||||
const n = nodes.map((x) => x.id).sort().join(',')
|
||||
const e = edges.map((x) => `${x.source}->${x.target}`).sort().join(',')
|
||||
return `${n}|${e}`
|
||||
}
|
||||
|
||||
function computeForceLayout(
|
||||
topoNodes: TopologyNode[],
|
||||
topoEdges: TopologyEdge[]
|
||||
): Map<string, { x: number; y: number }> {
|
||||
const positions = new Map<string, { x: number; y: number }>()
|
||||
if (topoNodes.length === 0) return positions
|
||||
|
||||
const simNodes: LayoutNode[] = topoNodes.map((n, i) => ({
|
||||
...n,
|
||||
// 初始位置:环形分布避免重叠
|
||||
x: Math.cos((2 * Math.PI * i) / Math.max(topoNodes.length, 1)) * 250,
|
||||
y: Math.sin((2 * Math.PI * i) / Math.max(topoNodes.length, 1)) * 250,
|
||||
}))
|
||||
const nodeIndex = new Map(simNodes.map((n, i) => [n.id, i]))
|
||||
|
||||
const simLinks = topoEdges
|
||||
.filter((e) => nodeIndex.has(e.source) && nodeIndex.has(e.target))
|
||||
.map((e) => {
|
||||
const cost = e.cost > 0 ? e.cost : e.delay
|
||||
// 延迟越高距离越远;基准距离 120px,按 ns 缩放
|
||||
const distance = Math.max(80, Math.min(400, 120 + Math.log10(Math.max(cost, 1)) * 20))
|
||||
return { source: nodeIndex.get(e.source)!, target: nodeIndex.get(e.target)!, distance }
|
||||
})
|
||||
|
||||
const simulation = forceSimulation(simNodes)
|
||||
.force('charge', forceManyBody().strength(-600))
|
||||
.force(
|
||||
'link',
|
||||
forceLink(simLinks).id((d: SimulationNodeDatum) => (d as LayoutNode).id).distance((l: { distance: number }) => l.distance).strength(0.6)
|
||||
)
|
||||
.force('center', forceCenter(0, 0))
|
||||
.stop()
|
||||
|
||||
// 同步运行固定迭代数,提取最终坐标
|
||||
const ticks = 300
|
||||
for (let i = 0; i < ticks; i++) simulation.tick()
|
||||
|
||||
for (const n of simNodes) {
|
||||
positions.set(n.id, { x: n.x ?? 0, y: n.y ?? 0 })
|
||||
}
|
||||
return positions
|
||||
}
|
||||
|
||||
function makeEdgeId(source: string, target: string): string {
|
||||
return source < target ? `${source}__${target}` : `${target}__${source}`
|
||||
}
|
||||
|
||||
export function useTopology(): UseTopologyResult {
|
||||
const [nodes, setNodes] = useState<LayoutNode[]>([])
|
||||
const [edges, setEdges] = useState<LayoutEdge[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const lastSignatureRef = useRef<string>('')
|
||||
const savedPositionsRef = useRef<Map<string, { x: number; y: number }>>(new Map())
|
||||
const layoutPositionsRef = useRef<Map<string, { x: number; y: number }>>(new Map())
|
||||
const relayoutRequestedRef = useRef(false)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
const fetchTopology = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/nodes')
|
||||
if (!res.ok) {
|
||||
setError(`拓扑接口异常 (${res.status})`)
|
||||
return
|
||||
}
|
||||
const payload = (await res.json()) as Partial<TopologyData>
|
||||
if (!mountedRef.current) return
|
||||
|
||||
const topoNodes: TopologyNode[] = Array.isArray(payload.nodes)
|
||||
? payload.nodes.filter(
|
||||
(n) => n && typeof n.id === 'string' && n.id !== ''
|
||||
)
|
||||
: []
|
||||
const topoEdgesRaw: TopologyEdge[] = Array.isArray(payload.edges)
|
||||
? payload.edges
|
||||
: []
|
||||
|
||||
// 边去重(后端已做一次,这里再保险)并生成稳定 id
|
||||
const edgeMap = new Map<string, TopologyEdge>()
|
||||
for (const e of topoEdgesRaw) {
|
||||
if (!e.source || !e.target || e.source === e.target) continue
|
||||
const id = makeEdgeId(e.source, e.target)
|
||||
edgeMap.set(id, { ...e })
|
||||
}
|
||||
const topoEdges = Array.from(edgeMap.values())
|
||||
|
||||
const signature = structureSignature(topoNodes, topoEdges)
|
||||
const structureChanged =
|
||||
signature !== lastSignatureRef.current ||
|
||||
relayoutRequestedRef.current
|
||||
|
||||
if (structureChanged) {
|
||||
let positions: Map<string, { x: number; y: number }>
|
||||
if (
|
||||
!relayoutRequestedRef.current &&
|
||||
layoutPositionsRef.current.size > 0 &&
|
||||
lastSignatureRef.current === ''
|
||||
) {
|
||||
positions = layoutPositionsRef.current
|
||||
} else {
|
||||
positions = computeForceLayout(topoNodes, topoEdges)
|
||||
}
|
||||
|
||||
// 合并用户拖拽过的位置
|
||||
for (const [id, pos] of savedPositionsRef.current) {
|
||||
if (positions.has(id)) positions.set(id, pos)
|
||||
}
|
||||
|
||||
layoutPositionsRef.current = positions
|
||||
lastSignatureRef.current = signature
|
||||
relayoutRequestedRef.current = false
|
||||
|
||||
setNodes(
|
||||
topoNodes.map((n) => ({
|
||||
...n,
|
||||
...(positions.get(n.id) ?? { x: 0, y: 0 }),
|
||||
}))
|
||||
)
|
||||
} else {
|
||||
// 结构未变:仅原地刷新延迟等元数据,位置保持不变
|
||||
setNodes((prev) =>
|
||||
prev.length === topoNodes.length
|
||||
? prev.map((n) => {
|
||||
const fresh = topoNodes.find((t) => t.id === n.id)
|
||||
return fresh ? { ...n, deviceName: fresh.deviceName } : n
|
||||
})
|
||||
: prev
|
||||
)
|
||||
}
|
||||
|
||||
setEdges(
|
||||
topoEdges.map((e) => ({
|
||||
id: makeEdgeId(e.source, e.target),
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
delay: e.delay,
|
||||
cost: e.cost,
|
||||
}))
|
||||
)
|
||||
setError(null)
|
||||
} catch (err: unknown) {
|
||||
if (mountedRef.current) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
setError(msg)
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const relayout = useCallback(() => {
|
||||
relayoutRequestedRef.current = true
|
||||
savedPositionsRef.current.clear()
|
||||
fetchTopology()
|
||||
}, [fetchTopology])
|
||||
|
||||
// 轮询
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
fetchTopology()
|
||||
const timer = window.setInterval(fetchTopology, POLL_INTERVAL_MS)
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [fetchTopology])
|
||||
|
||||
return { nodes, edges, isLoading, error, relayout }
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useState, useMemo, useCallback } from 'react'
|
||||
import { ReactFlowProvider } from '@xyflow/react'
|
||||
import {
|
||||
Share2,
|
||||
Search,
|
||||
RefreshCw,
|
||||
Network,
|
||||
Link2,
|
||||
AlertCircle,
|
||||
} from 'lucide-react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useTopology } from '@/hooks/use-topology'
|
||||
import { TopologyCanvas } from '@/components/topology/topology-canvas'
|
||||
import { NodeDetailSheet } from '@/components/topology/node-detail-sheet'
|
||||
|
||||
export function TopologyPage() {
|
||||
const { nodes, edges, isLoading, error, relayout } = useTopology()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null)
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null)
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
|
||||
const handleCopy = useCallback((text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
setCopiedId(text)
|
||||
setTimeout(() => setCopiedId(null), 2000)
|
||||
}, [])
|
||||
|
||||
const handleNodeSelect = useCallback((nodeId: string | null) => {
|
||||
setSelectedNodeId(nodeId)
|
||||
if (nodeId) setSheetOpen(true)
|
||||
}, [])
|
||||
|
||||
const handleNodeDragEnd = useCallback(
|
||||
(_id: string, _x: number, _y: number) => {
|
||||
// 受控模式下坐标由 ReactFlow 内部维护至下次结构刷新;
|
||||
// 结构刷新后 d3-force 会重新计算,拖拽位置保留策略由后续迭代增强。
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// 选中的节点详情
|
||||
const selectedNode = useMemo(
|
||||
() => nodes.find((n) => n.id === selectedNodeId) ?? null,
|
||||
[nodes, selectedNodeId]
|
||||
)
|
||||
|
||||
// 邻居信息(基于边集合推导)
|
||||
const neighbors = useMemo(() => {
|
||||
if (!selectedNode) return []
|
||||
return edges
|
||||
.filter((e) => e.source === selectedNode.id || e.target === selectedNode.id)
|
||||
.map((e) => {
|
||||
const otherId = e.source === selectedNode.id ? e.target : e.source
|
||||
const other = nodes.find((n) => n.id === otherId)
|
||||
return {
|
||||
address: other?.address ?? otherId,
|
||||
deviceName: other?.deviceName,
|
||||
delay: e.delay,
|
||||
cost: e.cost,
|
||||
}
|
||||
})
|
||||
}, [edges, nodes, selectedNode])
|
||||
|
||||
const sheetNode = useMemo(
|
||||
() =>
|
||||
selectedNode
|
||||
? {
|
||||
id: selectedNode.id,
|
||||
address: selectedNode.address,
|
||||
compressedAddress: selectedNode.compressedAddress,
|
||||
isSelf: selectedNode.isSelf,
|
||||
deviceName: selectedNode.deviceName,
|
||||
}
|
||||
: null,
|
||||
[selectedNode]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-4 p-6">
|
||||
{/* Toolbar */}
|
||||
<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">
|
||||
<Share2 className="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold tracking-tight">网络拓扑</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
SRv6 全网节点与链路的实时可视化视图
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="ml-2 hidden items-center gap-2 sm:flex">
|
||||
<Badge variant="secondary" className="gap-1 px-2 py-0.5 font-mono text-xs">
|
||||
<Network className="size-3" />
|
||||
{nodes.length} 节点
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="gap-1 px-2 py-0.5 font-mono text-xs">
|
||||
<Link2 className="size-3" />
|
||||
{edges.length} 链路
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative w-full max-w-xs">
|
||||
<Search className="absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="搜索设备名或 IPv6 地址..."
|
||||
className="pl-8"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={relayout}
|
||||
disabled={isLoading}
|
||||
title="重新运行力导向自动布局"
|
||||
>
|
||||
<RefreshCw data-icon="inline-start" className={isLoading ? 'animate-spin' : ''} />
|
||||
重新布局
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error banner */}
|
||||
{error && !nodes.length && (
|
||||
<Card className="border-destructive/40 bg-destructive/5 shadow-2xs">
|
||||
<CardContent className="flex items-center gap-2 p-3 text-sm text-destructive">
|
||||
<AlertCircle className="size-4 shrink-0" />
|
||||
无法获取拓扑数据:{error}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Canvas */}
|
||||
<Card className="min-h-96 flex-1 overflow-hidden shadow-2xs">
|
||||
<div className="h-full min-h-[520px] w-full">
|
||||
<ReactFlowProvider>
|
||||
<TopologyCanvas
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
searchQuery={searchQuery}
|
||||
copiedId={copiedId}
|
||||
onCopy={handleCopy}
|
||||
onNodeDragEnd={handleNodeDragEnd}
|
||||
onNodeSelect={handleNodeSelect}
|
||||
/>
|
||||
</ReactFlowProvider>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Detail Sheet */}
|
||||
<NodeDetailSheet
|
||||
open={sheetOpen}
|
||||
onOpenChange={(open) => {
|
||||
setSheetOpen(open)
|
||||
if (!open) setSelectedNodeId(null)
|
||||
}}
|
||||
node={sheetNode}
|
||||
neighbors={neighbors}
|
||||
copiedId={copiedId}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user