|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import React, { useEffect, useState } from 'react'; |
| 4 | +import { measureWebVitals, PerformanceMetric } from '../../utils/performanceUtils'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Component to monitor and display performance metrics in real-time. |
| 8 | + * In a production environment, this could be hidden or restricted to admin users. |
| 9 | + */ |
| 10 | +const PerformanceMonitor: React.FC = () => { |
| 11 | + const [metrics, setMetrics] = useState<Record<string, PerformanceMetric>>({}); |
| 12 | + const [isVisible, setIsVisible] = useState(false); |
| 13 | + |
| 14 | + useEffect(() => { |
| 15 | + measureWebVitals((metric) => { |
| 16 | + setMetrics((prev: Record<string, PerformanceMetric>) => ({ |
| 17 | + ...prev, |
| 18 | + [metric.name]: metric, |
| 19 | + })); |
| 20 | + |
| 21 | + // Logic for alerts based on thresholds |
| 22 | + if (metric.name === 'LCP' && metric.value > 2500) { |
| 23 | + console.warn(`[Performance Alert] LCP is high: ${metric.value.toFixed(2)}ms`); |
| 24 | + } |
| 25 | + if (metric.name === 'FID' && metric.value > 100) { |
| 26 | + console.warn(`[Performance Alert] FID is high: ${metric.value.toFixed(2)}ms`); |
| 27 | + } |
| 28 | + }); |
| 29 | + }, []); |
| 30 | + |
| 31 | + if (process.env.NODE_ENV === 'production' && !isVisible) return null; |
| 32 | + |
| 33 | + return ( |
| 34 | + <div className={`fixed bottom-4 right-4 z-50 p-4 rounded-lg bg-black/80 text-white text-xs font-mono shadow-xl transition-opacity ${isVisible ? 'opacity-100' : 'opacity-0 hover:opacity-100'}`}> |
| 35 | + <div className="flex justify-between items-center mb-2 border-b border-white/20 pb-1"> |
| 36 | + <span className="font-bold ">🚀 Performance Monitor</span> |
| 37 | + <button onClick={() => setIsVisible(!isVisible)} className="ml-2 hover:text-blue-400"> |
| 38 | + {isVisible ? 'Hide' : 'Show'} |
| 39 | + </button> |
| 40 | + </div> |
| 41 | + <div className="space-y-1"> |
| 42 | + {Object.values(metrics).map((metric) => ( |
| 43 | + <div key={metric.name} className="flex justify-between gap-4"> |
| 44 | + <span>{metric.name}:</span> |
| 45 | + <span className={metric.value > 2000 ? 'text-red-400' : 'text-green-400'}> |
| 46 | + {metric.value.toFixed(2)}{metric.label || ''} |
| 47 | + </span> |
| 48 | + </div> |
| 49 | + ))} |
| 50 | + </div> |
| 51 | + </div> |
| 52 | + ); |
| 53 | +}; |
| 54 | + |
| 55 | +export default PerformanceMonitor; |
0 commit comments