import { useState, useEffect } from "react"; import { Cpu } from "lucide-react"; import { useTranslation } from "react-i18next"; import type { ServerMetrics } from "@/main-axios"; import { RadialGauge, Sparkline, MiniStat } from "@/components/charts"; import { MetricCard } from "@/components/metric-card"; import { LineChart, type LineChartSeries } from "@/components/charts/LineChart"; import { getMetricsHistory, type MetricsHistoryRow, } from "@/api/host-metrics-api"; import { CardTimeTabs, type HistoryTab } from "./CardTimeTabs"; function computeChartData(rows: MetricsHistoryRow[]) { return { data: rows.map((r) => r.cpu_percent), timestamps: rows.map((r) => r.ts), }; } export function CpuCard({ metrics, history, hostId, }: { metrics: ServerMetrics | null; history: number[]; hostId: number | null; }) { const { t } = useTranslation(); const [activeTab, setActiveTab] = useState("live"); const [rows, setRows] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { if (activeTab === "live" || hostId == null) return; let cancelled = false; setLoading(true); setRows(null); getMetricsHistory(hostId, { range: activeTab }) .then((res) => { if (!cancelled) { setRows(res.rows); setLoading(false); } }) .catch(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [activeTab, hostId]); const percent = metrics?.cpu?.percent ?? null; const cores = metrics?.cpu?.cores ?? null; const load = metrics?.cpu?.load ?? null; const series: LineChartSeries[] = [ { key: "cpu", label: t("hostMetrics.cpuUsage"), color: "var(--accent-brand)", data: rows?.map((r) => r.cpu_percent) ?? [], }, ]; const timestamps = rows?.map((r) => r.ts) ?? []; return ( } action={ hostId != null ? ( ) : undefined } >
{activeTab === "live" && (
{load && (
)}
)} {activeTab !== "live" && ( <> {loading && (
{t("common.loading")}
)} {!loading && rows !== null && rows.length === 0 && (
{t("metricsHistory.noData")}
)} {!loading && rows !== null && rows.length > 0 && ( `${v.toFixed(0)}%`} height={160} /> )} )}
); }