All files / src/lib route-prefetcher.ts

76.31% Statements 29/38
69.23% Branches 9/13
70.58% Functions 12/17
78.37% Lines 29/37

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                                        3x           3x       11x 4x 4x     4x     4x   4x                     3x       6x   1x 1x 1x                 3x     1x           1x           1x           1x                                     3x     3x 3x   18x             3x 11x         3x               3x   1x     1x     1x    
import type { ComponentType } from 'react';
import { lazy } from 'react';
import { prefetchWithServiceWorker } from './service-worker';
import {
  AUTH_ROUTES,
  DASHBOARD_ROUTES,
  WALLET_ROUTES,
  STATS_ROUTES,
  PROFILE_ROUTES,
} from '@/constants/route';
 
// Route prefetching utilities
export interface RouteConfig {
  path: string;
  component: () => Promise<{ default: ComponentType<any> }>;
  priority: 'high' | 'medium' | 'low';
  preload?: boolean;
}
 
// Store for prefetched components
const prefetchedComponents = new Map<
  string,
  Promise<{ default: ComponentType<any> }>
>();
 
// Prefetch a route component
export const prefetchRoute = (
  importFn: () => Promise<{ default: ComponentType<any> }>,
  routeName: string
): void => {
  if (!prefetchedComponents.has(routeName)) {
    const componentPromise = importFn();
    prefetchedComponents.set(routeName, componentPromise);
 
    // Also prefetch with service worker if available
    prefetchWithServiceWorker(routeName);
 
    // Handle prefetch success/failure
    componentPromise
      .then(() => {
        console.log(`✅ Prefetched ${routeName} successfully`);
      })
      .catch(error => {
        console.warn(`⚠️ Failed to prefetch ${routeName}:`, error);
        // Remove failed prefetch from cache
        prefetchedComponents.delete(routeName);
      });
  }
};
 
// Create a lazy component with prefetching support
export const createLazyComponent = (
  importFn: () => Promise<{ default: ComponentType<any> }>,
  routeName: string
) => {
  return lazy(() => {
    // Check if component is already prefetched
    const prefetched = prefetchedComponents.get(routeName);
    Eif (prefetched) {
      return prefetched;
    }
 
    // If not prefetched, import normally
    return importFn();
  });
};
 
// Route definitions with prefetching configuration
export const routes: RouteConfig[] = [
  {
    path: AUTH_ROUTES.LOGIN,
    component: () => import('@/features/auth/auth-page'),
    priority: 'high',
    preload: true, // Always preload auth page
  },
  {
    path: DASHBOARD_ROUTES.OVERVIEW,
    component: () => import('@/features/dashboard/dashboard-page'),
    priority: 'high',
    preload: true, // Dashboard is usually the first page users see
  },
  {
    path: WALLET_ROUTES.WALLET,
    component: () => import('@/features/wallet/wallet-page'),
    priority: 'high',
    preload: true, // Wallet is frequently accessed
  },
  {
    path: WALLET_ROUTES.TRANSACTIONS,
    component: () => import('@/features/transaction/transaction-page'),
    priority: 'medium',
    preload: true, // Transaction page is commonly used
  },
  {
    path: STATS_ROUTES.STATISTICS,
    component: () => import('@/features/statistics/statistics-page'),
    priority: 'medium',
    preload: false, // Statistics might be less frequently accessed
  },
  {
    path: PROFILE_ROUTES.SETTINGS,
    component: () => import('@/features/setting/setting-page'),
    priority: 'low',
    preload: false, // Settings are accessed less frequently
  },
];
 
// Prefetch routes based on priority
export const prefetchRoutes = (
  priority: 'high' | 'medium' | 'low' = 'high'
): void => {
  console.log(`Prefetching ${priority} priority routes...`);
  const routesToPrefetch = routes.filter(
    route =>
      route.preload &&
      (priority === 'low' ||
        (priority === 'medium' &&
          ['high', 'medium'].includes(route.priority)) ||
        (priority === 'high' && route.priority === 'high'))
  );
 
  routesToPrefetch.forEach(route => {
    prefetchRoute(route.component, route.path);
  });
};
 
// Prefetch routes on user interaction (hover, focus, etc.)
export const prefetchOnInteraction = (routeName: string): void => {
  const route = routes.find(r => r.path === routeName);
  if (route) {
    prefetchRoute(route.component, routeName);
  }
};
 
// Intelligent prefetching based on user behavior
export const intelligentPrefetch = (): void => {
  // Prefetch high-priority routes immediately
  prefetchRoutes('high');
 
  // Prefetch medium-priority routes immediately after high
  prefetchRoutes('medium');
 
  // Prefetch low-priority routes immediately after medium
  prefetchRoutes('low');
};