All files / web/src/hooks use-navigation-performance.ts

67.14% Statements 141/210
65.11% Branches 28/43
100% Functions 2/2
67.14% Lines 141/210

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292    1x 1x                                       1x 1x   1x 43x 43x 43x 43x 43x 43x 43x 43x 43x     43x 21x   21x 21x 21x 4x 4x 4x 21x 1x   1x 1x 1x     1x 43x     43x 21x 21x   21x   21x 21x 21x 21x     21x     21x 21x 21x                               21x   21x 21x 21x 21x     21x   21x 21x 21x     21x 21x 21x   20x 20x 19x 4x     4x                                                                                           4x 19x 20x 20x     21x 1x 1x 1x 1x 20x 20x 20x         20x   20x 20x     21x 21x 21x 21x 21x 21x     21x 21x 21x 21x 21x 21x     21x 19x 19x 21x         21x 21x 21x 21x 21x     21x 43x     43x 2x   1x 2x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 2x       2x 2x 2x 2x 43x     43x 43x 1x 1x 43x 43x     43x 1x 1x 1x 1x     43x     43x 42x                 43x   43x 43x 43x 43x 43x 43x 43x 43x  
'use client';
 
import { useLocation } from '@tanstack/react-router';
import { useCallback, useEffect, useRef, useState } from 'react';
 
export interface NavigationMetrics {
  route: string;
  timestamp: number;
  loadTime?: number;
  renderTime?: number;
  ttfb?: number; // Time to first byte
  fcp?: number; // First contentful paint
  lcp?: number; // Largest contentful paint
}
 
interface PerformanceReport {
  currentRoute: string;
  metrics: NavigationMetrics;
  averageLoadTime: number;
  slowestRoute?: string;
  fastestRoute?: string;
}
 
const METRICS_STORAGE_KEY = 'agent-navigation-metrics';
const MAX_STORED_METRICS = 100;
 
