diff --git a/app/(main)/network-map/page.tsx b/app/(main)/network-map/page.tsx index 7f6edc51..fb1f3eb1 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -1,10 +1,13 @@ "use client" -import { useState, useRef, useEffect, useMemo, useCallback, Suspense } from "react" -import {fitNetworkMapCamera} from "@/lib/network-map-camera" +import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback, Suspense } from "react" import { projectNetworkMapDensity, densityWanKey } from "@/lib/network-map-density" -import { channelStatus, collectGroupLinks, countGroupGre, type MapGroupConnection, type GroupLinkEnd, type MapGroupLink } from "@/lib/network-map-group-links" +import { deviceLane, layoutNetworkMapColumns } from "@/lib/network-map-columns" +import { mapCardMetrics } from "@/lib/network-map-card-metrics" +import { channelStatus, collectGroupLinks, countGroupGre, type MapGroupConnection, type GroupLinkEnd } from "@/lib/network-map-group-links" import { MapGroupLinks, MapGroupMark } from "@/components/network-map/group-marks" +import { MapAccessMark } from "@/components/network-map/access-mark" +import { ServerNode, ServiceNode, WanSatNode } from "@/components/network-map/map-nodes" import { mapObservationRoute } from "@/lib/network-map-observation-route" import { useSearchParams } from "next/navigation" import {readNetworkMapUrl,patchNetworkMapUrl,type NetworkMapFilter} from "@/lib/network-map-url-state" @@ -16,6 +19,8 @@ import {usePrefersReducedMotion} from "@/hooks/use-prefers-reduced-motion" import {toast} from "sonner" import { PageHeader } from "@/components/page-header" import { PageTitle } from "@/components/page-title" +import { DataPageToolbarFrame } from "@/components/data-page-toolbar" +import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group" import { MapKpiStrip, ruPlural } from "@/components/network-map/map-kpi-strip" import { MapChannelList, MapSiteDirectory, mapSiteName } from "@/components/network-map/map-site-directory" import { NetworkMapLegend } from "@/components/network-map-legend" @@ -43,28 +48,15 @@ import { buildWanJhEdges, mapLinkPath, mapLinkPoint, - mapRibbons, placeMapLinkLabels, type MapBox, - MAP_LANES, MAP_CARD_W, - MAP_CARD_H, - MAP_WAN_W, - MAP_WAN_H, MAP_PILL_H, - MAP_SERVICE_COMPACT_W, computeNetworkMapLayout, - MAP_SERVICE_NODE_H, - MAP_SERVICE_NODE_W, - NETWORK_MAP_H, NETWORK_MAP_LAYOUT_REVISION, - NETWORK_MAP_PIPELINE_Y, NETWORK_MAP_W, findServerByGreRemote, greTunnelProbe, - placeCountryServiceNodes, - placeServiceNodes, - SERVICE_COL_W, type GreMapEdge, type WanJhEdge, } from "@/lib/network-map-layout" @@ -99,9 +91,9 @@ import { formatBytes, fmtRate } from "@/lib/fmt-rate" import { projectTrafficObservations } from "@/lib/traffic-observations" import type { FlowMapCountryServiceGroup, FlowMapHopsDto, FlowMapInterfaceTraffic, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow" import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon" +import { MapFaultBadge } from "@/components/network-map/wire-badge" import { InspectorMetrics, InspectorUsers, NodeHistory, ServiceInspector, serviceUsers } from "@/components/network-map/inspector-traffic" import { Spinner } from "@/components/ui/spinner" -import { CountryFlagSvg } from "@/components/network-map/country-flag-svg" import { Button, buttonVariants } from "@/components/ui/button" import { StatusBadge } from "@/components/status-badge" import { StatusDot } from "@/components/status-dot" @@ -109,7 +101,7 @@ import { DownloadIcon, XIcon, LockIcon, LockOpenIcon, WifiIcon, RefreshCwIcon, SearchIcon, ChevronLeftIcon, ChevronRightIcon, TriangleAlertIcon, LayersIcon, FilterIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon, - CableIcon, ActivityIcon, ArrowDownLeftIcon, ArrowUpRightIcon, UsersIcon, ChevronDownIcon, ChevronUpIcon, CircleHelpIcon, + CableIcon, ActivityIcon, UsersIcon, CircleHelpIcon, } from "lucide-react" import { cn } from "@/lib/utils" import { formatServicePathLabel, formatServicePathTitle, servicePathKey } from "@/lib/format-service-path-label" @@ -282,8 +274,6 @@ function Sparkline({ history }: { history: number[] }) { // ─── Canvas dimensions ──────────────────────────────────────────────────────── -const W = NETWORK_MAP_W -const H = NETWORK_MAP_H const ZOOM_MIN = 0.2 const ZOOM_MAX = 6 @@ -485,8 +475,10 @@ function MapLinkPill({ x, y, w, text, tone, opacity, label, hint, onOpen }: { > {hint} {onOpen ? : null} - - {text} + {tone === "wn" || tone === "er" ? : <> + + {text} + } ) } @@ -505,7 +497,7 @@ function SvgTooltip({ n }: { n: Server & { x: number; y: number } }) { const lines = [ n.name, `${TYPE_LABELS[n.type]} · ${n.site || n.country?.toUpperCase() || "—"}`, - n.latency != null ? `${n.latency} мс` : "Офлайн", + n.latency != null ? `${n.latency} мс` : n.status === "offline" ? "Офлайн" : "RTT · нет данных", n.model ?? "", ].filter(Boolean) const bw = 148, bh = lines.length * 14 + 14 @@ -535,60 +527,6 @@ const STATUS_DOT: Record = { unknown: "var(--muted-foreground)", } -/** Карточка устройства макета v3: плитка роли, точка статуса, имя, задержка и площадка, флаг. */ -function ServerNode({ n, isSel, isVis, isDragged, hideCatalogLatency, rates, onClick, onDblClick, onHoverChange, onContextMenu, onPointerDown }: { - n: Server & { x: number; y: number } - isSel: boolean; isVis: boolean; isDragged: boolean - /** Не дублировать «N мс» из каталога, если на карте уже показаны метрики GRE. */ - hideCatalogLatency?: boolean - rates?: { rxMbps: number; txMbps: number } - onClick: () => void - onDblClick: () => void - onHoverChange: (hov: boolean) => void - onContextMenu: (e: React.MouseEvent) => void - onPointerDown: (e: React.PointerEvent) => void -}) { - const ts = TYPE_STYLE[n.type] - const hw = MAP_CARD_W / 2 - const hh = MAP_CARD_H / 2 - const border = n.status === "degraded" - ? "color-mix(in oklch, var(--warning) 45%, transparent)" - : n.status === "offline" ? "color-mix(in oklch, var(--destructive) 45%, transparent)" : "var(--border)" - const sub = [hideCatalogLatency ? null : n.latency == null ? "—" : `${n.latency} мс`, n.site || n.country?.toUpperCase() || null].filter(Boolean).join(" · ") - const iso = n.country?.trim() - // Имя — от x = −24 до флага (x = 58) с зазором, без флага — до правого поля карточки. - const name = mapCardName(n.name, iso ? 74 : 94) - return ( - {if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onClick()}}} - transform={`translate(${n.x},${n.y})`} - style={{ cursor: isDragged ? "grabbing" : "grab", transition: isDragged ? "none" : "opacity 0.25s" }} - opacity={isVis ? 1 : 0.07} - onPointerDown={e => { e.stopPropagation(); onPointerDown(e) }} - onClick={e => { e.stopPropagation(); onClick() }} - onDoubleClick={e => { e.stopPropagation(); onDblClick() }} - onContextMenu={e => { e.preventDefault(); e.stopPropagation(); onContextMenu(e) }} - onMouseEnter={() => onHoverChange(true)} - onMouseLeave={() => onHoverChange(false)} - > - - - - {ts.label} - - {name.text} - {iso ? : null} - {n.status === "offline" ? "нет ответа" : sub || "—"} - {rates && - RouterOS · RX {fmtRate(rates.rxMbps)} · TX {fmtRate(rates.txMbps)} - - {compactMapRate(fmtRate(rates.rxMbps))} - - {compactMapRate(fmtRate(rates.txMbps))} - } - - ) -} function serviceMapSubtitle(service: FlowMapService): string { const top = service.trafficTypes?.[0] @@ -596,83 +534,6 @@ function serviceMapSubtitle(service: FlowMapService): string { return top.application ? shortName(`≈ ${top.application} · ${top.transport}`, 25) : top.transport } -function ServiceNode({ - label, - share, - x, - y, - isSel, - isVis, - isDragged, - destMode, - iso, - dim, - shareLabel, - category, - rate, - compact, - expanded, - onClick, - onPointerDown, -}: { - label: string - share: number | null - /** Категория сервиса под названием (у страны — «Страна»). */ - category?: string - /** Скорость за окно NetFlow справа сверху. */ - rate?: string - /** Узкая строка: раскрытая страна показывает две колонки назначений. */ - compact?: boolean - expanded?: boolean - x: number - y: number - isSel: boolean - isVis: boolean - isDragged: boolean - destMode: DestMode - iso?: string - /** Приглушение узла при раскрытии другой страны (остаётся на холсте). */ - dim?: boolean - /** Подпись доли в tooltip: у вложенных сервисов — доля страны, не окна. */ - shareLabel?: string - onClick: () => void - onPointerDown: (e: React.PointerEvent) => void -}) { - const bw = compact ? MAP_SERVICE_COMPACT_W : MAP_SERVICE_NODE_W - const bh = MAP_SERVICE_NODE_H - const hw = bw / 2 - const barW = bw - 72 - const flagIso = destMode === "countries" && iso && iso !== "Прочее" ? iso : "" - return ( - {if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onClick()}}} - transform={`translate(${x},${y})`} - style={{ cursor: expanded !== undefined ? "pointer" : isDragged ? "grabbing" : "grab" }} - opacity={isVis ? (dim ? 0.35 : 1) : 0.08} - onPointerDown={(e) => { e.stopPropagation(); onPointerDown(e) }} - onClick={(e) => { e.stopPropagation(); onClick() }} - > - {share === null ? label + " · Доля неизвестна" : `${label} · ${serviceSharePct(share)} ${shareLabel ?? "трафика окна"}`} - - {isSel && } - - - - {flagIso - ? - : expanded !== undefined ? expanded ? : - : destMode === "categories" ? - : - {shortName(label, expanded === undefined ? compact ? 8 : 18 : 28)} - {compact ? serviceSharePct(share) : category || (destMode === "countries" ? "Страна" : "Сервис")} - {!compact && rate ? {rate} : null} - {!compact ? {serviceSharePct(share)} : null} - - {share !== null && } - - ) -} function ServicePathList({ paths, @@ -733,36 +594,6 @@ function ServicePathList({ ) } -function WanSatNode({ x, y, wan, color, active, isSel, isDragged, traffic, onSelect, onPointerDown }: { - x: number; y: number - wan: { name: string; isp: string; maxDl: number; maxUl: number } - color: string; active: boolean; isSel: boolean; isDragged: boolean - traffic?: string - onSelect: () => void - onPointerDown: (e: React.PointerEvent) => void -}) { - const hw = MAP_WAN_W / 2 - return ( - {if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onSelect()}}} - transform={`translate(${x},${y})`} - style={{ cursor: isDragged ? "grabbing" : "grab" }} - onPointerDown={e => { e.stopPropagation(); onPointerDown(e) }} - onClick={e => { e.stopPropagation(); onSelect() }}> - {traffic && {traffic}} - - {isSel && } - - - - - - - {shortName(wan.isp || wan.name, 12)} - {traffic ? compactMapRate(traffic) : `${shortName(wan.name, 8)} · ↓${wan.maxDl}`} - - ) -} // ─── Context menu ───────────────────────────────────────────────────────────── @@ -812,24 +643,19 @@ function ContextMenu({ menu, onClose, trafficHref }: { menu: CtxMenu; onClose: ( // ─── Minimap ────────────────────────────────────────────────────────────────── -const MM_W = 208, MM_H = 112 +const MM_W = 95, MM_H = 52 -function Minimap({ viewportHeight, pan, zoom, nodes, greEdges, groupLinks, groups, wanPoints, wanLinks, servicePos, onClose, onPan }: { +function Minimap({ viewportWidth, viewportHeight, extent, pan, zoom, marks, onClose, onPan }: { + viewportWidth: number viewportHeight: number + extent: {left:number;top:number;width:number;height:number} pan: { x: number; y: number }; zoom: number - nodes: (Server & { x: number; y: number })[] - greEdges: {key:string;from:{x:number;y:number};to:{x:number;y:number};status:GreTunnel["status"]}[] - groupLinks: MapGroupLink[] - groups: {id:string;x:number;y:number}[] - wanPoints: {x:number;y:number;owner:string;index:number}[] - wanLinks: {key:string;link:ReturnType;edge:WanJhEdge}[] - servicePos: Record + marks: { x:number; y:number; color:string }[] onClose: () => void onPan: (x: number, y: number) => void }) { - const points = [...groups,...nodes,...wanPoints,...Object.values(servicePos)] - const left = Math.min(0,...points.map(p=>p.x-20)), top = Math.min(0,...points.map(p=>p.y-20)) - const worldWidth = Math.max(Math.max(W,...points.map(p=>p.x+20))-left,(Math.max(H,...points.map(p=>p.y+20))-top)*MM_W/MM_H) + const {left,top} = extent + const worldWidth = Math.max(extent.width,extent.height*MM_W/MM_H) const worldHeight = worldWidth*MM_H/MM_W function handleClick(e: React.MouseEvent) { @@ -837,7 +663,7 @@ function Minimap({ viewportHeight, pan, zoom, nodes, greEdges, groupLinks, group const rect = e.currentTarget.getBoundingClientRect() const svgX = left+(e.clientX - rect.left) / rect.width * worldWidth const svgY = top+(e.clientY - rect.top) / rect.height * worldHeight - onPan(svgX - W / zoom / 2, svgY - viewportHeight / zoom / 2) + onPan(svgX - viewportWidth / zoom / 2, svgY - viewportHeight / zoom / 2) } return ( @@ -847,34 +673,10 @@ function Minimap({ viewportHeight, pan, zoom, nodes, greEdges, groupLinks, group - {/* simplified edges */} - {greEdges.map((e) => ( - - ))} - {/* WAN edges */} - {wanLinks.map(({key,link,edge}) => )} - {groupLinks.map(l => )} - {groups.map(g => )} - {/* nodes */} - {nodes.map(n => ( - - ))} - {/* WAN satellites */} - {wanPoints.map(p => )} - {Object.entries(servicePos).map(([id, p]) => ( - - ))} + + {marks.map((mark,i) => )} {/* viewport rect */} - {Math.round(zoom * 100)}% + ) } @@ -1017,7 +822,7 @@ function NetworkMapContent() { const [dataError, setDataError] = useState(null) const [dataLoading, setDataLoading] = useState(false) const [hasSnapshot,setHasSnapshot]=useState(false) - const [nodeTraffic, setNodeTraffic] = useState<{ base: string; current: Map }>() + const [nodeTraffic, setNodeTraffic] = useState<{ base: string; current: Map }>() const [readAt,setReadAt]=useState(null) const reader=useRef({alive:true,epoch:0}) useEffect(()=>{const state=reader.current;state.alive=true;return()=>{state.alive=false;state.epoch++}},[]) @@ -1137,11 +942,12 @@ function NetworkMapContent() { ) // ── View state ────────────────────────────────────────────────────────────── - const [pan, setPan] = useState({ x: 0, y: 0 }) + const [requestedPan, setPan] = useState({ x: 0, y: 0 }) const [zoom, setZoom] = useState(1) - const [viewportHeight,setViewportHeight]=useState(H) const [canvasMeasured,setCanvasMeasured]=useState(false) const [canvasPx,setCanvasPx]=useState({w:0,h:0}) + const viewportWidth = canvasPx.w || 938 + const viewportHeight = canvasPx.h || 390 const [revealSearch, setRevealSearch] = useState(0) const [isDragging, setIsDragging] = useState(false) @@ -1210,20 +1016,20 @@ function NetworkMapContent() { const search=urlState.search const setFilter=(value:FilterKey)=>updateUrl({filter:value==="all"?null:value}) const setSearch=(value:string)=>updateUrl({q:value||null},true) - const [showPingBadges, setShowPingBadges] = useState(true) + const [showPingBadges, setShowPingBadges] = useState(false) const [showNetflow, setShowNetflow] = useState(true) useEffect(() => { if (!useLiveData || !hasSnapshot || !showNetflow) return const controller = new AbortController() let timer: ReturnType async function refresh() { - const current = new Map() + const current = new Map() try { const result = await apiFetch<{ servers: Array<{ id: string | number }> }>("/api/traffic/servers?range=5m", { signal: controller.signal }) for (const server of result.servers) { try { const { rxNow, txNow } = projectTrafficObservations(server) - if (rxNow !== null && txNow !== null) current.set(String(server.id), { rxMbps: rxNow, txMbps: txNow }) + if (rxNow !== null || txNow !== null) current.set(String(server.id), { rxMbps: rxNow, txMbps: txNow }) } catch { /* An invalid series cannot confirm a current speed. */ } } } finally { @@ -1239,8 +1045,8 @@ function NetworkMapContent() { const missingNetflow = !showNetflow ? "Слой выключен" : flowReadAt && !flowError ? "Нет записей" : "Нет данных" const [showServices, setShowServices] = useState(true) const reducedMotion=usePrefersReducedMotion() - const [showAnimDots, setShowAnimDots] = useState(true) - const [showMinimap, setShowMinimap] = useState(true) + const [showAnimDots, setShowAnimDots] = useState(false) + const [showMinimap, setShowMinimap] = useState(false) const [showHints, setShowHints] = useState(false) const [showAuxLinks, setShowAuxLinks] = useState(true) const [showLayers, setShowLayers] = useState(false) @@ -1314,9 +1120,7 @@ function NetworkMapContent() { } }, [useLiveData, showNetflow, showServices, apiFetch,flowRefresh]) - const compactLanes = homeRouters.length === 0 ? 180 : 0 - const baseNodePos = useMemo(() => Object.fromEntries(Object.entries(autoLayout.nodePos) - .map(([id,p]) => [id, {x:p.x - compactLanes, y:p.y}])), [autoLayout.nodePos, compactLanes]) + const baseNodePos = autoLayout.nodePos const greEdges = useMemo( () => buildGreMapEdges(mapGreTunnels, mapServers, baseNodePos, autoLayout.wanSatPos, greResolvedMap), @@ -1371,16 +1175,6 @@ function NetworkMapContent() { if (selectedGreStored.fromWanIndex != null) revealWans.add(densityWanKey(selectedGreStored.fromServer.id, selectedGreStored.fromWanIndex)) if (selectedGreStored.toWanIndex != null) revealWans.add(densityWanKey(selectedGreStored.toServer.id, selectedGreStored.toWanIndex)) } - const density = projectNetworkMapDensity(scopedServers, baseNodePos, autoLayout.wanSatPos, openedGroups, {serverIds:revealServers, wanKeys:revealWans}) - const groupById = new Map(density.groups.map(g => [g.id,g])) - const nodePosById = Object.fromEntries(mapServers.map(s => [s.id, (!density.hiddenServers.has(s.id) && nodePositions[s.id]) || density.nodePos[s.id] || baseNodePos[s.id]])) - const effectiveSatPos: Record = Object.fromEntries(homeRouters.map(router => { - const defaults = density.wanSatPos[router.id] ?? autoLayout.wanSatPos[router.id] ?? [] - const manual = satPositions[router.id] - return [router.id, defaults.map((p,i) => (!density.hiddenWans.has(densityWanKey(router.id,i)) && manual?.length === defaults.length && manual[i]) || p)] - })) - const visibleWanPoints = scopedServers.flatMap(s => (effectiveSatPos[s.id] ?? []).flatMap((p, index) => - density.hiddenWans.has(densityWanKey(s.id,index)) ? [] : [{...p, owner:s.id, index}])) function toggleGroups(ids: string[]) { setOpenedGroups(previous => { const next = new Set(previous) @@ -1604,6 +1398,27 @@ function NetworkMapContent() { const hasMinorServices = showServices && groupedServices.length > 0 const visibleMapServices = showServices && showSmallServices ? [...mainServices, ...groupedServices] : mainServices const collapsedMinorIds = new Set(showSmallServices ? [] : groupedServices.map(service => service.id)) + const projection = projectNetworkMapDensity(scopedServers, baseNodePos, autoLayout.wanSatPos, openedGroups, {serverIds:revealServers, wanKeys:revealWans}) + const destinationRows = [ + ...mainServices.map(s => ({id:s.id, name:destDisplayLabel(s,destMode)})), + ...(hasMinorServices ? [{id:"minor-services", name:showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${groupedServices.length})`}] : []), + ...(showSmallServices ? groupedServices.map(s => ({id:s.id, name:destDisplayLabel(s,destMode)})) : []), + ] + const scene = layoutNetworkMapColumns(viewportWidth,scopedServers,projection, + showUsers && usersInTopology.length ? {name:pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи"), individual:Boolean(pickedUser)} : null, + destinationRows, nestedServices.map(s => ({id:s.id,name:s.label}))) + const density = {...projection, groups:scene.groups, nodePos:scene.nodePos, wanSatPos:scene.wanSatPos} + const {cardWidths,accessPosition} = scene + const widthForServer = (type: ServerType) => cardWidths[deviceLane(type)] + const groupById = new Map(density.groups.map(g => [g.id,g])) + const nodePosById = Object.fromEntries(mapServers.map(s => [s.id, (!density.hiddenServers.has(s.id) && nodePositions[s.id]) || density.nodePos[s.id] || baseNodePos[s.id]])) + const effectiveSatPos: Record = Object.fromEntries(homeRouters.map(router => { + const defaults = density.wanSatPos[router.id] ?? autoLayout.wanSatPos[router.id] ?? [] + const manual = satPositions[router.id] + return [router.id, defaults.map((p,i) => (!density.hiddenWans.has(densityWanKey(router.id,i)) && manual?.length === defaults.length && manual[i]) || p)] + })) + const visibleWanPoints = scopedServers.flatMap(s => (effectiveSatPos[s.id] ?? []).flatMap((p, index) => + density.hiddenWans.has(densityWanKey(s.id,index)) ? [] : [{...p, owner:s.id, index}])) const visibleServiceEdges = showServices ? [ ...destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId)), ...groupDestinationEdges(destEdges, id => collapsedMinorIds.has(id) ? "minor-services" : undefined), @@ -1631,44 +1446,55 @@ function NetworkMapContent() { const nodeById = Object.fromEntries(nodes.map((n) => [n.id, n])) const visibleNodes = nodes.filter(n => !density.hiddenServers.has(n.id)) - const autoServicePos = placeServiceNodes( - [...mainServices.map((s) => s.id), ...(hasMinorServices ? ["minor-services"] : [])], - nodes - .filter((s) => s.type === "exit-node") - .map((s) => nodePosById[s.id]) - .filter((p): p is { x: number; y: number } => Boolean(p)), - ) - // Раскрытая страна: колонка стран уходит влево, правый x занимает столбец её сервисов. - const countryColShift = expandedCountryGroup ? SERVICE_COL_W : 0 - const emptyExitShift = destMode !== "countries" && nodes.some(node => node.type === "jump-host") - && !nodes.some(node => node.type === "exit-node" || node.type === "ix-node") ? 100 : 0 - const autoDestPos = Object.fromEntries(Object.entries(autoServicePos).map(([id, p]) => [id, { x: p.x - countryColShift - compactLanes - emptyExitShift, y: p.y }])) - const minorPosition = autoDestPos["minor-services"] - if (minorPosition && showSmallServices) for (const [index, service] of groupedServices.entries()) { - autoDestPos[service.id] = { x: minorPosition.x, y: minorPosition.y + (index + 1) * (MAP_SERVICE_NODE_H + 10) } - } - const servicePosById = Object.fromEntries( - visibleMapServices.map((s) => [s.id, servicePositions[s.id] ?? autoDestPos[s.id]!]), - ) - const autoNestedPos = placeCountryServiceNodes( - nestedServices.map((s) => s.id), - expandedCountryId ? servicePosById[expandedCountryId] ?? autoDestPos[expandedCountryId] : undefined, - ) - const nestedPosById = Object.fromEntries( - nestedServices - .map((s) => { - const position = autoNestedPos[s.id] - return [s.id, servicePositions[s.id] ?? (position && { x: position.x - compactLanes, y: position.y })] as const - }) - .filter((entry): entry is readonly [string, { x: number; y: number }] => Boolean(entry[1])), - ) + const minorPosition = scene.destPos["minor-services"] + const servicePosById = Object.fromEntries(visibleMapServices.map(s => [s.id, servicePositions[s.id] ?? scene.destPos[s.id]])) + const nestedPosById = Object.fromEntries(nestedServices.map(s => [s.id, servicePositions[s.id] ?? scene.nestedPos[s.id]])) // ── Refs ───────────────────────────────────────────────────────────────────── const svgRef = useRef(null) - const canvasRef=useRef(null) - const initialFit=useRef(false) - const manualCamera = useRef(false) - useEffect(()=>{const element=canvasRef.current;if(!element)return;const observer=new ResizeObserver(entries=>{const {width,height}=entries[0].contentRect;if(width<=0||height<=0)return;setViewportHeight(W*height/width);setCanvasPx({w:width,h:height});setCanvasMeasured(true)});observer.observe(element);return()=>observer.disconnect()},[]) + const scrollRef = useRef(null) + const destHalfW = (expandedCountryGroup ? cardWidths.nested : cardWidths.dest) / 2 + function boxAt(point: { x:number; y:number }, name: string, kind: Parameters[1], w: number): MapBox { + const h = mapCardMetrics(name, kind, w).height + return {x:point.x-w/2, y:point.y-h/2, w, h} + } + const mapObstacles: MapBox[] = [ + ...visibleNodes.map(n => boxAt(n, n.name, "device", widthForServer(n.type))), + ...density.groups.map(g => boxAt(g, g.label, "group", g.kind === "wan" ? cardWidths.wan : widthForServer(g.type))), + ...(showUsers && usersInTopology.length ? [boxAt(accessPosition,pickedUser?.name ?? (ixOnly ? "Linux-клиенты" : "Пользователи"),pickedUser ? "user" : "access",cardWidths.access)] : []), + ...(minorPosition ? [boxAt(minorPosition,showSmallServices ? "Свернуть остальные" : `Остальные сервисы (${groupedServices.length})`,"destination",2*destHalfW)] : []), + ...visibleWanPoints.map(p => { const wan = nodeById[p.owner]?.wanUplinks?.[p.index]; return boxAt(p,wan?.isp || wan?.name || "WAN","wan",cardWidths.wan) }), + ...visibleMapServices.flatMap(s => servicePosById[s.id] ? [boxAt(servicePosById[s.id],destDisplayLabel(s,destMode),"destination",2*destHalfW)] : []), + ...nestedServices.flatMap(s => nestedPosById[s.id] ? [boxAt(nestedPosById[s.id],s.label,"destination",cardWidths.nested)] : []), + ] + const worldLeft = Math.min(0, ...mapObstacles.map(box => box.x - 6)) + const worldTop = Math.min(0, ...mapObstacles.map(box => box.y - 6)) + const worldWidth = Math.max(scene.worldWidth, ...mapObstacles.map(box => box.x + box.w + 6)) - worldLeft + const worldHeight = Math.max(scene.worldHeight, ...mapObstacles.map(box => box.y + box.h + 6)) - worldTop + const clampX = (x:number) => Math.max(worldLeft,Math.min(x,worldLeft+worldWidth-viewportWidth/zoom)) + const pan = {x:clampX(requestedPan.x),y:Math.max(worldTop,Math.min(requestedPan.y,worldTop+worldHeight-viewportHeight/zoom))} + useEffect(() => { + const element = scrollRef.current + if (!element) return + const observer = new ResizeObserver(() => { + const w=element.clientWidth, h=element.clientHeight + if (w && h) {setCanvasPx(last => last.w===w && last.h===h ? last : {w,h});setCanvasMeasured(true)} + }) + observer.observe(element) + return () => observer.disconnect() + }, []) + useLayoutEffect(() => { + const el=scrollRef.current + if (!el) return + const x=(pan.x-worldLeft)*zoom,y=(pan.y-worldTop)*zoom + if (Math.abs(el.scrollLeft-x)>0.75) el.scrollLeft=x + if (Math.abs(el.scrollTop-y)>0.75) el.scrollTop=y + }, [pan.x,pan.y,zoom,worldLeft,worldTop]) + function onViewportScroll(e:React.UIEvent) { + const {scrollLeft,scrollTop}=e.currentTarget + if (Math.abs(scrollLeft-(pan.x-worldLeft)*zoom)<1 && Math.abs(scrollTop-(pan.y-worldTop)*zoom)<1) return + setPan({x:worldLeft+scrollLeft/zoom,y:worldTop+scrollTop/zoom}) + } // Canvas pan drag const dragRef = useRef<{ @@ -1690,27 +1516,29 @@ function NetworkMapContent() { const zoomRef = useRef(zoom) const panRef = useRef(pan) - useEffect(()=>{zoomRef.current=zoom;panRef.current=pan},[zoom,pan]) + useEffect(()=>{zoomRef.current=zoom;panRef.current={x:pan.x,y:pan.y}},[zoom,pan.x,pan.y]) // ── SVG export ─────────────────────────────────────────────────────────── function exportSvg() { const svg = svgRef.current if (!svg) return const clone = svg.cloneNode(true) as SVGSVGElement - const x = Math.min(0, ...mapObstacles.map(box => box.x - 20)) - const y = Math.min(0, lanesTop - 16, ...observationTracks.map(track => track - 20)) - const width = Math.ceil(Math.max(W, ...mapObstacles.map(box => box.x + box.w + 20)) - x) - const height = Math.ceil(Math.max(H, lanesBottom + 16, ...observationTracks.map(track => track + 20)) - y) - clone.querySelectorAll(".network-map-focus-ring").forEach(ring => ring.remove()) + const x = Math.min(worldLeft, ...mapObstacles.map(box => box.x)) + const y = Math.min(worldTop, ...observationTracks.map(track => track - 10)) + const width = Math.ceil(Math.max(worldLeft+worldWidth, ...mapObstacles.map(box => box.x+box.w)) - x) + const height = Math.ceil(Math.max(worldTop+worldHeight, ...observationTracks.map(track => track+10)) - y) + const exportWidth = Math.max(NETWORK_MAP_W,width), exportHeight = Math.round(height*exportWidth/width) + clone.querySelectorAll(".network-map-focus-ring,[data-map-runtime-badge]").forEach(node => node.remove()) + clone.querySelectorAll("[data-map-export-badge]").forEach(badge => badge.removeAttribute("display")) clone.setAttribute("viewBox", `${x} ${y} ${width} ${height}`) - clone.setAttribute("width", String(width)) - clone.setAttribute("height", String(height)) + clone.setAttribute("width", String(exportWidth)) + clone.setAttribute("height", String(exportHeight)) clone.setAttribute("xmlns","http://www.w3.org/2000/svg") const computed=getComputedStyle(svg) const variables=new Set([...clone.outerHTML.matchAll(/var\((--[a-zA-Z0-9_-]+)/g)].map(match=>match[1])) variables.add("--background") for(const name of variables){const value=computed.getPropertyValue(name).trim();if(!value)continue;clone.style.setProperty(name,value);for(const match of value.matchAll(/var\((--[a-zA-Z0-9_-]+)/g))variables.add(match[1])} - clone.style.width=width+"px";clone.style.height=height+"px" + clone.style.width=exportWidth+"px";clone.style.height=exportHeight+"px" const background=document.createElementNS("http://www.w3.org/2000/svg","rect") background.setAttribute("x",String(x));background.setAttribute("y",String(y));background.setAttribute("width",String(width));background.setAttribute("height",String(height));background.setAttribute("fill","var(--background)");clone.prepend(background) const grid = clone.querySelector("[data-map-background]") @@ -1732,20 +1560,20 @@ function NetworkMapContent() { const svg = svgRef.current if (!svg) return const handler = (e: WheelEvent) => { - manualCamera.current = true + if (!e.ctrlKey && !e.metaKey) return e.preventDefault() const z = zoomRef.current const p = panRef.current const rect = svg.getBoundingClientRect() - const svgX = p.x + (e.clientX - rect.left) / rect.width * (W / z) - const svgY = p.y + (e.clientY - rect.top) / rect.height * ((W * rect.height / rect.width) / z) + const svgX = p.x + (e.clientX - rect.left) / z + const svgY = p.y + (e.clientY - rect.top) / z // trackpad pinch sends ctrlKey, use smaller step const step = e.ctrlKey ? 1.06 : 1.14 const factor = e.deltaY < 0 ? step : 1 / step const newZoom = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z * factor)) setPan({ - x: svgX - (e.clientX - rect.left) / rect.width * (W / newZoom), - y: svgY - (e.clientY - rect.top) / rect.height * ((W * rect.height / rect.width) / newZoom), + x: svgX - (e.clientX - rect.left) / newZoom, + y: svgY - (e.clientY - rect.top) / newZoom, }) setZoom(newZoom) } @@ -1757,120 +1585,42 @@ function NetworkMapContent() { // ── Zoom helpers ────────────────────────────────────────────────────────── const applyZoomCenter=useCallback((factor: number) => { - manualCamera.current = true const newZoom = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom * factor)) - setPan(p => ({ - x: p.x + (W / zoom - W / newZoom) / 2, - y: p.y + (viewportHeight / zoom - viewportHeight / newZoom) / 2, - })) + setPan({x:pan.x + (viewportWidth / zoom - viewportWidth / newZoom) / 2, + y:pan.y + (viewportHeight / zoom - viewportHeight / newZoom) / 2}) setZoom(newZoom) - },[zoom,viewportHeight]) + },[zoom,viewportWidth,viewportHeight,pan.x,pan.y]) - // Миникарта — только на широком холсте; снизу резервируем полосу под неё и панель масштаба. - const accessPosition = { x: homeRouters.some(router => onMap(router.id)) ? -105 : MAP_LANES.home.cx, - y: Math.max(80, [...accessGroups.keys()].reduce((sum, id) => sum + (nodePosById[id]?.y ?? 0), 0) / (accessGroups.size || 1)) } const detailsOpen = Boolean(selected || activeService || selectedGreEdge || userDetailsOpen) - const sideInspector = canvasPx.w >= 620 && detailsOpen - const minimapVisible = showMinimap && canvasPx.w >= 640 && !detailsOpen - const overlayReserve = canvasPx.h ? ((minimapVisible ? 112 : 36) + 20) / canvasPx.h + (detailsOpen && !sideInspector ? 0.35 : 0) : 0 - const fitWidth = sideInspector ? W * (1 - 302 / canvasPx.w) : W - const narrowCanvas = canvasMeasured && canvasPx.w < 620 - const destBounds = { x0: MAP_LANES.dest.x0 - emptyExitShift, x1: MAP_LANES.dest.x1 - emptyExitShift } - const mapLanes = [ - { id: "access", label: "Подключения", points: showUsers && usersInTopology.length ? [accessPosition] : [], - bounds: {x0: accessPosition.x - 96 + compactLanes, x1: accessPosition.x + 96 + compactLanes} }, - { id: "home", label: "Домашние роутеры", points: nodes.filter(n => n.type === "home-router"), bounds: MAP_LANES.home }, - { id: "wan", label: "Аплинки WAN", points: [...visibleWanPoints, ...density.groups.filter(group => group.kind === "wan")], - count: nodes.reduce((sum, node) => sum + (node.wanUplinks?.length ?? 0), 0), bounds: MAP_LANES.wan }, - { id: "access-nodes", label: "Узлы доступа", points: nodes.filter(n => n.type === "jump-host"), bounds: MAP_LANES.jh }, - { id: "exits", label: ixOnly ? "IX" : nodes.some(n => n.type === "ix-node") ? "Интернет-выходы и IX" : "Интернет-выходы", - points: nodes.filter(n => n.type === "exit-node" || n.type === "ix-node"), bounds: MAP_LANES.en }, - { id: "destinations", label: destMode === "countries" ? "Страны" : destMode === "categories" ? "Категории" : "Сервисы", - points: [...Object.values(servicePosById), ...(minorPosition ? [minorPosition] : [])], - bounds: expandedCountryGroup ? {...destBounds, x1: MAP_LANES.dest.cx - 24} : destBounds }, - { id: "nested", label: destMode === "categories" ? "Сервисы категории" : "Сервисы страны", points: Object.values(nestedPosById), - bounds: {x0: MAP_LANES.dest.cx - 24, x1: MAP_LANES.dest.x1} }, - ].filter(lane => lane.points.length).map(lane => ({ - ...lane, anchor: lane.points.reduce((first, p) => p.y < first.y ? p : first), - })) - const currentLane = mapLanes.reduce((nearest, lane, index) => { - const center = pan.x + W / (2 * zoom) - return Math.abs(lane.anchor.x - center) < Math.abs(mapLanes[nearest].anchor.x - center) ? index : nearest - }, 0) - const centerCamera = useCallback((x: number, y: number, z: number, hasDetails = false, usableWidth = W) => { - setPan({ x: x - usableWidth / (2 * z), y: y - viewportHeight * (hasDetails ? 0.28 : 0.44) / z }) - setZoom(z) - }, [viewportHeight]) + const minimapVisible = showMinimap && canvasPx.w >= 600 && !detailsOpen + const mapLanes = scene.columns.map(column => { + const labels = {access:ixOnly ? "Linux-клиенты" : "Подключения", home:"Домашние роутеры", wan:"Аплинки WAN", + jh:"Узлы доступа", en:ixOnly ? "IX" : "Интернет-выходы", dest:destMode === "countries" ? "Страны" : destMode === "categories" ? "Категории трафика" : "Сервисы", + nested:"Сервисы страны"} + const id = column.id + const count = id === "access" ? pickerUsers.length : id === "dest" ? destNodes.length : id === "nested" ? nestedServices.length : + id === "wan" ? scopedServers.reduce((sum,n) => sum + (n.wanUplinks?.length ?? 0),0) : scopedServers.filter(s => deviceLane(s.type) === id).length + return {...column, id:id === "jh" ? "access-nodes" : id === "en" ? "exits" : id === "dest" ? "destinations" : id, label:labels[id], count} + }) + const narrowCanvas = canvasMeasured && worldWidth * zoom > viewportWidth + 2 + const [navigation, setNavigation] = useState<{id:string;x:number} | null>(null) + const firstInView = mapLanes.findIndex(lane => lane.x1 > pan.x + 12 / zoom) + const chosenLane = navigation && Math.abs(clampX(navigation.x)-pan.x)*zoom < 2 ? mapLanes.findIndex(lane => lane.id === navigation.id) : -1 + const currentLane = chosenLane >= 0 ? chosenLane : Math.max(0, firstInView) + function navigateLane(index: number) { - const point = mapLanes[index]?.anchor - if (point) centerCamera(point.x, point.y, zoom, detailsOpen) - } - function selectedTunnelCenter(edge: GreMapEdge) { - const from = (edge.fromWanIndex != null ? effectiveSatPos[edge.fromServer.id]?.[edge.fromWanIndex] : nodePosById[edge.fromServer.id]) ?? edge.from - const to = (edge.toWanIndex != null ? effectiveSatPos[edge.toServer.id]?.[edge.toWanIndex] : nodePosById[edge.toServer.id]) ?? edge.to - return {x: (from.x + to.x) / 2, y: (from.y + to.y) / 2} - } - const mobileObject = selected && selWanIdx !== null ? effectiveSatPos[selected.id]?.[selWanIdx] - : selected ? nodePosById[selected.id] : activeService ? nestedPosById[activeService.id] ?? servicePosById[activeService.id] - : selectedGreEdge ? selectedTunnelCenter(selectedGreEdge) - : pickedUser ? accessPosition : undefined - const mobileObjectKey = selected ? `server/${selected.id}/${selWanIdx ?? ""}` : activeService ? "destination/" + activeService.id - : selectedGreEdge ? "gre/" + greEdgeKey(selectedGreEdge) : pickedUser ? "user/" + pickedUser.id : "" - const mobileScope = JSON.stringify([ixOnly, pickedUserId, filteredServiceId]) - const mobileCameraState = useRef<{scope: string; object: string; search: number} | null>(null) - const mobileStart = mapLanes[0]?.anchor - const mobileX = mobileObject?.x ?? mobileStart?.x - const mobileY = mobileObject?.y ?? mobileStart?.y - const locatedObject = mobileObject ? mobileObjectKey : "" - useEffect(() => { - if (!narrowCanvas) { mobileCameraState.current = null; return } - if (mobileX == null || mobileY == null) return - const previous = mobileCameraState.current - mobileCameraState.current = {scope: mobileScope, object: locatedObject, search: revealSearch} - if (previous?.scope === mobileScope && (!locatedObject || previous.object === locatedObject && previous.search === revealSearch)) return - const scale = Math.min(ZOOM_MAX, Math.max(W / canvasPx.w, previous ? zoomRef.current : 1)) - queueMicrotask(() => centerCamera(mobileX, mobileY, scale, Boolean(locatedObject))) - }, [narrowCanvas, mobileScope, locatedObject, revealSearch, mobileX, mobileY, canvasPx.w, centerCamera]) - const {pan:{x:fitX,y:fitY},zoom:fitZoom}=fitNetworkMapCamera([...visibleNodes,...density.groups,...visibleWanPoints,...(showUsers && usersInTopology.length ? [accessPosition] : []),...(minorPosition ? [minorPosition] : []),...Object.values(servicePosById).map(p=>({x:p.x+(expandedCountryGroup?MAP_SERVICE_COMPACT_W:MAP_SERVICE_NODE_W)/2-100,y:p.y})),...Object.values(nestedPosById).map(p=>({x:p.x+MAP_SERVICE_COMPACT_W/2-100,y:p.y}))],fitWidth,viewportHeight,overlayReserve) - function fitView(){manualCamera.current=false;setPan({x:fitX,y:fitY});setZoom(fitZoom)} - useEffect(()=>{if(narrowCanvas||initialFit.current||!canvasMeasured||!mapServers.length)return;initialFit.current=true;queueMicrotask(()=>{setPan({x:fitX,y:fitY});setZoom(fitZoom)})},[narrowCanvas,canvasMeasured,mapServers.length,fitX,fitY,fitZoom]) - const viewKey = `${ixOnly}:${destMode}:${pickedUserId ?? ""}:${filteredServiceId ?? ""}:${showSmallServices}:${fitWidth !== W}:${showUsers}:${Math.round(canvasPx.w)}x${Math.round(canvasPx.h)}` - const availabilityKey = `${splitIx}:${Boolean(recent?.data)}:${usersInTopology.length > 0}` - const lastViewKey = useRef(viewKey) - const lastAvailability = useRef(availabilityKey) - const lastUserView = useRef(pickedUser?.id) - useEffect(() => { - const newView = lastViewKey.current !== viewKey - const dataChanged = lastAvailability.current !== availabilityKey - lastViewKey.current = viewKey - lastAvailability.current = availabilityKey - if (!newView && (!dataChanged || manualCamera.current)) return - if (!narrowCanvas) queueMicrotask(() => { setPan({ x: fitX, y: fitY }); setZoom(fitZoom) }) - if (lastUserView.current !== pickedUser?.id) { - lastUserView.current = pickedUser?.id - if (!reducedMotion) svgRef.current?.animate([{ opacity: 0.6 }, { opacity: 1 }], { duration: 200, easing: "cubic-bezier(0.22,1,0.36,1)" }) + const lane = mapLanes[index] + if (lane) { + setNavigation({id:lane.id,x:lane.x0}) + setPan({x:lane.x0, y:pan.y}) } - }, [viewKey, availabilityKey, fitX, fitY, fitZoom, pickedUser?.id, reducedMotion, narrowCanvas]) - - const desktopFocus = useRef({ object: "", search: 0 }) - const selectedInGroup = Boolean(selected && density.groups.some(group => group.expanded && group.serverIds.includes(selected.id))) - useEffect(() => { - if (!canvasMeasured || narrowCanvas || !locatedObject || mobileX == null || mobileY == null) { - desktopFocus.current.object = "" - return - } - const previous = desktopFocus.current - desktopFocus.current = {object: locatedObject, search: revealSearch} - if (previous.search === revealSearch && (!selectedInGroup || previous.object === locatedObject)) return - manualCamera.current = true - const scale = Math.min(ZOOM_MAX, Math.max(zoomRef.current, W / canvasPx.w)) - queueMicrotask(() => centerCamera(mobileX, mobileY, scale, false, fitWidth)) - }, [canvasMeasured, narrowCanvas, locatedObject, mobileX, mobileY, revealSearch, selectedInGroup, canvasPx.w, centerCamera, fitWidth]) - + } + const fitZoom = Math.max(ZOOM_MIN,Math.min(1,viewportWidth/worldWidth,(viewportHeight-(minimapVisible?72:0))/worldHeight)) + const fitX = worldLeft, fitY = worldTop + function fitView(){setNavigation(null);setPan({x:fitX,y:fitY});setZoom(fitZoom)} function focusNode(x: number, y: number) { - manualCamera.current = true - const newZoom = Math.min(ZOOM_MAX, Math.max(zoom * 1.8, 2)) - centerCamera(x, y, newZoom, narrowCanvas && detailsOpen, fitWidth) + const z = Math.min(ZOOM_MAX,Math.max(zoom,1)) + setPan({x:x-viewportWidth/(2*z),y:y-viewportHeight/(2*z)});setZoom(z) } // ── Keyboard shortcuts ──────────────────────────────────────────────────── @@ -1889,7 +1639,7 @@ function NetworkMapContent() { } if (e.key === "=" || e.key === "+") applyZoomCenter(1.25) if (e.key === "-") applyZoomCenter(1 / 1.25) - if (e.key === "0" || e.key.toLowerCase() === "f") {manualCamera.current=false;setPan({x:fitX,y:fitY});setZoom(fitZoom)} + if (e.key === "0" || e.key.toLowerCase() === "f") {setNavigation(null);setPan({x:fitX,y:fitY});setZoom(fitZoom)} if (e.key.toLowerCase() === "m") setShowMinimap(v => !v) if (e.key.toLowerCase() === "p") setShowPingBadges(v => !v) } @@ -1915,9 +1665,8 @@ function NetworkMapContent() { const dx = e.clientX - nd.startX const dy = e.clientY - nd.startY if (Math.abs(dx) > 2 || Math.abs(dy) > 2) nd.moved = true - const rect = e.currentTarget.getBoundingClientRect() - const svgDx = dx * (W / zoom) / rect.width - const svgDy = dy * (viewportHeight / zoom) / rect.height + const svgDx = dx / zoom + const svgDy = dy / zoom const nx = nd.origX + svgDx const ny = nd.origY + svgDy @@ -1939,11 +1688,9 @@ function NetworkMapContent() { const dx = e.clientX - dragRef.current.startX const dy = e.clientY - dragRef.current.startY if (Math.abs(dx) > 4 || Math.abs(dy) > 4) dragRef.current.moved = true - if (dragRef.current.moved) manualCamera.current = true - const rect = e.currentTarget.getBoundingClientRect() setPan({ - x: dragRef.current.panX - dx * (W / zoom / rect.width), - y: dragRef.current.panY - dy * (viewportHeight / zoom / rect.height), + x: dragRef.current.panX - dx / zoom, + y: dragRef.current.panY - dy / zoom, }) } @@ -2177,15 +1924,17 @@ function NetworkMapContent() { // ── Связи макета v3: линия + одна «таблетка» на связь; подписи раскладываются без наложений. const rttLabel = (ms: number | null) => (ms == null ? "—" : `${ms} мс`) const groupedConnections: MapGroupConnection[] = [] + let faultRow = 0 + const nextFaultTrack = () => 49 + Math.min(faultRow++, 2) * 15 function endpoint(id: string, index?: number | null): GroupLinkEnd { const server = nodeById[id] const wan = index != null ? server.wanUplinks?.[index] : undefined const wanKey = index != null ? densityWanKey(id,index) : null const groupId = (wanKey && density.hiddenWans.get(wanKey)) || density.hiddenServers.get(id) const group = groupId ? groupById.get(groupId) : undefined - if (group) return {id:group.id, name:group.label, x:group.x, y:group.y, halfWidth:MAP_CARD_W/2, groupId:group.id} + if (group) return {id:group.id, name:group.label, x:group.x, y:group.y, halfWidth:(group.kind === "wan" ? cardWidths.wan : widthForServer(group.type))/2, groupId:group.id} const point = index != null && effectiveSatPos[id]?.[index] || server - return {id:wanKey ? "wan:"+wanKey : "server:"+id, name:wan?.name ?? server.name, x:point.x, y:point.y, halfWidth:(wan ? MAP_WAN_W : MAP_CARD_W)/2} + return {id:wanKey ? "wan:"+wanKey : "server:"+id, name:wan?.name ?? server.name, x:point.x, y:point.y, halfWidth:(wan ? cardWidths.wan : widthForServer(server.type))/2} } function groupedConnection(row: MapGroupConnection) { if (!row.from.groupId && !row.to.groupId) return false @@ -2211,7 +1960,6 @@ function NetworkMapContent() { opacity: dimmed ? 0.05 : highlightedPath ? greMatchesPath(e, highlightedPath) ? 1 : 0.16 : activeService ? selectedDestPaths.some(path => greMatchesPath(e, path)) ? 1 : 0.2 : selected && selected.id !== e.fromServer.id && selected.id !== e.toServer.id ? 0.3 : 1, - link: mapLinkPath(from,from.halfWidth,to,to.halfWidth), }] }) const busiestLiveLink = showNetflow ? liveTrafficTargets.reduce<{ name: string; bps: number; bpsFwd: number; bpsRev: number } | undefined>((best, target) => { @@ -2231,10 +1979,13 @@ function NetworkMapContent() { const lead = group.find(({e}) => channelStatus(e) === "down") ?? group.find(({e}) => channelStatus(e) === "degraded") ?? group.find(g => greTunnelIdsWithMapBadge.has(g.id)) ?? group[0] - return {group,counts,health,lead} + const {from,to} = lead.e + const link = mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles:mapObstacles, faultY:health === "up" ? undefined : nextFaultTrack()}) + return {group,counts,health,lead,link} }) // Полная подпись связи — в title линии: короткая «таблетка» может не влезть между карточками. const greLinkTitle = new Map() + const greLinkHint = new Map() const maxPerGreOwner = (edges: typeof greLinks, getValue: (edge: typeof greLinks[number]) => number | undefined) => { const totals = new Map() for (const edge of edges) { @@ -2246,7 +1997,7 @@ function NetworkMapContent() { } return totals.size ? Math.max(...totals.values()) : null } - const greLabels = greGroups.flatMap(({group,counts,health,lead}) => { + const greLabels = greGroups.flatMap(({group,counts,health,lead,link}) => { // Distinct tunnel pairs can have a different reporting owner even when they share one line. const links = [...group.reduce((m, g) => { const key = g.e.ambiguousPeerKey ?? g.id @@ -2264,14 +2015,12 @@ function NetworkMapContent() { : flowBps != null ? `≈${formatNetflowRate({ bps: flowBps })}` : "" const rtt = showPingBadges && lead.merged.pingMs != null ? rttLabel(lead.merged.pingMs) : "" const many = count > 1 ? `GRE ×${count}` : "" - // «—» — только когда не известно ничего: известное, но не влезающее значение не подменяем прочерком. - const texts = down ? ["нет связи"] : counts.down ? [`Недоступно ${counts.down} из ${count}`,`↓ ${counts.down}/${count}`] : counts.degraded ? [`Деградация ${counts.degraded} из ${count}`,`! ${counts.degraded}/${count}`] : rtt || rate || many ? [...new Set([ - rate || rtt || many, - compactMapRate(rate), many, - ].filter(Boolean))] : ["—"] - const fullText = [health !== "up" ? texts[0] : rate || rtt, many].filter(Boolean).join(" · ") || "—" - for (const g of group) greLinkTitle.set(g.id, `Связь ${lead.e.fromServer.name} → ${lead.e.toServer.name}: ${fullText}`) - if (health === "up" && ((!showPingBadges && !showNetflow) || selected && !group.some(({ e }) => e.fromServer.id === selected.id || e.toServer.id === selected.id))) return [] + const issue = down ? count === 1 ? "Канал недоступен" : `Недоступно каналов · ${count} из ${count}` : counts.down ? `${counts.down} из ${count} каналов ${ruPlural(counts.down,"недоступен","недоступны","недоступны")}` : counts.degraded ? `Деградация ${counts.degraded} из ${count}` : "" + const focused = group.some(({e,id}) => selectedGreEdge && greEdgeKey(selectedGreEdge) === id || selected?.id === e.fromServer.id || selected?.id === e.toServer.id || highlightedPath && greMatchesPath(e,highlightedPath)) + const texts = issue ? ["GRE · " + issue,issue,`${counts.down || counts.degraded}/${count}`] : [ + [many || "GRE", compactMapRate(rate), rtt].filter(Boolean).join(" · "), compactMapRate(rate) || rtt, + ].filter(Boolean) + const fullText = [health !== "up" ? texts[0] : rate || rtt, many].filter(Boolean).join(" · ") || "GRE" const outer = greOuterSummaryLine(lead.e.tunnel, nodeById[lead.e.fromServer.id], nodeById[lead.e.toServer.id], greResolvedMap) const hint = (outer ? outer + ". " : "") + @@ -2281,8 +2030,11 @@ function NetworkMapContent() { (showNetflow && liveBps != null ? `RouterOS Live · ${formatNetflowRate({ bps: liveBps })}. ` : "") + (flow ? `NetFlow · ${mapWindow}: ${formatNetflowRate(flow)} (${formatNetflowDir(flow)}). ` : flowBps != null ? `NetFlow · ${mapWindow}: ${formatNetflowRate({ bps: flowBps })} по ${count} туннелям. ` : "") + "Клик — панель справа." + greLinkTitle.set(lead.id, `Связь ${lead.e.fromServer.name} → ${lead.e.toServer.name}: ${fullText}`) + greLinkHint.set(lead.id, hint) + if (health === "up" && (!rtt && !rate && !focused || lead.opacity < 1)) return [] return [{ - id: "gre:" + lead.id, link: lead.link, texts, hint, open: lead.open, fullText, + id: "gre:" + lead.id, link, texts, hint, open: lead.open, fullText, fault: Boolean(issue), opacity: Math.max(...group.map((g) => g.opacity)), tone: down ? "er" as const : health === "degraded" ? "wn" as const : !rtt && !rate ? "mu" as const : "fg" as const, name: `${lead.e.fromServer.name} → ${lead.e.toServer.name}`, @@ -2295,13 +2047,13 @@ function NetworkMapContent() { const key = wanJhEdgeMapKey(edge) const sp = speedProbeByWanJhKey.get(key) const merged = mergeGreMetricsWithSpeedProbe(sp, { pingMs: useLiveData ? null : edge.pingMs, dlMbps: null, ulMbps: null }) - return [{ edge, key, sp, merged, jh, link: mapLinkPath(sat, MAP_WAN_W / 2, jh, MAP_CARD_W / 2) }] + return [{ edge, key, sp, merged, jh, link: mapLinkPath(sat, cardWidths.wan / 2, jh, widthForServer(jh.type) / 2, {obstacles:mapObstacles}) }] }) const wanLabels = wanLinks.flatMap(({ edge, key, sp, merged, jh, link }) => { const vis = filter === "all" || filter === "home-router" || filter === "jump-host" || filter === "online" const hl = selected?.id === edge.homeId && (selWanIdx === null || selWanIdx === edge.wanIdx) const suppressed = merged.hasSpeedMonitor ? suppressWanJhSpeedBadgeDuplicate.has(key) : suppressWanJhPingBadge.has(key) - const rtt = showPingBadges && !suppressed ? rttLabel(merged.pingMs) : "" + const rtt = showPingBadges && !suppressed && merged.pingMs != null ? rttLabel(merged.pingMs) : "" if (!rtt) return [] return [{ id: "wan:" + key, link, texts: [rtt], opacity: vis ? (hl ? 1 : 0.6) : 0.05, @@ -2311,45 +2063,69 @@ function NetworkMapContent() { open: merged.hasSpeedMonitor ? (ev: React.SyntheticEvent) => openWanJhSpeedDetail(ev, edge) : undefined, }] }) - const destHalfW = (expandedCountryGroup ? MAP_SERVICE_COMPACT_W : MAP_SERVICE_NODE_W) / 2 const accessLinks = [...accessGroups].flatMap(([id, users]) => { const target = nodeById[id] if (!target || !isVisible(target)) return [] - if (groupedConnection({from:{...accessPosition,id:"access:users",name:pickedUser?.name ?? "Пользователи",halfWidth:MAP_CARD_W/2},to:endpoint(id),type:"user",count:users.length})) return [] + if (groupedConnection({from:{...accessPosition,id:"access:users",name:pickedUser?.name ?? "Пользователи",halfWidth:cardWidths.access/2},to:endpoint(id),type:"user",count:users.length})) return [] const bindings = pickedUser?.bindings.filter(binding => binding.node === id) ?? [] const rate = accessRate(bindings, access.rates) - const text = pickedUser ? showNetflow && rate.measured ? rate.label : "" : `${users.length} чел.` - const link = mapLinkPath(accessPosition, MAP_CARD_W / 2, target, MAP_CARD_W / 2) + const text = pickedUser && showNetflow && rate.measured ? rate.label : "" + const link = mapLinkPath(accessPosition, cardWidths.access / 2, target, widthForServer(target.type) / 2, {obstacles:mapObstacles}) return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`, opacity: bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1, tone: "fg" as const, hint: pickedUser ? `RouterOS · RX ${fmtRate(rate.measured ? rate.rx : null)} · TX ${fmtRate(rate.measured ? rate.tx : null)} · ${rate.measured}/${rate.total} замеров` : "Привязки из каталога пользователей", open: () => { if (pickedUser) { setSelected(null); setSelectedGreEdge(null); setSelectedService(null); setInspectUser(true) } else setUserPicker(true) }, }] }) - // Карточки, аплинки и строки назначений — препятствия для подписей. - const mapObstacles: MapBox[] = [ - ...[...visibleNodes,...density.groups].map((n) => ({ x: n.x - MAP_CARD_W / 2, y: n.y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })), - ...(showUsers && usersInTopology.length ? [{ x: accessPosition.x - MAP_CARD_W / 2, y: accessPosition.y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H }] : []), - ...(minorPosition ? [{ x: minorPosition.x - destHalfW, y: minorPosition.y - MAP_SERVICE_NODE_H / 2, w: 2 * destHalfW, h: MAP_SERVICE_NODE_H }] : []), - ...visibleWanPoints.map(p => ({x:p.x - MAP_WAN_W/2,y:p.y - MAP_WAN_H/2,w:MAP_WAN_W,h:MAP_WAN_H})), - ...visibleMapServices.flatMap((s) => servicePosById[s.id] ? [{ x: servicePosById[s.id].x - destHalfW, y: servicePosById[s.id].y - MAP_SERVICE_NODE_H / 2, w: destHalfW * 2, h: MAP_SERVICE_NODE_H }] : []), - ...(expandedCountryGroup ? nestedServices : []).flatMap((s) => nestedPosById[s.id] ? [{ x: nestedPosById[s.id].x - MAP_SERVICE_COMPACT_W / 2, y: nestedPosById[s.id].y - MAP_SERVICE_NODE_H / 2, w: MAP_SERVICE_COMPACT_W, h: MAP_SERVICE_NODE_H }] : []), - ] const observationTracks: number[] = [] const destRibbons = [...visibleServiceEdges].sort((a, b) => Number(b.toId === activeService?.id) - Number(a.toId === activeService?.id) || b.bps - a.bps || a.fromId.localeCompare(b.fromId) || a.toId.localeCompare(b.toId), ).flatMap(edge => { const from = nodeById[edge.fromId], to = edge.toId === "minor-services" ? minorPosition : servicePosById[edge.toId] if (!from || !to) return [] - const direct = edge.observedOnly || from.type === "jump-host" || from.type === "home-router" + const direct = Boolean(edge.observedOnly) if (direct && !showAuxLinks) return [] if (groupedConnection({from:endpoint(edge.fromId),to:{...to,id:"dest:"+edge.toId,name:edge.toId === "minor-services" ? "Остальные сервисы" : destNodes.find(s=>s.id===edge.toId)?.label ?? edge.toId,halfWidth:destHalfW},type:direct?"observation":"service"})) return [] - const link = mapLinkPath(from, MAP_CARD_W / 2, to, destHalfW) + const link = mapLinkPath(from, widthForServer(from.type) / 2, to, destHalfW, {obstacles:mapObstacles}) const detour = direct ? mapObservationRoute(link, mapObstacles, observationTracks) : null if (detour) observationTracks.push(detour.track) return [{ edge, direct, detour, link }] }) const observationMarkers = destRibbons.flatMap(({ edge, detour }) => edge.observedOnly && detour?.marker ? [{ x: detour.marker.x - 17, y: detour.marker.y - 7, w: 34, h: 14 }] : []) - const linkLabels = placeMapLinkLabels([...accessLinks.filter(link => link.texts[0]), ...greLabels, ...wanLabels], [...mapObstacles, ...observationMarkers]) + const linkLabels = placeMapLinkLabels([...greLabels.sort((a,b) => Number(b.fault)-Number(a.fault)), ...accessLinks.filter(link => link.texts[0]), ...wanLabels], [...mapObstacles, ...observationMarkers]) + function selectedTunnelCenter(edge: GreMapEdge) { + const key = greEdgeKey(edge) + const channel = greGroups.find(({group}) => group.some(item => item.id === key)) + if (channel) { + const badge = linkLabels.find(label => label.id === "gre:" + channel.lead.id) + return badge ?? mapLinkPoint(channel.link, 0.5) + } + const from = (edge.fromWanIndex != null ? effectiveSatPos[edge.fromServer.id]?.[edge.fromWanIndex] : nodePosById[edge.fromServer.id]) ?? edge.from + const to = (edge.toWanIndex != null ? effectiveSatPos[edge.toServer.id]?.[edge.toWanIndex] : nodePosById[edge.toServer.id]) ?? edge.to + return {x:(from.x+to.x)/2, y:(from.y+to.y)/2} + } + const objectPoint = selected && selWanIdx !== null ? effectiveSatPos[selected.id]?.[selWanIdx] + : selected ? nodePosById[selected.id] : activeService ? nestedPosById[activeService.id] ?? servicePosById[activeService.id] + : selectedGreEdge ? selectedTunnelCenter(selectedGreEdge) : pickedUser ? accessPosition : undefined + const cameraObjectKey = selected ? `server/${selected.id}/${selWanIdx ?? ""}` : activeService ? "destination/" + activeService.id + : selectedGreEdge ? "gre/" + greEdgeKey(selectedGreEdge) : pickedUser ? "user/" + pickedUser.id : "" + const objectX = objectPoint?.x, objectY = objectPoint?.y + const objectLane = mapLanes.find(lane => objectX != null && objectX >= lane.x0 && objectX < lane.x1)?.id + const scope = JSON.stringify([ixOnly, pickedUserId, filteredServiceId]) + const cameraSelection = useRef({scope, object:"", search:0, width:0, height:0}) + useEffect(() => { + if (!canvasMeasured) return + const previous = cameraSelection.current + const located = objectX != null && objectY != null ? cameraObjectKey : "" + cameraSelection.current = {scope, object:located, search:revealSearch, width:viewportWidth, height:viewportHeight} + if (!located || objectX == null || objectY == null) { + if (previous.scope !== scope) queueMicrotask(() => {setPan({x:0,y:0});setZoom(1);setNavigation(null)}) + return + } + if (previous.object === located && previous.search === revealSearch && previous.width === viewportWidth && previous.height === viewportHeight) return + const z = Math.max(1,zoomRef.current) + const x = objectX-viewportWidth/(2*z), y = objectY-viewportHeight/(2*z) + queueMicrotask(() => {setPan({x,y});setZoom(z);setNavigation(objectLane ? {id:objectLane,x} : null)}) + }, [canvasMeasured,scope,cameraObjectKey,objectX,objectY,objectLane,revealSearch,viewportWidth,viewportHeight]) const ixSegments = [...new Map((showIx ? ixLinks : []).map(link => [[Math.min(link.from,link.to),Math.max(link.from,link.to),link.segment].join(":"),link] as const)).entries()] .filter(([,link]) => onMap(String(link.from)) && onMap(String(link.to)) && @@ -2357,9 +2133,9 @@ function NetworkMapContent() { const ownershipLinks = (showAuxLinks ? scopedServers.filter(router => router.type === "home-router") : []).flatMap(router => (router.wanUplinks ?? []).flatMap((_,i) => { const from = endpoint(router.id), to = endpoint(router.id,i) if (groupedConnection({from,to,type:"wan"})) return [] - return [{key:densityWanKey(router.id,i),link:mapLinkPath(from,from.halfWidth,to,to.halfWidth)}] + return [{key:densityWanKey(router.id,i),link:mapLinkPath(from,from.halfWidth,to,to.halfWidth,{obstacles:mapObstacles})}] })) - const groupLinks = collectGroupLinks(groupedConnections) + const groupLinks = collectGroupLinks(groupedConnections, mapObstacles, nextFaultTrack) const groupProblems = new Map(density.groups.map(g => { const ids = new Set(g.serverIds) const channels = scopedGreEdges.filter(e => @@ -2368,10 +2144,19 @@ function NetworkMapContent() { const problems = countGroupGre(channels) return [g.id,g.problemCount + problems.down + problems.degraded] })) - const nestedRibbons = mapRibbons((expandedCountryGroup?.edges ?? []).flatMap((edge) => { + const channelProblemByDevice = new Map() + for (const edge of scopedGreEdges) { + const {tunnel,peerTunnel} = edge + if (tunnel.status === "up" && (!peerTunnel || peerTunnel.status === "up")) continue + const down = tunnel.status === "down" && (!peerTunnel || peerTunnel.status === "down") + for (const id of [edge.fromServer.id,edge.toServer.id]) { + if (down || !channelProblemByDevice.has(id)) channelProblemByDevice.set(id,down ? "down" : "degraded") + } + } + const nestedRibbons = (expandedCountryGroup?.edges ?? []).flatMap((edge) => { const from = servicePosById[edge.fromId], to = nestedPosById[edge.toId] - return from && to ? [{ edge, from, fromHalfW: MAP_SERVICE_COMPACT_W / 2, to, toHalfW: MAP_SERVICE_COMPACT_W / 2, bps: destinationRate(edge).bps }] : [] - }), 24) + return from && to ? [{ edge, d:mapLinkPath(from, destHalfW, to, cardWidths.nested/2, {obstacles:mapObstacles}).d }] : [] + }) // ── Рабочая панель под картой: потоки, RTT каналов, назначения, события const rateOf = (bytes: number, bps: number) => formatNetflowRate({ bytes, bps, bpsFwd: bps, bpsRev: 0 }) @@ -2389,6 +2174,7 @@ function NetworkMapContent() { id: servicePathKey(p), client: p.clientId === "—" ? "Без привязки" : p.clientName, exit: p.enName || p.enId || `IPFIX · ${p.viaName || p.viaId}`, + confirmed: Boolean(p.enId), bps: p.bps, bytes: p.bytes, dest: filterService?.label ?? destDisplayLabel(scopedDest.services.find(svc => svc.id === p.serviceId), destMode, p.serviceId), rate: rateOf(p.bytes, p.bps), volume: formatBytes(p.bytes), @@ -2396,15 +2182,17 @@ function NetworkMapContent() { })) const rttRows = greEdges.filter(edge => onMap(edge.fromServer.id) && onMap(edge.toServer.id)).map(e => { const key = greEdgeKey(e) + const status = channelStatus(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}`, + rttMs: merged.pingMs, 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" ? "Деградация" : "Недоступен", + tone: status === "up" ? "ok" as const : status === "degraded" ? "wn" as const : "er" as const, + status: status === "up" ? "Работает" : status === "degraded" ? "Деградация" : "Недоступен", hl: selected ? e.fromServer.id === selected.id || e.toServer.id === selected.id : selectedGreEdge ? greEdgeKey(selectedGreEdge) === key : false, } }) @@ -2419,22 +2207,23 @@ function NetworkMapContent() { share: shareKnown ? svc.share : null, hl: activeService?.id === svc.id || Boolean(selected && destEdges.some(edge => edge.fromId === selected.id && edge.toId === svc.id)), })) - const mapLinkCount = greGroups.length + wanLinks.length + groupLinks.filter(l => l.type === "gre" || l.type === "wan-jh").length - const activeMapPoints = [...visibleNodes, ...density.groups, ...visibleWanPoints, ...Object.values(servicePosById), ...Object.values(nestedPosById), ...(minorPosition ? [minorPosition] : [])] - const lanesTop = Math.min(...activeMapPoints.map(point => point.y), NETWORK_MAP_PIPELINE_Y) - 66 - const lanesBottom = Math.max(...activeMapPoints.map(point => point.y), NETWORK_MAP_PIPELINE_Y) + 52 + const greChannelCount = countGroupGre(scopedGreEdges).count + const lanesTop = worldTop + const lanesBottom = Math.max(worldTop + worldHeight,pan.y+viewportHeight/zoom) const recentIncidents = eventRows.filter(event => (event.tone === "er" || event.tone === "wn") && event.ts >= eventsAt - 86_400_000) const siteNames = summaryOpen || searchOpen ? [...new Set(nodes.map(mapSiteName))].sort((a,b) => a.localeCompare(b, "ru")) : [] const mapHeadSub = ( <> {useLiveData ? (readAt ? "Снимок сети" : "Данные карты неизвестны") : "Демонстрационные данные"} - {" · "}{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {mapLinkCount} {ruPlural(mapLinkCount, "связь", "связи", "связей")} + {(hasSnapshot || !useLiveData) && <>{" · "}{nodes.length} {ruPlural(nodes.length, "узел", "узла", "узлов")} · {greChannelCount} {ruPlural(greChannelCount, "туннель GRE", "туннеля GRE", "туннелей GRE")}} {useLiveData && (showNetflow || showServices) && <>{" · "}{destinationReadAt ? IPFIX · среднее за {destinationWindow}{!destinationListener ? " · приёмник выключен" : ""} : Данные NetFlow неизвестны}} ) const faultLinks = scopedGreEdges.filter(edge => edge.tunnel.enabled && [nodeById[edge.fromServer.id], nodeById[edge.toServer.id]].some(node => node && isVisible(node))) const downLink = faultLinks.find(edge => edge.tunnel.status === "down") + const deviceFaults = selected ? faultLinks.filter(edge => edge.tunnel.status === "down" && + (edge.fromServer.id === selected.id || edge.toServer.id === selected.id)) : [] const offlineNode = nodes.find(node => node.enabled && node.status === "offline" && isVisible(node)) const faultLink = downLink ?? (!offlineNode ? faultLinks.find(edge => edge.tunnel.status === "degraded") : undefined) const faultNode = offlineNode ?? nodes.find(node => node.enabled && node.status === "degraded" && isVisible(node)) @@ -2471,6 +2260,39 @@ function NetworkMapContent() { (selectedCategoryMembers && bottomTab === "flows" ? " · категория " + activeService?.label : filterService && bottomTab === "flows" ? " · фильтр: " + filterService.label : selected || activeService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : "") const refreshBusy = dataLoading || flowLoading && (showNetflow || showServices) || requestRecent && recent?.refresh !== flowRefresh const inspectorOpen = detailsOpen + const object = { + server: selected?.id ?? null, + wan: selWanIdx, + service: activeServiceId ?? null, + gre: selectedGreEdge ? greEdgeKey(selectedGreEdge) : null, + user: userDetailsOpen, + mode: destMode, + path: highlightedPath, + } + const objectKey = object.server || object.service || object.gre || object.user ? + JSON.stringify([object.server, object.wan, object.service, object.gre, object.user, object.mode, object.path && servicePathKey(object.path)]) : null + const trailScope = JSON.stringify([pickedUserId, ixOnly]) + const [trail, setTrail] = useState<{scope: string; entries: {key: string; object: typeof object}[]}>({scope:trailScope, entries:[]}) + const last = trail.entries.at(-1) + if (trail.scope !== trailScope || objectKey !== (last?.key ?? null)) { + const previous = trail.scope === trailScope ? trail.entries : [] + setTrail({scope:trailScope, entries:objectKey ? [...previous.slice(-19),{key:objectKey,object}] : []}) + } + function backToObject() { + const entry = trail.entries.at(-2) + if (!entry) return + const saved = entry.object + setTrail({scope:trailScope, entries:trail.entries.slice(0,-1)}) + setSelectedService(null) + setSelectedGreEdge(saved.gre ? greEdges.find(edge => greEdgeKey(edge) === saved.gre) ?? null : null) + setHighlightedPath(saved.path) + setExpandedCountryId(null) + setInspectUser(saved.user) + updateUrl({dest:saved.mode === "services" ? null : saved.mode, server:saved.server, wan:saved.wan == null ? null : String(saved.wan), service:saved.service},true) + } + const inspectorBack = trail.entries.length > 1 ? + : null + function inspectEvent(event: MapEventRow) { setInspectedEvent(event) setBottomTab("events") @@ -2486,6 +2308,7 @@ function NetworkMapContent() { setHighlightedPath(path) } const pickedBindings = new Map([...accessGroups.keys()].map(id => [id, pickedUser?.bindings.filter(binding => binding.node === id) ?? []])) + const onlyBinding = pickedBindings.size === 1 ? nodeById[[...pickedBindings.keys()][0]] : undefined const selectedNodeRate = !selectedNodeTraffic.error && isFreshMapTrafficSample(selectedNodeTraffic.sample) ? selectedNodeTraffic.sample : undefined function nodeTrafficHref(server: string) { const context = new URLSearchParams({ server, from: "map" }) @@ -2498,7 +2321,7 @@ function NetworkMapContent() {
-
+
} title="Карта сети" @@ -2511,8 +2334,8 @@ function NetworkMapContent() { Обновить )} - } @@ -2546,26 +2369,24 @@ function NetworkMapContent() { } {pickedUserId && !pickedUser && !(ixOnly ? access.linuxPending : access.pending) && Пользователь карты недоступен} -
- - + {/* Поиск узла или назначения с подсказками */}
{ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setSearchOpen(false) }}> - + {searchOpen && (
{searchHits.map(hit => ( @@ -2619,8 +2440,8 @@ function NetworkMapContent() { {/* Фильтр статуса и роли */} - }> -