Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2da1b17b65 | ||
|
|
876a61f705 |
No files matched your search
+439
-602
File diff suppressed because it is too large.
Load diff
@@ -13,8 +13,8 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
|||||||
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
||||||
return (
|
return (
|
||||||
<Popover key={compact ? "compact" : "overview"}>
|
<Popover key={compact ? "compact" : "overview"}>
|
||||||
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
<PopoverTrigger render={<Button type="button" variant="outline" size="sm" aria-label="Легенда" title="Легенда" />}>
|
||||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
<InfoIcon aria-hidden="true" className="size-4" /><span className="@max-[430px]/network-map:hidden">Легенда</span>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
|
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
|
||||||
<p className={head}>Статус</p>
|
<p className={head}>Статус</p>
|
||||||
@@ -36,15 +36,17 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
|||||||
</div>
|
</div>
|
||||||
<p className={head}>Связи</p>
|
<p className={head}>Связи</p>
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-1.5">
|
||||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>GRE-туннель исправен</span>
|
||||||
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
|
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
|
||||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--destructive)" strokeWidth="3" /></svg>GRE · нет связи</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--status-degraded)" strokeWidth="3" strokeDasharray="6 3" /></svg>Каналы · частичный отказ или деградация</span>
|
||||||
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--status-offline)" strokeWidth="3" strokeDasharray="2 3" /></svg>GRE · нет связи</span>
|
||||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
|
||||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
|
||||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12"><path d="M0 3H12Q16 3 16 6T20 9H32" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом · выход подтверждён</span>
|
||||||
<span className="flex items-center gap-2"><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
|
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10"><path d="M0 5H32" stroke="var(--muted-foreground)" strokeWidth="2" strokeDasharray="4 3" /></svg><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||||
|
<p className="text-muted-foreground leading-snug">Цвет на линии — только у проблем. Скорость подписана от 1 Мбит/с и у выбранного объекта; остальное — в подсказке и панели справа.</p>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { UsersIcon } from "lucide-react"
|
||||||
|
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
|
||||||
|
|
||||||
|
export function MapAccessMark({ x, y, name, meta, selected, ariaLabel, onPick, width = 150 }: {
|
||||||
|
x: number; y: number; name: string; meta: string; selected: boolean; ariaLabel: string; onPick: () => void; width?: number
|
||||||
|
}) {
|
||||||
|
const kind = selected ? "user" : "access"
|
||||||
|
const { height, lines } = mapCardMetrics(name, kind, width)
|
||||||
|
const iconX = selected ? 19 : 15, nameX = selected ? 35 : 29
|
||||||
|
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-node-kind={kind}
|
||||||
|
role="button" aria-label={ariaLabel} tabIndex={0} className="network-map-focusable cursor-pointer"
|
||||||
|
onPointerDown={event => event.stopPropagation()}
|
||||||
|
onClick={event => { event.stopPropagation(); onPick() }}
|
||||||
|
onKeyDown={event => {
|
||||||
|
if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); onPick() }
|
||||||
|
}}>
|
||||||
|
<title>{[name, meta].filter(Boolean).join(" · ")}</title>
|
||||||
|
<rect className="network-map-focus-ring" x="-3" y="-3" width={width + 6} height={height + 6} rx="11" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||||
|
<rect data-map-box="access" width={width} height={height} rx="9" fill="var(--card)" stroke={selected ? "var(--foreground)" : "var(--border)"} strokeWidth={selected ? 2 : 1.5} />
|
||||||
|
<circle cx={iconX} cy="21" r="12" fill="var(--muted)" />
|
||||||
|
<UsersIcon x={iconX - 8} y="13" width="16" height="16" color="var(--chart-2)" aria-hidden="true" />
|
||||||
|
{lines.map((line, i) => <text key={i} x={nameX} y={18 + i * 14} fill="var(--foreground)" fontSize="13" fontWeight="600">{line}</text>)}
|
||||||
|
<text x={nameX} y={33 + (lines.length - 1) * 14} fill="var(--muted-foreground)" fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="10.5">
|
||||||
|
{mapCardMeta(meta, width - nameX - 7)}
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
}
|
||||||
@@ -2,7 +2,19 @@
|
|||||||
|
|
||||||
import { flagCdnUrl } from "@/components/flag"
|
import { flagCdnUrl } from "@/components/flag"
|
||||||
|
|
||||||
|
const flags = {
|
||||||
|
RU: {w:4.5,h:3,art:<><rect width="4.5" height="3" fill="#fff"/><path d="M0 1h4.5v1H0z" fill="#0039a6"/><path d="M0 2h4.5v1H0z" fill="#d52b1e"/></>},
|
||||||
|
DE: {w:5,h:3,art:<><rect width="5" height="3" fill="#000"/><path d="M0 1h5v1H0z" fill="#d00"/><path d="M0 2h5v1H0z" fill="#ffce00"/></>},
|
||||||
|
SE: {w:16,h:10,art:<><rect width="16" height="10" fill="#006aa7"/><path d="M5 0h2v10H5zM0 4h16v2H0z" fill="#fecc02"/></>},
|
||||||
|
FI: {w:18,h:11,art:<><rect width="18" height="11" fill="#fff"/><path d="M5 0h3v11H5zM0 4h18v3H0z" fill="#002f6c"/></>},
|
||||||
|
}
|
||||||
|
|
||||||
export function CountryFlagSvg({ iso, size = 22 }: { iso: string; size?: number }) {
|
export function CountryFlagSvg({ iso, size = 22 }: { iso: string; size?: number }) {
|
||||||
|
const code = iso.trim().toUpperCase()
|
||||||
|
if (Object.hasOwn(flags,code)) {
|
||||||
|
const {w,h,art} = flags[code as keyof typeof flags]
|
||||||
|
return <svg aria-hidden="true" width={size} height={size*h/w} viewBox={`0 0 ${w} ${h}`}>{art}</svg>
|
||||||
|
}
|
||||||
const url = flagCdnUrl(iso, size)
|
const url = flagCdnUrl(iso, size)
|
||||||
if (!url) return null
|
if (!url) return null
|
||||||
const h = Math.round(size * 0.75)
|
const h = Math.round(size * 0.75)
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
|
import { ChevronsUpDownIcon } from "lucide-react"
|
||||||
import type { KeyboardEvent } from "react"
|
import type { KeyboardEvent } from "react"
|
||||||
import { MAP_CARD_H, MAP_CARD_W, placeMapLinkLabels, type MapBox } from "@/lib/network-map-layout"
|
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
|
||||||
|
import { MapFaultBadge } from "./wire-badge"
|
||||||
|
import { placeMapLinkLabels, type MapBox } from "@/lib/network-map-layout"
|
||||||
import type { MapGroupLink } from "@/lib/network-map-group-links"
|
import type { MapGroupLink } from "@/lib/network-map-group-links"
|
||||||
|
|
||||||
function activate(event: KeyboardEvent<SVGGElement>, action: () => void) {
|
function activate(event: KeyboardEvent<SVGGElement>, action: () => void) {
|
||||||
@@ -16,28 +18,30 @@ const roleColors: Record<string, string> = {
|
|||||||
HR: "var(--chart-2)", JH: "var(--chart-1)", EN: "var(--chart-3)", IX: "var(--chart-4)", WAN: "var(--muted-foreground)",
|
HR: "var(--chart-2)", JH: "var(--chart-1)", EN: "var(--chart-3)", IX: "var(--chart-4)", WAN: "var(--muted-foreground)",
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MapGroupMark({ id, x, y, name, code, count, expanded, problems = 0, unknownCount = 0, onToggle, visible = true }: {
|
export function MapGroupMark({ id, x, y, name, code, count, expanded, problems = 0, unknownCount = 0, onToggle, visible = true, width = code === "WAN" ? 155 : 157 }: {
|
||||||
id: string; x: number; y: number; name: string; code: string; count: number; expanded: boolean
|
id: string; x: number; y: number; name: string; code: string; count: number; expanded: boolean
|
||||||
problems?: number; unknownCount?: number; onToggle: () => void; visible?: boolean
|
problems?: number; unknownCount?: number; onToggle: () => void; visible?: boolean; width?: number
|
||||||
}) {
|
}) {
|
||||||
const width = MAP_CARD_W, height = MAP_CARD_H
|
const {height, lines} = mapCardMetrics(name, "group", width)
|
||||||
const color = roleColors[code] ?? "var(--muted-foreground)"
|
const color = roleColors[code] ?? "var(--muted-foreground)"
|
||||||
const Chevron = expanded ? ChevronDownIcon : ChevronRightIcon
|
|
||||||
const health = problems ? `Проблемы · ${problems}` : unknownCount ? `Нет данных · ${unknownCount}` : ""
|
const health = problems ? `Проблемы · ${problems}` : unknownCount ? `Нет данных · ${unknownCount}` : ""
|
||||||
const label = [name, `${code} × ${count}`, health, problems && unknownCount ? `Нет данных · ${unknownCount}` : ""].filter(Boolean).join(" · ")
|
const label = [name, `${code} × ${count}`, health, problems && unknownCount ? `Нет данных · ${unknownCount}` : ""].filter(Boolean).join(" · ")
|
||||||
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-map-group={id}
|
const meta = `${code === "WAN" ? "WAN" : "Устройств"} · ${count}`
|
||||||
|
return <g transform={`translate(${x - width / 2},${y - height / 2})`} data-map-group={id} data-node-kind="group"
|
||||||
role="button" tabIndex={visible ? 0 : -1} aria-expanded={expanded} aria-label={`${expanded ? "Свернуть" : "Раскрыть"} группу · ${label}`}
|
role="button" tabIndex={visible ? 0 : -1} aria-expanded={expanded} aria-label={`${expanded ? "Свернуть" : "Раскрыть"} группу · ${label}`}
|
||||||
className="network-map-focusable cursor-pointer" opacity={visible ? 1 : 0.1}
|
className="network-map-focusable cursor-pointer" opacity={visible ? 1 : 0.38}
|
||||||
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onToggle() }}
|
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onToggle() }}
|
||||||
onKeyDown={event => activate(event, onToggle)}>
|
onKeyDown={event => activate(event, onToggle)}>
|
||||||
<title>{label}</title>
|
<title>{[name, `${code} ×${count}`, health].filter(Boolean).join(" · ")}</title>
|
||||||
<rect className="network-map-focus-ring" x="-4" y="-4" width={width + 8} height={height + 8} rx="14" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
<rect className="network-map-focus-ring" x="-3" y="-3" width={width + 6} height={height + 6} rx="11" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||||
<rect data-map-box="group" width={width} height={height} rx="11" fill="var(--card)" stroke={problems ? "var(--warning)" : "var(--border)"} strokeWidth="1.5" strokeDasharray={expanded ? "4 3" : undefined} />
|
<rect data-map-box="group" width={width} height={height} rx="9" fill="var(--card)" stroke={problems ? "color-mix(in oklch,var(--warning) 50%,transparent)" : "var(--border)"} strokeWidth="1.5" strokeDasharray="4 2" />
|
||||||
<rect x="8" y="7" width="50" height="19" rx="5" fill={color} fillOpacity=".15" />
|
<rect data-role-tile={code} x="7" y="7" width="24" height="24" rx="7" fill={color} fillOpacity=".18" />
|
||||||
<text x="33" y="20" textAnchor="middle" fill={color} fontSize="10.5" fontFamily="Geist Mono,monospace" fontWeight="600">{code} ×{count}</text>
|
<text x="19" y="23" textAnchor="middle" fill={color} fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="11.5" fontWeight="700">{code}</text>
|
||||||
<text x="64" y="20" fill={problems ? "var(--status-degraded-fg)" : "var(--muted-foreground)"} fontSize="10.5">{health}</text>
|
<ChevronsUpDownIcon x={width - 21} y="6" width="16" height="16" color="var(--muted-foreground)" aria-hidden="true" />
|
||||||
<Chevron x={width - 19} y="32" width="14" height="14" color="var(--muted-foreground)" />
|
{lines.map((line, i) => <text key={i} x="37" y={18 + i * 14} fill="var(--foreground)" fontSize="13" fontWeight="600">{line}</text>)}
|
||||||
<text x="10" y="43" fill="var(--foreground)" fontSize={name.length > 18 ? 11 : 12} fontWeight="600">{name.length > 21 ? name.slice(0, 20) + "…" : name}</text>
|
<text x="37" y={33 + (lines.length - 1) * 14} fill="var(--muted-foreground)" fontFamily="var(--font-mono,Geist Mono,monospace)" fontSize="10.5">{mapCardMeta(meta, width - 44) === meta ? meta : `×${count}`}</text>
|
||||||
|
{health && <text x="8" y={height - 5} fill={problems ? "var(--status-degraded-fg)" : "var(--muted-foreground)"} fontFamily={problems ? undefined : "var(--font-mono,Geist Mono,monospace)"}
|
||||||
|
fontSize={problems ? 11 : 10.5} fontWeight={problems ? 500 : 400}>{mapCardMeta(health, width - 18)}</text>}
|
||||||
</g>
|
</g>
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,8 +52,6 @@ const linkNames: Record<MapGroupLink["type"], string> = {
|
|||||||
function linkColor(link: MapGroupLink) {
|
function linkColor(link: MapGroupLink) {
|
||||||
if (link.down === link.count) return "var(--status-offline)"
|
if (link.down === link.count) return "var(--status-offline)"
|
||||||
if (link.down || link.degraded) return "var(--status-degraded)"
|
if (link.down || link.degraded) return "var(--status-degraded)"
|
||||||
if (link.type === "gre") return "var(--status-online)"
|
|
||||||
if (link.type === "user") return "var(--chart-2)"
|
|
||||||
if (link.type === "service" || link.type === "ix") return "var(--chart-4)"
|
if (link.type === "service" || link.type === "ix") return "var(--chart-4)"
|
||||||
return "var(--muted-foreground)"
|
return "var(--muted-foreground)"
|
||||||
}
|
}
|
||||||
@@ -61,9 +63,10 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
|
|||||||
const entries = [...links].sort((a, b) => b.down - a.down || b.degraded - a.degraded).map(row => {
|
const entries = [...links].sort((a, b) => b.down - a.down || b.degraded - a.degraded).map(row => {
|
||||||
const type = linkNames[row.type], color = linkColor(row)
|
const type = linkNames[row.type], color = linkColor(row)
|
||||||
const summary = [`${type} ×${row.count}`, row.down ? `недоступно ${row.down} из ${row.count}` : "", row.degraded ? `ухудшено · ${row.degraded}` : ""].filter(Boolean).join(" · ")
|
const summary = [`${type} ×${row.count}`, row.down ? `недоступно ${row.down} из ${row.count}` : "", row.degraded ? `ухудшено · ${row.degraded}` : ""].filter(Boolean).join(" · ")
|
||||||
const texts = row.down ? [`Недоступно ${row.down} из ${row.count}`, `↓ ${row.down}/${row.count}`] :
|
// Коротко на линии; полная сводка — в title.
|
||||||
row.degraded ? [`Ухудшено ${row.degraded} из ${row.count}`, `! ${row.degraded}/${row.count}`] : [`${type} ×${row.count}`, `×${row.count}`]
|
const texts = row.down ? [`${row.down === row.count ? "Нет связи" : "Отказ"} ${row.down}/${row.count}`, `${row.down}/${row.count}`] :
|
||||||
return { ...row, color, texts, title: `${row.from.name} → ${row.to.name} · ${summary}` }
|
row.degraded ? [`Деградация ${row.degraded}/${row.count}`, `${row.degraded}/${row.count}`] : []
|
||||||
|
return { ...row, color, texts, fault:Boolean(row.down || row.degraded), title: `${row.from.name} → ${row.to.name} · ${summary}` }
|
||||||
})
|
})
|
||||||
const labels = layer === "lines" ? [] : placeMapLinkLabels(entries, obstacles)
|
const labels = layer === "lines" ? [] : placeMapLinkLabels(entries, obstacles)
|
||||||
return <>
|
return <>
|
||||||
@@ -74,8 +77,8 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
|
|||||||
onKeyDown={event => activate(event, () => onExpand(row.groups))}>
|
onKeyDown={event => activate(event, () => onExpand(row.groups))}>
|
||||||
<title>{row.title}</title>
|
<title>{row.title}</title>
|
||||||
<path className="network-map-focus-ring" d={row.link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
|
<path className="network-map-focus-ring" d={row.link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
|
||||||
<path d={row.link.d} fill="none" stroke={row.color} strokeWidth={row.type === "gre" ? 2.5 : 1.7}
|
<path d={row.link.d} fill="none" stroke={row.color} strokeWidth={row.fault ? 2.2 : 1.6} opacity={row.fault ? 1 : row.type === "observation" ? .56 : .6}
|
||||||
strokeDasharray={row.down || row.degraded || row.type === "observation" ? "5 4" : undefined} strokeLinecap="round" />
|
strokeDasharray={row.down === row.count ? "2 3" : row.fault ? "6 3" : row.type === "observation" ? "4 3" : undefined} strokeLinejoin="round" strokeLinecap="round" />
|
||||||
<path d={row.link.d} fill="none" stroke="transparent" strokeWidth="16" />
|
<path d={row.link.d} fill="none" stroke="transparent" strokeWidth="16" />
|
||||||
</g>
|
</g>
|
||||||
))}
|
))}
|
||||||
@@ -83,8 +86,7 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
|
|||||||
<g key={row.id} transform={`translate(${row.x},${row.y})`} data-map-group-link-label={row.type} className="cursor-pointer" aria-hidden="true"
|
<g key={row.id} transform={`translate(${row.x},${row.y})`} data-map-group-link-label={row.type} className="cursor-pointer" aria-hidden="true"
|
||||||
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}>
|
onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); onExpand(row.groups) }}>
|
||||||
<title>{row.title}</title>
|
<title>{row.title}</title>
|
||||||
<rect data-map-box="pill" x={-row.w / 2} y="-10" width={row.w} height="20" rx="10" fill="var(--card)" stroke={row.down || row.degraded ? row.color : "var(--border)"} />
|
<MapFaultBadge width={row.w} text={row.text} down={row.down === row.count} />
|
||||||
<text textAnchor="middle" dy="4" fill={row.down === row.count ? "var(--status-offline-fg)" : row.down || row.degraded ? "var(--status-degraded-fg)" : "var(--foreground)"} fontSize="11" fontFamily="Geist Mono,monospace">{row.text}</text>
|
|
||||||
</g>
|
</g>
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ function CategoryEvidence({service, path, onCategory}: {
|
|||||||
const evidence = observation.serviceEvidence ?? []
|
const evidence = observation.serviceEvidence ?? []
|
||||||
return <div className="space-y-1.5 text-xs">
|
return <div className="space-y-1.5 text-xs">
|
||||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||||
<span className="text-muted-foreground">Категория трафика</span>
|
{path && <span className="text-muted-foreground">Категория потока</span>}
|
||||||
{onCategory ? <Button type="button" size="xs" variant="link" className="h-auto p-0" onClick={() => onCategory(category)}>{category}</Button> : <strong>{category}</strong>}
|
{onCategory ? <Button type="button" size="xs" variant="link" className="h-auto max-w-full justify-start whitespace-normal p-0 text-left text-[13px] font-semibold" onClick={() => onCategory(category)}>{category}<ChevronRightIcon aria-hidden className="size-3 text-muted-foreground" /></Button> : <strong>{category}</strong>}
|
||||||
</div>
|
</div>
|
||||||
{evidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
{evidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
||||||
{evidence.map(row => <li key={row.basis}><Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}>
|
{evidence.map(row => <li key={row.basis}><Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}>
|
||||||
@@ -50,10 +50,10 @@ function CategoryEvidence({service, path, onCategory}: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||||||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
return <dl className="px-3">
|
||||||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 border-b py-2">
|
||||||
<dt className="text-[11px] text-muted-foreground">{name}</dt>
|
<dt className="text-[13px] text-muted-foreground">{name}</dt>
|
||||||
<dd className="font-mono text-sm font-semibold leading-tight [overflow-wrap:anywhere]">{value}</dd>
|
<dd className="min-w-0 text-right font-mono text-[13px] font-semibold tabular-nums [overflow-wrap:anywhere]">{value}</dd>
|
||||||
</div>)}
|
</div>)}
|
||||||
</dl>
|
</dl>
|
||||||
}
|
}
|
||||||
@@ -134,7 +134,10 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, shareKnown = true, flowAt, stale, activePath, onPath, onClose, onCategory, filtered, onFilter, userId, ix, topology }: {
|
export function ServiceInspector({ back, onNode, onUser, service, paths, exits, exitName, country, base, refresh, windowLabel, history, shareOfVisible, shareKnown = true, flowAt, stale, activePath, onPath, onClose, onCategory, filtered, onFilter, userId, ix, topology }: {
|
||||||
|
back?: ReactNode
|
||||||
|
onNode: (id: string) => (() => void) | undefined
|
||||||
|
onUser: (id: string) => (() => void) | undefined
|
||||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||||
history?: {service?: FlowMapService; window: string}
|
history?: {service?: FlowMapService; window: string}
|
||||||
@@ -200,22 +203,14 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
}
|
}
|
||||||
if (countryFilter) trafficQuery.set("country", countryFilter)
|
if (countryFilter) trafficQuery.set("country", countryFilter)
|
||||||
return <>
|
return <>
|
||||||
<header className="flex items-center gap-2 px-3 py-3">
|
<header className="flex shrink-0 items-center gap-1 border-b px-3 py-3">
|
||||||
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
<div className="min-w-0 flex-1">
|
||||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
<p className="mb-1 text-xs text-muted-foreground">Сервис</p>
|
||||||
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[country, "IPFIX", windowLabel].filter(Boolean).join(" · ")}</p></div>
|
<h2 className="flex items-center gap-2 break-words text-[15px] font-semibold"><ServiceBrandIcon label={service.label} size={16} />{service.label}</h2>
|
||||||
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
</div>
|
||||||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
{back}<Button size="icon-sm" variant="outline" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
||||||
</header>
|
</header>
|
||||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
|
||||||
<InspectorMetrics rows={[
|
|
||||||
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
|
|
||||||
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", shareKnown ? percent.format(service.share) : "Нет данных", "IPFIX · " + windowLabel],
|
|
||||||
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
|
||||||
exitIds.length || !exporterIds.length
|
|
||||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
|
||||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
|
||||||
]} />
|
|
||||||
{selectedPath && <section aria-label="Выбранный поток" className="space-y-2 border-b px-3.5 py-3 text-xs">
|
{selectedPath && <section aria-label="Выбранный поток" className="space-y-2 border-b px-3.5 py-3 text-xs">
|
||||||
<h3 className="font-medium">Выбранный поток</h3>
|
<h3 className="font-medium">Выбранный поток</h3>
|
||||||
<p className="break-words">{[selectedPath.clientId === "—" ? "Без привязки" : selectedPath.clientName, selectedPath.viaName || selectedPath.viaId, selectedPath.enId !== selectedPath.viaId && (selectedPath.enName || selectedPath.enId), service.label].filter(Boolean).join(" → ")}</p>
|
<p className="break-words">{[selectedPath.clientId === "—" ? "Без привязки" : selectedPath.clientName, selectedPath.viaName || selectedPath.viaId, selectedPath.enId !== selectedPath.viaId && (selectedPath.enName || selectedPath.enId), service.label].filter(Boolean).join(" → ")}</p>
|
||||||
@@ -227,7 +222,10 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
<p className="font-mono tabular-nums">IPFIX · среднее за {windowLabel} · {formatNetflowRate(selectedPath)} · {formatBytes(selectedPath.bytes)}</p>
|
<p className="font-mono tabular-nums">IPFIX · среднее за {windowLabel} · {formatNetflowRate(selectedPath)} · {formatBytes(selectedPath.bytes)}</p>
|
||||||
</section>}
|
</section>}
|
||||||
<section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
<section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
||||||
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
|
<div className="flex flex-wrap items-center justify-between gap-1">
|
||||||
|
<h3 className="text-sm font-semibold">Категория трафика</h3>
|
||||||
|
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
||||||
|
</div>
|
||||||
<CategoryEvidence service={service} onCategory={onCategory} />
|
<CategoryEvidence service={service} onCategory={onCategory} />
|
||||||
{trafficTypes.length > 0 && service.bytes > 0 && <dl className="space-y-1">
|
{trafficTypes.length > 0 && service.bytes > 0 && <dl className="space-y-1">
|
||||||
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
||||||
@@ -239,23 +237,52 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
||||||
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
||||||
</section>
|
</section>
|
||||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
<section className="space-y-2 border-b px-3 py-3"><h3 className="flex items-baseline gap-2 text-sm font-semibold">Пути по данным IPFIX <span className="font-mono text-xs font-normal text-muted-foreground">{paths.length}</span></h3>
|
||||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
{paths.map((path, index) => {
|
||||||
{paths.map(p => {
|
const key = servicePathKey(path)
|
||||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "",
|
const active = selectedPath && servicePathKey(selectedPath) === key
|
||||||
p.enName, service.label].filter(Boolean)
|
const expanded = active || (!selectedPath && index === 0)
|
||||||
const key = servicePathKey(p)
|
const user = path.clientId === "—" ? "Без привязки" : path.clientName
|
||||||
const active = activePath && servicePathKey(activePath) === key
|
const hops = [
|
||||||
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
{role:"Пользователь", name:user, go:onUser(path.clientId)},
|
||||||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
...(path.viaId !== path.enId ? [{role:path.enId ? "Узел доступа" : "Экспортёр IPFIX", name:path.viaName || path.viaId, go:onNode(path.viaId)}] : []),
|
||||||
<span className="basis-full text-[10px] text-muted-foreground">{p.enId ? "Выход подтверждён" :
|
...(path.enId ? [{role:"Подтверждённый выход", name:path.enName || path.enId, go:onNode(path.enId)}] : []),
|
||||||
`Наблюдение IPFIX${p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён`}</span>
|
{role:path.enId ? "Назначение" : "Назначение записи", name:service.label, go:undefined},
|
||||||
</button>
|
]
|
||||||
|
return <div key={key} className="border-t py-1 text-xs">
|
||||||
|
<button type="button" onClick={() => onPath(path)} aria-pressed={Boolean(active)} className="grid w-full gap-1 rounded-sm py-1.5 text-left hover:bg-muted/50">
|
||||||
|
<span className="flex items-baseline gap-1.5"><ChevronRightIcon aria-hidden className={cn("size-3 shrink-0", expanded && "rotate-90")} />
|
||||||
|
<b className="min-w-0 break-words">{user} → {service.label}</b><span className="ml-auto shrink-0 font-mono text-muted-foreground">{formatNetflowRate(path)}</span>
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-1 text-[11px] text-muted-foreground">
|
||||||
|
<i aria-hidden className={cn("w-4 border-t-2", path.enId ? "border-chart-4" : "border-dashed")} />
|
||||||
|
{path.enId ? "Выход подтверждён" : `Наблюдение IPFIX${path.viaIface ? ` · интерфейс ${path.viaIface}` : ""} · выход не подтверждён`}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{expanded && <ol className="ml-1.5 py-2" aria-label="Путь потока">
|
||||||
|
{hops.map(({role,name,go},i) => <li key={role} className={cn("relative border-l pl-4 pb-2 last:border-transparent last:pb-0",
|
||||||
|
i === 0 ? "border-chart-2" : i === hops.length - 2 ? path.enId ? "border-chart-4" : "border-dashed border-muted-foreground" : "border-border")}>
|
||||||
|
<i aria-hidden className={cn("absolute top-0 left-[-4px] size-[7px] rounded-full border bg-card", i === 0 ? "border-chart-2" : i === hops.length-1 && path.enId ? "border-chart-4" : "border-muted-foreground")} />
|
||||||
|
<small className="block text-[11px] leading-none text-muted-foreground">{role}</small>
|
||||||
|
{go ? <button type="button" onClick={go} className="mt-1 flex min-h-7 w-full items-center justify-between gap-2 rounded px-1 text-left font-semibold hover:bg-muted">
|
||||||
|
{name}<ChevronRightIcon aria-hidden className="size-3 text-muted-foreground" /></button> : <strong className="mt-1 block py-1">{name}</strong>}
|
||||||
|
</li>)}
|
||||||
|
</ol>}
|
||||||
|
</div>
|
||||||
})}
|
})}
|
||||||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||||||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||||
</section>
|
</section>
|
||||||
|
<InspectorMetrics rows={[
|
||||||
|
["Средняя за " + averageWindow, average ? formatNetflowRate(average) : "—", "Скорость по сохранённым потокам IPFIX"],
|
||||||
|
[shareOfVisible ? "Доля показанных сервисов" : country ? "Доля страны" : "Доля трафика", shareKnown ? percent.format(service.share) : "Нет данных", "IPFIX · " + windowLabel],
|
||||||
|
["Объём · " + (currentVolume ? averageWindow : volume?.window ?? "24 ч"), <>{volumeBytes == null ? "—" : formatBytes(volumeBytes)}{!currentVolume && volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||||
|
exitIds.length || !exporterIds.length
|
||||||
|
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||||
|
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||||
|
]} />
|
||||||
|
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · IPFIX{recent ? ` · ${recent.data.sourceWindow?.effectiveMinutes ?? 5} мин` : ""}</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · IPFIX{recent ? ` · ${recent.data.sourceWindow?.effectiveMinutes ?? 5} мин` : ""}</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||||||
{flows.map((f,i) => {
|
{flows.map((f,i) => {
|
||||||
const port = f.internetPeerPort ?? (f.direction === "to_client" ? f.srcPort : f.dstPort)
|
const port = f.internetPeerPort ?? (f.direction === "to_client" ? f.srcPort : f.dstPort)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { UsersIcon, XIcon } from "lucide-react"
|
import { UsersIcon, XIcon } from "lucide-react"
|
||||||
import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange"
|
import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||||
@@ -168,7 +168,8 @@ export function MapUserPicker({ open, onOpenChange, users, pending, unavailable,
|
|||||||
</CommandDialog>
|
</CommandDialog>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
export function MapUserDetails({ back, user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
||||||
|
back?: ReactNode
|
||||||
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
|
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
|
||||||
userRate?: ReturnType<typeof projectTrafficObservations>
|
userRate?: ReturnType<typeof projectTrafficObservations>
|
||||||
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
|
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
|
||||||
@@ -177,7 +178,7 @@ export function MapUserDetails({ user, groups, paths, services, rates, userRate,
|
|||||||
<header className="flex items-center gap-2 border-b p-3">
|
<header className="flex items-center gap-2 border-b p-3">
|
||||||
<UsersIcon className="size-4 shrink-0" aria-hidden />
|
<UsersIcon className="size-4 shrink-0" aria-hidden />
|
||||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
|
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
|
||||||
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
|
{back}<Button size="icon-sm" variant="outline" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
|
||||||
</header>
|
</header>
|
||||||
<div className="flex flex-col gap-3 overflow-y-auto p-3">
|
<div className="flex flex-col gap-3 overflow-y-auto p-3">
|
||||||
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
|
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useMemo, useState, type ReactNode } from "react"
|
import { useMemo, useState } from "react"
|
||||||
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
import { ArrowUpRightIcon, ChevronDownIcon, ChevronUpIcon, HistoryIcon } from "lucide-react"
|
||||||
import { FramePanel } from "@/components/reui/frame"
|
import { FramePanel } from "@/components/reui/frame"
|
||||||
import { Badge } from "@/components/reui/badge"
|
import { Badge } from "@/components/reui/badge"
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
import { ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { CompactDataGrid, type CompactDataGridColumn } from "@/components/data-grids/compact-data-grid"
|
import { CompactDataGrid, type CompactDataGridColumn } from "@/components/data-grids/compact-data-grid"
|
||||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||||
import { Flag } from "@/components/flag"
|
import { Flag } from "@/components/flag"
|
||||||
|
|
||||||
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
|
export type MapFlowRow = { id: string; client: string; exit: string; confirmed: boolean; dest: string; bps: number; bytes: number; 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 MapRttRow = { id: string; name: string; route: string; rttMs: number | null; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
|
||||||
export type MapDestRow = {
|
export type MapDestRow = {
|
||||||
id: string; label: string; category: string; rate: string; bps: number; share: number | null; hl: boolean
|
id: string; label: string; category: string; rate: string; bps: number; share: number | null; hl: boolean
|
||||||
kind?: "service" | "country" | "category"; countryCode?: string
|
kind?: "service" | "country" | "category"; countryCode?: string
|
||||||
@@ -21,27 +20,14 @@ export type MapDestRow = {
|
|||||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
||||||
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
||||||
|
|
||||||
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
|
function AnalysisGrid<T extends {id:string}>({rows, columns, empty}: {
|
||||||
return (
|
rows:T[]; columns:CompactDataGridColumn<T>[]; empty:string
|
||||||
<div className="max-h-[min(34svh,310px)] overflow-auto">
|
}) {
|
||||||
<div className="min-w-[720px]">
|
return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
|
||||||
<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)}>
|
<CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle={empty} />
|
||||||
{head.map((h) => <span key={h}>{h}</span>)}
|
</div>
|
||||||
</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 EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
|
|
||||||
|
|
||||||
function Destinations({ rows, onDestination, onCategory }: {
|
function Destinations({ rows, onDestination, onCategory }: {
|
||||||
rows: MapDestRow[]
|
rows: MapDestRow[]
|
||||||
onDestination: (id: string) => void
|
onDestination: (id: string) => void
|
||||||
@@ -67,16 +53,14 @@ function Destinations({ rows, onDestination, onCategory }: {
|
|||||||
<span className="font-mono text-xs tabular-nums">{Math.round(row.share * 100)}%</span>
|
<span className="font-mono text-xs tabular-nums">{Math.round(row.share * 100)}%</span>
|
||||||
</span> },
|
</span> },
|
||||||
], [onDestination, onCategory])
|
], [onDestination, onCategory])
|
||||||
return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
|
return <AnalysisGrid rows={rows} columns={columns} empty="Назначений за окно нет" />
|
||||||
<CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle="Назначений за окно нет" />
|
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
||||||
* Строки выбранного объекта подсвечены.
|
* Строки выбранного объекта подсвечены.
|
||||||
*/
|
*/
|
||||||
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, onCategory, eventsError, stat }: {
|
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onTunnel, onDestination, onCategory, eventsError, stat }: {
|
||||||
tab: MapBottomTab
|
tab: MapBottomTab
|
||||||
onTab: (tab: MapBottomTab) => void
|
onTab: (tab: MapBottomTab) => void
|
||||||
open: boolean
|
open: boolean
|
||||||
@@ -87,12 +71,33 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
events: MapEventRow[]
|
events: MapEventRow[]
|
||||||
onEvent: (event: MapEventRow) => void
|
onEvent: (event: MapEventRow) => void
|
||||||
onFlow: (id: string) => void
|
onFlow: (id: string) => void
|
||||||
|
onTunnel: (id: string) => void
|
||||||
onDestination: (id: string) => void
|
onDestination: (id: string) => void
|
||||||
onCategory?: (category: string) => void
|
onCategory?: (category: string) => void
|
||||||
eventsError: string | null
|
eventsError: string | null
|
||||||
stat: string
|
stat: string
|
||||||
}) {
|
}) {
|
||||||
const [showRoutineEvents, setShowRoutineEvents] = useState(false)
|
const [showRoutineEvents, setShowRoutineEvents] = useState(false)
|
||||||
|
const flowColumns: CompactDataGridColumn<MapFlowRow>[] = [
|
||||||
|
{id:"dest",header:"Поток к назначению",size:156,cell:r=><Button variant="link" size="xs" data-map-highlight={r.hl || undefined} onClick={() => onFlow(r.id)}>{r.dest}</Button>},
|
||||||
|
{id:"client",header:"Пользователь",size:142},
|
||||||
|
{id:"exit",header:"Выход / экспортёр",size:178,cell:r=><div><span>{r.exit}</span><small className="block text-muted-foreground">{r.confirmed ? "Выход подтверждён" : "Выход не подтверждён"}</small></div>},
|
||||||
|
{id:"bps",header:"Скорость",size:125,cell:r=><span className="tabular-nums">{r.rate}</span>},
|
||||||
|
{id:"bytes",header:"Объём",size:120,cell:r=><span className="tabular-nums">{r.volume}</span>},
|
||||||
|
]
|
||||||
|
const rttColumns: CompactDataGridColumn<MapRttRow>[] = [
|
||||||
|
{id:"name",header:"Канал",size:160,cell:r=><Button variant="link" size="xs" data-map-highlight={r.hl || undefined} onClick={() => onTunnel(r.id)}>{r.name}</Button>},
|
||||||
|
{id:"route",header:"Участок",size:180},
|
||||||
|
{id:"rttMs",header:"RTT",size:90,cell:r=>r.rtt},
|
||||||
|
{id:"speed",header:"Скорость ↓/↑",size:152,enableSorting:false},
|
||||||
|
{id:"status",header:"Состояние",size:125,cell:r=><ToneBadge tone={r.tone}>{r.status}</ToneBadge>},
|
||||||
|
]
|
||||||
|
const eventColumns: CompactDataGridColumn<MapEventRow>[] = [
|
||||||
|
{id:"ts",header:"Время",size:84,cell:r=><time dateTime={new Date(r.ts).toISOString()}>{new Date(r.ts).toLocaleTimeString("ru-RU", {hour:"2-digit",minute:"2-digit"})}</time>},
|
||||||
|
{id:"title",header:"Событие",size:225,cell:r=><Button variant="link" size="xs" onClick={()=>onEvent(r)}>{r.title}</Button>},
|
||||||
|
{id:"label",header:"Тип",size:112,cell:r=><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge>},
|
||||||
|
{id:"message",header:"Подробности",size:255},
|
||||||
|
]
|
||||||
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
|
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
|
||||||
const visibleEvents = showRoutineEvents ? events : incidentEvents
|
const visibleEvents = showRoutineEvents ? events : incidentEvents
|
||||||
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
|
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
|
||||||
@@ -102,46 +107,29 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
{ id: "events", label: "События", count: visibleEvents.length },
|
{ id: "events", label: "События", count: visibleEvents.length },
|
||||||
]
|
]
|
||||||
return (
|
return (
|
||||||
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0">
|
<section aria-label="Рабочая панель карты" className="@container/workbench min-w-0 shrink-0 rounded-xl border bg-card">
|
||||||
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1">
|
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-0">
|
||||||
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
|
<div className="flex min-w-0 items-center gap-1.5 p-1.5">
|
||||||
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель">
|
<div className="min-w-0 flex-1"><TabsList aria-label="Рабочая панель" className="max-w-full flex-wrap justify-start gap-y-1" style={{height:"auto"}}>
|
||||||
{tabs.map((t) => (
|
{tabs.map((t) => (
|
||||||
<TabsTrigger key={t.id} value={t.id} className="px-2.5" onClick={() => onOpenChange(true)}>
|
<TabsTrigger key={t.id} value={t.id} className="h-7 flex-none px-2.5" onClick={() => onOpenChange(true)}>
|
||||||
{t.label}
|
{t.label}
|
||||||
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
|
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
))}
|
))}
|
||||||
</TabsList></div>
|
</TabsList></div>
|
||||||
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
|
<Button type="button" variant="outline" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
|
||||||
</div>
|
</div>
|
||||||
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
|
<FramePanel id="network-map-analysis" hidden={!open} className="min-w-0 rounded-none border-0 border-t p-3">
|
||||||
{open && <p className="px-3 py-1 text-[11px] text-muted-foreground">{stat}</p>}
|
{open && <header className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||||
|
<h2 className="text-base font-semibold">{tabs.find(item => item.id === tab)?.label}</h2>
|
||||||
|
<span className="text-[11px] text-muted-foreground">{stat}</span>
|
||||||
|
</header>}
|
||||||
<TabsContent value="flows">
|
<TabsContent value="flows">
|
||||||
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
<AnalysisGrid rows={flows} columns={flowColumns} empty="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>
|
|
||||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onFlow(r.id)}><span className="truncate">{r.dest}</span></Button>
|
|
||||||
<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>
|
||||||
<TabsContent value="rtt">
|
<TabsContent value="rtt">
|
||||||
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}>
|
<AnalysisGrid rows={rtt} columns={rttColumns} empty="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>
|
||||||
<TabsContent value="dest">
|
<TabsContent value="dest">
|
||||||
<Destinations rows={destinations} onDestination={onDestination} onCategory={onCategory} />
|
<Destinations rows={destinations} onDestination={onDestination} onCategory={onCategory} />
|
||||||
@@ -152,20 +140,11 @@ export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, des
|
|||||||
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
|
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
|
||||||
</div>
|
</div>
|
||||||
{eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>}
|
{eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>}
|
||||||
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={visibleEvents.length ? null : eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"}>
|
<AnalysisGrid rows={visibleEvents} columns={eventColumns} empty={eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"} />
|
||||||
{visibleEvents.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>
|
|
||||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onEvent(r)}><span className="truncate">{r.title}</span></Button>
|
|
||||||
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
|
|
||||||
</Row>
|
|
||||||
))}
|
|
||||||
</Table>
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</FramePanel>
|
</FramePanel>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</SectionFrame>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,40 +162,35 @@ export function MapTimeline({ events, now, state, onPick, onJournal }: { events:
|
|||||||
group.push(event)
|
group.push(event)
|
||||||
hours.set(hour, group)
|
hours.set(hour, group)
|
||||||
}
|
}
|
||||||
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
|
const yesterday = new Date(from).toLocaleTimeString("ru-RU", {hour:"2-digit", minute:"2-digit"})
|
||||||
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
|
|
||||||
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
|
|
||||||
return (
|
return (
|
||||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
|
<section aria-label="Лента инцидентов" className="@container/incidents min-w-0 shrink-0 rounded-xl border bg-card">
|
||||||
<small className="flex flex-col text-xs text-muted-foreground" title={state}>Инциденты{state ? <span role="status" className="hidden sm:inline">{state}</span> : null}</small>
|
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1 px-3 py-1.5 @min-[590px]/incidents:grid-cols-[auto_minmax(0,1fr)_auto] @min-[590px]/incidents:gap-x-5">
|
||||||
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
|
<div className="flex items-center gap-2">
|
||||||
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
|
<HistoryIcon aria-hidden className="size-4 shrink-0 text-muted-foreground" />
|
||||||
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
|
<div className="flex flex-wrap items-baseline gap-x-2 @min-[590px]/incidents:block">
|
||||||
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
|
<strong className="block text-[13px] font-semibold">Инциденты</strong>
|
||||||
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label === "−1 ч" ? <span className="hidden xl:inline">{label}</span> : label}
|
<small className="block text-[11px] text-muted-foreground">24 ч · Вся сеть{state && <span role="status"> · {state}</span>}</small>
|
||||||
</span>
|
</div>
|
||||||
))}
|
</div>
|
||||||
{[...hours].map(([hour, group]) => {
|
<div role="group" aria-label="Инциденты карты за 24 часа" className="col-span-2 row-start-2 min-w-0 px-1.5 @min-[590px]/incidents:col-span-1 @min-[590px]/incidents:col-start-2 @min-[590px]/incidents:row-start-1">
|
||||||
const e = group.find(event => event.tone === "er") ?? group[0]
|
<div className="relative h-6 before:absolute before:inset-x-0 before:top-1/2 before:border-t">
|
||||||
const label = `${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
|
{[...hours.values()].map(group => {
|
||||||
return (
|
const event = group.find(item => item.tone === "er") ?? group[0]
|
||||||
<button
|
const label = `${new Date(event.ts).toLocaleTimeString("ru-RU", {hour:"2-digit",minute:"2-digit"})} · ${event.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
|
||||||
key={e.id}
|
return <button key={event.id} type="button" onClick={() => onPick(event)} aria-label={label} title={label}
|
||||||
type="button"
|
className="absolute top-1/2 grid size-6 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
onClick={() => onPick(e)}
|
style={{left:`${(event.ts-from)/86_400_000*100}%`}}>
|
||||||
aria-label={label}
|
<span aria-hidden className="h-2.5 w-2 rounded-[2px]" style={{background:TONE_COLOR[event.tone]}} />
|
||||||
title={label}
|
</button>
|
||||||
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2"
|
})}
|
||||||
style={{ left: at((hour + 0.5) / 24) }}
|
</div>
|
||||||
>
|
<div aria-hidden className="flex justify-between font-mono text-[10px] tabular-nums text-muted-foreground">
|
||||||
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
|
<span>Вчера, {yesterday}</span><span>−12 ч</span><span>Сейчас</span>
|
||||||
</button>
|
</div>
|
||||||
)})}
|
</div>
|
||||||
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
|
<Button type="button" variant="ghost" size="xs" className="col-start-2 row-start-1 @min-[590px]/incidents:col-start-3" onClick={onJournal}>Журнал <ArrowUpRightIcon aria-hidden /></Button>
|
||||||
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<Button type="button" variant="ghost" size="xs" onClick={onJournal}>Журнал</Button>
|
</section>
|
||||||
</div>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import type { KeyboardEvent, MouseEvent, PointerEvent } from "react"
|
||||||
|
import { ArrowDownLeftIcon, ArrowUpRightIcon, ChevronDownIcon, ChevronUpIcon, GlobeIcon, LayersIcon } from "lucide-react"
|
||||||
|
import type { Server, WanUplink } from "@/lib/data"
|
||||||
|
import { fmtRate } from "@/lib/fmt-rate"
|
||||||
|
import { mapCardMeta, mapCardMetrics } from "@/lib/network-map-card-metrics"
|
||||||
|
import type { MapDestinationMode } from "@/lib/network-map-url-state"
|
||||||
|
import { CountryFlagSvg } from "./country-flag-svg"
|
||||||
|
import { ServiceBrandIcon } from "./service-brand-icon"
|
||||||
|
|
||||||
|
const mono = "var(--font-mono,Geist Mono,monospace)"
|
||||||
|
const sans = "var(--font-sans,Geist,sans-serif)"
|
||||||
|
const muted = "var(--muted-foreground)"
|
||||||
|
const ink = "var(--foreground)"
|
||||||
|
const role = {
|
||||||
|
"home-router": {code:"HR",color:"var(--chart-2)"}, "jump-host": {code:"JH",color:"var(--chart-1)"},
|
||||||
|
"exit-node": {code:"EN",color:"var(--chart-3)"}, "ix-node": {code:"IX",color:"var(--chart-4)"},
|
||||||
|
}
|
||||||
|
const statusColor = { online:"var(--success)",degraded:"var(--warning)",offline:"var(--destructive)",unknown:muted }
|
||||||
|
|
||||||
|
function keys(event: KeyboardEvent<SVGGElement>, open: () => void) {
|
||||||
|
if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); open() }
|
||||||
|
}
|
||||||
|
|
||||||
|
function NameLines({ x, y, lines }: { x:number;y:number;lines:string[] }) {
|
||||||
|
return <g fontFamily={sans} fill={ink} fontSize={13} fontWeight={600} pointerEvents="none">
|
||||||
|
{lines.map((part,i) => <text key={i} x={x} y={y+i*14}>{part}</text>)}
|
||||||
|
</g>
|
||||||
|
}
|
||||||
|
|
||||||
|
function FocusRing({width,height,radius}: {width:number;height:number;radius:number}) {
|
||||||
|
return <rect className="network-map-focus-ring" x={-width/2-4} y={-height/2-4} width={width+8} height={height+8}
|
||||||
|
rx={radius+3} fill="none" stroke="var(--ring)" strokeWidth={2}/>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Frame({width,height,kind,radius,stroke,selected,halo,fill="var(--card)"}: {
|
||||||
|
width:number;height:number;kind:"wan"|"card"|"dest";radius:number;stroke:string;selected:boolean;halo?:boolean;fill?:string
|
||||||
|
}) {
|
||||||
|
return <>
|
||||||
|
{selected && halo && <rect x={-3} y={-3} width={width+6} height={height+6} rx={radius+3} fill="none" stroke={stroke} strokeWidth={1.3} strokeDasharray="4 3"/>}
|
||||||
|
<rect data-map-box={kind} width={width} height={height} rx={radius} fill={fill} stroke={stroke} strokeWidth={selected?2:1.5}/>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Signal({x,y,status}:{x:number;y:number;status:Server["status"]}) {
|
||||||
|
return <circle data-node-status={status} cx={x} cy={y} r={4.3} fill={statusColor[status]} stroke="var(--card)" strokeWidth={1.7}/>
|
||||||
|
}
|
||||||
|
|
||||||
|
function shortRate(rate: string) {
|
||||||
|
return rate.replace(/(\d+(?:[.,]\d+)?) ([ГМК]?)бит\/с/g, (_, value: string, unit: string) => {
|
||||||
|
const reading = Number(value.replace(",","."))
|
||||||
|
return reading === 0 ? "0" : reading.toLocaleString("ru-RU",{maximumFractionDigits:2})+(unit||"б/с")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type PointerDown = (e: PointerEvent<SVGGElement>)=>void
|
||||||
|
|
||||||
|
export function ServerNode({ n,width,isSel,isVis,dim,isDragged,hideCatalogLatency,channelProblem,rates,onClick,onDblClick,onHoverChange,onContextMenu,onPointerDown }: {
|
||||||
|
n:Server & {x:number;y:number};width:number;isSel:boolean;isVis:boolean;dim?:boolean;isDragged:boolean
|
||||||
|
hideCatalogLatency?:boolean;channelProblem?:"down"|"degraded";rates?:{rxMbps:number|null;txMbps:number|null}
|
||||||
|
onClick:()=>void;onDblClick:()=>void;onHoverChange:(hover:boolean)=>void;onContextMenu:(e:MouseEvent)=>void;onPointerDown:PointerDown
|
||||||
|
}) {
|
||||||
|
const {height,lines} = mapCardMetrics(n.name,"device",width)
|
||||||
|
const {code,color} = role[n.type]
|
||||||
|
// Рамка и точка — состояние самого узла; отказ канала показан на его линии.
|
||||||
|
const status = n.status
|
||||||
|
const offline = status === "offline", warn = status === "degraded" || Boolean(channelProblem && !offline)
|
||||||
|
const border = isSel ? ink : status === "degraded" ? "color-mix(in oklch,var(--warning) 50%,transparent)" : offline ? "var(--destructive)" : "var(--border)"
|
||||||
|
const iso = /^[A-Za-z]{2}$/.test(n.country?.trim() || "") ? n.country.trim() : ""
|
||||||
|
const metaY = 34 + (lines.length-1)*14, metaX = iso?60:42
|
||||||
|
const site = n.site?.trim() && n.site.trim() !== "—" ? n.site.trim() : "Без площадки"
|
||||||
|
const reading = offline ? "Нет ответа" : channelProblem === "down" ? "Отказ канала" : channelProblem ? "Деградация канала" :
|
||||||
|
!hideCatalogLatency && n.latency != null ? `RTT · ${n.latency} мс` : "Нет данных"
|
||||||
|
return <g role="button" className="network-map-focusable" aria-label={"Устройство "+n.name} aria-pressed={isSel} tabIndex={isVis?0:-1}
|
||||||
|
transform={`translate(${n.x},${n.y})`} data-node-kind="device" data-node-id={n.id} style={{cursor:isDragged?"grabbing":"grab",transition:"opacity .3s"}} opacity={isVis&&!dim?1:.38}
|
||||||
|
onKeyDown={e=>keys(e,onClick)} onClick={e=>{e.stopPropagation();onClick()}}
|
||||||
|
onDoubleClick={e=>{e.stopPropagation();onDblClick()}} onContextMenu={e=>{e.preventDefault();e.stopPropagation();onContextMenu(e)}}
|
||||||
|
onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}} onMouseEnter={()=>onHoverChange(true)} onMouseLeave={()=>onHoverChange(false)}>
|
||||||
|
<title>{[n.name,site,rates?`RouterOS · RX ${fmtRate(rates.rxMbps)} · TX ${fmtRate(rates.txMbps)}`:reading].join(" · ")}</title>
|
||||||
|
<FocusRing width={width} height={height} radius={12}/>
|
||||||
|
<g transform={`translate(${-width/2},${-height/2})`}>
|
||||||
|
<Frame width={width} height={height} kind="card" radius={12} selected={isSel} stroke={border} fill={offline?"color-mix(in oklch,var(--destructive) 10%,var(--card))":"var(--card)"}/>
|
||||||
|
<rect data-role-tile={code} x={7} y={7} width={29} height={29} rx={7} fill={color} fillOpacity={.18}/>
|
||||||
|
<text x={21.5} y={25.5} textAnchor="middle" fill={color} fontSize={11.5} fontWeight={700} fontFamily={mono}>{code}</text>
|
||||||
|
<Signal x={35} y={8} status={status}/>
|
||||||
|
<NameLines x={42} y={19} lines={lines}/>
|
||||||
|
{iso && <g data-country-flag={iso.toUpperCase()} transform={`translate(42,${metaY-8})`}><CountryFlagSvg iso={iso} size={14}/></g>}
|
||||||
|
<text x={metaX} y={metaY} fill={muted} fontFamily={mono} fontSize={10.5}>{mapCardMeta(site,width-metaX-7)}</text>
|
||||||
|
{rates ? (["rx","tx"] as const).map((dir,i)=>{
|
||||||
|
const x=i?width/2+1:8
|
||||||
|
const RxTx=dir==="rx"?ArrowDownLeftIcon:ArrowUpRightIcon
|
||||||
|
const rate=dir==="rx"?rates.rxMbps:rates.txMbps
|
||||||
|
return <g key={dir} data-rate-dir={dir}>
|
||||||
|
<title>{`RouterOS ${dir.toUpperCase()} · ${fmtRate(rate)}`}</title>
|
||||||
|
<RxTx x={x} y={height-19} width={12} height={12} color={dir==="rx"?"var(--chart-rx)":"var(--chart-tx)"}/>
|
||||||
|
<text x={x+14} y={height-9} fill={ink} fontFamily={mono} fontSize={11} fontWeight={500}>{shortRate(fmtRate(rate))}</text>
|
||||||
|
</g>
|
||||||
|
}) : <text x={8} y={height-9} fill={warn?"var(--status-degraded-fg)":ink} fontSize={11} fontWeight={500} fontFamily={warn?sans:mono}>{mapCardMeta(reading,width-15)}</text>}
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WanSatNode({x,y,wan,width,index,active,isSel,isDragged,traffic,onSelect,onPointerDown}: {
|
||||||
|
x:number;y:number;wan:WanUplink;width:number;index:number;active:boolean;isSel:boolean;isDragged:boolean;traffic?:string
|
||||||
|
onSelect:()=>void;onPointerDown:PointerDown
|
||||||
|
}) {
|
||||||
|
const name=wan.isp||wan.name
|
||||||
|
const {height,lines}=mapCardMetrics(name,"wan",width)
|
||||||
|
const status = active || traffic?.startsWith("Live ") ? "online" : "unknown"
|
||||||
|
return <g data-node-kind="wan" data-wan-index={index} role="button" aria-label={"Аплинк "+wan.name} aria-pressed={isSel} tabIndex={0} className="network-map-focusable"
|
||||||
|
transform={`translate(${x},${y})`} style={{cursor:isDragged?"grabbing":"grab"}} onKeyDown={e=>keys(e,onSelect)}
|
||||||
|
onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}} onClick={e=>{e.stopPropagation();onSelect()}}>
|
||||||
|
<title>{[name,wan.name,wan.iface,traffic||"Нет данных"].filter(Boolean).join(" · ")}</title>
|
||||||
|
<FocusRing width={width} height={height} radius={24}/>
|
||||||
|
<g transform={`translate(${-width/2},${-height/2})`}>
|
||||||
|
<Frame width={width} height={height} kind="wan" radius={24} stroke={isSel?ink:"var(--border)"} halo selected={isSel}/>
|
||||||
|
<circle cx={19} cy={21} r={12} fill="var(--muted)"/>
|
||||||
|
<GlobeIcon x={11} y={13} width={16} height={16} color={muted}/>
|
||||||
|
<Signal x={29} y={11} status={status}/>
|
||||||
|
<NameLines x={35} y={18} lines={lines}/>
|
||||||
|
<text x={35} y={33+(lines.length-1)*14} fill={muted} fontFamily={mono} fontSize={10.5}>{mapCardMeta(traffic?shortRate(traffic):"Нет данных",width-42)}</text>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ServiceNode({label,share,x,y,width,isSel,isVis,isDragged,destMode,iso,dim,shareLabel,category,rate,expanded,onClick,onPointerDown}: {
|
||||||
|
label:string;share:number|null;x:number;y:number;width:number;isSel:boolean;isVis:boolean;isDragged:boolean;destMode:MapDestinationMode
|
||||||
|
iso?:string;dim?:boolean;shareLabel?:string;category?:string;rate?:string;expanded?:boolean;onClick:()=>void;onPointerDown:PointerDown
|
||||||
|
}) {
|
||||||
|
const {height,lines} = mapCardMetrics(label,"destination",width)
|
||||||
|
const kind=expanded!==undefined?"minor-services":destMode==="categories"?"category":destMode==="countries"?"country":"service"
|
||||||
|
const aria=kind==="minor-services"?label:(kind==="service"?"Сервис ":kind==="country"?"Страна ":"Категория ")+label
|
||||||
|
const percent=share!=null?`${Math.round(share*100)}%`:"—"
|
||||||
|
const speed = rate?.replace(/\d+(?:[.,]\d+)?(?= [ГМК]?бит\/с)/g,
|
||||||
|
value => Number(value.replace(",",".")).toLocaleString("ru-RU",{maximumFractionDigits:2}))
|
||||||
|
const attrs=kind==="service"?{"data-service-brand":label}:kind==="country"?{"data-country-flag":iso}:kind==="category"?{"data-traffic-category":label}:{}
|
||||||
|
const Chevron=expanded?ChevronUpIcon:ChevronDownIcon
|
||||||
|
const subtitle=category||(kind==="country"?"Страна":"Сервис")
|
||||||
|
return <g data-node-kind={kind} role="button" aria-label={aria} aria-pressed={expanded===undefined?isSel:undefined} aria-expanded={expanded} tabIndex={isVis?0:-1} className="network-map-focusable"
|
||||||
|
transform={`translate(${x},${y})`} style={{cursor:expanded!==undefined?"pointer":isDragged?"grabbing":"grab"}} opacity={!isVis||dim ? .38 : 1}
|
||||||
|
onKeyDown={e=>keys(e,onClick)} onClick={e=>{e.stopPropagation();onClick()}} onPointerDown={e=>{e.stopPropagation();onPointerDown(e)}}>
|
||||||
|
<title>{[label,subtitle,speed,share===null?"Доля неизвестна":percent+" "+(shareLabel??"трафика окна")].filter(Boolean).join(" · ")}</title>
|
||||||
|
<FocusRing width={width} height={height} radius={9}/>
|
||||||
|
<g transform={`translate(${-width/2},${-height/2})`}>
|
||||||
|
<Frame width={width} height={height} kind="dest" radius={9} stroke={isSel?"var(--chart-4)":"var(--border)"} selected={isSel} halo/>
|
||||||
|
<circle cx={22} cy={21} r={14.5} fill="var(--muted)"/>
|
||||||
|
<g {...attrs} aria-hidden="true">
|
||||||
|
{kind==="minor-services"?<Chevron x={14} y={13} width={16} height={16} color={muted}/>:
|
||||||
|
kind==="category"?<LayersIcon x={14} y={13} width={16} height={16} color="var(--chart-4)"/>:
|
||||||
|
kind==="country"&&iso&&/^[a-z]{2}$/i.test(iso)?<g transform="translate(11,13)"><CountryFlagSvg iso={iso} size={22}/></g>:
|
||||||
|
kind==="country"?<GlobeIcon x={14} y={13} width={16} height={16} color={muted}/>:
|
||||||
|
<g transform="translate(11,10)"><ServiceBrandIcon label={label} size={22}/></g>}
|
||||||
|
</g>
|
||||||
|
<NameLines x={42} y={18} lines={lines}/>
|
||||||
|
<text x={kind==="minor-services" && width<150 ? 8 : 42} y={33+(lines.length-1)*14} fill={muted} fontFamily={sans} fontSize={11}>
|
||||||
|
{kind==="minor-services"&&!expanded?subtitle:mapCardMeta(subtitle,width-49)}</text>
|
||||||
|
<text x={8} y={height-12} fill={ink} fontFamily={mono} fontSize={11} fontWeight={500}>{mapCardMeta(speed||"Нет данных",width-46)}</text>
|
||||||
|
<text x={width-7} y={height-12} textAnchor="end" fill={muted} fontFamily={mono} fontSize={10.5}>{percent}</text>
|
||||||
|
{share!==null && <><rect x={8} y={height-7} width={width-16} height={2.5} rx={1.25} fill="var(--muted)"/>
|
||||||
|
<rect data-service-share={share*100} x={8} y={height-7} width={(width-16)*Math.max(0,Math.min(1,share))} height={2.5} rx={1.25} fill="var(--chart-4)"/></>}
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { TriangleAlertIcon } from "lucide-react"
|
||||||
|
import { Badge } from "@/components/reui/badge"
|
||||||
|
|
||||||
|
export function MapFaultBadge({ width, text, down }: { width: number; text: string; down: boolean }) {
|
||||||
|
const tone = down ? "var(--status-offline-fg)" : "var(--status-degraded-fg)"
|
||||||
|
return <>
|
||||||
|
<rect data-map-box="pill" x={-width/2} y="-11" width={width} height="22" rx="5" fill="var(--card)" />
|
||||||
|
<foreignObject data-map-runtime-badge x={-width/2} y="-11" width={width} height="22" pointerEvents="none">
|
||||||
|
<div className="flex h-full items-center justify-center dark:[--destructive-foreground:var(--status-offline-fg)] dark:[--warning-foreground:var(--status-degraded-fg)]">
|
||||||
|
<Badge size="lg" variant={down ? "destructive-light" : "warning-light"}><TriangleAlertIcon aria-hidden="true" />{text}</Badge>
|
||||||
|
</div>
|
||||||
|
</foreignObject>
|
||||||
|
<g data-map-export-badge display="none" aria-hidden="true">
|
||||||
|
<rect x={-width/2} y="-11" width={width} height="22" rx="5" fill={down ? "var(--destructive)" : "var(--warning)"} fillOpacity=".14" />
|
||||||
|
<TriangleAlertIcon x={-width/2+6} y="-6" width="12" height="12" color={tone} />
|
||||||
|
<text x="7" y="4" textAnchor="middle" fill={tone} fontSize="12" fontWeight="500" fontFamily="Geist,sans-serif">{text}</text>
|
||||||
|
</g>
|
||||||
|
</>
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
type CardKind = "device" | "wan" | "destination" | "access" | "user" | "group"
|
||||||
|
|
||||||
|
const cards: Record<CardKind, {height:number; inset:number}> = {
|
||||||
|
device: {height:63, inset:48}, wan: {height:51, inset:41}, destination: {height:64, inset:46},
|
||||||
|
access: {height:47, inset:33}, user: {height:47, inset:41}, group: {height:53, inset:62},
|
||||||
|
}
|
||||||
|
|
||||||
|
let measuringContext: CanvasRenderingContext2D | null = null
|
||||||
|
function textWidth(text: string) {
|
||||||
|
if (!measuringContext && typeof document !== "undefined") {
|
||||||
|
measuringContext = document.createElement("canvas").getContext("2d")
|
||||||
|
if (measuringContext) measuringContext.font = "600 13px " + getComputedStyle(document.body).fontFamily
|
||||||
|
}
|
||||||
|
if (measuringContext) return measuringContext.measureText(text).width
|
||||||
|
return [...text].reduce((w, ch) => w + (/[il1.,:'!|-]/.test(ch) ? 4.3 : /[mwMWШЩЖМЮ]/.test(ch) ? 11 : /[A-ZА-ЯЁ0-9]/.test(ch) ? 8.5 : 7.3), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SVG marks, row placement and link routing share the same wrapped title and physical bounds. */
|
||||||
|
export function mapCardMetrics(name: string, kind: CardKind, width: number) {
|
||||||
|
const {height,inset} = cards[kind]
|
||||||
|
const room = Math.max(12,width-inset)
|
||||||
|
if (textWidth(name) <= room) return {width,height,lines:[name || "—"]}
|
||||||
|
const lines: string[] = []
|
||||||
|
let line = ""
|
||||||
|
function flush() {
|
||||||
|
if (line.trim()) lines.push(line.trim())
|
||||||
|
line = ""
|
||||||
|
}
|
||||||
|
function word(part: string) {
|
||||||
|
if (textWidth((line+part).trim()) <= room) { line += part; return }
|
||||||
|
if (line.trim()) flush()
|
||||||
|
if (textWidth(part.trim()) <= room) { line = part; return }
|
||||||
|
for (const char of part) {
|
||||||
|
if (line.trim() && textWidth((line+char).trim()) > room) flush()
|
||||||
|
line += char
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nameParts = (text: string) => text.match(/[^\s-]+-?|\s+|-/gu) ?? []
|
||||||
|
const host = kind === "device" && /^[\w-]+(?:\.[\w-]+){2,}$/.test(name)
|
||||||
|
// Домен хоста — в подсказке и панели справа; на карточке только короткое имя в одну строку.
|
||||||
|
if (host) nameParts(name.slice(0,name.indexOf("."))).forEach(word)
|
||||||
|
else nameParts(name).forEach(word)
|
||||||
|
flush()
|
||||||
|
if (!lines.length) lines.push("—")
|
||||||
|
return {width, lines, height:height+(lines.length-1)*14}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapCardMeta(text: string, room: number) {
|
||||||
|
const max = Math.max(7,Math.floor(room/6.2))
|
||||||
|
return text.length > max ? text.slice(0,max-1)+"…" : text
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import type { Server } from "./data"
|
||||||
|
import type { projectNetworkMapDensity, MapPoint } from "./network-map-density"
|
||||||
|
import { densityWanKey } from "./network-map-density"
|
||||||
|
import { mapCardMetrics } from "./network-map-card-metrics"
|
||||||
|
|
||||||
|
export type MapLane = "access" | "home" | "wan" | "jh" | "en" | "dest" | "nested"
|
||||||
|
export const deviceLane = (type: Server["type"]) => type === "home-router" ? "home" : type === "jump-host" ? "jh" : "en"
|
||||||
|
const minimum = {access:147, home:158, wan:147, jh:157, en:162, dest:167, nested:167}
|
||||||
|
const preferredCard = {access:150, home:157, wan:155, jh:157, en:157, dest:174, nested:174}
|
||||||
|
const laneOrder: MapLane[] = ["access", "home", "wan", "jh", "en", "dest", "nested"]
|
||||||
|
type Row = {
|
||||||
|
name: string
|
||||||
|
kind: Parameters<typeof mapCardMetrics>[1]
|
||||||
|
order: number
|
||||||
|
place: (point: MapPoint) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Place the visible rows at their real text size; retain the projected anchors for all folded members. */
|
||||||
|
export function layoutNetworkMapColumns(
|
||||||
|
viewWidth: number,
|
||||||
|
servers: readonly Server[],
|
||||||
|
projection: ReturnType<typeof projectNetworkMapDensity>,
|
||||||
|
access: {name:string; individual:boolean} | null,
|
||||||
|
destinations: ReadonlyArray<{id:string; name:string}>,
|
||||||
|
nested: ReadonlyArray<{id:string; name:string}>,
|
||||||
|
) {
|
||||||
|
const rows: Record<MapLane, Row[]> = {access:[], home:[], wan:[], jh:[], en:[], dest:[], nested:[]}
|
||||||
|
const nodePos = {...projection.nodePos}
|
||||||
|
const wanSatPos = Object.fromEntries(Object.entries(projection.wanSatPos).map(([id, points]) => [id, [...points]]))
|
||||||
|
const groups = projection.groups.map(group => ({...group}))
|
||||||
|
let accessPosition: MapPoint = {x:0, y:0}
|
||||||
|
const destPos: Record<string, MapPoint> = {}
|
||||||
|
const nestedPos: Record<string, MapPoint> = {}
|
||||||
|
if (access) {
|
||||||
|
rows.access.push({
|
||||||
|
name: access.name, kind: access.individual ? "user" : "access", order: 0,
|
||||||
|
place: point => { accessPosition = point },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const routers = servers.filter(server => server.type === "home-router")
|
||||||
|
.sort((a, b) => nodePos[a.id].y - nodePos[b.id].y || a.id.localeCompare(b.id))
|
||||||
|
const routerOrder = new Map(routers.map((server, index) => [server.id, index]))
|
||||||
|
for (const server of servers) {
|
||||||
|
if (!projection.hiddenServers.has(server.id)) {
|
||||||
|
rows[deviceLane(server.type)].push({
|
||||||
|
name: server.name, kind: "device", order: nodePos[server.id].y,
|
||||||
|
place: point => { nodePos[server.id] = point },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (server.type !== "home-router") continue
|
||||||
|
const uplinks = server.wanUplinks ?? []
|
||||||
|
for (const [index, wan] of uplinks.entries()) {
|
||||||
|
if (projection.hiddenWans.has(densityWanKey(server.id, index))) continue
|
||||||
|
rows.wan.push({
|
||||||
|
name: wan.isp || wan.name, kind: "wan",
|
||||||
|
// The group header sorts first, followed by its uplinks in router interface order.
|
||||||
|
order: routerOrder.get(server.id)! + (index + 1) / (uplinks.length + 1),
|
||||||
|
place: point => { wanSatPos[server.id][index] = point },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const group of groups) {
|
||||||
|
const lane = group.kind === "wan" ? "wan" : deviceLane(group.type)
|
||||||
|
rows[lane].push({
|
||||||
|
name: group.label, kind: "group", order: group.routerId ? routerOrder.get(group.routerId)! : group.y,
|
||||||
|
place: point => Object.assign(group, point),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
destinations.forEach((item, index) => {
|
||||||
|
rows.dest.push({name:item.name, kind:"destination", order:index, place:point => { destPos[item.id] = point }})
|
||||||
|
})
|
||||||
|
nested.forEach((item, index) => {
|
||||||
|
rows.nested.push({name:item.name, kind:"destination", order:index, place:point => { nestedPos[item.id] = point }})
|
||||||
|
})
|
||||||
|
const active = laneOrder.filter(lane => rows[lane].length)
|
||||||
|
const minimumWidth = active.reduce((sum,id) => sum + minimum[id], 0)
|
||||||
|
const worldWidth = Math.max(viewWidth,minimumWidth)
|
||||||
|
const extra = active.length ? (worldWidth-minimumWidth)/active.length : 0
|
||||||
|
const cardWidths = {...preferredCard}
|
||||||
|
let left = 0
|
||||||
|
const columns = active.map(id => {
|
||||||
|
const width = minimum[id] + extra
|
||||||
|
const x0 = left
|
||||||
|
left += width
|
||||||
|
cardWidths[id] = Math.min(preferredCard[id], width - 17)
|
||||||
|
const items = rows[id].sort((a, b) => a.order - b.order).map(row => ({
|
||||||
|
row, height: mapCardMetrics(row.name, row.kind, cardWidths[id]).height,
|
||||||
|
}))
|
||||||
|
return {id, x0, x1:left, cx:x0+width/2, items}
|
||||||
|
})
|
||||||
|
const gap = 15, top = 86
|
||||||
|
const tallest = Math.max(0, ...columns.map(({items}) => items.slice(0,5).reduce((sum,item) => sum+item.height+gap,0)))
|
||||||
|
const bodyHeight = Math.max(225,Math.min(390,tallest))
|
||||||
|
let worldHeight = Math.max(340, top+bodyHeight+24)
|
||||||
|
for (const {cx,items} of columns) {
|
||||||
|
const stack = items.reduce((sum,item) => sum+item.height+gap,-gap)
|
||||||
|
let y = top + Math.max(0,(bodyHeight-stack)/2)
|
||||||
|
for (const {row,height} of items) {
|
||||||
|
row.place({x:cx,y:y+height/2})
|
||||||
|
y += height+gap
|
||||||
|
}
|
||||||
|
worldHeight = Math.max(worldHeight,y-gap+26)
|
||||||
|
}
|
||||||
|
const groupById = new Map(groups.map(g => [g.id,g]))
|
||||||
|
for (const [id, parent] of projection.hiddenServers) {
|
||||||
|
const {x, y} = groupById.get(parent)!
|
||||||
|
nodePos[id] = {x, y}
|
||||||
|
}
|
||||||
|
for (const server of servers) for (const [i] of (server.wanUplinks ?? []).entries()) {
|
||||||
|
const parent = projection.hiddenWans.get(densityWanKey(server.id, i))
|
||||||
|
if (parent) {
|
||||||
|
const {x, y} = groupById.get(parent)!
|
||||||
|
wanSatPos[server.id][i] = {x, y}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {groups, nodePos, wanSatPos, accessPosition, destPos, nestedPos, columns, cardWidths, worldWidth, worldHeight}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import assert from "node:assert/strict"
|
import assert from "node:assert/strict"
|
||||||
import { test } from "node:test"
|
import { test } from "node:test"
|
||||||
import type { GreTunnel, Server } from "./data"
|
import { greTunnels, type GreTunnel, type Server } from "./data"
|
||||||
import { densityWanKey, projectNetworkMapDensity } from "./network-map-density"
|
import { densityWanKey, projectNetworkMapDensity } from "./network-map-density"
|
||||||
import { collectGroupLinks } from "./network-map-group-links"
|
import { collectGroupLinks, countGroupGre } from "./network-map-group-links"
|
||||||
import { buildGreMapEdges, computeNetworkMapLayout, MAP_CARD_H, MAP_WAN_H } from "./network-map-layout"
|
import { buildGreMapEdges, computeNetworkMapLayout, MAP_CARD_H, MAP_WAN_H } from "./network-map-layout"
|
||||||
|
|
||||||
function server(id: string, type: Server["type"], site: string, wanCount = 0): Server {
|
function server(id: string, type: Server["type"], site: string, wanCount = 0): Server {
|
||||||
@@ -120,3 +120,22 @@ test("обратный отчёт GRE привязан к нужному WAN, г
|
|||||||
from:{...group,name:group.label,groupId:group.id,halfWidth:80},to:{...gre.to,id:jh.id,name:jh.name,halfWidth:80}})))
|
from:{...group,name:group.label,groupId:group.id,halfWidth:80},to:{...gre.to,id:jh.id,name:jh.name,halfWidth:80}})))
|
||||||
assert.deepEqual([bundle.count,bundle.down,bundle.degraded],[3,1,0])
|
assert.deepEqual([bundle.count,bundle.down,bundle.degraded],[3,1,0])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("отказ между двумя узлами доступа одной группы учитывается свёрнутым и ведёт к обоим узлам после раскрытия", () => {
|
||||||
|
const servers = Array.from({length:12},(_,i) => ({...server("nsk-jh-"+(i+1),"jump-host","NSK"),host:`192.0.2.${i+1}`}))
|
||||||
|
const [first] = servers, last = servers.at(-1)!
|
||||||
|
const tunnel: GreTunnel = {...greTunnels[0],id:"nsk-internal",serverId:last.id,localAddress:last.host,remoteAddress:first.host,status:"down"}
|
||||||
|
const base = computeNetworkMapLayout(servers,[tunnel])
|
||||||
|
const edges = buildGreMapEdges([tunnel],servers,base.nodePos,base.wanSatPos)
|
||||||
|
const closed = projectNetworkMapDensity(servers,base.nodePos,base.wanSatPos,new Set())
|
||||||
|
const [group] = closed.groups
|
||||||
|
assert.equal(closed.hiddenServers.get(first.id),group.id)
|
||||||
|
assert.equal(closed.hiddenServers.get(last.id),group.id)
|
||||||
|
assert.deepEqual(countGroupGre(edges.filter(e=>group.serverIds.includes(e.fromServer.id)||group.serverIds.includes(e.toServer.id))),
|
||||||
|
{count:1,down:1,degraded:0})
|
||||||
|
const open = projectNetworkMapDensity(servers,base.nodePos,base.wanSatPos,new Set([group.id]))
|
||||||
|
const [channel] = buildGreMapEdges([tunnel],servers,open.nodePos,open.wanSatPos)
|
||||||
|
assert.deepEqual(new Set([channel.fromServer.id,channel.toServer.id]),new Set([first.id,last.id]))
|
||||||
|
assert.equal(channel.from.x,channel.to.x)
|
||||||
|
assert.notEqual(channel.from.y,channel.to.y)
|
||||||
|
})
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { mapLinkPath, type GreMapEdge } from "./network-map-layout"
|
import { mapLinkPath, type GreMapEdge, type MapBox } from "./network-map-layout"
|
||||||
|
|
||||||
export type GroupLinkEnd = {
|
export type GroupLinkEnd = {
|
||||||
id: string
|
id: string
|
||||||
@@ -54,7 +54,7 @@ export function channelStatus({ tunnel, peerTunnel }: GreMapEdge) {
|
|||||||
return peerTunnel && peerTunnel.status !== tunnel.status ? "degraded" : tunnel.status
|
return peerTunnel && peerTunnel.status !== tunnel.status ? "degraded" : tunnel.status
|
||||||
}
|
}
|
||||||
|
|
||||||
export function collectGroupLinks(rows: Iterable<MapGroupConnection>) {
|
export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?: MapBox[]) {
|
||||||
const buckets = new Map<string, MapGroupConnection[]>()
|
const buckets = new Map<string, MapGroupConnection[]>()
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (!(row.from.groupId || row.to.groupId) || row.from.id === row.to.id) continue
|
if (!(row.from.groupId || row.to.groupId) || row.from.id === row.to.id) continue
|
||||||
@@ -75,7 +75,8 @@ export function collectGroupLinks(rows: Iterable<MapGroupConnection>) {
|
|||||||
return {
|
return {
|
||||||
id, from, to, type, ...totals,
|
id, from, to, type, ...totals,
|
||||||
groups: [from.groupId, to.groupId].filter((group): group is string => Boolean(group)),
|
groups: [from.groupId, to.groupId].filter((group): group is string => Boolean(group)),
|
||||||
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth),
|
// Отказ рисуется на своём обычном маршруте: цвет и значок, без отдельной полки над картой.
|
||||||
|
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles}),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-27
@@ -66,30 +66,60 @@ const NESTED_SERVICE_X = 1160
|
|||||||
const MIN_NODE_Y = 80
|
const MIN_NODE_Y = 80
|
||||||
const MAX_NODE_Y = H - 44
|
const MAX_NODE_Y = H - 44
|
||||||
|
|
||||||
/**
|
type MapPoint = { x: number; y: number }
|
||||||
* Плавная связь между боковыми гранями двух карточек: горизонтальная кривая Безье, как в макете.
|
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number; points: MapPoint[] }
|
||||||
* Если карточки в одной полосе — дуга справа от обеих.
|
|
||||||
*/
|
/** Ортогональные участки соединяются закруглениями до 7 единиц, как на карте раздела. */
|
||||||
export function mapLinkPath(
|
export function roundedMapPath(points: MapPoint[]) {
|
||||||
a: { x: number; y: number }, aHalfW: number,
|
const clean = points.filter((p, i) => !i || p.x !== points[i-1].x || p.y !== points[i-1].y)
|
||||||
b: { x: number; y: number }, bHalfW: number,
|
let d = `M ${clean[0].x} ${clean[0].y}`
|
||||||
): MapLink {
|
for (let i = 1; i < clean.length - 1; i++) {
|
||||||
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) {
|
const a = clean[i-1], p = clean[i], b = clean[i+1]
|
||||||
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48
|
const before = Math.hypot(a.x - p.x, a.y - p.y), after = Math.hypot(b.x - p.x, b.y - p.y)
|
||||||
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: bend }
|
const r = Math.min(7, before/2, after/2)
|
||||||
|
d += ` L ${p.x + (a.x-p.x)*r/before} ${p.y + (a.y-p.y)*r/before} Q ${p.x} ${p.y} ${p.x + (b.x-p.x)*r/after} ${p.y + (b.y-p.y)*r/after}`
|
||||||
}
|
}
|
||||||
const dir = b.x > a.x ? 1 : -1
|
const end = clean.at(-1)!
|
||||||
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2
|
return clean.length > 1 ? d + ` L ${end.x} ${end.y}` : d
|
||||||
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: mx }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Связь карты: путь и опорные точки кривой (cx — x обеих управляющих точек). */
|
export function mapLinkPath(
|
||||||
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number }
|
a: MapPoint, aHalfW: number, b: MapPoint, bHalfW: number,
|
||||||
|
options?: { obstacles?: readonly MapBox[] },
|
||||||
|
): MapLink {
|
||||||
|
const sameLane = Math.abs(b.x - a.x) < aHalfW + bHalfW || a.x === b.x
|
||||||
|
const dir = b.x >= a.x ? 1 : -1
|
||||||
|
const startSide = sameLane ? 1 : dir
|
||||||
|
const endSide = sameLane ? 1 : -dir
|
||||||
|
const x1 = a.x + startSide * aHalfW, x2 = b.x + endSide * bHalfW
|
||||||
|
const cx = sameLane ? Math.max(x1, x2) + 6 : (x1 + x2) / 2
|
||||||
|
const inner = (options?.obstacles ?? []).filter(box => box.x > Math.min(a.x, b.x) && box.x + box.w < Math.max(a.x, b.x))
|
||||||
|
const middle = (a.y + b.y) / 2
|
||||||
|
const intersectsRow = (y: number) => inner.some(box => y > box.y - 5 && y < box.y + box.h + 5)
|
||||||
|
let rail: number | undefined
|
||||||
|
if (inner.length) {
|
||||||
|
const rows = [middle, ...inner.flatMap(box => [box.y - 6, box.y + box.h + 6])]
|
||||||
|
rail = rows.filter(y => !intersectsRow(y)).sort((l, r) => Math.abs(l-middle) - Math.abs(r-middle))[0]
|
||||||
|
}
|
||||||
|
const start = {x:x1, y:a.y}, end = {x:x2, y:b.y}
|
||||||
|
const first = x1 + startSide * 5, last = x2 + endSide * 6
|
||||||
|
const points = rail === undefined
|
||||||
|
? [start, {x:cx, y:a.y}, {x:cx, y:b.y}, end]
|
||||||
|
: [start, {x:first,y:a.y}, {x:first,y:rail}, {x:last,y:rail}, {x:last,y:b.y}, end]
|
||||||
|
return { d: roundedMapPath(points), x1, y1:a.y, x2, y2:b.y, cx, points }
|
||||||
|
}
|
||||||
|
|
||||||
/** Точка кривой связи при параметре t ∈ [0, 1]. */
|
|
||||||
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
|
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
|
||||||
const u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t
|
const lengths = l.points.slice(1).map((b, i) => Math.hypot(b.x - l.points[i].x, b.y - l.points[i].y))
|
||||||
return { x: a * l.x1 + (b + c) * l.cx + d * l.x2, y: (a + b) * l.y1 + (c + d) * l.y2 }
|
let remaining = Math.max(0, Math.min(1, t)) * lengths.reduce((sum, n) => sum + n, 0)
|
||||||
|
for (const [i, length] of lengths.entries()) {
|
||||||
|
if (length && remaining <= length) {
|
||||||
|
const a = l.points[i], b = l.points[i+1], ratio = remaining / length
|
||||||
|
return { x:a.x + ratio*(b.x-a.x), y:a.y + ratio*(b.y-a.y) }
|
||||||
|
}
|
||||||
|
remaining -= length
|
||||||
|
}
|
||||||
|
return { x:l.x2, y:l.y2 }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Прямоугольник на холсте (левый верхний угол и размеры). */
|
/** Прямоугольник на холсте (левый верхний угол и размеры). */
|
||||||
@@ -101,14 +131,14 @@ export const mapPillWidth = (text: string) => Math.round(text.length * 6.6 + 16)
|
|||||||
|
|
||||||
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||||
/** Сначала середина кривой (как в макете), затем ближе к концам. */
|
/** Сначала середина кривой (как в макете), затем ближе к концам. */
|
||||||
const LABEL_T = [0.5, 0.42, 0.58, 0.34, 0.66, 0.27, 0.73]
|
const LABEL_T = [0.5, 0.32, 0.68, 0.18, 0.82]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
|
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
|
||||||
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
|
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
|
||||||
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
|
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
|
||||||
*/
|
*/
|
||||||
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[] }>(
|
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[]; fault?: boolean }>(
|
||||||
labels: T[],
|
labels: T[],
|
||||||
obstacles: MapBox[],
|
obstacles: MapBox[],
|
||||||
gap = 4,
|
gap = 4,
|
||||||
@@ -116,17 +146,29 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
|
|||||||
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
|
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
|
||||||
const out: Array<T & { x: number; y: number; w: number; text: string }> = []
|
const out: Array<T & { x: number; y: number; w: number; text: string }> = []
|
||||||
for (const label of labels) {
|
for (const label of labels) {
|
||||||
|
const segments = label.link.points.slice(1).map((b, i) => ({ a:label.link.points[i], b, i,
|
||||||
|
length:Math.hypot(b.x-label.link.points[i].x, b.y-label.link.points[i].y) })).filter(s => s.length)
|
||||||
|
segments.sort((a,b) => (label.fault ? Number(b.i===2)-Number(a.i===2) : 0) || b.length-a.length)
|
||||||
|
let placed = false
|
||||||
search: for (const text of label.texts) {
|
search: for (const text of label.texts) {
|
||||||
const w = mapPillWidth(text)
|
const w = mapPillWidth(text) + (label.fault ? 16 : 0)
|
||||||
for (const t of LABEL_T) {
|
for (const {a,b} of segments) for (const t of LABEL_T) {
|
||||||
const p = mapLinkPoint(label.link, t)
|
const p = { x:a.x+t*(b.x-a.x), y:a.y+t*(b.y-a.y) }
|
||||||
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
|
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
|
||||||
if (taken.some((o) => boxesHit(box, o))) continue
|
if (taken.some((o) => boxesHit(box, o))) continue
|
||||||
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
|
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
|
||||||
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
||||||
|
placed = true
|
||||||
break search
|
break search
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Отказ не пропадает с карты: без свободного места короткая метка встаёт на середину самого длинного участка.
|
||||||
|
if (!placed && label.fault && segments.length && label.texts.length) {
|
||||||
|
const {a,b} = segments.reduce((best, s) => s.length > best.length ? s : best)
|
||||||
|
const text = label.texts.at(-1)!, w = mapPillWidth(text) + 16, p = { x:(a.x+b.x)/2, y:(a.y+b.y)/2 }
|
||||||
|
taken.push({ x: p.x - w / 2 - gap, y: p.y - MAP_PILL_H / 2 - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
|
||||||
|
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
@@ -936,10 +978,9 @@ export function buildGreMapEdges(
|
|||||||
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
|
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
|
||||||
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
|
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
|
||||||
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
|
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
|
||||||
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue
|
if (la == null || lb == null) continue
|
||||||
|
|
||||||
// Строгий поток слева направо: HR → JH → EN.
|
// Keep an undirected channel in the same position for reports from either end.
|
||||||
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
|
|
||||||
let fromServer = a
|
let fromServer = a
|
||||||
let toServer = b
|
let toServer = b
|
||||||
if (la > lb || la === lb && a.id > b.id) {
|
if (la > lb || la === lb && a.id > b.id) {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import type { MapBox, MapLink } from "./network-map-layout"
|
import { roundedMapPath, type MapBox, type MapLink } from "./network-map-layout"
|
||||||
|
|
||||||
/** Find a clear horizontal track between the sides facing the connection after dragging. */
|
/** Find a clear horizontal track between the sides facing the connection after dragging. */
|
||||||
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
|
export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], usedTracks: readonly number[]) {
|
||||||
const { x1, y1, x2, y2, cx } = link
|
const { x1, y1, x2, y2, cx } = link
|
||||||
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(20, Math.abs(cx - x))
|
const stub = (x: number) => x + Math.sign(cx - x) * Math.min(6, Math.abs(cx - x))
|
||||||
const first = stub(x1), last = stub(x2)
|
const first = stub(x1), last = stub(x2)
|
||||||
const middle = (y1 + y2) / 2
|
const middle = (y1 + y2) / 2
|
||||||
const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2))
|
const obstacles = boxes.filter(box => box.x < Math.max(x1, first, last, x2) && box.x + box.w > Math.min(x1, first, last, x2))
|
||||||
@@ -23,7 +23,7 @@ export function mapObservationRoute(link: MapLink, boxes: readonly MapBox[], use
|
|||||||
if (y === undefined) return null
|
if (y === undefined) return null
|
||||||
|
|
||||||
return {
|
return {
|
||||||
d: `M ${x1} ${y1} H ${first} V ${y} H ${last} V ${y2} H ${x2}`,
|
d: roundedMapPath([{x:x1,y:y1},{x:first,y:y1},{x:first,y},{x:last,y},{x:last,y:y2},{x:x2,y:y2}]),
|
||||||
marker: markerFits(y) ? { x: markerX, y } : undefined,
|
marker: markerFits(y) ? { x: markerX, y } : undefined,
|
||||||
track: y,
|
track: y,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import type { Page } from "@playwright/test"
|
||||||
|
import { emptyMapFlow } from "./map-flow"
|
||||||
|
import { observedTrafficFixturePayload } from "../traffic-observation-fixture"
|
||||||
|
|
||||||
|
const ip = (id: number) => "192.0.2." + id
|
||||||
|
const server = (id: number, name: string, type: string, site: string, providers: string[] = []) => ({
|
||||||
|
id, name, type, site, host: ip(id), country: site === "ARN" ? "SE" : site ? "RU" : "", enabled: true,
|
||||||
|
status: id === 7 ? null : "online", latency: id === 7 ? null : id + 2,
|
||||||
|
wanUplinks: providers.map((provider, i) => ({ id: id + "-wan" + (i + 1), name: provider, iface: "ether" + (i + 1),
|
||||||
|
isp: provider, ip: `198.51.100.${id * 16 + i + 1}`, maxDl: 100, maxUl: 100 })),
|
||||||
|
})
|
||||||
|
|
||||||
|
const destinations = [
|
||||||
|
{label:"YouTube", country:"SE", category:"Видео / стриминг", mbps:24.8, user:"north", via:3, exit:8},
|
||||||
|
{label:"Cloudflare", country:"SE", category:"CDN", mbps:13.2, user:"north", via:4, exit:9},
|
||||||
|
{label:"Instagram", country:"DE", category:"Видео / стриминг", mbps:8.4, user:"east", via:5, exit:0},
|
||||||
|
{label:"Telegram", country:"FI", category:"Мессенджеры", mbps:10.4, user:"baltic", via:6, exit:8},
|
||||||
|
{label:"Microsoft", country:"SE", category:"CDN", mbps:2.4, user:"baltic", via:6, exit:8},
|
||||||
|
{label:"AWS", country:"DE", category:"CDN", mbps:0.6, user:"baltic", via:6, exit:8},
|
||||||
|
]
|
||||||
|
|
||||||
|
export async function serveMapVisual(page: Page, dense = false) {
|
||||||
|
const nskProviders = ["Обь Телеком", "Сибирская линия", "Городская сеть"]
|
||||||
|
const servers = [
|
||||||
|
server(1,"msk-home01","home-router","MSK",["Северная сеть","Городская линия"]),
|
||||||
|
server(2,"nsk-home01","home-router","NSK",Array.from({length:dense ? 12 : 2},(_,i) =>
|
||||||
|
i < 3 ? nskProviders[i] : nskProviders[i % 3] + " " + (i + 1))),
|
||||||
|
server(3,"msk-gw01","jump-host","MSK"), server(4,"msk-gw02","jump-host","MSK"),
|
||||||
|
server(5,"nsk-gw01","jump-host","NSK"), server(6,"spb-gw01","jump-host","SPB"),
|
||||||
|
server(7,"spare-gw01","jump-host",""), server(8,"arn-exit01","exit-node","ARN"),
|
||||||
|
server(9,"arn-exit02","exit-node","ARN"), server(10,"spb-ix01","ix-node","SPB"), server(11,"lab-ix01","ix-node","IX-LAB"),
|
||||||
|
...Array.from({length:dense ? 11 : 0},(_,i)=>server(22+i,"nsk-gw"+String(i+2).padStart(2,"0"),"jump-host","NSK")),
|
||||||
|
]
|
||||||
|
const gre = (name:string, from:number, to:number, failed = false) => ({
|
||||||
|
id:name, name, serverId:String(from), localAddress:ip(from), remoteAddress:ip(to), localInnerIp:"", remoteInnerIp:"",
|
||||||
|
poolId:"", ipsec:null, mtu:1476, keepaliveInterval:10, keepaliveRetries:3, dscp:"inherit",
|
||||||
|
clampTcpMss:true, allowFastPath:false, comment:"", enabled:true, status:failed ? "down" : "up",
|
||||||
|
})
|
||||||
|
const tunnels = [gre("gre-arn-main",3,8),gre("gre-arn-backup",3,8),gre("gre-arn-reserve",3,8,true),
|
||||||
|
gre("gre-msk-nsk",3,5),gre("gre-nsk-spb",5,6),gre("gre-msk02-arn02",4,9),
|
||||||
|
...Array.from({length:dense ? 11 : 0},(_,i)=>gre("gre-nsk-"+String(i+2).padStart(2,"0"),22+i,5,i===10))]
|
||||||
|
const links = [[1,3],[1,4],[2,5],[6,8],[6,10]].map(([from,to])=>({from,to,segment:"wg-"+from+"-"+to}))
|
||||||
|
const timestamp = new Date().toISOString()
|
||||||
|
const users = [
|
||||||
|
{id:"north",name:"Северный офис",via:1}, {id:"east",name:"Восточный офис",via:2}, {id:"baltic",name:"Балтийский офис",via:6},
|
||||||
|
].map(u=>{
|
||||||
|
const node=servers.find(s=>s.id===u.via)!
|
||||||
|
return {id:u.id,name:u.name,login:u.id,email:u.id+"@example.test",active:true,role:"viewer",avatar:u.name[0],
|
||||||
|
createdAt:timestamp,updatedAt:timestamp,lastSeen:null,sections:[],servers:[],bindings:[
|
||||||
|
{id:"binding-"+u.id,userId:u.id,serverId:node.id,serverName:node.name,serverSite:node.site,serverCountry:node.country,
|
||||||
|
interfaceName:"gre-"+u.id,interfaceType:"gre",comment:"",createdAt:timestamp,updatedAt:timestamp},
|
||||||
|
]}
|
||||||
|
})
|
||||||
|
const readings = [[1,48.8,12.6],[2,51.2,22.9],[3,132.1,86.3],[4,24.5,17.5],[5,20.4,30.8],[6,18.1,15.1],[8,78.3,95.3],[9,22.9,19.1],[10,10.4,5.2]]
|
||||||
|
const interfaceRates = new Map<string,number>([
|
||||||
|
["3/gre-arn-main",126.4],["3/gre-arn-backup",42],["3/gre-arn-reserve",0],
|
||||||
|
["3/gre-msk-nsk",28.6],["5/gre-nsk-spb",22.6],["4/gre-msk02-arn02",29.4],
|
||||||
|
])
|
||||||
|
for (const router of servers.filter(s=>s.wanUplinks.length)) {
|
||||||
|
router.wanUplinks.forEach((wan,i)=>{
|
||||||
|
if(i!==11) interfaceRates.set(router.id+"/"+wan.iface,i===0 ? (router.id===1?48.8:51.2) : 0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const routerTraffic = observedTrafficFixturePayload(readings.map(([id,rxNow,txNow])=>({
|
||||||
|
id, rxNow, txNow, rxPeak:rxNow, txPeak:txNow, rxTotal:0, txTotal:0, rxSeries:[rxNow], txSeries:[txNow],
|
||||||
|
})))
|
||||||
|
function mapFlow(url:URL) {
|
||||||
|
const window=emptyMapFlow(url)
|
||||||
|
if(window.includesCurrentMinute) window.windowSec=60
|
||||||
|
const selectedUser=url.searchParams.get("userId")
|
||||||
|
const rows=destinations.filter(p=>!selectedUser || p.user===selectedUser)
|
||||||
|
const totalBps=rows.reduce((sum,p)=>sum+Math.round(p.mbps*1e6),0)
|
||||||
|
const services=rows.map(p=>{
|
||||||
|
const bps=Math.round(p.mbps*1e6), bytes=bps*window.windowSec/8
|
||||||
|
return {id:"svc:"+p.label.toLowerCase(),label:p.label,category:p.category,bytes,bps,share:bps/totalBps,
|
||||||
|
trafficTypes:[{transport:p.label==="Instagram"?"UDP/443":"TCP/443",application:p.label==="Instagram"?"QUIC":"HTTPS",bytes}],
|
||||||
|
serviceEvidence:[{basis:p.category==="Видео / стриминг"?"heuristic":"network",bytes}]}
|
||||||
|
})
|
||||||
|
const servicePaths=rows.map((p,i)=>({clientId:p.user,clientName:users.find(u=>u.id===p.user)!.name,
|
||||||
|
viaId:String(p.via),viaName:servers.find(s=>s.id===p.via)!.name,enId:p.exit ? String(p.exit) : "",enName:servers.find(s=>s.id===p.exit)?.name ?? "",
|
||||||
|
serviceId:services[i].id,bps:services[i].bps,bytes:services[i].bytes,serviceEvidence:services[i].serviceEvidence,trafficTypes:services[i].trafficTypes}))
|
||||||
|
const serviceEdges=servicePaths.map(p=>({fromId:p.enId || p.viaId,toId:p.serviceId,...(!p.enId ? {observedOnly:true} : {}),
|
||||||
|
bytes:p.bytes,bps:p.bps,bpsFwd:p.bps,bpsRev:0,clientId:p.clientId,clientName:p.clientName}))
|
||||||
|
const countries=[...new Set(rows.map(s=>s.country))].map(code=>{
|
||||||
|
const bps=rows.reduce((sum,p)=>sum+(p.country===code?Math.round(p.mbps*1e6):0),0)
|
||||||
|
return {id:"cc:"+code.toLowerCase(),label:code,category:"Страна",bps,bytes:bps*window.windowSec/8,share:bps/totalBps}
|
||||||
|
})
|
||||||
|
const countryId=(i:number)=>"cc:"+rows[i].country.toLowerCase()
|
||||||
|
return {...window,live:true,totalBytes:totalBps*window.windowSec/8,namedBytes:totalBps*window.windowSec/8,asnLoaded:true,countryLoaded:true,
|
||||||
|
mapServiceMinSharePct:0,services,servicePaths,serviceEdges,countries,
|
||||||
|
countryPaths:servicePaths.map((p,i)=>({...p,serviceId:countryId(i)})),countryEdges:serviceEdges.map((e,i)=>({...e,toId:countryId(i)})),
|
||||||
|
countryServiceGroups:countries.map(c=>{
|
||||||
|
const indexes=rows.flatMap((_,i)=>countryId(i)===c.id?[i]:[])
|
||||||
|
return {countryId:c.id,services:indexes.map(i=>({...services[i],id:c.id+"|"+services[i].id,share:services[i].bytes/c.bytes})),
|
||||||
|
edges:indexes.map(i=>({...serviceEdges[i],fromId:c.id,toId:c.id+"|"+services[i].id})),
|
||||||
|
paths:indexes.map(i=>({...servicePaths[i],serviceId:c.id+"|"+services[i].id}))}
|
||||||
|
})}
|
||||||
|
}
|
||||||
|
await page.route("**/health",route=>route.fulfill({json:{ok:true}}))
|
||||||
|
await page.route("**/api/**",route=>{
|
||||||
|
const url=new URL(route.request().url()), pathname=url.pathname
|
||||||
|
if(pathname==="/api/traffic/flow/map-hops") return route.fulfill({json:mapFlow(url)})
|
||||||
|
const live=pathname.match(/^\/api\/traffic\/servers\/(\d+)\/live$/)
|
||||||
|
if(live && url.searchParams.get("once")==="1") {
|
||||||
|
const sample=(iface:string)=>{
|
||||||
|
const mbps=interfaceRates.get(live[1]+"/"+iface)
|
||||||
|
return mbps==null ? null : {rxMbps:mbps,txMbps:0,at:new Date().toISOString(),timestampKind:"backend-receipt"}
|
||||||
|
}
|
||||||
|
const iface=url.searchParams.get("iface")
|
||||||
|
return route.fulfill({json:iface ? sample(iface) : {
|
||||||
|
interfaces:Object.fromEntries((url.searchParams.get("ifaces")??"").split(",").map(key=>[key,sample(key)])),
|
||||||
|
}})
|
||||||
|
}
|
||||||
|
const endpoints:Record<string,unknown>={
|
||||||
|
"/api/auth/config":{required:false}, "/api/servers":servers, "/api/users":{users}, "/api/filters/gre-tunnels":{tunnels,failures:[]},
|
||||||
|
"/api/uptime/speed-probes":{probes:[]}, "/api/traffic/servers":{servers:routerTraffic}, "/api/ix/topology":{links},
|
||||||
|
"/api/ix/segments":{items:[{id:"lab",appliedRevision:1}]}, "/api/ix/segments/lab/linux":{items:[
|
||||||
|
{serverId:11,interfaceName:"wg-lab-a",kind:"wireguard",name:"Linux-клиент Альфа",enabled:true},
|
||||||
|
{serverId:11,interfaceName:"gre-lab-b",kind:"gre",name:"Linux-клиент Бета",enabled:true}]},
|
||||||
|
"/api/events":{events:[{id:"gre-arn-reserve-down",createdAt:new Date(Date.parse(timestamp)-8*60_000).toISOString(),
|
||||||
|
level:"warning",eventType:"monitor",sourceModule:"alerts",title:"Недоступен gre-arn-reserve",message:"Не отвечает резервный GRE в ARN",entityType:"server",entityId:"3"}]},
|
||||||
|
}
|
||||||
|
return route.fulfill({json:endpoints[pathname] ?? {}})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -33,7 +33,9 @@ test("Карта: выбранный GRE обновляется и неизве
|
|||||||
let changed=false
|
let changed=false
|
||||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[{...tunnel,name:changed?"gre-new":"gre-home",status:changed?"down":"up"}],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
await page.locator("g").filter({has:page.locator("title",{hasText:"RTT неизвестен."})}).last().click()
|
const link=page.getByRole("button",{name:/^Связь Домашний → Jump:/})
|
||||||
|
await expect(link.locator("title")).toContainText("RTT неизвестен.")
|
||||||
|
await link.press("Enter")
|
||||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
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()
|
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 expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
|
||||||
@@ -44,7 +46,9 @@ test("Карта: GRE сохраняет частичное измерение,
|
|||||||
const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"}
|
const probe={id:"measured-probe",srcServerId:"1",dstServerId:"2",srcInterface:"gre-home",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0.125,lastRxAvgMbps:null,lastPingAt:"2020-01-01T00:00:00Z"}
|
||||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[probe]}:p==="/api/traffic/flow/map-hops"?emptyMapFlow(r.request().url()):p==="/api/auth/config"?{required:false}:{}})})
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
await page.locator("g").filter({has:page.locator("title",{hasText:"Проба measured-probe"})}).last().click()
|
const link=page.getByRole("button",{name:/^Связь /})
|
||||||
|
await expect(link.locator("title")).toContainText("Проба measured-probe")
|
||||||
|
await link.press("Enter")
|
||||||
await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible()
|
await expect(page.getByText("0 мс",{exact:true}).last()).toBeVisible()
|
||||||
await expect(page.getByText("↓0.125 ↑—",{exact:true}).last()).toBeVisible()
|
await expect(page.getByText("↓0.125 ↑—",{exact:true}).last()).toBeVisible()
|
||||||
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
|
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ test("Карта и трафик сохраняют пользователя и
|
|||||||
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
|
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
|
||||||
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
|
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
|
||||||
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
|
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
|
||||||
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('rect[fill="var(--card)"]')).toHaveAttribute("stroke", "var(--border)")
|
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('[data-map-box="access"]')).toHaveAttribute("stroke", "var(--foreground)")
|
||||||
await panel.getByRole("button", {name: /DNS/}).click()
|
await panel.getByRole("button", {name: /DNS/}).click()
|
||||||
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
|
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
|
||||||
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
|
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
|
||||||
@@ -129,7 +129,7 @@ test("Карта показывает скорость и долю за коро
|
|||||||
const url = new URL(response.url())
|
const url = new URL(response.url())
|
||||||
return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status
|
return url.pathname === flowPath && url.searchParams.get("range") === "1m" && url.searchParams.get("userId") === "boris" && response.status() === status
|
||||||
})
|
})
|
||||||
await page.getByRole("button", {name: "Алиса", exact: true}).click()
|
await page.getByRole("button", {name: "Алиса", exact: true}).and(page.locator('[aria-haspopup="dialog"]')).click()
|
||||||
await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()])
|
await Promise.all([borisResponse(503), page.getByRole("option", {name: /Борис/}).click()])
|
||||||
await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible()
|
await expect(card.getByRole("heading", {name: "Борис", exact: true})).toBeVisible()
|
||||||
await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible()
|
await expect(page.getByRole("status").filter({hasText: "Скорости сервисов пока недоступны"})).toBeVisible()
|
||||||
@@ -325,9 +325,10 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
|||||||
})
|
})
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
const badge = page.getByRole("button", { name: /^Связь / })
|
const badge = page.getByRole("button", { name: /^Связь / })
|
||||||
await expect(badge.locator("text")).toHaveText("—")
|
await expect(badge).toHaveAccessibleName(/^Связь .*: GRE(?: ×2)?$/)
|
||||||
|
await expect(badge.locator("text")).toHaveCount(0)
|
||||||
await expect.poll(() => liveReads).toBeGreaterThan(0)
|
await expect.poll(() => liveReads).toBeGreaterThan(0)
|
||||||
await badge.click()
|
await badge.press("Enter")
|
||||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||||
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
|
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
|
||||||
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
|
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
|
||||||
|
|||||||
@@ -18,8 +18,12 @@ for (const width of [320, 390]) test("Карта: мобильные колон
|
|||||||
const nav = page.getByRole("navigation", {name: "Колонки карты"})
|
const nav = page.getByRole("navigation", {name: "Колонки карты"})
|
||||||
const lane = nav.getByRole("combobox", {name: "Перейти к колонке"})
|
const lane = nav.getByRole("combobox", {name: "Перейти к колонке"})
|
||||||
await expect(lane).toHaveValue("home")
|
await expect(lane).toHaveValue("home")
|
||||||
|
const scroller = page.locator("[data-map-scroll]")
|
||||||
|
expect(await scroller.evaluate(el => el.scrollWidth > el.clientWidth)).toBe(true)
|
||||||
|
await expect(page.getByRole("group", {name:"Масштаб карты"})).toContainText("100%")
|
||||||
await nav.getByRole("button", {name: "Следующая колонка"}).click()
|
await nav.getByRole("button", {name: "Следующая колонка"}).click()
|
||||||
await expect(lane).toHaveValue("wan")
|
await expect(lane).toHaveValue("wan")
|
||||||
|
await expect.poll(() => scroller.evaluate(el => el.scrollLeft)).toBeGreaterThan(0)
|
||||||
await nav.getByRole("button", {name: "Предыдущая колонка"}).click()
|
await nav.getByRole("button", {name: "Предыдущая колонка"}).click()
|
||||||
await expect(lane).toHaveValue("home")
|
await expect(lane).toHaveValue("home")
|
||||||
await lane.selectOption("access-nodes")
|
await lane.selectOption("access-nodes")
|
||||||
@@ -27,6 +31,10 @@ for (const width of [320, 390]) test("Карта: мобильные колон
|
|||||||
await nav.getByRole("button", {name: "К отказу"}).click()
|
await nav.getByRole("button", {name: "К отказу"}).click()
|
||||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||||
await expect(panel).toContainText(tunnel.name)
|
await expect(panel).toContainText(tunnel.name)
|
||||||
|
await expect.poll(() => map.locator("[data-map-runtime-badge]").first().evaluate(element => {
|
||||||
|
const badge = element.getBoundingClientRect(), viewport = element.closest("svg")!.getBoundingClientRect()
|
||||||
|
return badge.left >= viewport.left && badge.right <= viewport.right && badge.top >= viewport.top && badge.bottom <= viewport.bottom
|
||||||
|
})).toBe(true)
|
||||||
await page.keyboard.press("Escape")
|
await page.keyboard.press("Escape")
|
||||||
await expect(panel).toHaveCount(0)
|
await expect(panel).toHaveCount(0)
|
||||||
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
|
const search = page.getByRole("textbox", {name: "Поиск узла или назначения"})
|
||||||
@@ -83,8 +91,10 @@ for(const width of [1440,390,320])test("Карта: доступные дета
|
|||||||
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
|
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||||
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
|
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
|
||||||
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
|
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
|
||||||
expect(map!.height).toBeGreaterThanOrEqual(390)
|
expect(map!.height).toBeGreaterThanOrEqual(320)
|
||||||
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2)
|
expect(map!.height).toBeLessThanOrEqual(490)
|
||||||
|
if(width>=1024)expect(bounds!.x).toBeGreaterThanOrEqual(map!.x+map!.width-2)
|
||||||
|
else expect(bounds!.y).toBeGreaterThanOrEqual(map!.y+map!.height-2)
|
||||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
||||||
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
|
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
|
||||||
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
|
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
|
||||||
@@ -156,6 +166,11 @@ test("Карта: пропорции камеры, ручной масштаб
|
|||||||
await expect.poll(async()=>Number((await map.getAttribute("viewBox"))!.split(" ")[2])).toBeLessThan(1240)
|
await expect.poll(async()=>Number((await map.getAttribute("viewBox"))!.split(" ")[2])).toBeLessThan(1240)
|
||||||
const camera=await map.evaluate((element:SVGSVGElement)=>{const rect=element.getBoundingClientRect(),box=element.viewBox.baseVal;return {ratio:box.width/box.height,screenRatio:rect.width/rect.height}})
|
const camera=await map.evaluate((element:SVGSVGElement)=>{const rect=element.getBoundingClientRect(),box=element.viewBox.baseVal;return {ratio:box.width/box.height,screenRatio:rect.width/rect.height}})
|
||||||
expect(camera.ratio).toBeCloseTo(camera.screenRatio,3)
|
expect(camera.ratio).toBeCloseTo(camera.screenRatio,3)
|
||||||
|
await map.hover()
|
||||||
|
await page.mouse.wheel(65,0)
|
||||||
|
const scroller=page.locator("[data-map-scroll]")
|
||||||
|
await expect.poll(()=>scroller.evaluate(el=>el.scrollLeft)).toBeGreaterThan(40)
|
||||||
|
await expect.poll(()=>map.evaluate((svg:SVGSVGElement)=>svg.viewBox.baseVal.x)).toBeGreaterThan(40)
|
||||||
await page.getByRole("button",{name:"Увеличить карту",exact:true}).click()
|
await page.getByRole("button",{name:"Увеличить карту",exact:true}).click()
|
||||||
const manual=await map.getAttribute("viewBox")
|
const manual=await map.getAttribute("viewBox")
|
||||||
await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||||
@@ -170,9 +185,10 @@ test("Карта: пропорции камеры, ручной масштаб
|
|||||||
|
|
||||||
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
|
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
|
||||||
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
|
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
|
||||||
await expect(node).toBeVisible();await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");expect(await map.getAttribute("viewBox")).not.toBe(before)
|
await expect(node).toBeVisible();await page.getByRole("button",{name:"Увеличить карту"}).click()
|
||||||
|
await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");await expect(map).not.toHaveAttribute("viewBox",before!)
|
||||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||||
const transform=await node.getAttribute("transform"),point=await node.evaluate((g:SVGGElement)=>{const matrix=g.getScreenCTM()!;return {x:matrix.e,y:matrix.f}})
|
const transform=await node.getAttribute("transform"),point=await node.evaluate(g=>{const box=g.getBoundingClientRect();return {x:box.x+box.width/2,y:box.y+box.height/2}})
|
||||||
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
|
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
|
||||||
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
|
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
|
||||||
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
|
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
|
||||||
@@ -185,9 +201,13 @@ test("Карта: touch pan и отмена жеста без залипания
|
|||||||
await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
|
await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
|
||||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||||
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
|
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
|
||||||
|
await map.scrollIntoViewIfNeeded()
|
||||||
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
|
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
|
||||||
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+20,y:box.y+box.height-70,id:1}]})
|
const x=box.x+110,y=box.y+box.height-12
|
||||||
await session.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:box.x+70,y:box.y+box.height-100,id:1}]})
|
expect(await page.evaluate(({x,y})=>document.elementFromPoint(x,y)?.hasAttribute("data-map-background"),{x,y})).toBe(true)
|
||||||
|
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x,y,id:1}]})
|
||||||
|
await session.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:x-60,y:y-30,id:1}]})
|
||||||
|
await expect.poll(()=>page.locator("[data-map-scroll]").evaluate(el=>el.scrollLeft)).toBeGreaterThan(30)
|
||||||
await session.send("Input.dispatchTouchEvent",{type:"touchCancel",touchPoints:[]})
|
await session.send("Input.dispatchTouchEvent",{type:"touchCancel",touchPoints:[]})
|
||||||
expect(await map.getAttribute("viewBox")).not.toBe(before)
|
expect(await map.getAttribute("viewBox")).not.toBe(before)
|
||||||
const stopped=await map.getAttribute("viewBox");await page.mouse.move(box.x+150,box.y+50);expect(await map.getAttribute("viewBox")).toBe(stopped)
|
const stopped=await map.getAttribute("viewBox");await page.mouse.move(box.x+150,box.y+50);expect(await map.getAttribute("viewBox")).toBe(stopped)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ test("Карта: раскрытая легенда объясняет стат
|
|||||||
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
|
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
|
||||||
return hit !== null && element.contains(hit)
|
return hit !== null && element.contains(hit)
|
||||||
})).toBe(true)
|
})).toBe(true)
|
||||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом · выход подтверждён", "Каналы · частичный отказ или деградация"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||||
await expect(legend).toContainText("нет измерения")
|
await expect(legend).toContainText("нет измерения")
|
||||||
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
||||||
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { test, expect, type Page } from "@playwright/test"
|
|||||||
|
|
||||||
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
|
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
|
||||||
import { emptyMapFlow } from "./fixtures/map-flow"
|
import { emptyMapFlow } from "./fixtures/map-flow"
|
||||||
|
import { serveMapVisual } from "./fixtures/network-map-visual"
|
||||||
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
|
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
|
||||||
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
|
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
|
||||||
const gre = (id: string, owner: number, peer: number, status = "up") => ({
|
const gre = (id: string, owner: number, peer: number, status = "up") => ({
|
||||||
@@ -23,7 +24,7 @@ async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof
|
|||||||
async function overlaps(page: Page) {
|
async function overlaps(page: Page) {
|
||||||
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
|
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
|
||||||
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
|
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
|
||||||
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи.
|
// Учитываем включённые наложения, например миникарту.
|
||||||
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
|
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
|
||||||
const hits: string[] = []
|
const hits: string[] = []
|
||||||
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
|
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
|
||||||
@@ -31,7 +32,7 @@ async function overlaps(page: Page) {
|
|||||||
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
|
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
|
||||||
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
|
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
|
||||||
}
|
}
|
||||||
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
|
return { rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,8 +83,13 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
|
|||||||
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
||||||
const result = await overlaps(page)
|
const result = await overlaps(page)
|
||||||
expect(result.cards).toBe(5)
|
expect(result.cards).toBe(5)
|
||||||
expect(result.overlays).toBe(2)
|
|
||||||
expect(result.hits).toEqual([])
|
expect(result.hits).toEqual([])
|
||||||
|
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
|
||||||
|
const controls = page.getByRole("group", {name: "Масштаб карты"})
|
||||||
|
const [canvas, footer] = await Promise.all([map.boundingBox(), controls.boundingBox()])
|
||||||
|
expect(footer!.y).toBeGreaterThanOrEqual(canvas!.y + canvas!.height - 1)
|
||||||
|
const openMini = controls.getByRole("button", {name: "Показать миникарту"})
|
||||||
|
await expect(openMini).toHaveAttribute("aria-pressed", "false")
|
||||||
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
|
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
|
||||||
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
|
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
|
||||||
// Имя хоста без домена, параллельные туннели — одной подписью.
|
// Имя хоста без домена, параллельные туннели — одной подписью.
|
||||||
@@ -91,6 +97,10 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
|
|||||||
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
|
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
|
||||||
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
|
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
|
||||||
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
|
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
|
||||||
|
await openMini.click()
|
||||||
|
await expect(page.getByRole("button", {name: "Закрыть миникарту"})).toBeVisible()
|
||||||
|
await controls.getByRole("button", {name: "Вписать карту"}).click()
|
||||||
|
await expect.poll(async () => (await overlaps(page)).hits).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
|
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
|
||||||
@@ -192,3 +202,33 @@ test("Карта: сетка JH × Exit и аплинки WAN без налож
|
|||||||
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
|
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
|
||||||
expect((await overlaps(page)).hits).toEqual([])
|
expect((await overlaps(page)).hits).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("Скрытый GRE в NSK остаётся в RTT и после раскрытия соединяет две карточки JH", async ({page}) => {
|
||||||
|
await serveMapVisual(page, true)
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||||
|
const group = map.getByRole("button", {name: /^Раскрыть группу.*NSK.*Узлы доступа/i})
|
||||||
|
const count = page.getByText(/\d+ уз(?:ел|ла|лов) · 17 туннелей GRE$/)
|
||||||
|
await expect(count).toBeVisible()
|
||||||
|
await expect(group).toHaveAttribute("aria-expanded", "false")
|
||||||
|
await expect(group).toContainText("Проблемы · 1")
|
||||||
|
await expect(map.getByRole("button", {name: "Устройство nsk-gw12", exact: true})).toHaveCount(0)
|
||||||
|
await page.getByRole("tab", {name: /^RTT каналов/}).click()
|
||||||
|
await expect(page.getByRole("row").filter({has: page.getByRole("button", {name: "gre-nsk-12", exact: true})})).toContainText("Недоступен")
|
||||||
|
|
||||||
|
await group.press("Enter")
|
||||||
|
await expect(count).toBeVisible()
|
||||||
|
const broken = map.locator('[data-gre-status="down"] > path[stroke="var(--status-offline)"]')
|
||||||
|
await expect(broken).toHaveAttribute("stroke-dasharray", "2 3")
|
||||||
|
const error = await broken.evaluate(path => {
|
||||||
|
const wire = path as SVGPathElement
|
||||||
|
const project = (length: number) => wire.getPointAtLength(length).matrixTransform(wire.getScreenCTM()!)
|
||||||
|
const ends = [project(0), project(wire.getTotalLength())].sort((a,b) => a.y-b.y)
|
||||||
|
const cards = ["nsk-gw01", "nsk-gw12"].map(name => {
|
||||||
|
const card = wire.ownerSVGElement!.querySelector(`[aria-label="Устройство ${name}"] [data-map-box="card"]`)!.getBoundingClientRect()
|
||||||
|
return {x: card.right, y: card.top + card.height / 2}
|
||||||
|
}).sort((a,b) => a.y-b.y)
|
||||||
|
return Math.max(Math.abs(cards[0].x-cards[1].x), ...ends.map((p,i) => Math.hypot(p.x-cards[i].x, p.y-cards[i].y)))
|
||||||
|
})
|
||||||
|
expect(error, "Оба конца на правых гранях карточек одной колонки").toBeLessThan(1)
|
||||||
|
})
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { mkdir, writeFile } from "node:fs/promises"
|
||||||
|
import path from "node:path"
|
||||||
|
import { expect, test } from "@playwright/test"
|
||||||
|
import { serveMapVisual } from "./fixtures/network-map-visual"
|
||||||
|
|
||||||
|
// The approved atlas has 63px device cards, 13px names and 15px row gutters.
|
||||||
|
// Measure screen coordinates: inspecting SVG attributes alone misses a compressed viewBox.
|
||||||
|
for (const width of [998, 1320, 320, 390]) {
|
||||||
|
for (const dense of [false, true]) {
|
||||||
|
const theme = (width === 998 || width === 390) === !dense ? "dark" : "light"
|
||||||
|
const size = dense ? "dense" : "ordinary"
|
||||||
|
test(`Карта сети: физический масштаб и подписи ${width} · ${size} · ${theme}`, async ({ page }, info) => {
|
||||||
|
await page.setViewportSize({ width, height: width < 500 ? 1040 : 915 })
|
||||||
|
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" })
|
||||||
|
await page.addInitScript(scheme => localStorage.setItem("rl-theme", scheme), theme)
|
||||||
|
await serveMapVisual(page, dense)
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
|
||||||
|
await expect(map.getByRole("button", { name: "Устройство msk-gw01", exact: true })).toBeVisible()
|
||||||
|
await expect(map.getByRole("button", { name: "Сервис YouTube", exact: true })).toBeVisible()
|
||||||
|
await expect(map.getByRole("button", { name: /^Остальные сервисы \(2\)/ })).toBeVisible()
|
||||||
|
await expect(page.locator("html")).toHaveClass(new RegExp(theme))
|
||||||
|
await page.evaluate(() => document.fonts.ready)
|
||||||
|
if (width < 500) {
|
||||||
|
const lane = page.getByRole("combobox", { name: "Перейти к колонке" })
|
||||||
|
await lane.selectOption("access-nodes")
|
||||||
|
await expect(lane).toHaveValue("access-nodes")
|
||||||
|
await lane.blur()
|
||||||
|
} else {
|
||||||
|
await expect(page.getByRole("button", { name: "Боковое меню" })).toHaveAttribute("aria-expanded", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizes = await map.evaluate(svg => {
|
||||||
|
const position = (element: Element) => {
|
||||||
|
const r = element.getBoundingClientRect()
|
||||||
|
return { x:r.x,y:r.y,w:r.width,h:r.height }
|
||||||
|
}
|
||||||
|
const buttons = Array.from(svg.querySelectorAll("g[role=button]"))
|
||||||
|
const measure = (label: string, word: string, box: string) => {
|
||||||
|
const node = buttons.find(n => n.getAttribute("aria-label") === label)
|
||||||
|
const plate = node?.querySelector('[data-map-box="'+box+'"]')
|
||||||
|
const name = Array.from(node?.querySelectorAll<SVGTextElement>("text") ?? []).find(n => n.textContent?.includes(word))
|
||||||
|
if (!plate || !name) throw Error("Нет подписанной карточки " + label)
|
||||||
|
const matrix = name.getScreenCTM()!
|
||||||
|
return {...position(plate), font:parseFloat(getComputedStyle(name).fontSize)*Math.hypot(matrix.a,matrix.b)}
|
||||||
|
}
|
||||||
|
const host = position(svg)
|
||||||
|
const gateway = measure("Устройство msk-gw01", "msk-gw01","card")
|
||||||
|
const otherGateway = measure("Устройство msk-gw02", "msk-gw02","card")
|
||||||
|
const service = measure("Сервис YouTube","YouTube","dest")
|
||||||
|
const visibleDevice = Array.from(svg.querySelectorAll('[data-map-box="card"]')).map(position)
|
||||||
|
.filter(card=>card.x+card.w>host.x && card.x<host.x+host.w && card.y+card.h>host.y && card.y<host.y+host.h)
|
||||||
|
const span = visibleDevice.length ? Math.max(...visibleDevice.map(c=>c.y+c.h))-Math.min(...visibleDevice.map(c=>c.y)) : 0
|
||||||
|
return {host,gateway,service,span,rowPitch:Math.abs(otherGateway.y-gateway.y), overflow:document.documentElement.scrollWidth-innerWidth}
|
||||||
|
})
|
||||||
|
const stage = process.env.MAP_VISUAL_STAGE
|
||||||
|
if (stage === "before" || stage === "after") {
|
||||||
|
const folder = path.resolve("work/map-release-preview",stage)
|
||||||
|
const name = [width,size,theme].join("-")
|
||||||
|
await mkdir(folder,{recursive:true})
|
||||||
|
await page.screenshot({path:path.join(folder,name+".png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
|
||||||
|
await writeFile(info.outputPath("geometry.json"),JSON.stringify(sizes,null,2))
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(sizes.overflow, "Горизонтальный скролл принадлежит полотну").toBeLessThanOrEqual(1)
|
||||||
|
// The reference uses 938px for its six minimum column widths. Surplus space is shared evenly.
|
||||||
|
const expectedGatewayWidth=Math.min(157,140+Math.max(0,sizes.host.w-938)/6)
|
||||||
|
expect(Math.abs(sizes.gateway.w-expectedGatewayWidth),"Физическая ширина карточки JH из эталона").toBeLessThanOrEqual(3)
|
||||||
|
expect(Math.abs(sizes.gateway.h-63),"Физическая высота карточки JH из эталона").toBeLessThanOrEqual(2)
|
||||||
|
expect(Math.abs(sizes.gateway.font-13),"Размер имени при открытии").toBeLessThanOrEqual(.5)
|
||||||
|
expect(Math.abs(sizes.service.font-13),"Размер имени сервиса при открытии").toBeLessThanOrEqual(.5)
|
||||||
|
expect(sizes.service.w/sizes.gateway.w,"Пропорция ширины сервиса и устройства").toBeGreaterThan(0.9)
|
||||||
|
expect(sizes.service.w/sizes.gateway.w).toBeLessThan(1.35)
|
||||||
|
expect(sizes.service.h/sizes.gateway.h,"Сервис рисуется полноценной карточкой").toBeGreaterThan(0.85)
|
||||||
|
expect(sizes.rowPitch,"Между московскими JH остаётся зазор").toBeGreaterThanOrEqual(sizes.gateway.h+8)
|
||||||
|
const gateway=map.getByRole("button",{name:"Устройство msk-gw01",exact:true})
|
||||||
|
const roleTile=gateway.locator('[data-role-tile="JH"]')
|
||||||
|
await expect(roleTile).toHaveAttribute("width","29")
|
||||||
|
await expect(gateway.locator('[data-country-flag="RU"]')).toHaveCount(1)
|
||||||
|
await expect(gateway.locator('[data-rate-dir="rx"]')).toContainText("132")
|
||||||
|
await expect(gateway.locator('[data-rate-dir="tx"]')).toContainText("86")
|
||||||
|
const youtube=map.getByRole("button",{name:"Сервис YouTube",exact:true})
|
||||||
|
await expect(youtube.locator('[data-service-brand="YouTube"]')).toHaveCount(1)
|
||||||
|
await expect(youtube.locator('[data-service-share]')).toHaveCount(1)
|
||||||
|
await expect(map.locator('[data-map-lane]')).toHaveCount(6)
|
||||||
|
const nodes=map.locator('g[data-node-kind=device]')
|
||||||
|
await expect(nodes).toHaveCount(dense ? 9 : 10)
|
||||||
|
if (dense) {
|
||||||
|
const hiddenJhs=map.getByRole("button",{name:/^Раскрыть группу.*NSK.*Узлы доступа/i})
|
||||||
|
await expect(hiddenJhs).toHaveAttribute("aria-expanded","false")
|
||||||
|
await expect(hiddenJhs).toContainText(/(?:отказ|проблем)\S*\s*·?\s*1/i)
|
||||||
|
}
|
||||||
|
const intersections=await map.evaluate(root=>{
|
||||||
|
const nodes=[...root.querySelectorAll('[data-map-box="card"],[data-map-box="group"],[data-map-box="dest"],[data-map-box="wan"],[data-map-box="access"]')].map(e=>({
|
||||||
|
name:e.closest('[role=button]')?.getAttribute("aria-label") ?? e.getAttribute("data-map-box"),box:e.getBoundingClientRect()
|
||||||
|
}))
|
||||||
|
return nodes.flatMap(({name,box:a},i)=>nodes.slice(i+1).filter(({box:b})=>
|
||||||
|
Math.min(a.right,b.right)-Math.max(a.left,b.left)>2 && Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top)>2
|
||||||
|
).map(n=>[name,n.name]))
|
||||||
|
})
|
||||||
|
expect(intersections,"Карточки и заголовки групп имеют непересекающиеся области нажатия").toEqual([])
|
||||||
|
if (width >= 998) {
|
||||||
|
expect(sizes.span,"Узлы занимают по высоте минимум три ряда карточек").toBeGreaterThan(260)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const width of [320,1320]) {
|
||||||
|
test(`Карта сети: расположение карточки назначения и возврат к категории · ${width}`, async ({page})=>{
|
||||||
|
await page.setViewportSize({width,height:width===320 ? 1040 : 915})
|
||||||
|
await serveMapVisual(page)
|
||||||
|
await page.goto("/network-map")
|
||||||
|
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
|
||||||
|
const details=page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||||
|
await page.getByRole("button",{name:"Категории",exact:true}).click()
|
||||||
|
const category=map.getByRole("button",{name:"Категория CDN",exact:true})
|
||||||
|
if(width===320)await page.getByRole("combobox",{name:"Перейти к колонке"}).selectOption("destinations")
|
||||||
|
await category.press("Enter")
|
||||||
|
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
|
||||||
|
await details.getByRole("button",{name:/^Cloudflare/}).click()
|
||||||
|
await expect(details.getByRole("heading",{name:"Cloudflare",exact:true})).toBeVisible()
|
||||||
|
const bounds=await details.boundingBox(),canvas=await map.boundingBox()
|
||||||
|
if (!bounds || !canvas) throw Error("Нет карты или карточки выбранного сервиса")
|
||||||
|
if (width===320) expect(bounds.y).toBeGreaterThanOrEqual(canvas.y+canvas.height-2)
|
||||||
|
else expect(bounds.x).toBeGreaterThanOrEqual(canvas.x+canvas.width-2)
|
||||||
|
expect(bounds.height,"Панель не схлопнулась после включения contain:size").toBeGreaterThan(220)
|
||||||
|
const scroll=await details.evaluate(aside=>{
|
||||||
|
const body=Array.from(aside.querySelectorAll<HTMLElement>("div")).find(el=>el.classList.contains("flex-1") && getComputedStyle(el).overflowY==="auto")
|
||||||
|
if (!body) return null
|
||||||
|
const max=body.scrollHeight-body.clientHeight
|
||||||
|
body.scrollTop=max
|
||||||
|
const reached=body.scrollTop
|
||||||
|
body.scrollTop=0
|
||||||
|
return {client:body.clientHeight,max,reached}
|
||||||
|
})
|
||||||
|
expect(scroll).not.toBeNull()
|
||||||
|
expect(scroll!.client).toBeGreaterThan(70)
|
||||||
|
expect(scroll!.reached).toBeGreaterThanOrEqual(scroll!.max-1)
|
||||||
|
if(width===1320 && process.env.MAP_VISUAL_STAGE==="after"){
|
||||||
|
await page.screenshot({path:path.resolve("work/map-release-preview/after/1320-service-inspector.png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
|
||||||
|
}
|
||||||
|
expect(await page.evaluate(()=>document.documentElement.scrollWidth-innerWidth)).toBeLessThanOrEqual(1)
|
||||||
|
await details.getByRole("button",{name:"Назад к предыдущему объекту"}).click()
|
||||||
|
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
|
||||||
|
const workbench=page.getByRole("region",{name:"Рабочая панель карты"})
|
||||||
|
await workbench.getByRole("tab",{name:/^Назначения/}).click()
|
||||||
|
await expect(workbench.locator("table")).toBeVisible()
|
||||||
|
expect((await map.boundingBox())!.height,"Раскрытая диагностика не обрезает холст").toBeGreaterThanOrEqual(canvas.height-2)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -20,11 +20,30 @@ test("наблюдение IPFIX огибает промежуточный уз
|
|||||||
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
|
const link = mapLinkPath({x: sourceX, y: 100}, 80, {x: serviceX, y: 100}, 140)
|
||||||
const route = mapObservationRoute(link, [blocker], [])
|
const route = mapObservationRoute(link, [blocker], [])
|
||||||
assert.ok(route)
|
assert.ok(route)
|
||||||
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`H ${link.x2}`))
|
assert.ok(route.d.startsWith(`M ${link.x1} 100 `) && route.d.endsWith(`L ${link.x2} 100`))
|
||||||
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
|
assert.ok(route.track < blocker.y || route.track > blocker.y + blocker.h)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("связь обходит промежуточную колонку по свободной полосе", () => {
|
||||||
|
const a = {x: 100, y: 170}, b = {x: 680, y: 230}
|
||||||
|
const normal = mapLinkPath(a, 70, b, 75, {obstacles:[{x:340,y:140,w:120,h:125}]})
|
||||||
|
assert.match(normal.d, / Q /)
|
||||||
|
assert.equal(normal.x1, 170)
|
||||||
|
assert.equal(normal.x2, 605)
|
||||||
|
assert.ok(normal.points[2].y < 140 || normal.points[2].y > 265)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("GRE одной колонки остаётся снаружи правых граней обеих карточек", () => {
|
||||||
|
const top = {x: 400, y: 120}, bottom = {x: 400, y: 320}
|
||||||
|
for (const [a,b] of [[top,bottom],[bottom,top]]) {
|
||||||
|
const link = mapLinkPath(a, 70, b, 70)
|
||||||
|
assert.deepEqual(mapLinkPoint(link,0), {x:470,y:a.y})
|
||||||
|
assert.deepEqual(mapLinkPoint(link,1), {x:470,y:b.y})
|
||||||
|
assert.ok(link.points.slice(1,-1).every(p => p.x > 470))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
|
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
|
||||||
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
|
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
|
||||||
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
|
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
|
||||||
@@ -47,6 +66,13 @@ test("подписи не наезжают на карточки и друг н
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("метка отказа остаётся на линии, даже если свободного места нет", () => {
|
||||||
|
const link = mapLinkPath({ x: 542, y: 400 }, MAP_CARD_W / 2, { x: 780, y: 400 }, MAP_CARD_W / 2)
|
||||||
|
const [placed] = placeMapLinkLabels([{ id: "down", link, texts: ["GRE · Канал недоступен"], fault: true }], [card(542, 400), card(780, 400)])
|
||||||
|
assert.equal(placed?.text, "GRE · Канал недоступен")
|
||||||
|
assert.equal(placed.y, 400)
|
||||||
|
})
|
||||||
|
|
||||||
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
|
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
|
||||||
const exit = { x: 780, y: 300 }
|
const exit = { x: 780, y: 300 }
|
||||||
const flows = [
|
const flows = [
|
||||||
|
|||||||
Reference in new issue
Block a user