triyak-react-performance
Version:
Advanced React performance optimization toolkit - Built with modern React best practices and performance optimization techniques
272 lines • 13.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const performanceThresholds_1 = require("../constants/performanceThresholds");
const TriyakPerformanceMonitor = ({ lcpThreshold = performanceThresholds_1.PERFORMANCE_THRESHOLDS.LCP.ENTERPRISE_TARGET, fidThreshold = performanceThresholds_1.PERFORMANCE_THRESHOLDS.FID.ENTERPRISE_TARGET, clsThreshold = performanceThresholds_1.PERFORMANCE_THRESHOLDS.CLS.ENTERPRISE_TARGET, ttfbThreshold = performanceThresholds_1.PERFORMANCE_THRESHOLDS.TTFB.ENTERPRISE_TARGET, fcpThreshold = performanceThresholds_1.PERFORMANCE_THRESHOLDS.FCP.ENTERPRISE_TARGET, enableAIOptimization = true, optimizationMode = 'aggressive', monitoring = true, alerts = true, reporting = true, autoOptimize = true, onPerformanceAlert, onMetrics, onReport, onOptimization, children, config = {} }) => {
// State for performance metrics
const [metrics, setMetrics] = (0, react_1.useState)({
lcp: 0,
fid: 0,
cls: 0,
ttfb: 0,
fcp: 0,
timestamp: Date.now()
});
// State for alerts and reports
const [performanceAlerts, setPerformanceAlerts] = (0, react_1.useState)([]);
const [reports, setReports] = (0, react_1.useState)([]);
// Refs for performance observers
const lcpObserverRef = (0, react_1.useRef)(null);
const fidObserverRef = (0, react_1.useRef)(null);
const clsObserverRef = (0, react_1.useRef)(null);
const navigationObserverRef = (0, react_1.useRef)(null);
const paintObserverRef = (0, react_1.useRef)(null);
// Configuration
const finalConfig = {
enableAIOptimization,
optimizationMode,
monitoring,
alerts,
reporting,
autoOptimize,
...config
};
// Calculate performance score
const calculateScore = (0, react_1.useCallback)((metrics) => {
let score = 100;
// LCP scoring (40% weight)
if (metrics.lcp <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.LCP.GOOD) {
score -= 0;
}
else if (metrics.lcp <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.LCP.NEEDS_IMPROVEMENT) {
score -= 20;
}
else {
score -= 40;
}
// FID scoring (30% weight)
if (metrics.fid <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.FID.GOOD) {
score -= 0;
}
else if (metrics.fid <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.FID.NEEDS_IMPROVEMENT) {
score -= 15;
}
else {
score -= 30;
}
// CLS scoring (30% weight)
if (metrics.cls <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.CLS.GOOD) {
score -= 0;
}
else if (metrics.cls <= performanceThresholds_1.PERFORMANCE_THRESHOLDS.CLS.NEEDS_IMPROVEMENT) {
score -= 15;
}
else {
score -= 30;
}
return Math.max(0, score);
}, []);
// Calculate performance grade
const calculateGrade = (0, react_1.useCallback)((score) => {
if (score >= 90)
return 'A';
if (score >= 80)
return 'B';
if (score >= 70)
return 'C';
if (score >= 60)
return 'D';
return 'F';
}, []);
// Generate performance report
const generateReport = (0, react_1.useCallback)((metrics) => {
const score = calculateScore(metrics);
const grade = calculateGrade(score);
return {
metrics,
alerts: performanceAlerts,
optimizations: [], // Will be populated by optimization engine
score,
grade,
timestamp: Date.now(),
url: window.location.href,
userAgent: navigator.userAgent
};
}, [performanceAlerts, calculateScore, calculateGrade]);
// Monitor Core Web Vitals
const monitorCoreWebVitals = (0, react_1.useCallback)(() => {
if (!finalConfig.monitoring || !('PerformanceObserver' in window))
return;
// Monitor LCP (Largest Contentful Paint)
try {
lcpObserverRef.current = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const lcp = entry.startTime;
setMetrics(prev => ({ ...prev, lcp, timestamp: Date.now() }));
// Check threshold and generate alert
if (alerts && lcp > lcpThreshold) {
const alert = {
metric: 'lcp',
value: lcp,
threshold: lcpThreshold,
severity: lcp > lcpThreshold * 1.5 ? 'critical' : 'warning',
timestamp: Date.now(),
recommendation: `Optimize LCP by reducing image sizes, implementing resource hints, and optimizing server response times. Target: < ${lcpThreshold}ms`
};
setPerformanceAlerts(prev => [...prev, alert]);
onPerformanceAlert?.(alert);
}
}
});
lcpObserverRef.current.observe({ entryTypes: ['largest-contentful-paint'] });
}
catch (error) {
console.warn('Triyak Performance Monitor: LCP monitoring failed:', error);
}
// Monitor FID (First Input Delay)
try {
fidObserverRef.current = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const fid = entry.processingStart - entry.startTime;
setMetrics(prev => ({ ...prev, fid, timestamp: Date.now() }));
// Check threshold and generate alert
if (alerts && fid > fidThreshold) {
const alert = {
metric: 'fid',
value: fid,
threshold: fidThreshold,
severity: fid > fidThreshold * 1.5 ? 'critical' : 'warning',
timestamp: Date.now(),
recommendation: `Optimize FID by reducing JavaScript execution time, implementing code splitting, and using web workers for heavy computations. Target: < ${fidThreshold}ms`
};
setPerformanceAlerts(prev => [...prev, alert]);
onPerformanceAlert?.(alert);
}
}
});
fidObserverRef.current.observe({ entryTypes: ['first-input'] });
}
catch (error) {
console.warn('Triyak Performance Monitor: FID monitoring failed:', error);
}
// Monitor CLS (Cumulative Layout Shift)
try {
clsObserverRef.current = new PerformanceObserver((list) => {
let cls = 0;
for (const entry of list.getEntries()) {
cls += entry.value;
}
setMetrics(prev => ({ ...prev, cls, timestamp: Date.now() }));
// Check threshold and generate alert
if (alerts && cls > clsThreshold) {
const alert = {
metric: 'cls',
value: cls,
threshold: clsThreshold,
severity: cls > clsThreshold * 1.5 ? 'critical' : 'warning',
timestamp: Date.now(),
recommendation: `Optimize CLS by setting explicit dimensions for images and ads, avoiding inserting content above existing content, and using CSS transforms for animations. Target: < ${clsThreshold}`
};
setPerformanceAlerts(prev => [...prev, alert]);
onPerformanceAlert?.(alert);
}
});
clsObserverRef.current.observe({ entryTypes: ['layout-shift'] });
}
catch (error) {
console.warn('Triyak Performance Monitor: CLS monitoring failed:', error);
}
// Monitor TTFB (Time to First Byte)
try {
navigationObserverRef.current = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const navigationEntry = entry;
const ttfb = navigationEntry.responseStart - navigationEntry.requestStart;
setMetrics(prev => ({ ...prev, ttfb, timestamp: Date.now() }));
// Check threshold and generate alert
if (alerts && ttfb > ttfbThreshold) {
const alert = {
metric: 'ttfb',
value: ttfb,
threshold: ttfbThreshold,
severity: ttfb > ttfbThreshold * 1.5 ? 'critical' : 'warning',
timestamp: Date.now(),
recommendation: `Optimize TTFB by improving server response times, implementing caching strategies, and optimizing database queries. Target: < ${ttfbThreshold}ms`
};
setPerformanceAlerts(prev => [...prev, alert]);
onPerformanceAlert?.(alert);
}
}
});
navigationObserverRef.current.observe({ entryTypes: ['navigation'] });
}
catch (error) {
console.warn('Triyak Performance Monitor: TTFB monitoring failed:', error);
}
// Monitor FCP (First Contentful Paint)
try {
paintObserverRef.current = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === 'first-contentful-paint') {
const fcp = entry.startTime;
setMetrics(prev => ({ ...prev, fcp, timestamp: Date.now() }));
// Check threshold and generate alert
if (alerts && fcp > fcpThreshold) {
const alert = {
metric: 'fcp',
value: fcp,
threshold: fcpThreshold,
severity: fcp > fcpThreshold * 1.5 ? 'critical' : 'warning',
timestamp: Date.now(),
recommendation: `Optimize FCP by reducing critical resources, implementing resource hints, and optimizing CSS delivery. Target: < ${fcpThreshold}ms`
};
setPerformanceAlerts(prev => [...prev, alert]);
onPerformanceAlert?.(alert);
}
}
}
});
paintObserverRef.current.observe({ entryTypes: ['paint'] });
}
catch (error) {
console.warn('Triyak Performance Monitor: FCP monitoring failed:', error);
}
}, [finalConfig.monitoring, alerts, lcpThreshold, fidThreshold, clsThreshold, ttfbThreshold, fcpThreshold, onPerformanceAlert]);
// Send metrics to parent
(0, react_1.useEffect)(() => {
if (metrics.lcp > 0 || metrics.fid > 0 || metrics.cls > 0) {
onMetrics?.(metrics);
// Generate and send report if reporting is enabled
if (finalConfig.reporting) {
const report = generateReport(metrics);
setReports(prev => [...prev, report]);
onReport?.(report);
}
}
}, [metrics, finalConfig.reporting, generateReport, onMetrics, onReport]);
// Start monitoring when component mounts
(0, react_1.useEffect)(() => {
monitorCoreWebVitals();
// Cleanup function
return () => {
lcpObserverRef.current?.disconnect();
fidObserverRef.current?.disconnect();
clsObserverRef.current?.disconnect();
navigationObserverRef.current?.disconnect();
paintObserverRef.current?.disconnect();
};
}, [monitorCoreWebVitals]);
// AI-powered optimization (placeholder for future implementation)
(0, react_1.useEffect)(() => {
if (finalConfig.enableAIOptimization && finalConfig.autoOptimize) {
// This would integrate with Triyak's AI optimization engine
// For now, we'll log that AI optimization is enabled
console.log('Triyak Performance Monitor: AI optimization enabled');
}
}, [finalConfig.enableAIOptimization, finalConfig.autoOptimize]);
// Render children with performance context
return ((0, jsx_runtime_1.jsxs)("div", { className: "triyak-performance-monitor", "data-version": "1.0.0", children: [children, process.env.NODE_ENV === 'development' && ((0, jsx_runtime_1.jsxs)("div", { style: { display: 'none' }, children: [(0, jsx_runtime_1.jsxs)("div", { children: ["LCP: ", metrics.lcp, "ms"] }), (0, jsx_runtime_1.jsxs)("div", { children: ["FID: ", metrics.fid, "ms"] }), (0, jsx_runtime_1.jsxs)("div", { children: ["CLS: ", metrics.cls] }), (0, jsx_runtime_1.jsxs)("div", { children: ["TTFB: ", metrics.ttfb, "ms"] }), (0, jsx_runtime_1.jsxs)("div", { children: ["FCP: ", metrics.fcp, "ms"] }), (0, jsx_runtime_1.jsxs)("div", { children: ["Alerts: ", performanceAlerts.length] }), (0, jsx_runtime_1.jsxs)("div", { children: ["Reports: ", reports.length] })] }))] }));
};
exports.default = TriyakPerformanceMonitor;
//# sourceMappingURL=TriyakPerformanceMonitor.js.map