Files
MikrotikManager/components/system-monitor-popover.tsx
T

223 lines
9.0 KiB
TypeScript

"use client"
import { useEffect, useMemo, useState, type ReactNode } from "react"
import { Activity, Filter, HeartPulse, Server } from "lucide-react"
import { Badge } from "@/components/reui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { useDataSource } from "@/lib/data-source"
import { filters, pingProbes, servers } from "@/lib/data"
import type { SidebarCountsDto } from "@/lib/sidebar-badges"
import { getBackendHealth } from "@/shared/api/backend-health"
import {can,ensureAuthConfig} from "@/lib/auth"
import {getSidebarCounts} from "@/shared/api/sidebar-counts"
type MonitorMetric = {
id: string
label: string
value: string
unit: string
percent: number|null
icon: ReactNode
tone: "success" | "warning" | "destructive" | "info"
alert: boolean
}
function toneColor(tone: MonitorMetric["tone"]) {
switch (tone) {
case "success":
return "var(--color-success)"
case "warning":
return "var(--color-warning)"
case "destructive":
return "var(--color-destructive)"
default:
return "var(--color-info)"
}
}
function MetricBar({ percent, color }: { percent: number; color: string }) {
return (
<div className="bg-muted h-1 w-full overflow-hidden rounded-full">
<div
className="h-full rounded-full"
style={{
width: `${Math.min(100, Math.max(0, percent))}%`,
backgroundColor: color,
}}
/>
</div>
)
}
function MetricCell({ metric }: { metric: MonitorMetric }) {
const color = toneColor(metric.tone)
return (
<div className="flex flex-col gap-2 p-3">
<div className="flex items-center justify-between gap-1">
<div className="flex min-w-0 items-center gap-1.5">
<div
className="flex size-5 shrink-0 items-center justify-center rounded-md"
style={{ backgroundColor: `${color}18`, color }}
>
{metric.icon}
</div>
<span className="text-muted-foreground min-w-0 break-words text-[11px]">{metric.label}</span>
</div>
<span className="text-foreground shrink-0 text-xs font-semibold tabular-nums">
{metric.value}
<span className="text-muted-foreground ml-0.5 text-[10px] font-normal">{metric.unit}</span>
</span>
</div>
{metric.percent!==null?<MetricBar percent={metric.percent} color={color} />:null}
</div>
)
}
/** Live system monitor popover — app-shell-7. @see https://reui.io/preview/base/app-shell-7 */
export function SystemMonitorPopover() {
const { mode, backendUrl, prefsHydrated } = useDataSource()
const source=JSON.stringify([mode,backendUrl])
const [snapshot,setSnapshot]=useState<{source:string;healthOk:boolean|null;counts:SidebarCountsDto|null;receivedAt:string|null;countsError:string|null}|null>(null)
const data=snapshot?.source===source?snapshot:null,healthOk=mode!=="live"?true:data?.healthOk??null
const counts=mode!=="live"?{servers:servers.length,filterRules:filters.length,monitoringItems:pingProbes.length}:can("mm:dashboard:read")?data?.counts:null
useEffect(()=>{
if(!prefsHydrated||mode!=="live")return
let cancelled=false,revision=0,controller:AbortController|null=null
const load=async()=>{
controller?.abort();controller=new AbortController();const request=++revision,signal=controller.signal
const publish=(patch:Partial<NonNullable<typeof snapshot>>)=>{if(cancelled||request!==revision)return;setSnapshot(previous=>({...((previous?.source===source?previous:null)??{source,healthOk:null,counts:null,receivedAt:null,countsError:null}),...patch}))}
await Promise.allSettled([
(async()=>{try{await getBackendHealth(backendUrl,signal);publish({healthOk:true})}catch{publish({healthOk:false})}})(),
(async()=>{await ensureAuthConfig();if(cancelled||request!==revision)return;if(!can("mm:dashboard:read")){publish({counts:null,countsError:"Нет доступа к сводке"});return}try{const result=await getSidebarCounts(backendUrl,AbortSignal.any([signal,AbortSignal.timeout(30_000)]));if(can("mm:dashboard:read"))publish({counts:result,receivedAt:new Date().toISOString(),countsError:null})}catch{publish({countsError:"Сводка не обновлена; показан последний успешный снимок, если он есть."})}})(),
])
}
void load();const timer=window.setInterval(load,30_000)
return()=>{cancelled=true;revision++;controller?.abort();window.clearInterval(timer)}
},[mode,backendUrl,prefsHydrated,source])
const serversCount=mode!=="live"||can("mm:servers:read")?counts?.servers:undefined
const filtersCount=mode!=="live"||can("mm:filters:read")?counts?.filterRules:undefined
const monitoringCount=mode!=="live"||can("mm:uptime:read")?counts?.monitoringItems:undefined
const apiOk = healthOk === true
const metrics = useMemo<MonitorMetric[]>(
() => [
{
id: "api",
label: "API",
value: healthOk == null ? "…" : apiOk ? "OK" : "—",
unit: "",
percent: healthOk===null?null:apiOk ? 100 : 0,
icon: <Activity className="size-3" aria-hidden />,
tone: apiOk ? "success" : "destructive",
alert: healthOk === false,
},
{
id: "servers",
label: "Серверы",
value: serversCount===undefined?"—":String(serversCount),
unit: "шт.",
percent: null,
icon: <Server className="size-3" aria-hidden />,
tone: (serversCount??0) > 0 ? "success" : "warning",
alert: false,
},
{
id: "filters",
label: "Фильтры",
value: filtersCount===undefined?"—":String(filtersCount),
unit: "шт.",
percent: null,
icon: <Filter className="size-3" aria-hidden />,
tone: "info",
alert: false,
},
{
id: "uptime",
label: "Мониторинг",
value: monitoringCount===undefined?"—":String(monitoringCount),
unit: "шт.",
percent: null,
icon: <HeartPulse className="size-3" aria-hidden />,
tone: (monitoringCount??0) > 0 ? "success" : "warning",
alert: false,
},
],
[apiOk, filtersCount, healthOk, monitoringCount, serversCount],
)
const spiking = metrics.some((m) => m.alert)
return (
<Popover>
<PopoverTrigger
render={
<button
type="button"
aria-label="Монитор системы"
className={cn(
"relative inline-flex h-8 items-center gap-1.5 rounded-md border px-2 transition-colors outline-none",
"border-border hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
)}
/>
}
>
<span className="relative flex size-3.5 items-center justify-center">
<Activity
aria-hidden
className={cn(
"size-3.5 transition-colors",
spiking ? "text-destructive" : "text-muted-foreground",
)}
/>
{spiking ? (
<span className="bg-destructive/25 absolute inset-0 animate-ping rounded-full" aria-hidden />
) : null}
</span>
<span className="text-foreground hidden text-xs font-medium sm:inline">Система</span>
<Badge
variant={spiking ? "destructive-light" : apiOk?"success-light":"outline"}
size="xs"
className={cn("h-4 px-1.5 text-[10px]",apiOk&&"text-emerald-700 dark:text-emerald-400",spiking&&"text-red-700 dark:text-red-400")}
>
{spiking?"Нет связи":apiOk?"API доступен":"Нет данных"}
</Badge>
</PopoverTrigger>
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-0! p-0!">
<div className="border-border flex items-center justify-between border-b px-3 py-2.5">
<span className="text-foreground text-xs font-medium">Монитор MikrotikManager</span>
<span className="text-muted-foreground text-[11px] tabular-nums">
{mode!=="live"?"Демо":data?.receivedAt?new Date(data.receivedAt).toLocaleTimeString("ru-RU"):"Снимок не получен"}
</span>
</div>
{data?.countsError?<p role="status" className="px-3 py-2 text-xs text-muted-foreground">{data.countsError}</p>:null}
<div className="grid grid-cols-2">
{metrics.map((metric, i) => (
<div
key={metric.id}
className={cn(
i % 2 === 1 && "border-border border-l",
i >= 2 && "border-border border-t",
)}
>
<MetricCell metric={metric} />
</div>
))}
</div>
<div className="border-border text-muted-foreground border-t px-3 py-2 text-[11px]">
Источник:{" "}
<span className="text-foreground font-medium">
{mode === "live" ? "API" : "мок"}
</span>
</div>
</PopoverContent>
</Popover>
)
}