Files
MikrotikManager/components/network-map/map-bottom-panel.tsx
T
Denozordec 545a9bbcd2
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m8s
Docker images / frontend-image (push) Successful in 2m25s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m1s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
feat(network-map): добавить сворачивание групп и категории трафика
2026-12-03 09:58:24 +07:00

223 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client"
import { useMemo, useState, type ReactNode } from "react"
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { CompactDataGrid, type CompactDataGridColumn } from "@/components/data-grids/compact-data-grid"
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
import { Flag } from "@/components/flag"
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
export type MapDestRow = {
id: string; label: string; category: string; rate: string; bps: number; share: number | null; hl: boolean
kind?: "service" | "country" | "category"; countryCode?: 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"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
return (
<div className="max-h-[min(34svh,310px)] overflow-auto">
<div className="min-w-[720px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
{head.map((h) => <span key={h}>{h}</span>)}
</div>
{empty ? <p className="text-muted-foreground px-4 py-8 text-center text-sm">{empty}</p> : children}
</div>
</div>
)
}
function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: ReactNode }) {
return <div className={cn("grid min-h-11 items-center gap-x-3 border-b px-4 py-1.5 text-[13px] last:border-b-0", cols, hl && "bg-primary/8")}>{children}</div>
}
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
function Destinations({ rows, onDestination, onCategory }: {
rows: MapDestRow[]
onDestination: (id: string) => void
onCategory?: (category: string) => void
}) {
const columns = useMemo<CompactDataGridColumn<MapDestRow>[]>(() => [
{ id: "label", header: "Назначение", size: 125, cell: row => (
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.label}
data-map-highlight={row.hl || undefined} onClick={() => onDestination(row.id)}>
{row.countryCode ? <span aria-hidden><Flag code={row.countryCode} size={16} /></span> :
(row.kind ?? "service") === "service" && <ServiceBrandIcon label={row.label} size={16} />}
<span className="truncate">{row.label}</span>
</Button>
) },
{ id: "category", header: "Категория", size: 145, cell: row => onCategory && (row.kind ?? "service") === "service" ?
<Button type="button" variant="link" size="xs" className="max-w-full justify-start" title={row.category}
onClick={() => onCategory(row.category)}><span className="truncate">{row.category}</span></Button> :
<span className="text-muted-foreground">{row.category}</span> },
{ id: "bps", header: "Скорость", size: 124, cell: row => <span className="font-mono tabular-nums">{row.rate}</span> },
{ id: "share", header: "Доля окна", size: 145, cell: row => row.share == null ? "Нет данных" :
<span className="flex items-center gap-2">
<span aria-hidden className="bg-muted h-1.5 w-14 overflow-hidden rounded-full"><i className="block h-full rounded-full bg-chart-4" style={{width: `${Math.round(row.share * 100)}%`}} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(row.share * 100)}%</span>
</span> },
], [onDestination, onCategory])
return <div className="max-h-[min(34svh,310px)] overflow-y-auto [&_tr:has([data-map-highlight])]:bg-primary/8">
<CompactDataGrid data={rows} columns={columns} horizontalScroll emptyTitle="Назначений за окно нет" />
</div>
}
/**
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены.
*/
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, onCategory, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
open: boolean
onOpenChange: (open: boolean) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
onEvent: (event: MapEventRow) => void
onFlow: (id: string) => void
onDestination: (id: string) => void
onCategory?: (category: string) => void
eventsError: string | null
stat: string
}) {
const [showRoutineEvents, setShowRoutineEvents] = useState(false)
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
const visibleEvents = showRoutineEvents ? events : incidentEvents
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
{ id: "rtt", label: "RTT каналов", count: rtt.length },
{ id: "dest", label: "Назначения", count: destinations.length },
{ id: "events", label: "События", count: visibleEvents.length },
]
return (
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0">
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1">
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель">
{tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5" onClick={() => onOpenChange(true)}>
{t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger>
))}
</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>
</div>
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
{open && <p className="px-3 py-1 text-[11px] text-muted-foreground">{stat}</p>}
<TabsContent value="flows">
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<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 value="rtt">
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}>
{rtt.map((r) => (
<Row key={r.id} cols={RTT_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.name}</span>
<span className="truncate font-mono">{r.route}</span>
<span className="font-mono tabular-nums">{r.rtt}</span>
<span className="font-mono tabular-nums">{r.speed}</span>
<span><ToneBadge tone={r.tone}>{r.status}</ToneBadge></span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="dest">
<Destinations rows={destinations} onDestination={onDestination} onCategory={onCategory} />
</TabsContent>
<TabsContent value="events">
<div className="flex items-center gap-2 border-b px-3 py-1">
<Button type="button" size="xs" variant={showRoutineEvents ? "outline" : "secondary"} aria-pressed={!showRoutineEvents} onClick={() => setShowRoutineEvents(false)}>Сбои и предупреждения</Button>
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
</div>
{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 ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"}>
{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>
</FramePanel>
</Tabs>
</SectionFrame>
)
}
/**
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/
export function MapTimeline({ events, now, state, onPick, onJournal }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void; onJournal: () => void }) {
const from = now - 24 * 3_600_000
const hours = new Map<number, MapEventRow[]>()
for (const event of events) {
if (event.ts < from || event.ts > now || event.tone !== "er" && event.tone !== "wn") continue
const hour = Math.min(23, Math.floor((event.ts - from) / 3_600_000))
const group = hours.get(hour) ?? []
group.push(event)
hours.set(hour, group)
}
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
<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 role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
<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}
</span>
))}
{[...hours].map(([hour, group]) => {
const e = group.find(event => event.tone === "er") ?? group[0]
const label = `${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
return (
<button
key={e.id}
type="button"
onClick={() => onPick(e)}
aria-label={label}
title={label}
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) }}
>
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
</button>
)})}
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
<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>
<Button type="button" variant="ghost" size="xs" onClick={onJournal}>Журнал</Button>
</div>
)
}