import React, { useState, useEffect, useMemo } from 'react'; import { XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Area, AreaChart } from 'recharts'; import { Cpu, MemoryStick, HardDrive, TrendingUp } from 'lucide-react'; import api from '../services/api'; // Chart colors - matching new_dashboard_3 style const CHART_COLORS = { cpu: '#6366f1', // Purple/Indigo memory: '#10b981', // Green (RAM) disk: '#f59e0b' // Amber/Orange (Disk) }; const MetricsGraph = ({ compact = false, timezone, serverId }) => { const [data, setData] = useState(null); const [period, setPeriod] = useState('1h'); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [visibleMetrics, setVisibleMetrics] = useState({ cpu: true, memory: true, disk: true }); const periods = ['1h', '6h', '24h', '7d', '30d']; const toggleMetric = (metric) => { setVisibleMetrics(prev => ({ ...prev, [metric]: !prev[metric] })); }; useEffect(() => { loadHistory(); }, [period, serverId]); async function loadHistory() { try { setLoading(true); const response = serverId ? await api.getServerMetricsHistory(serverId, period) : await api.getMetricsHistory(period); setData(response); setError(null); } catch (err) { setError(err.message); } finally { setLoading(false); } } function formatTimestamp(isoString) { const date = new Date(isoString); const tz = timezone || undefined; if (period === '1h' || period === '6h' || period === '24h') { return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', timeZone: tz }); } else if (period === '7d') { return date.toLocaleDateString([], { weekday: 'short', hour: '2-digit', timeZone: tz }); } else { return date.toLocaleDateString([], { month: 'short', day: 'numeric', timeZone: tz }); } } const chartData = data?.data?.map(point => ({ time: formatTimestamp(point.timestamp), cpu: point.cpu?.percent ?? point.cpu_percent ?? 0, memory: point.memory?.percent ?? point.memory_percent ?? 0, disk: point.disk?.percent ?? point.disk_percent ?? 0 })) || []; // Auto-zoom: compute Y-axis ceiling from visible metrics const yDomain = useMemo(() => { if (chartData.length === 0) return [0, 100]; const activeKeys = Object.entries(visibleMetrics) .filter(([, visible]) => visible) .map(([key]) => key); if (activeKeys.length === 0) return [0, 100]; let maxVal = 0; chartData.forEach(point => { activeKeys.forEach(key => { if (point[key] > maxVal) maxVal = point[key]; }); }); // Add 20% headroom, floor at 10% const ceiling = Math.max(10, maxVal * 1.2); // Snap to nearest nice tick value const steps = [5, 10, 15, 20, 25, 30, 40, 50, 60, 75, 100]; const niceMax = steps.find(s => s >= ceiling) || 100; return [0, niceMax]; }, [chartData, visibleMetrics]); if (loading && !data) { return (
); } if (error) { return (
Failed to load metrics history
); } if (!data || data.points === 0) { return (
No historical data yet Metrics are collected every minute
); } const CustomTooltip = ({ active, payload, label }) => { if (active && payload && payload.length) { return (
{label}
{payload.map((entry, index) => (
{entry.name}: {entry.value?.toFixed(1)}%
))}
); } return null; }; if (compact) { return (
System Metrics
{periods.map(p => ( ))}
} />
{data.summary.cpu_avg}%
{data.summary.memory_avg}%
{data.summary.disk_avg}%
); } return (
Real-time Performance
{periods.map(p => ( ))}
{/* CPU Gradient - Purple/Indigo */} {/* Memory Gradient - Green */} {/* Disk Gradient - Orange */} `${value}%`} /> } /> {visibleMetrics.cpu && ( )} {visibleMetrics.memory && ( )} {visibleMetrics.disk && ( )}
); }; export default MetricsGraph;