fix(network-map): разгрузить отрисовку карты сети
- отказ GRE рисуется на своём маршруте, без верхней полки над картой; короткая метка на линии, полная формулировка у выбранного канала - метка отказа не пропадает: без свободного места встаёт на середину участка - исправные каналы, доступ пользователей и WAN нейтральные, цвет только у проблем - подписи скорости только от 1 Мбит/с, у выбранного объекта или при слое RTT; «0К» не показывается - при выборе устройства приглушаются узлы, WAN и сервисы вне его GRE-связей - имя хоста на карточке в одну строку; рамка карточки показывает состояние узла, а не канала - легенда описывает новые обозначения Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
876a61f705
commit
2f86ef0558
8 files changed
+77
-60
No files matched your search
@@ -1924,8 +1924,6 @@ function NetworkMapContent() {
|
||||
// ── Связи макета v3: линия + одна «таблетка» на связь; подписи раскладываются без наложений.
|
||||
const rttLabel = (ms: number | null) => (ms == null ? "—" : `${ms} мс`)
|
||||
const groupedConnections: MapGroupConnection[] = []
|
||||
let faultRow = 0
|
||||
const nextFaultTrack = () => 49 + Math.min(faultRow++, 2) * 15
|
||||
function endpoint(id: string, index?: number | null): GroupLinkEnd {
|
||||
const server = nodeById[id]
|
||||
const wan = index != null ? server.wanUplinks?.[index] : undefined
|
||||
@@ -1942,6 +1940,9 @@ function NetworkMapContent() {
|
||||
return true
|
||||
}
|
||||
const scopedGreEdges = greEdges.filter(e => onMap(e.fromServer.id) && onMap(e.toServer.id))
|
||||
// Выбрано устройство: в фокусе оно и соседи по GRE, остальное приглушено.
|
||||
const focusIds = selected && selWanIdx === null ? new Set([selected.id, ...scopedGreEdges.flatMap(e =>
|
||||
e.fromServer.id === selected.id ? [e.toServer.id] : e.toServer.id === selected.id ? [e.fromServer.id] : [])]) : null
|
||||
const greLinks = scopedGreEdges.flatMap((e, i) => {
|
||||
const from = endpoint(e.fromServer.id,e.fromWanIndex), to = endpoint(e.toServer.id,e.toWanIndex)
|
||||
if (groupedConnection({from,to,type:"gre",gre:e})) return []
|
||||
@@ -1980,7 +1981,7 @@ function NetworkMapContent() {
|
||||
?? group.find(({e}) => channelStatus(e) === "degraded")
|
||||
?? group.find(g => greTunnelIdsWithMapBadge.has(g.id)) ?? group[0]
|
||||
const {from,to} = lead.e
|
||||
const link = mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles:mapObstacles, faultY:health === "up" ? undefined : nextFaultTrack()})
|
||||
const link = mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles:mapObstacles})
|
||||
return {group,counts,health,lead,link}
|
||||
})
|
||||
// Полная подпись связи — в title линии: короткая «таблетка» может не влезть между карточками.
|
||||
@@ -2017,8 +2018,13 @@ function NetworkMapContent() {
|
||||
const many = count > 1 ? `GRE ×${count}` : ""
|
||||
const issue = down ? count === 1 ? "Канал недоступен" : `Недоступно каналов · ${count} из ${count}` : counts.down ? `${counts.down} из ${count} каналов ${ruPlural(counts.down,"недоступен","недоступны","недоступны")}` : counts.degraded ? `Деградация ${counts.degraded} из ${count}` : ""
|
||||
const focused = group.some(({e,id}) => selectedGreEdge && greEdgeKey(selectedGreEdge) === id || selected?.id === e.fromServer.id || selected?.id === e.toServer.id || highlightedPath && greMatchesPath(e,highlightedPath))
|
||||
const texts = issue ? ["GRE · " + issue,issue,`${counts.down || counts.degraded}/${count}`] : [
|
||||
[many || "GRE", compactMapRate(rate), rtt].filter(Boolean).join(" · "), compactMapRate(rate) || rtt,
|
||||
const bps = liveBps ?? flowBps ?? 0
|
||||
const ratio = `${counts.down || counts.degraded}/${count}`
|
||||
// Без выбора отказ подписан коротко; полная формулировка — у выбранного канала, в title и панели справа.
|
||||
const brief = down ? count === 1 ? "Нет связи" : `Нет связи ${ratio}` : counts.down ? `Отказ ${ratio}` : count === 1 ? "Деградация" : `Деградация ${ratio}`
|
||||
const shownRate = bps > 0 ? compactMapRate(rate) : ""
|
||||
const texts = issue ? focused ? ["GRE · " + issue,issue,ratio] : [brief,ratio] : [
|
||||
[many || "GRE", shownRate, rtt].filter(Boolean).join(" · "), shownRate || rtt,
|
||||
].filter(Boolean)
|
||||
const fullText = [health !== "up" ? texts[0] : rate || rtt, many].filter(Boolean).join(" · ") || "GRE"
|
||||
const outer = greOuterSummaryLine(lead.e.tunnel, nodeById[lead.e.fromServer.id], nodeById[lead.e.toServer.id], greResolvedMap)
|
||||
@@ -2032,10 +2038,12 @@ function NetworkMapContent() {
|
||||
"Клик — панель справа."
|
||||
greLinkTitle.set(lead.id, `Связь ${lead.e.fromServer.name} → ${lead.e.toServer.name}: ${fullText}`)
|
||||
greLinkHint.set(lead.id, hint)
|
||||
if (health === "up" && (!rtt && !rate && !focused || lead.opacity < 1)) return []
|
||||
// Исправный канал подписан только у выбранного объекта, при слое RTT или от 1 Мбит/с — остальное в title.
|
||||
if (health === "up" && (!rtt && !focused && bps < 1_000_000 || lead.opacity < 1)) return []
|
||||
return [{
|
||||
id: "gre:" + lead.id, link, texts, hint, open: lead.open, fullText, fault: Boolean(issue),
|
||||
opacity: Math.max(...group.map((g) => g.opacity)),
|
||||
// Линия отказа не приглушается при выборе другого узла — её метка тоже.
|
||||
opacity: issue ? 1 : Math.max(...group.map((g) => g.opacity)),
|
||||
tone: down ? "er" as const : health === "degraded" ? "wn" as const : !rtt && !rate ? "mu" as const : "fg" as const,
|
||||
name: `${lead.e.fromServer.name} → ${lead.e.toServer.name}`,
|
||||
}]
|
||||
@@ -2071,7 +2079,8 @@ function NetworkMapContent() {
|
||||
const rate = accessRate(bindings, access.rates)
|
||||
const text = pickedUser && showNetflow && rate.measured ? rate.label : ""
|
||||
const link = mapLinkPath(accessPosition, cardWidths.access / 2, target, widthForServer(target.type) / 2, {obstacles:mapObstacles})
|
||||
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`, opacity: bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1,
|
||||
return [{ id: `access:${id}`, link, texts: [text], name: `${pickedUser?.name ?? "Пользователи"} → ${target.name}`,
|
||||
opacity: (bindings.length && bindings.every(binding => binding.enabled === false) ? 0.48 : 1) * (focusIds && !focusIds.has(id) ? 0.3 : 1),
|
||||
tone: "fg" as const, hint: pickedUser ? `RouterOS · RX ${fmtRate(rate.measured ? rate.rx : null)} · TX ${fmtRate(rate.measured ? rate.tx : null)} · ${rate.measured}/${rate.total} замеров` : "Привязки из каталога пользователей",
|
||||
open: () => { if (pickedUser) { setSelected(null); setSelectedGreEdge(null); setSelectedService(null); setInspectUser(true) } else setUserPicker(true) },
|
||||
}]
|
||||
@@ -2135,7 +2144,7 @@ function NetworkMapContent() {
|
||||
if (groupedConnection({from,to,type:"wan"})) return []
|
||||
return [{key:densityWanKey(router.id,i),link:mapLinkPath(from,from.halfWidth,to,to.halfWidth,{obstacles:mapObstacles})}]
|
||||
}))
|
||||
const groupLinks = collectGroupLinks(groupedConnections, mapObstacles, nextFaultTrack)
|
||||
const groupLinks = collectGroupLinks(groupedConnections, mapObstacles)
|
||||
const groupProblems = new Map(density.groups.map(g => {
|
||||
const ids = new Set(g.serverIds)
|
||||
const channels = scopedGreEdges.filter(e =>
|
||||
@@ -2600,7 +2609,7 @@ function NetworkMapContent() {
|
||||
))}
|
||||
|
||||
<g id="network-map-wires">
|
||||
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke="var(--chart-2)" strokeWidth={pickedUser ? 2.2 : 1.5} opacity={opacity * (pickedUser ? 1 : .75)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
|
||||
{accessLinks.map(({ id, link, name, open, opacity }) => <path key={id} d={link.d} fill="none" stroke={pickedUser ? "var(--foreground)" : "var(--muted-foreground)"} strokeWidth={pickedUser ? 2.2 : 1.5} opacity={opacity * (pickedUser ? .8 : .55)} pointerEvents="stroke" onPointerDown={e => e.stopPropagation()} onClick={open}><title>{name}</title></path>)}
|
||||
{/* Наблюдаемые пути от выходов и экспортёров к сервисам. */}
|
||||
{destRibbons.map(({ edge, direct, detour, link }) => {
|
||||
const hop = destinationRate(edge)
|
||||
@@ -2668,9 +2677,10 @@ function NetworkMapContent() {
|
||||
className="network-map-focusable cursor-pointer" onPointerDown={ev => ev.stopPropagation()} onClick={open}
|
||||
onKeyDown={ev => {if(ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); open(ev) }}}>
|
||||
<path className="network-map-focus-ring" d={link.d} fill="none" stroke="var(--ring)" strokeWidth="6" />
|
||||
<path d={link.d} fill="none" stroke={ts.stroke}
|
||||
strokeWidth={focused ? 3.5 : health === "up" ? 2.4 : 2.8}
|
||||
strokeDasharray={health === "down" ? "2 3" : health === "degraded" ? "6 3" : undefined} strokeLinejoin="round" strokeLinecap="round" opacity={health === "up" && !focused ? .76 : 1} />
|
||||
{/* Цвет только у проблем: исправный канал серый, у выбранного объекта — контрастный. */}
|
||||
<path d={link.d} fill="none" stroke={health !== "up" ? ts.stroke : focused ? "var(--foreground)" : "var(--muted-foreground)"}
|
||||
strokeWidth={focused ? 2.6 : health === "up" ? 1.6 : 2.2}
|
||||
strokeDasharray={health === "down" ? "2 3" : health === "degraded" ? "6 3" : undefined} strokeLinejoin="round" strokeLinecap="round" opacity={health !== "up" ? 1 : focused ? .8 : .6} />
|
||||
<path d={link.d} fill="none" stroke="transparent" strokeWidth={16} strokeLinecap="round">
|
||||
<title>{greLinkTitle.get(id)}. {greLinkHint.get(id)}</title>
|
||||
</path>
|
||||
@@ -2730,6 +2740,7 @@ function NetworkMapContent() {
|
||||
key={n.id} n={n} width={widthForServer(n.type)} channelProblem={channelProblemByDevice.get(n.id)}
|
||||
isSel={selected?.id === n.id}
|
||||
isVis={isVisible(n)}
|
||||
dim={focusIds ? !focusIds.has(n.id) : false}
|
||||
isDragged={draggedNodeId === n.id}
|
||||
rates={showNetflow && n.status !== "offline" ? (n.id === selected?.id ? selectedNodeRate : undefined) ?? (nodeTraffic?.base === backendUrl ? nodeTraffic.current.get(n.id) : undefined) : undefined}
|
||||
hideCatalogLatency={hideCatalogLatencyByNodeId.has(n.id)}
|
||||
@@ -2750,16 +2761,15 @@ function NetworkMapContent() {
|
||||
return (router.wanUplinks ?? []).map((wan, wIdx) => {
|
||||
const sat = effectiveSatPos[router.id]?.[wIdx]
|
||||
if (!sat || density.hiddenWans.has(densityWanKey(router.id,wIdx))) return null
|
||||
const color = WAN_COLORS[wIdx % WAN_COLORS.length]
|
||||
const isActive = wanJhEdges.filter(e => e.homeId === router.id && e.wanIdx === wIdx).some(e => e.active)
|
||||
const isSatSel = selected?.id === router.id && selWanIdx === wIdx
|
||||
const satKey = `${router.id}-${wIdx}`
|
||||
const live = showNetflow ? getInterfaceLiveRate(`wan:${router.id}:${wIdx}`) : undefined
|
||||
const flow = netflowByWanKey.get(`${router.id}\t${wIdx}`)
|
||||
return (
|
||||
<g key={`${router.id}-wan-${wIdx}`} opacity={vis ? 1 : 0.06} style={{ transition: "opacity 0.3s" }}>
|
||||
<g key={`${router.id}-wan-${wIdx}`} opacity={!vis ? 0.06 : focusIds && !focusIds.has(router.id) ? 0.38 : 1} style={{ transition: "opacity 0.3s" }}>
|
||||
<WanSatNode
|
||||
x={sat.x} y={sat.y} wan={wan} color={color} index={wIdx} width={cardWidths.wan}
|
||||
x={sat.x} y={sat.y} wan={wan} index={wIdx} width={cardWidths.wan}
|
||||
active={isActive} isSel={isSatSel}
|
||||
traffic={live ? `Live ${formatNetflowRate(live)}` : flow ? `≈${formatNetflowRate(flow)}` : undefined}
|
||||
isDragged={draggedSatKey === satKey}
|
||||
@@ -2794,7 +2804,7 @@ function NetworkMapContent() {
|
||||
y={pos.y}
|
||||
isSel={activeService?.id === svc.id}
|
||||
isVis
|
||||
dim={Boolean(expandedCountryGroup) && svc.id !== expandedCountryId}
|
||||
dim={Boolean(expandedCountryGroup) && svc.id !== expandedCountryId || Boolean(focusIds) && !visibleServiceEdges.some(e => e.fromId === selected?.id && e.toId === svc.id)}
|
||||
isDragged={draggedSvcId === svc.id}
|
||||
destMode={destMode}
|
||||
iso={svc.label}
|
||||
|
||||
@@ -36,7 +36,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
</div>
|
||||
<p className={head}>Связи</p>
|
||||
<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"><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>
|
||||
@@ -46,6 +46,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
<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>
|
||||
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||
<p className="text-muted-foreground leading-snug">Цвет на линии — только у проблем. Скорость подписана от 1 Мбит/с и у выбранного объекта; остальное — в подсказке и панели справа.</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
|
||||
@@ -52,8 +52,6 @@ const linkNames: Record<MapGroupLink["type"], string> = {
|
||||
function linkColor(link: MapGroupLink) {
|
||||
if (link.down === link.count) return "var(--status-offline)"
|
||||
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)"
|
||||
return "var(--muted-foreground)"
|
||||
}
|
||||
@@ -65,8 +63,9 @@ 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 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 texts = row.down ? [`${type} · Недоступно ${row.down} из ${row.count}`, `Недоступно ${row.down} из ${row.count}`, `↓ ${row.down}/${row.count}`] :
|
||||
row.degraded ? [`${type} · Деградация ${row.degraded} из ${row.count}`, `! ${row.degraded}/${row.count}`] : []
|
||||
// Коротко на линии; полная сводка — в title.
|
||||
const texts = row.down ? [`${row.down === row.count ? "Нет связи" : "Отказ"} ${row.down}/${row.count}`, `${row.down}/${row.count}`] :
|
||||
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)
|
||||
@@ -78,7 +77,7 @@ export function MapGroupLinks({ links, obstacles, onExpand, layer = "all" }: {
|
||||
onKeyDown={event => activate(event, () => onExpand(row.groups))}>
|
||||
<title>{row.title}</title>
|
||||
<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.fault ? 2.8 : row.type === "gre" ? 2.4 : 1.6} opacity={row.fault ? 1 : row.type === "observation" ? .56 : .76}
|
||||
<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.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" />
|
||||
</g>
|
||||
|
||||
@@ -56,23 +56,24 @@ function shortRate(rate: string) {
|
||||
|
||||
type PointerDown = (e: PointerEvent<SVGGElement>)=>void
|
||||
|
||||
export function ServerNode({ n,width,isSel,isVis,isDragged,hideCatalogLatency,channelProblem,rates,onClick,onDblClick,onHoverChange,onContextMenu,onPointerDown }: {
|
||||
n:Server & {x:number;y:number};width:number;isSel:boolean;isVis:boolean;isDragged:boolean
|
||||
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 !== "offline" && channelProblem ? "degraded" : n.status
|
||||
const offline = status === "offline", warn = status === "degraded"
|
||||
const border = isSel ? ink : warn ? "color-mix(in oklch,var(--warning) 50%,transparent)" : offline ? "var(--destructive)" : "var(--border)"
|
||||
// Рамка и точка — состояние самого узла; отказ канала показан на его линии.
|
||||
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"}} opacity={isVis?1:.38}
|
||||
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)}>
|
||||
@@ -100,8 +101,8 @@ export function ServerNode({ n,width,isSel,isVis,isDragged,hideCatalogLatency,ch
|
||||
</g>
|
||||
}
|
||||
|
||||
export function WanSatNode({x,y,wan,width,color,index,active,isSel,isDragged,traffic,onSelect,onPointerDown}: {
|
||||
x:number;y:number;wan:WanUplink;width:number;color:string;index:number;active:boolean;isSel:boolean;isDragged:boolean;traffic?:string
|
||||
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
|
||||
@@ -113,7 +114,7 @@ export function WanSatNode({x,y,wan,width,color,index,active,isSel,isDragged,tra
|
||||
<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={color} halo selected={isSel}/>
|
||||
<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}/>
|
||||
|
||||
@@ -37,12 +37,9 @@ export function mapCardMetrics(name: string, kind: CardKind, width: number) {
|
||||
}
|
||||
const nameParts = (text: string) => text.match(/[^\s-]+-?|\s+|-/gu) ?? []
|
||||
const host = kind === "device" && /^[\w-]+(?:\.[\w-]+){2,}$/.test(name)
|
||||
if (host) {
|
||||
const dot = name.indexOf(".")
|
||||
nameParts(name.slice(0,dot)).forEach(word)
|
||||
flush()
|
||||
word(name.slice(dot))
|
||||
} else nameParts(name).forEach(word)
|
||||
// Домен хоста — в подсказке и панели справа; на карточке только короткое имя в одну строку.
|
||||
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}
|
||||
|
||||
@@ -54,7 +54,7 @@ export function channelStatus({ tunnel, peerTunnel }: GreMapEdge) {
|
||||
return peerTunnel && peerTunnel.status !== tunnel.status ? "degraded" : tunnel.status
|
||||
}
|
||||
|
||||
export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?: MapBox[], nextFaultTrack?: () => number) {
|
||||
export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?: MapBox[]) {
|
||||
const buckets = new Map<string, MapGroupConnection[]>()
|
||||
for (const row of rows) {
|
||||
if (!(row.from.groupId || row.to.groupId) || row.from.id === row.to.id) continue
|
||||
@@ -75,7 +75,8 @@ export function collectGroupLinks(rows: Iterable<MapGroupConnection>, obstacles?
|
||||
return {
|
||||
id, from, to, type, ...totals,
|
||||
groups: [from.groupId, to.groupId].filter((group): group is string => Boolean(group)),
|
||||
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles, faultY:totals.down || totals.degraded ? nextFaultTrack?.() : undefined}),
|
||||
// Отказ рисуется на своём обычном маршруте: цвет и значок, без отдельной полки над картой.
|
||||
link: mapLinkPath(from, from.halfWidth, to, to.halfWidth, {obstacles}),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -85,20 +85,19 @@ export function roundedMapPath(points: MapPoint[]) {
|
||||
|
||||
export function mapLinkPath(
|
||||
a: MapPoint, aHalfW: number, b: MapPoint, bHalfW: number,
|
||||
options?: { faultY?: number; obstacles?: readonly MapBox[] },
|
||||
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 fault = options?.faultY !== undefined
|
||||
const startSide = sameLane ? 1 : fault ? -dir : dir
|
||||
const endSide = sameLane ? 1 : fault ? dir : -dir
|
||||
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 = options?.faultY
|
||||
if (!fault && inner.length) {
|
||||
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]
|
||||
}
|
||||
@@ -150,6 +149,7 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
|
||||
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) {
|
||||
const w = mapPillWidth(text) + (label.fault ? 16 : 0)
|
||||
for (const {a,b} of segments) for (const t of LABEL_T) {
|
||||
@@ -158,9 +158,17 @@ export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts:
|
||||
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 })
|
||||
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
||||
placed = true
|
||||
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
|
||||
}
|
||||
|
||||
@@ -25,29 +25,22 @@ test("наблюдение IPFIX огибает промежуточный уз
|
||||
}
|
||||
})
|
||||
|
||||
test("неисправная связь выходит на отдельную верхнюю полку, обычная обходит промежуточную колонку", () => {
|
||||
test("связь обходит промежуточную колонку по свободной полосе", () => {
|
||||
const a = {x: 100, y: 170}, b = {x: 680, y: 230}
|
||||
const issue = mapLinkPath(a, 70, b, 75, {faultY: 49})
|
||||
assert.equal(issue.x1, 30)
|
||||
assert.equal(issue.x2, 755)
|
||||
assert.deepEqual(issue.points.slice(2, 4), [{x:25,y:49}, {x:761,y:49}])
|
||||
assert.match(issue.d, / Q /)
|
||||
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 одной колонки остаётся снаружи правых граней обеих карточек при любом состоянии", () => {
|
||||
test("GRE одной колонки остаётся снаружи правых граней обеих карточек", () => {
|
||||
const top = {x: 400, y: 120}, bottom = {x: 400, y: 320}
|
||||
for (const [a,b] of [[top,bottom],[bottom,top]]) {
|
||||
for (const faultY of [undefined,64]) {
|
||||
const link = mapLinkPath(a, 70, b, 70, {faultY})
|
||||
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))
|
||||
if (faultY != null) assert.ok(link.points.some(p => p.y === faultY))
|
||||
}
|
||||
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))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -73,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 уложены стопкой у узла и толще у большей скорости", () => {
|
||||
const exit = { x: 780, y: 300 }
|
||||
const flows = [
|
||||
|
||||
Reference in new issue
Block a user