Этап 0 и пилот интеграции макета v3: - оболочка: inset-сайдбар, крошки «Главная / … /», индикатор свежести, заголовок страницы PageTitle; - общие блоки reui-kit/ops-blocks: SectionFrame, CapacityGrid, SparkKpiGrid, ToneBadge; - дашборд: ёмкость, показатели со спарклайнами, сводка источников, вкладки «Обзор / Источники и время получения / История RTT», здоровье сети, лента инцидентов, схема Internet path, сводка маршрута, таблица «Требует внимания», настройка видимости виджетов; - статистика: вкладки «Обзор / Сводная (куб) / Срезы», доли объёма; - трафик: вкладки разделов со счётчиками, рамки списка и деталей, кнопка «Месячный отчёт». Co-Authored-By: Claude Opus 5.5 <[email protected]>
150 lines
7.9 KiB
TypeScript
150 lines
7.9 KiB
TypeScript
"use client"
|
||
|
||
import type { ReactNode } from "react"
|
||
import { ActivityIcon, BellIcon, BoxIcon, ChartColumnIcon, DatabaseIcon, GlobeIcon, LinkIcon, LockIcon, RouteIcon, ServerIcon } from "lucide-react"
|
||
import { Button } from "@/components/ui/button"
|
||
import { FramePanel } from "@/components/reui/frame"
|
||
import { IconTile } from "@/components/reui/icon-tile"
|
||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||
import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state"
|
||
import { cn } from "@/lib/utils"
|
||
|
||
const SOURCE_ICON: Record<DashboardSource, ReactNode> = {
|
||
servers: <ServerIcon />, probes: <ActivityIcon />, bgp: <RouteIcon />, gre: <LinkIcon />, wg: <LockIcon />,
|
||
vxlan: <BoxIcon />, traffic: <ChartColumnIcon />, internetPath: <GlobeIcon />, events: <BellIcon />,
|
||
}
|
||
|
||
export type SourceRow = {
|
||
key: DashboardSource
|
||
name: string
|
||
tone: Tone
|
||
label: string
|
||
receivedAt: number | null
|
||
sampledAt: string | null
|
||
error: string | null
|
||
}
|
||
|
||
/** Состояние каждого источника дашборда: обновлён, устарел (ошибка после успеха), нет загрузок или ожидание. */
|
||
export function dashboardSourceRows(sources: DashboardSources): SourceRow[] {
|
||
return (Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => {
|
||
const source = sources[key]
|
||
const receivedAt = source?.receivedAt ?? null
|
||
const error = source?.error ?? null
|
||
const sampledAt = source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) ? source.sampledAt : null
|
||
const tone: Tone = error ? (receivedAt != null ? "wn" : "er") : receivedAt != null ? "ok" : "mu"
|
||
const label = error ? (receivedAt != null ? "Устарел" : "Нет загрузок") : receivedAt != null ? "Обновлён" : "Ожидание"
|
||
return { key, name: DASHBOARD_SOURCES[key], tone, label, receivedAt, sampledAt, error }
|
||
})
|
||
}
|
||
|
||
function Clock({ at }: { at: number | string | null }) {
|
||
if (at == null) return <b className="text-foreground font-mono font-medium">—</b>
|
||
const date = new Date(at)
|
||
return (
|
||
<time dateTime={typeof at === "string" ? at : date.toISOString()} className="text-foreground font-mono font-medium">
|
||
{date.toLocaleTimeString("ru-RU")}
|
||
</time>
|
||
)
|
||
}
|
||
|
||
export function sourceErrorText(row: SourceRow) {
|
||
if (!row.error) return null
|
||
return row.receivedAt != null
|
||
? `Ошибка обновления — ${row.error} · данные могут быть устаревшими`
|
||
: `Ошибка обновления — ${row.error} · успешных загрузок ещё нет`
|
||
}
|
||
|
||
/**
|
||
* Сводка источников дашборда (блок sources макета v3): итог слева, плитки источников справа.
|
||
* @see https://reui.io/docs/components/base/frame
|
||
*/
|
||
export function DashboardSourcesSummary({ rows, refreshing, onRefresh }: {
|
||
rows: SourceRow[]
|
||
refreshing: boolean
|
||
onRefresh: () => void
|
||
}) {
|
||
const count = (tone: Tone) => rows.filter((row) => row.tone === tone).length
|
||
const ok = count("ok")
|
||
const segments = ([
|
||
["ok", "Обновлены", count("ok")],
|
||
["wn", "С ошибкой", count("wn")],
|
||
["er", "Нет загрузок", count("er")],
|
||
["mu", "Ожидание", count("mu")],
|
||
] as const).filter(([, , n]) => n > 0)
|
||
const sub = [
|
||
count("wn") ? `${count("wn")} с ошибкой — показаны прошлые данные` : null,
|
||
count("er") ? `${count("er")} без успешных загрузок` : null,
|
||
count("mu") ? `${count("mu")} ожидают первой загрузки` : null,
|
||
].filter(Boolean).join(" · ") || "Все источники получены"
|
||
|
||
return (
|
||
<SectionFrame
|
||
title="Сводка источников"
|
||
description="Время получения и замера по каждому источнику дашборда · подробности — на вкладке «Источники и время получения»"
|
||
icon={<DatabaseIcon />}
|
||
bare
|
||
actions={
|
||
<>
|
||
<span role="status" className="text-muted-foreground text-xs">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
|
||
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing} aria-label="Обновить данные источников">Обновить данные</Button>
|
||
</>
|
||
}
|
||
>
|
||
<FramePanel className="grid grid-cols-1 p-0 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]">
|
||
<div className="flex min-w-0 flex-col gap-2 border-b px-[18px] py-4 min-[1100px]:border-r min-[1100px]:border-b-0">
|
||
<div className="text-muted-foreground text-[0.8rem]">Источники обновлены</div>
|
||
<div className="flex items-baseline gap-0.5">
|
||
<span className="text-[30px] leading-tight font-semibold tracking-tight tabular-nums">{ok}</span>
|
||
<span className="text-muted-foreground ml-0.5 text-base">/ {rows.length}</span>
|
||
</div>
|
||
<div className="text-muted-foreground text-xs">{sub}</div>
|
||
<div role="img" aria-label={segments.map(([, label, n]) => `${label}: ${n}`).join(", ")} className="mt-1.5 flex h-2 gap-[3px]">
|
||
{segments.map(([tone, label, n]) => (
|
||
<i key={label} className="block h-full min-w-1.5 rounded-full" style={{ flex: n, background: TONE_COLOR[tone] }} />
|
||
))}
|
||
</div>
|
||
<div className="text-muted-foreground grid grid-cols-2 gap-x-3.5 gap-y-1.5 text-xs">
|
||
{segments.map(([tone, label, n]) => (
|
||
<span key={label} className="flex min-w-0 items-center gap-1.5">
|
||
<i aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[tone] }} />
|
||
{label}
|
||
<b className="text-foreground ml-auto font-medium tabular-nums">{n}</b>
|
||
</span>
|
||
))}
|
||
</div>
|
||
<p className="text-muted-foreground mt-auto border-t border-dashed pt-2.5 text-xs leading-snug">
|
||
Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.
|
||
</p>
|
||
</div>
|
||
<ul className="grid grid-cols-2 min-[1100px]:grid-cols-3">
|
||
{rows.map((row) => {
|
||
const error = sourceErrorText(row)
|
||
return (
|
||
<li
|
||
key={row.key}
|
||
data-source={row.key}
|
||
className="flex min-w-0 flex-col gap-2 border-r border-b px-3.5 py-3 max-[1099px]:even:border-r-0 min-[1100px]:[&:nth-child(3n)]:border-r-0 min-[1100px]:[&:nth-last-child(-n+3)]:border-b-0"
|
||
>
|
||
<div className="flex min-w-0 items-center gap-2.5">
|
||
<IconTile variant="outline" size="sm" aria-hidden="true" style={{ color: row.tone === "ok" || row.tone === "mu" ? "var(--muted-foreground)" : TONE_COLOR[row.tone] }}>
|
||
{SOURCE_ICON[row.key]}
|
||
</IconTile>
|
||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{row.name}</span>
|
||
<ToneBadge tone={row.tone} size="default">{row.label}</ToneBadge>
|
||
</div>
|
||
<div className="text-muted-foreground flex flex-wrap gap-x-3.5 gap-y-1 text-xs">
|
||
<span>Получено <Clock at={row.receivedAt} /></span>
|
||
<span>Замер <Clock at={row.sampledAt} /></span>
|
||
</div>
|
||
{error ? (
|
||
<p className={cn("text-xs leading-snug", row.tone === "wn" ? "text-warning-foreground" : "text-destructive-foreground")}>{error}</p>
|
||
) : null}
|
||
</li>
|
||
)
|
||
})}
|
||
</ul>
|
||
</FramePanel>
|
||
</SectionFrame>
|
||
)
|
||
}
|