feat(ui): разделы карты сети по макету v3

- панель инструментов: поиск первым, вид «Вся сеть / IX и клиенты»,
  «Сервисы / Страны», окно «Фильтр» со статусами и ролями, справа
  «Слои» и «Легенда»;
- панель объекта: шапка с плиткой роли, адресом и статусом, вкладки
  «Обзор» (RTT, сессии, входящий/исходящий трафик, устройство,
  назначения через узел, ресурсы, действия), «Интерфейсы» (WAN-аплинки
  и трафик интерфейсов за окно NetFlow) и «GRE»;
- «Момент времени» под картой: инциденты из ленты событий за 24 часа
  и метка Live; архив снимков карты бэкенд не хранит;
- рабочая панель под картой: вкладки «Потоки NetFlow», «RTT каналов»,
  «Назначения» и «События», строки выбранного объекта подсвечены;
- на телефоне окно легенды растягивается по ширине экрана.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-25 00:08:07 +07:00
1 parent a4694b8481
commit dd6e6b0b77
13 files changed
+657 -334

No files matched your search

+485 -329
View File
@@ -16,6 +16,7 @@ import { MapKpiStrip } from "@/components/network-map/map-kpi-strip"
import { NetworkMapLegend } from "@/components/network-map-legend"
import {
servers as mockServers,
systemEvents as mockSystemEvents,
greTunnels as mockGreTunnels,
type GreTunnel,
type Server,
@@ -87,12 +88,17 @@ import { StatusDot } from "@/components/status-dot"
import {
DownloadIcon, XIcon, LockIcon, LockOpenIcon, WifiIcon, RefreshCwIcon,
ZoomInIcon, ZoomOutIcon, Maximize2Icon, SearchIcon,
LayersIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon,
LayersIcon, FilterIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon,
CableIcon, ActivityIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { formatServicePathLabel, formatServicePathTitle } from "@/lib/format-service-path-label"
import Link from "next/link"
import { MapBottomPanel, MapTimeline, type MapBottomTab, type MapEventRow } from "@/components/network-map/map-bottom-panel"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/reui/badge"
import { listEvents } from "@/shared/api/events"
import type { EventItem } from "@mmapp/contracts/events"
import { Flag, countryName } from "@/components/flag"
// ─── Resource metrics (для мини-блока справа; числа детерминированы по id узла) ─
@@ -1060,6 +1066,19 @@ function NetworkMapContent() {
const [flowListener,setFlowListener]=useState(false)
const [flowLoading,setFlowLoading]=useState(false)
const [flowRefresh,setFlowRefresh]=useState(0)
const [bottomTab, setBottomTab] = useState<MapBottomTab>("flows")
const [mapEvents, setMapEvents] = useState<EventItem[] | null>(null)
const [eventsError, setEventsError] = useState<string | null>(null)
const [eventsAt, setEventsAt] = useState(() => Date.now())
const [showFilter, setShowFilter] = useState(false)
useEffect(() => {
if (!useLiveData) return
let cancelled = false
listEvents(backendUrl, { limit: 50 })
.then(rows => { if (!cancelled) { setMapEvents(rows); setEventsError(null); setEventsAt(Date.now()) } })
.catch(error => { if (!cancelled) setEventsError(error instanceof Error ? error.message : "не удалось загрузить") })
return () => { cancelled = true }
}, [useLiveData, backendUrl, flowRefresh])
const [dnsError,setDnsError]=useState<string|null>(null)
const [dataError, setDataError] = useState<string | null>(null)
const [dataLoading, setDataLoading] = useState(false)
@@ -1981,6 +2000,50 @@ function NetworkMapContent() {
// Подписи связей (RTT, NetFlow) рисуются после карточек, чтобы карточка не перекрывала метку.
const linkBadgeLayer: React.ReactNode[] = []
// ── Рабочая панель под картой: потоки, RTT каналов, назначения, события
const rateOf = (bytes: number, bps: number) => formatNetflowRate({ bytes, bps, bpsFwd: bps, bpsRev: 0 })
const eventTone = (level: "critical" | "warning" | "info") => level === "critical" ? { tone: "er" as const, label: "Сбой" } : level === "warning" ? { tone: "wn" as const, label: "Внимание" } : { tone: "in" as const, label: "Инфо" }
const unitMs: Record<string, number> = { м: 60_000, ч: 3_600_000, д: 86_400_000 }
const eventRows: MapEventRow[] = (useLiveData
? (mapEvents ?? []).map(e => ({ id: e.id, ts: Date.parse(e.createdAt), ...eventTone(e.level), title: e.title, message: e.message }))
: mockSystemEvents.map(e => {
const m = /^(\d+)([мчд])$/.exec(e.when)
return { id: e.id, ts: eventsAt - (m ? Number(m[1]) * unitMs[m[2]] : 0), ...eventTone(e.sev === "destructive" ? "critical" : e.sev), title: e.title, message: e.message }
})
).filter(e => Number.isFinite(e.ts)).sort((a, b) => b.ts - a.ts)
const flowRows = [...destPaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({
id: servicePathKey(p),
client: p.clientName || p.viaName || p.viaId,
exit: p.enName || p.enId,
dest: destDisplayLabel(destNodes.find(svc => svc.id === p.serviceId), destMode, p.serviceId),
rate: rateOf(p.bytes, p.bps),
volume: formatBytes(p.bytes),
hl: Boolean(selected && (p.viaId === selected.id || p.enId === selected.id)) || selectedService?.id === p.serviceId,
}))
const rttRows = greEdges.map(e => {
const key = greEdgeKey(e)
const merged = mergeGreMetricsWithSpeedProbe(speedProbeByTunnelId.get(key), greTunnelProbe(e.tunnel, !useLiveData))
return {
id: key,
name: e.tunnel.name,
route: `${e.fromServer.name} → ${e.toServer.name}`,
rtt: merged.pingMs != null ? `${merged.pingMs} мс` : "—",
speed: merged.dlMbps != null && merged.ulMbps != null ? `${merged.dlMbps} / ${merged.ulMbps} Мбит/с` : "—",
tone: e.tunnel.status === "up" ? "ok" as const : e.tunnel.status === "degraded" ? "wn" as const : "er" as const,
status: e.tunnel.status === "up" ? "Работает" : e.tunnel.status === "degraded" ? "Деградация" : "Недоступен",
hl: selected ? e.fromServer.id === selected.id || e.toServer.id === selected.id : selectedGreEdge ? greEdgeKey(selectedGreEdge) === key : false,
}
})
const destRows = destNodes.map(svc => ({
id: svc.id,
label: destDisplayLabel(svc, destMode, svc.id),
category: destMode === "countries" ? "Страна" : svc.category,
rate: rateOf(svc.bytes, svc.bps),
share: svc.share,
hl: selectedService?.id === svc.id || Boolean(selected && destEdges.some(edge => edge.fromId === selected.id && edge.toId === svc.id)),
}))
const bottomStat = `Окно ${Math.round(mapWindowSec / 60)} мин${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}`
return (
<div className="flex flex-col h-full min-h-0 min-w-0 [&_button]:focus-visible:outline-2 [&_button]:focus-visible:outline-ring [&_button]:focus-visible:outline-offset-2">
<PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Карта сети" }]} />
@@ -2019,21 +2082,6 @@ function NetworkMapContent() {
<Frame spacing="sm" className="h-[max(420px,calc(100svh-13rem))] min-w-0 shrink-0 lg:h-[max(560px,calc(100svh-7rem))]">
<FramePanel className="flex items-center gap-2 p-2 grow-0 shrink-0 flex-wrap">
{/* Filter pills */}
<div className="flex items-center gap-0.5 rounded-md border border-border bg-muted/40 p-0.5 max-w-full overflow-x-auto">
{filterBtns.map(b => (
<button type="button" key={b.value} aria-pressed={filter===b.value} onClick={() => setFilter(b.value)}
className={cn(
"px-2.5 py-1 text-xs rounded transition-colors whitespace-nowrap",
filter === b.value
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}>
{b.label}
</button>
))}
</div>
{/* Search */}
<div className="relative">
<SearchIcon aria-hidden="true" className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none" />
@@ -2051,9 +2099,28 @@ function NetworkMapContent() {
)}
</div>
<select data-map-device-select aria-label="Устройство на карте" className="h-8 w-full md:w-auto min-w-0 max-w-full flex-none md:min-w-44 md:flex-1 rounded-md border border-border bg-background px-2 text-xs focus-visible:outline-2 focus-visible:outline-ring" value={selected?.id??""} disabled={useLiveData&&!hasSnapshot} onChange={e=>{setSelectedGreEdge(null);setSelectedService(null);setSelected(mapServers.find(server=>server.id===e.target.value)??null)}}>
<option value="">Выбрать устройство</option>{mapServers.map(server=><option key={server.id} value={server.id}>{server.name}</option>)}
</select>
{/* Вид карты */}
<div role="group" aria-label="Вид карты" className="flex items-center gap-0.5 rounded-md border border-border bg-muted/40 p-0.5">
{([
{ value: "all" as const, label: "Вся сеть" },
{ value: "ix-node" as const, label: "IX и клиенты" },
]).map((b) => (
<button type="button" key={b.value}
aria-pressed={b.value === "ix-node" ? filter === "ix-node" : filter !== "ix-node"}
disabled={b.value === "ix-node" && !hasIxNodes}
title={b.value === "ix-node" && !hasIxNodes ? "На карте нет IX-узлов" : undefined}
onClick={() => setFilter(b.value)}
className={cn(
"px-2.5 py-1 text-xs rounded transition-colors whitespace-nowrap disabled:opacity-50",
(b.value === "ix-node" ? filter === "ix-node" : filter !== "ix-node")
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}>
{b.label}
</button>
))}
</div>
{/* Dest overlay: services vs countries */}
<div className="flex items-center gap-0.5 rounded-md border border-border bg-muted/40 p-0.5">
{([
@@ -2075,6 +2142,40 @@ function NetworkMapContent() {
))}
</div>
{/* Фильтр статуса и роли */}
<Popover open={showFilter} onOpenChange={setShowFilter}>
<PopoverTrigger render={<button type="button"
className={cn(
"flex items-center gap-1.5 h-7 px-2.5 text-xs rounded-md border transition-colors",
showFilter || filter !== "all"
? "bg-muted text-foreground border-border"
: "border-border/60 text-muted-foreground hover:text-foreground hover:border-border",
)}>
<FilterIcon aria-hidden="true" className="size-3" />Фильтр{filter !== "all" && filter !== "ix-node" ? <Badge variant="secondary" size="sm">1</Badge> : null}
</button>} />
<PopoverContent align="start" aria-label="Фильтр карты" className="w-60 gap-2">
<div role="group" aria-label="Статус и роль узла" className="grid grid-cols-2 gap-1">
{filterBtns.map(b => (
<button type="button" key={b.value} aria-pressed={filter===b.value} onClick={() => setFilter(b.value)}
className={cn(
"px-2.5 py-1.5 text-xs rounded-md border border-transparent text-left transition-colors whitespace-nowrap",
filter === b.value
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}>
{b.label}
</button>
))}
</div>
</PopoverContent>
</Popover>
<select data-map-device-select aria-label="Устройство на карте" className="h-8 w-full md:w-auto min-w-0 max-w-full flex-none md:w-48 md:flex-none rounded-md border border-border bg-background px-2 text-xs focus-visible:outline-2 focus-visible:outline-ring" value={selected?.id??""} disabled={useLiveData&&!hasSnapshot} onChange={e=>{setSelectedGreEdge(null);setSelectedService(null);setSelected(mapServers.find(server=>server.id===e.target.value)??null)}}>
<option value="">Выбрать устройство</option>{mapServers.map(server=><option key={server.id} value={server.id}>{server.name}</option>)}
</select>
<span aria-hidden="true" className="hidden flex-1 md:block" />
{/* Layers dropdown */}
<Popover modal open={showLayers} onOpenChange={setShowLayers}>
<PopoverTrigger render={<button type="button"
@@ -2169,7 +2270,8 @@ function NetworkMapContent() {
<FramePanel className="flex flex-1 min-h-0 min-w-0 p-0 flex-col lg:flex-row">
{/* ── Canvas ── */}
<div ref={canvasRef} className={cn("flex-1 min-h-0 min-w-0 relative overflow-hidden bg-background select-none", (selected || selectedGreEdge || selectedService) && "hidden lg:block")}>
<div className={cn("flex min-h-0 min-w-0 flex-1 flex-col", (selected || selectedGreEdge || selectedService) && "hidden lg:flex")}>
<div ref={canvasRef} className="flex-1 min-h-0 min-w-0 relative overflow-hidden bg-background select-none">
{ixLinks.length > 0 && <button type="button" aria-pressed={showIx} onClick={() => setShowIx(value => !value)}
className="absolute right-3 top-3 z-20 rounded-md border bg-popover px-3 py-2 text-xs font-medium">
Связи IX
@@ -2747,6 +2849,8 @@ function NetworkMapContent() {
</div>
)}
</div>
<MapTimeline events={eventRows} now={eventsAt} onPick={() => setBottomTab("events")} />
</div>
{/* ── Side panel (узел или выбранное GRE-ребро) ── */}
{(selectedGreEdge || selected || selectedService) && (
@@ -3160,13 +3264,14 @@ function NetworkMapContent() {
</>
) : selected ? (
<>
<div className="flex items-start gap-2 px-4 py-3 border-b">
<div className="flex-1 min-w-0">
<div className="flex items-start gap-3 border-b px-3 py-3">
<span aria-hidden="true" className="inline-flex size-9 shrink-0 items-center justify-center rounded-lg font-mono text-xs font-bold" style={{ color: TYPE_STYLE[selected.type].fill, background: `color-mix(in oklch, ${TYPE_STYLE[selected.type].fill} 18%, transparent)` }}>{TYPE_STYLE[selected.type].label}</span>
<div className="min-w-0 flex-1">
<p className="font-mono font-semibold text-sm [overflow-wrap:anywhere]">{selected.name}</p>
<Button type="button" variant="outline" size="sm" className="mt-2" data-map-device-actions onClick={()=>setCtxMenu({x:0,y:0,server:selected})}>Действия устройства</Button>
<p className="text-xs text-muted-foreground font-mono mt-0.5">{selected.host}</p>
<p className="text-xs text-muted-foreground font-mono mt-0.5 [overflow-wrap:anywhere]">{TYPE_LABELS[selected.type]} · {selected.site || "—"} · {selected.host}</p>
</div>
<div className="flex items-center gap-1 mt-0.5">
<div className="flex shrink-0 items-center gap-1.5">
<StatusBadge status={selected.status} />
<button type="button"
onClick={() => { const n = nodes.find(x => x.id === selected.id); if (n) focusNode(n.x, n.y) }}
className="text-muted-foreground hover:text-foreground transition-colors"
@@ -3180,332 +3285,382 @@ function NetworkMapContent() {
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-4 flex flex-col gap-5">
{/* Badges */}
<div className="flex flex-wrap gap-2">
<StatusBadge status={selected.status} />
<span className={cn(
"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium",
selected.type === "jump-host" ? "bg-violet-950/40 text-violet-400" :
selected.type === "home-router" ? "bg-emerald-950/40 text-emerald-400" :
"bg-sky-950/40 text-sky-400",
)}>
{TYPE_STYLE[selected.type].label} · {TYPE_LABELS[selected.type]}
</span>
</div>
<Tabs key={selected.id} defaultValue="over" className="flex min-h-0 flex-1 flex-col gap-0">
<TabsList aria-label="Разделы панели" className="mx-3 mt-2.5 self-start">
<TabsTrigger value="over" className="px-2.5">Обзор</TabsTrigger>
<TabsTrigger value="ifaces" className="px-2.5">Интерфейсы</TabsTrigger>
<TabsTrigger value="gre" className="px-2.5">GRE<Badge variant="secondary" size="sm" className="font-mono">{connectedTunnels.length}</Badge></TabsTrigger>
</TabsList>
{/* Info rows */}
<div className="flex flex-col gap-0">
{[
["Площадка", selected.site],
["Модель", selected.model],
["RouterOS", selected.os],
...(selected.type !== "home-router"
? [["ASN", selected.asn], ["Сессий", useLiveData?(sessionCounts[selected.id]==null?"—":String(sessionCounts[selected.id])):String(selected.sessions)]]
: [["LAN", selected.lanSubnet ?? "—"]]),
].map(([k, v]) => (
<div key={k} className="flex items-center justify-between py-2 border-b border-border/50 last:border-0">
<span className="text-xs text-muted-foreground">{k}</span>
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{v}</span>
</div>
))}
<div className="flex items-center justify-between py-2">
<span className="text-xs text-muted-foreground">Задержка</span>
<span className="text-xs font-mono font-semibold" style={{ color: latencyColor(selected.latency) }}>
{selected.latency == null ? "—" : `${selected.latency} мс`}
</span>
</div>
</div>
<TabsContent value="over" className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 py-4">
{(() => {
const ifs = (interfaceTraffic ?? []).filter(t => t.serverId === selected.id && t.inWindow)
const rate = (bytes: number) => ifs.length ? rateOf(bytes, (bytes * 8) / mapWindowSec) : "—"
const sessions = useLiveData ? (sessionCounts[selected.id] == null ? "—" : String(sessionCounts[selected.id])) : String(selected.sessions)
return (
<div className="grid grid-cols-2 gap-2">
{[
["RTT", selected.latency == null ? "—" : `${selected.latency} мс`],
["Сессии", sessions],
["Входящий", rate(ifs.reduce((sum, t) => sum + t.rxBytes, 0))],
["Исходящий", rate(ifs.reduce((sum, t) => sum + t.txBytes, 0))],
].map(([k, v]) => (
<div key={k} className="bg-muted/25 rounded-lg border px-3 py-2">
<small className="text-muted-foreground block text-xs">{k}</small>
<b className="font-mono text-sm font-semibold">{v}</b>
</div>
))}
</div>
)
})()}
{/* WAN uplinks */}
{selected.type === "home-router" && selected.wanUplinks && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
WAN-аплинки ({selected.wanUplinks.length})
</p>
<div className="flex flex-col gap-2">
{selected.wanUplinks.map((wan, wIdx) => {
const color = WAN_COLORS[wIdx] ?? "var(--muted-foreground)"
const myEdges = wanJhEdges.filter(e => e.homeId === selected.id && e.wanIdx === wIdx)
const isActive = myEdges.some(e => e.active)
const isSel = selWanIdx === wIdx
return (
<div key={wan.id} role="button" tabIndex={0} aria-label={"WAN "+wan.name} aria-pressed={isSel}
onKeyDown={e=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();setSelWanIdx(prev=>prev===wIdx?null:wIdx)}}}
onClick={() => setSelWanIdx(prev => prev === wIdx ? null : wIdx)}
className={cn(
"rounded-lg border p-3 cursor-pointer transition-all",
isSel ? "bg-muted/60" : "bg-muted/20 hover:bg-muted/40",
)}
style={{ borderColor: isSel ? color : undefined }}>
<div className="flex items-center gap-2 mb-2">
<WifiIcon aria-hidden="true" className="size-3.5 shrink-0" style={{ color }} />
<span className="font-mono text-xs font-bold" style={{ color }}>{wan.name}</span>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">Устройство</p>
{/* Info rows */}
<div className="flex flex-col gap-0">
{[
["Площадка", selected.site],
["Модель", selected.model],
["RouterOS", selected.os],
...(selected.type !== "home-router"
? [["ASN", selected.asn], ["Сессий", useLiveData?(sessionCounts[selected.id]==null?"—":String(sessionCounts[selected.id])):String(selected.sessions)]]
: [["LAN", selected.lanSubnet ?? "—"]]),
].map(([k, v]) => (
<div key={k} className="flex items-center justify-between py-2 border-b border-border/50 last:border-0">
<span className="text-xs text-muted-foreground">{k}</span>
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{v}</span>
</div>
))}
<div className="flex items-center justify-between py-2">
<span className="text-xs text-muted-foreground">Задержка</span>
<span className="text-xs font-mono font-semibold" style={{ color: latencyColor(selected.latency) }}>
{selected.latency == null ? "—" : `${selected.latency} мс`}
</span>
</div>
</div>
</div>
{(selected.type === "jump-host" || selected.type === "exit-node") && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">Назначения через узел</p>
<ServicePathList
paths={destPaths
.filter((p) => (
selected.type === "exit-node"
? p.enId === selected.id
: p.viaId === selected.id
))
.slice()
.sort((a, b) => b.bps - a.bps)}
servers={mapServers}
services={destNodes}
highlight={highlightedPath}
viaMode="service"
destMode={destMode}
onToggle={togglePathHighlight}
/>
</div>
)}
{/* Resources */}
{(() => {
const res = srvResMap[selected.id]
if (!res) return null
const cpuPct = res.cpu
const ramPct = res.ramUsed==null||res.ramTotal==null||res.ramTotal===0?null:Math.round(res.ramUsed/res.ramTotal*100)
const hddPct = res.hddUsed==null||res.hddTotal==null||res.hddTotal===0?null:Math.round(res.hddUsed/res.hddTotal*100)
return (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">
Ресурсы
</p>
{!res.fromPoll && (
<p className="text-[9px] text-muted-foreground mb-3 leading-snug">
Нет снапшота опроса — показаны демо-значения. Включите опрос серверов или откройте «Серверы».
</p>
)}
{res.fromPoll && (
<p className="text-[9px] text-muted-foreground mb-3 leading-snug">
Последний poll: {res.measuredAt ? new Date(res.measuredAt).toLocaleString("ru-RU") : "время неизвестно"}. Неизвестные ресурсы — «—». История CPU и диск API не передаются.
</p>
)}
{/* CPU with sparkline */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">CPU</span>
<span className={cn("text-[10px] font-mono font-semibold", resPctColor(cpuPct))}>
{cpuPct==null?"—":cpuPct+"%"}
</span>
</div>
<div className="flex items-center gap-2">
{cpuPct!=null&&<MiniBar pct={cpuPct} />}
{res.cpuHistory.length>1&&<Sparkline history={res.cpuHistory} />}
</div>
</div>
{/* RAM */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">RAM</span>
<span className={cn("text-[10px] font-mono font-semibold", resPctColor(ramPct))}>
{fmtMB(res.ramUsed)} / {fmtMB(res.ramTotal)}
</span>
</div>
{ramPct!=null&&<MiniBar pct={ramPct} />}
</div>
{/* HDD (нет в GET /api/servers — всегда условная шкала) */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">
HDD
{!useLiveData && (
<span className="text-[8px] font-normal text-muted-foreground/70 ml-1">(оценка)</span>
)}
</span>
<span className="text-[10px] font-mono text-muted-foreground">
{fmtMB(res.hddUsed)} / {fmtMB(res.hddTotal)}
</span>
</div>
{hddPct!=null&&<MiniBar pct={hddPct} />}
</div>
{/* Misc metrics */}
<div className="flex flex-col gap-0">
<div className="flex items-center justify-between py-1.5 border-b border-border/40">
<span className="text-[10px] text-muted-foreground">Uptime</span>
<span className="text-[10px] font-mono">{fmtUptime(res.uptimeSeconds)}</span>
</div>
{res.temp != null && (
<div className="flex items-center justify-between py-1.5 border-b border-border/40">
<span className="text-[10px] text-muted-foreground">Температура</span>
<span className={cn(
"ml-auto text-[10px] font-medium px-1.5 py-0.5 rounded-full",
isActive ? "bg-emerald-500/10 text-emerald-400" : "bg-muted text-muted-foreground",
"text-[10px] font-mono font-semibold",
res.temp >= 70 ? "text-red-400" : res.temp >= 55 ? "text-amber-400" : "text-emerald-400",
)}>
{useLiveData?"Аплинк каталога":isActive ? "primary (демо)" : "backup (демо)"}
{res.temp}°C
</span>
</div>
<div className="flex flex-col gap-1">
{[["ISP", wan.isp], ["Iface", wan.iface], ["IP", wan.ip],
["Канал", `↓${wan.maxDl} ↑${wan.maxUl} Мбит`]].map(([k, v]) => (
<div key={k} className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">{k}</span>
<span className="text-[10px] font-mono">{v}</span>
</div>
))}
{(() => {
const hop = netflowByWanKey.get(`${selected.id}\t${wIdx}`)
if (!hopHasRate(hop)) return null
return (
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">Поток</span>
<span className="text-[10px] font-mono text-emerald-400">
{hop.bpsFwd > 0 && hop.bpsRev > 0
? formatNetflowDir(hop)
: formatNetflowRate(hop)}
</span>
)}
<div className="flex items-center justify-between py-1.5">
<span className="text-[10px] text-muted-foreground">Плата</span>
<span className="text-[10px] font-mono">{selected.model || "—"}</span>
</div>
</div>
</div>
)
})()}
<div className="flex flex-wrap gap-2">
<Button type="button" variant="outline" size="sm" data-map-device-actions onClick={()=>setCtxMenu({x:0,y:0,server:selected})}>Действия устройства</Button>
</div>
{/* Navigate hint */}
<button type="button"
onClick={() => { const n = nodes.find(x => x.id === selected.id); if (n) focusNode(n.x, n.y) }}
className="w-full flex items-center justify-center gap-2 py-2 rounded-lg border border-dashed border-border/60
text-xs text-muted-foreground hover:text-foreground hover:border-border transition-colors">
<HomeIcon aria-hidden="true" className="size-3" />
Навести карту на узел
</button>
</TabsContent>
<TabsContent value="ifaces" className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 py-4">
{/* WAN uplinks */}
{selected.type === "home-router" && selected.wanUplinks && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
WAN-аплинки ({selected.wanUplinks.length})
</p>
<div className="flex flex-col gap-2">
{selected.wanUplinks.map((wan, wIdx) => {
const color = WAN_COLORS[wIdx] ?? "var(--muted-foreground)"
const myEdges = wanJhEdges.filter(e => e.homeId === selected.id && e.wanIdx === wIdx)
const isActive = myEdges.some(e => e.active)
const isSel = selWanIdx === wIdx
return (
<div key={wan.id} role="button" tabIndex={0} aria-label={"WAN "+wan.name} aria-pressed={isSel}
onKeyDown={e=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();setSelWanIdx(prev=>prev===wIdx?null:wIdx)}}}
onClick={() => setSelWanIdx(prev => prev === wIdx ? null : wIdx)}
className={cn(
"rounded-lg border p-3 cursor-pointer transition-all",
isSel ? "bg-muted/60" : "bg-muted/20 hover:bg-muted/40",
)}
style={{ borderColor: isSel ? color : undefined }}>
<div className="flex items-center gap-2 mb-2">
<WifiIcon aria-hidden="true" className="size-3.5 shrink-0" style={{ color }} />
<span className="font-mono text-xs font-bold" style={{ color }}>{wan.name}</span>
<span className={cn(
"ml-auto text-[10px] font-medium px-1.5 py-0.5 rounded-full",
isActive ? "bg-emerald-500/10 text-emerald-400" : "bg-muted text-muted-foreground",
)}>
{useLiveData?"Аплинк каталога":isActive ? "primary (демо)" : "backup (демо)"}
</span>
</div>
<div className="flex flex-col gap-1">
{[["ISP", wan.isp], ["Iface", wan.iface], ["IP", wan.ip],
["Канал", `↓${wan.maxDl} ↑${wan.maxUl} Мбит`]].map(([k, v]) => (
<div key={k} className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">{k}</span>
<span className="text-[10px] font-mono">{v}</span>
</div>
)
})()}
</div>
{myEdges.length > 0 && (
<div className="mt-2 pt-2 border-t border-border/40">
<p className="text-[9px] uppercase text-muted-foreground tracking-wider mb-1.5">
Модель связей с JH · Ping модели
</p>
{myEdges.map((e) => {
const jh = mapServers.find(s => s.id === e.jhId)
const edgeKey = `${e.homeId}-${e.wanIdx}-${e.jhId}`
))}
{(() => {
const hop = netflowByWanKey.get(`${selected.id}\t${wIdx}`)
if (!hopHasRate(hop)) return null
return (
<div key={edgeKey} className="flex items-center justify-between py-0.5">
<span className="text-[10px] font-mono text-muted-foreground truncate">
→ {jh?.name ?? e.jhId}
</span>
<span className="text-[10px] font-mono font-semibold shrink-0 ml-2"
style={{ color: pingColor(e.pingMs) }}>
{e.pingMs == null ? "—" : `${e.pingMs} мс`}
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">Поток</span>
<span className="text-[10px] font-mono text-emerald-400">
{hop.bpsFwd > 0 && hop.bpsRev > 0
? formatNetflowDir(hop)
: formatNetflowRate(hop)}
</span>
</div>
)
})}
</div>
)}
</div>
)
})}
</div>
</div>
)}
{/* GRE tunnels */}
{connectedTunnels.length > 0 && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
GRE-туннели ({connectedTunnels.length})
</p>
<div className="flex flex-col gap-2">
{connectedTunnels.map(t => {
const ts = TUNNEL_STYLE[t.status]
const peer: Server | undefined =
t.serverId === selected.id
? findServerByGreRemote(mapServers, t.remoteAddress, greResolvedMap)
: mapServers.find((s) => s.id === t.serverId)
const fromServer = mapServers.find((s) => s.id === t.serverId)
const toServer = findServerByGreRemote(mapServers, t.remoteAddress, greResolvedMap)
const tunnelPanelKey =
fromServer && toServer
? `${fromServer.id}|${toServer.id}|${t.id}|${t.localAddress}|${t.remoteAddress}`
: `${t.serverId}|${t.id}|${t.localAddress}|${t.remoteAddress}`
const baseProbe = greTunnelProbe(t,!useLiveData)
const groupKey = peer?.id ?? (normalizeGreEndpointAddr(t.remoteAddress) || t.remoteAddress)
const isPrimary = grePrimaryByGroupKey.get(groupKey) === t.id
const spGre =
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
const pc = pingColor(merged.pingMs)
const greFlow = showNetflow ? matchNetflowForGreEdge({tunnel: t}, mapHops, interfaceTraffic, mapWindowSec) : undefined
const showMetrics =
merged.pingMs != null ||
(merged.dlMbps != null && merged.ulMbps != null) ||
!!greFlow
return (
<div key={tunnelPanelKey} className="rounded-md border border-border/60 px-3 py-2 bg-muted/20">
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{t.name}</span>
<div className="flex items-center gap-2">
<span className={cn(
"text-[10px] font-medium px-1.5 py-0.5 rounded-full",
isPrimary ? "bg-emerald-500/10 text-emerald-400" : "bg-muted text-muted-foreground",
)}>
{isPrimary ? "Основная на схеме" : "Дополнительная на схеме"}
</span>
<span className="text-[10px] font-medium" style={{ color: ts.stroke }}>
{t.status === "up" ? "Up" : t.status === "degraded" ? "Degraded" : "Down"}
</span>
})()}
</div>
{myEdges.length > 0 && (
<div className="mt-2 pt-2 border-t border-border/40">
<p className="text-[9px] uppercase text-muted-foreground tracking-wider mb-1.5">
Модель связей с JH · Ping модели
</p>
{myEdges.map((e) => {
const jh = mapServers.find(s => s.id === e.jhId)
const edgeKey = `${e.homeId}-${e.wanIdx}-${e.jhId}`
return (
<div key={edgeKey} className="flex items-center justify-between py-0.5">
<span className="text-[10px] font-mono text-muted-foreground truncate">
→ {jh?.name ?? e.jhId}
</span>
<span className="text-[10px] font-mono font-semibold shrink-0 ml-2"
style={{ color: pingColor(e.pingMs) }}>
{e.pingMs == null ? "—" : `${e.pingMs} мс`}
</span>
</div>
)
})}
</div>
)}
</div>
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground font-mono truncate max-w-[200px]">
→ {peer ? `${peer.name} · ${peer.site}` : t.remoteAddress}
</span>
{t.ipsec
? <span className="text-[10px] text-emerald-400 flex items-center gap-0.5"><LockIcon aria-hidden="true" className="size-2.5" />IPsec</span>
: <span className="text-[10px] text-muted-foreground flex items-center gap-0.5"><LockOpenIcon aria-hidden="true" className="size-2.5" />{useLiveData?"IPsec неизвестен":"Plain (демо)"}</span>}
</div>
{showMetrics && (
<div className="flex items-center justify-between pt-1 border-t border-border/30">
<span className="text-[9px] text-muted-foreground">
{merged.hasSpeedMonitor ? "Мониторинг (ping / TX·RX)" : "Модель ping / speed"}
</span>
<span className="text-[10px] font-mono" style={{ color: pc }}>
{merged.pingMs != null ? `${merged.pingMs} мс` : "—"}
{merged.dlMbps != null && merged.ulMbps != null && (
<span className={cn(
"text-[9px] ml-1.5",
merged.hasSpeedMonitor ? "text-sky-400/90" : "text-muted-foreground",
)}>
↓{merged.dlMbps} ↑{merged.ulMbps}
</span>
)}
{greFlow && (
<span className="text-[9px] ml-1.5 text-emerald-400">
NetFlow · {mapWindowSec / 60} мин · {greFlow.inWindow ? formatNetflowRate(greFlow) : "Нет записей"}{greFlow.source === "retained" ? " · выборка" : ""}
</span>
)}
</span>
</div>
)}
</div>
)
})}
)
})}
</div>
</div>
</div>
)}
)}
{(selected.type === "jump-host" || selected.type === "exit-node") && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">Пути</p>
<ServicePathList
paths={destPaths
.filter((p) => (
selected.type === "exit-node"
? p.enId === selected.id
: p.viaId === selected.id
))
.slice()
.sort((a, b) => b.bps - a.bps)}
servers={mapServers}
services={destNodes}
highlight={highlightedPath}
viaMode="service"
destMode={destMode}
onToggle={togglePathHighlight}
/>
</div>
)}
{/* Resources */}
{(() => {
const res = srvResMap[selected.id]
if (!res) return null
const cpuPct = res.cpu
const ramPct = res.ramUsed==null||res.ramTotal==null||res.ramTotal===0?null:Math.round(res.ramUsed/res.ramTotal*100)
const hddPct = res.hddUsed==null||res.hddTotal==null||res.hddTotal===0?null:Math.round(res.hddUsed/res.hddTotal*100)
return (
{(() => {
const ifs = (interfaceTraffic ?? []).filter(t => t.serverId === selected.id)
if (!ifs.length) return <p className="text-muted-foreground text-xs">{useLiveData && !flowReadAt ? "Трафик интерфейсов неизвестен: NetFlow не загружен." : "NetFlow не прислал трафик по интерфейсам этого узла за окно."}</p>
const rate = (bytes: number) => rateOf(bytes, (bytes * 8) / mapWindowSec)
return (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">Трафик интерфейсов · окно {Math.round(mapWindowSec / 60)} мин</p>
{ifs.map(t => (
<div key={t.iface} className="flex items-center justify-between gap-2 border-b py-2 text-xs last:border-b-0">
<span className="font-mono font-medium">{t.iface}</span>
<span className="text-muted-foreground font-mono">↓ {rate(t.rxBytes)} · ↑ {rate(t.txBytes)}{t.inWindow ? "" : " · вне окна"}</span>
</div>
))}
</div>
)
})()}
</TabsContent>
<TabsContent value="gre" className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 py-4">
{/* GRE tunnels */}
{connectedTunnels.length > 0 && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1">
Ресурсы
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
GRE-туннели ({connectedTunnels.length})
</p>
{!res.fromPoll && (
<p className="text-[9px] text-muted-foreground mb-3 leading-snug">
Нет снапшота опроса — показаны демо-значения. Включите опрос серверов или откройте «Серверы».
</p>
)}
{res.fromPoll && (
<p className="text-[9px] text-muted-foreground mb-3 leading-snug">
Последний poll: {res.measuredAt ? new Date(res.measuredAt).toLocaleString("ru-RU") : "время неизвестно"}. Неизвестные ресурсы — «—». История CPU и диск API не передаются.
</p>
)}
{/* CPU with sparkline */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">CPU</span>
<span className={cn("text-[10px] font-mono font-semibold", resPctColor(cpuPct))}>
{cpuPct==null?"—":cpuPct+"%"}
</span>
</div>
<div className="flex items-center gap-2">
{cpuPct!=null&&<MiniBar pct={cpuPct} />}
{res.cpuHistory.length>1&&<Sparkline history={res.cpuHistory} />}
</div>
</div>
{/* RAM */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">RAM</span>
<span className={cn("text-[10px] font-mono font-semibold", resPctColor(ramPct))}>
{fmtMB(res.ramUsed)} / {fmtMB(res.ramTotal)}
</span>
</div>
{ramPct!=null&&<MiniBar pct={ramPct} />}
</div>
{/* HDD (нет в GET /api/servers — всегда условная шкала) */}
<div className="mb-3">
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground">
HDD
{!useLiveData && (
<span className="text-[8px] font-normal text-muted-foreground/70 ml-1">(оценка)</span>
)}
</span>
<span className="text-[10px] font-mono text-muted-foreground">
{fmtMB(res.hddUsed)} / {fmtMB(res.hddTotal)}
</span>
</div>
{hddPct!=null&&<MiniBar pct={hddPct} />}
</div>
{/* Misc metrics */}
<div className="flex flex-col gap-0">
<div className="flex items-center justify-between py-1.5 border-b border-border/40">
<span className="text-[10px] text-muted-foreground">Uptime</span>
<span className="text-[10px] font-mono">{fmtUptime(res.uptimeSeconds)}</span>
</div>
{res.temp != null && (
<div className="flex items-center justify-between py-1.5 border-b border-border/40">
<span className="text-[10px] text-muted-foreground">Температура</span>
<span className={cn(
"text-[10px] font-mono font-semibold",
res.temp >= 70 ? "text-red-400" : res.temp >= 55 ? "text-amber-400" : "text-emerald-400",
)}>
{res.temp}°C
</span>
</div>
)}
<div className="flex items-center justify-between py-1.5">
<span className="text-[10px] text-muted-foreground">Плата</span>
<span className="text-[10px] font-mono">{selected.model || "—"}</span>
</div>
<div className="flex flex-col gap-2">
{connectedTunnels.map(t => {
const ts = TUNNEL_STYLE[t.status]
const peer: Server | undefined =
t.serverId === selected.id
? findServerByGreRemote(mapServers, t.remoteAddress, greResolvedMap)
: mapServers.find((s) => s.id === t.serverId)
const fromServer = mapServers.find((s) => s.id === t.serverId)
const toServer = findServerByGreRemote(mapServers, t.remoteAddress, greResolvedMap)
const tunnelPanelKey =
fromServer && toServer
? `${fromServer.id}|${toServer.id}|${t.id}|${t.localAddress}|${t.remoteAddress}`
: `${t.serverId}|${t.id}|${t.localAddress}|${t.remoteAddress}`
const baseProbe = greTunnelProbe(t,!useLiveData)
const groupKey = peer?.id ?? (normalizeGreEndpointAddr(t.remoteAddress) || t.remoteAddress)
const isPrimary = grePrimaryByGroupKey.get(groupKey) === t.id
const spGre =
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
const pc = pingColor(merged.pingMs)
const greFlow = showNetflow ? matchNetflowForGreEdge({tunnel: t}, mapHops, interfaceTraffic, mapWindowSec) : undefined
const showMetrics =
merged.pingMs != null ||
(merged.dlMbps != null && merged.ulMbps != null) ||
!!greFlow
return (
<div key={tunnelPanelKey} className="rounded-md border border-border/60 px-3 py-2 bg-muted/20">
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{t.name}</span>
<div className="flex items-center gap-2">
<span className={cn(
"text-[10px] font-medium px-1.5 py-0.5 rounded-full",
isPrimary ? "bg-emerald-500/10 text-emerald-400" : "bg-muted text-muted-foreground",
)}>
{isPrimary ? "Основная на схеме" : "Дополнительная на схеме"}
</span>
<span className="text-[10px] font-medium" style={{ color: ts.stroke }}>
{t.status === "up" ? "Up" : t.status === "degraded" ? "Degraded" : "Down"}
</span>
</div>
</div>
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] text-muted-foreground font-mono truncate max-w-[200px]">
→ {peer ? `${peer.name} · ${peer.site}` : t.remoteAddress}
</span>
{t.ipsec
? <span className="text-[10px] text-emerald-400 flex items-center gap-0.5"><LockIcon aria-hidden="true" className="size-2.5" />IPsec</span>
: <span className="text-[10px] text-muted-foreground flex items-center gap-0.5"><LockOpenIcon aria-hidden="true" className="size-2.5" />{useLiveData?"IPsec неизвестен":"Plain (демо)"}</span>}
</div>
{showMetrics && (
<div className="flex items-center justify-between pt-1 border-t border-border/30">
<span className="text-[9px] text-muted-foreground">
{merged.hasSpeedMonitor ? "Мониторинг (ping / TX·RX)" : "Модель ping / speed"}
</span>
<span className="text-[10px] font-mono" style={{ color: pc }}>
{merged.pingMs != null ? `${merged.pingMs} мс` : "—"}
{merged.dlMbps != null && merged.ulMbps != null && (
<span className={cn(
"text-[9px] ml-1.5",
merged.hasSpeedMonitor ? "text-sky-400/90" : "text-muted-foreground",
)}>
↓{merged.dlMbps} ↑{merged.ulMbps}
</span>
)}
{greFlow && (
<span className="text-[9px] ml-1.5 text-emerald-400">
NetFlow · {mapWindowSec / 60} мин · {greFlow.inWindow ? formatNetflowRate(greFlow) : "Нет записей"}{greFlow.source === "retained" ? " · выборка" : ""}
</span>
)}
</span>
</div>
)}
</div>
)
})}
</div>
</div>
)
})()}
)}
{/* Navigate hint */}
<button type="button"
onClick={() => { const n = nodes.find(x => x.id === selected.id); if (n) focusNode(n.x, n.y) }}
className="w-full flex items-center justify-center gap-2 py-2 rounded-lg border border-dashed border-border/60
text-xs text-muted-foreground hover:text-foreground hover:border-border transition-colors">
<HomeIcon aria-hidden="true" className="size-3" />
Навести карту на узел
</button>
</div>
{connectedTunnels.length === 0 ? <p className="text-muted-foreground text-xs">У узла нет GRE-туннелей на карте.</p> : null}
</TabsContent>
</Tabs>
</>
) : null}
</div>
@@ -3513,6 +3668,7 @@ function NetworkMapContent() {
</FramePanel>
</Frame>
<MapBottomPanel tab={bottomTab} onTab={setBottomTab} flows={flowRows} rtt={rttRows} destinations={destRows} events={eventRows} eventsError={useLiveData ? eventsError : null} stat={bottomStat} />
</div>
{/* ── Context menu ── */}
{ctxMenu&&currentCtxServer&&<ContextMenu menu={{...ctxMenu,server:currentCtxServer}} onClose={()=>setCtxMenu(null)} />}
+1 -1
View File
@@ -14,7 +14,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
<summary className="border-border/60 text-muted-foreground hover:text-foreground flex h-7 cursor-pointer list-none items-center gap-1.5 rounded-md border px-2.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
<InfoIcon aria-hidden="true" className="size-3.5" />Легенда
</summary>
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 flex max-h-[60vh] w-56 max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border px-3 py-2 text-xs shadow-md">
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-56 max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border px-3 py-2 text-xs shadow-md">
<div>
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5">
+166
View File
@@ -0,0 +1,166 @@
"use client"
import type { ReactNode } from "react"
import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string }
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
return (
<div className="max-h-[420px] overflow-auto">
<div className="min-w-[720px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
{head.map((h) => <span key={h}>{h}</span>)}
</div>
{empty ? <p className="text-muted-foreground px-4 py-8 text-center text-sm">{empty}</p> : children}
</div>
</div>
)
}
function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: ReactNode }) {
return <div className={cn("grid min-h-11 items-center gap-x-3 border-b px-4 py-1.5 text-[13px] last:border-b-0", cols, hl && "bg-primary/8")}>{children}</div>
}
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
const DEST_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_110px_minmax(140px,1fr)]"
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
/**
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены.
*/
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
eventsError: string | null
stat: string
}) {
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
{ id: "rtt", label: "RTT каналов", count: rtt.length },
{ id: "dest", label: "Назначения", count: destinations.length },
{ id: "events", label: "События", count: events.length },
]
return (
<SectionFrame aria-label="Рабочая панель карты" bare>
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
<TabsList aria-label="Рабочая панель">
{tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5">
{t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger>
))}
</TabsList>
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
</div>
<FramePanel className="p-0">
<TabsContent value="flows">
<Table head={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<span className="truncate">{r.dest}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="rtt">
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}>
{rtt.map((r) => (
<Row key={r.id} cols={RTT_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.name}</span>
<span className="truncate font-mono">{r.route}</span>
<span className="font-mono tabular-nums">{r.rtt}</span>
<span className="font-mono tabular-nums">{r.speed}</span>
<span><ToneBadge tone={r.tone}>{r.status}</ToneBadge></span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="dest">
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
{destinations.map((r) => (
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
<span className="truncate font-medium">{r.label}</span>
<span className="text-muted-foreground truncate">{r.category}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="flex items-center gap-2">
<span className="bg-muted h-1.5 w-20 overflow-hidden rounded-full"><i className="block h-full rounded-full" style={{ width: `${Math.round(Math.min(1, r.share) * 100)}%`, background: "var(--chart-4)" }} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(r.share * 100)}%</span>
</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="events">
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
{events.map((r) => (
<Row key={r.id} cols={EVENT_COLS}>
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
<span className="truncate font-medium">{r.title}</span>
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
</Row>
))}
</Table>
</TabsContent>
</FramePanel>
</Tabs>
</SectionFrame>
)
}
/**
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
const from = now - 24 * 3_600_000
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
const pos = (ts: number) => `calc(10px + (100% - 20px) * ${((ts - from) / (now - from)).toFixed(4)})`
return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 py-2">
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative h-8 min-w-0 flex-1">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-1/2 h-px" />
{[0, 0.75, 0.9583].map((t, i) => (
<span key={i} aria-hidden="true" className="text-muted-foreground absolute top-0 -translate-x-1/2 text-xs leading-none" style={{ left: `calc(10px + (100% - 20px) * ${t})` }}>{["−24 ч", "−6 ч", "−1 ч"][i]}</span>
))}
{marks.map((e) => (
<button
key={e.id}
type="button"
onClick={() => onPick(e)}
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
className="focus-visible:ring-ring absolute top-1/2 size-3 -translate-1/2 rounded-full border-2 border-[var(--card)] outline-none focus-visible:ring-2"
style={{ left: pos(e.ts), background: TONE_COLOR[e.tone] }}
/>
))}
<span className="text-success absolute top-1/2 right-0 flex translate-x-1/2 -translate-y-1/2 items-center gap-1 text-xs font-medium">
<ToneDot tone="ok" />Live
</span>
</div>
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
</div>
)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 161 KiB

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 149 KiB

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 63 KiB

+1 -1
View File
@@ -43,7 +43,7 @@ test("Карта: неизвестный статус не становится
await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true})).toBeVisible()
})
+2 -2
View File
@@ -20,7 +20,7 @@ test("Карта: модель WAN не утверждает активный м
await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await expect(page.getByText("primary",{exact:true})).toHaveCount(0);await expect(page.getByText("backup",{exact:true})).toHaveCount(0)
})
test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{
@@ -31,7 +31,7 @@ test("Карта: выбранный GRE обновляется и неизве
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
})
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
+1
View File
@@ -59,6 +59,7 @@ test("Карта: пропорции камеры, ручной масштаб
await page.getByRole("button",{name:"Вписать карту",exact:true}).click()
expect(await map.getAttribute("viewBox")).not.toBe(manual)
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click()
const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter")
await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true")
})
+1 -1
View File
@@ -10,7 +10,7 @@ test("Карта URL: устройство/WAN, фильтр, поиск, наз
await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router")
await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await page.getByRole("button",{name:"Онлайн",exact:true}).click()
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Онлайн",exact:true}).click()
await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/)
await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/)
await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")