export function useNavigationPerformance() {
  const location = useLocation();
  const pathname = location.pathname;
  const [metrics, setMetrics] = useState<NavigationMetrics[]>([]);
  const [currentMetric, setCurrentMetric] = useState<NavigationMetrics | null>(
    null,
  );
  const navigationStartTime = useRef<number>(0);
  const observer = useRef<PerformanceObserver | null>(null);
  const isMountedRef = useRef(true);
 
  // Load stored metrics on mount
  useEffect(() => {
    if (typeof window === 'undefined') return;
 
    try {
      const stored = localStorage.getItem(METRICS_STORAGE_KEY);
      if (stored && stored.trim() !== '') {
        const parsedMetrics = JSON.parse(stored);
        setMetrics(parsedMetrics.slice(-MAX_STORED_METRICS));
      }
    } catch (error) {
      console.warn('Failed to load navigation metrics:', error);
      // Clear corrupted data
      try {
        localStorage.removeItem(METRICS_STORAGE_KEY);
      } catch {
        // Ignore cleanup errors
      }
    }
  }, []);
 
  // Track navigation start
  useEffect(() => {
    isMountedRef.current = true;
    if (typeof performance === 'undefined') return;
 
    navigationStartTime.current = performance.now();
 
    const metric: NavigationMetrics = {
      route: pathname,
      timestamp: Date.now(),
    };
 
    // Mark navigation start
    performance.mark(`navigation-start-${pathname}`);
 
    // Setup performance observer for paint timings
    if (typeof window !== 'undefined' && 'PerformanceObserver' in window) {
      try {
        observer.current = new PerformanceObserver((list) => {
          const entries = list.getEntries();
 
          for (const entry of entries) {
            if (entry.entryType === 'paint') {
              if (entry.name === 'first-contentful-paint') {
                metric.fcp = entry.startTime;
              }
            } else if (entry.entryType === 'largest-contentful-paint') {
              metric.lcp = entry.startTime;
            }
          }
 
          if (isMountedRef.current) {
            setCurrentMetric({ ...metric });
          }
        });
 
        observer.current.observe({
          entryTypes: ['paint', 'largest-contentful-paint'],
        });
      } catch (error) {
        console.warn('Performance observer setup failed:', error);
      }
    }
 
    if (isMountedRef.current) {
      setCurrentMetric(metric);
    }
 
    // Wait for page to fully load before measuring
    let rafId: number | null = null;
    let timeoutId: ReturnType<typeof setTimeout> | null = null;
    const measurePerformance = () => {
      // More realistic timing - wait for next microtask and then measure
      Promise.resolve().then(() => {
        if (typeof window === 'undefined' || !isMountedRef.current) return;
        rafId = requestAnimationFrame(() => {
          const renderTime = performance.now() - navigationStartTime.current;
 
          // Final measurement after DOM settles
          timeoutId = setTimeout(() => {
            if (!isMountedRef.current) return;
            const finalLoadTime =
              performance.now() - navigationStartTime.current;
 
            const finalMetric = {
              ...metric,
              loadTime: finalLoadTime,
              renderTime: renderTime,
            };
 
            // Mark navigation end
            performance.mark(`navigation-end-${pathname}`);
 
            // Measure navigation duration
            try {
              performance.measure(
                `navigation-${pathname}`,
                `navigation-start-${pathname}`,
                `navigation-end-${pathname}`,
              );
            } catch (error) {
              console.warn('Performance measure failed:', error);
            }
 
            if (isMountedRef.current) {
              setCurrentMetric(finalMetric);
            }
 
            // Store metric
            if (!isMountedRef.current) return;
            setMetrics((prev) => {
              const updated = [...prev, finalMetric].slice(-MAX_STORED_METRICS);
 
              // Persist to localStorage
              try {
                localStorage.setItem(
                  METRICS_STORAGE_KEY,
                  JSON.stringify(updated),
                );
              } catch (error) {
                console.warn('Failed to store navigation metrics:', error);
              }
 
              return updated;
            });
          }, 10); // Small delay to let DOM settle
        });
      });
    };
 
    // Use different strategies based on document state
    if (typeof document !== 'undefined' && document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', measurePerformance, {
        once: true,
      });
    } else if (
      typeof document !== 'undefined' &&
      document.readyState === 'interactive'
    ) {
      // DOM is ready but resources might still be loading
      if (typeof window !== 'undefined') {
        window.addEventListener('load', measurePerformance, { once: true });
      }
    } else {
      // Everything is already loaded
      measurePerformance();
    }
 
    // Cleanup
    return () => {
      isMountedRef.current = false;
      if (observer.current) {
        observer.current.disconnect();
        observer.current = null;
      }
 
      // Remove event listeners
      if (typeof document !== 'undefined') {
        document.removeEventListener('DOMContentLoaded', measurePerformance);
      }
      if (typeof window !== 'undefined') {
        window.removeEventListener('load', measurePerformance);
      }
 
      // Cancel any pending RAF/timeout
      if (typeof window !== 'undefined' && rafId != null) {
        cancelAnimationFrame(rafId);
      }
      if (timeoutId != null) {
        clearTimeout(timeoutId);
      }
 
      // Clear performance marks
      try {
        performance.clearMarks(`navigation-start-${pathname}`);
        performance.clearMarks(`navigation-end-${pathname}`);
        performance.clearMeasures(`navigation-${pathname}`);
      } catch (_error) {
        // Ignore cleanup errors
      }
    };
  }, [pathname]);
 
  // Calculate performance report - memoized to prevent recreating on every render
  const getPerformanceReport = useCallback((): PerformanceReport | null => {
    if (metrics.length === 0) return null;
 
    const validMetrics = metrics.filter((m) => m.loadTime);
    if (validMetrics.length === 0) return null;
 
    const totalLoadTime = validMetrics.reduce(
      (sum, m) => sum + (m.loadTime || 0),
      0,
    );
    const averageLoadTime = totalLoadTime / validMetrics.length;
 
    const sorted = [...validMetrics].sort(
      (a, b) => (a.loadTime || 0) - (b.loadTime || 0),
    );
    const slowest = sorted[sorted.length - 1];
    const fastest = sorted[0];
 
    return {
      currentRoute: pathname,
      metrics: currentMetric || {
        route: pathname,
        timestamp: Date.now(),
      },
      averageLoadTime,
      slowestRoute: slowest?.route,
      fastestRoute: fastest?.route,
    };
  }, [metrics, pathname, currentMetric]);
 
  // Get metrics for specific route - memoized
  const getRouteMetrics = useCallback(
    (route: string): NavigationMetrics[] => {
      return metrics.filter((m) => m.route === route);
    },
    [metrics],
  );
 
  // Clear stored metrics - memoized
  const clearMetrics = useCallback(() => {
    setMetrics([]);
    try {
      localStorage.removeItem(METRICS_STORAGE_KEY);
    } catch (error) {
      console.warn('Failed to clear metrics:', error);
    }
  }, []);
 
  // Log slow navigations
  useEffect(() => {
    if (currentMetric?.loadTime && currentMetric.loadTime > 100) {
      console.warn('Slow navigation detected:', {
        route: currentMetric.route,
        loadTime: `${currentMetric.loadTime.toFixed(2)}ms`,
        renderTime: currentMetric.renderTime
          ? `${currentMetric.renderTime.toFixed(2)}ms`
          : 'N/A',
      });
    }
  }, [currentMetric]);
 
  return {
    currentMetric,
    metrics,
    getPerformanceReport,
    getRouteMetrics,
    clearMetrics,
  };
}