import React, { Suspense, lazy, useMemo } from 'react'; import { Routes, Route } from 'react-router-dom'; import { Layout } from './Layout'; import { ProtectedRoute } from './ProtectedRoute'; import { ProtectedAdminRoute } from './ProtectedAdminRoute'; import { ProtectedRouteByResource } from './ProtectedRouteByResource'; import { routeConfig, RouteDefinition } from '@/config/routeConfig'; // ============================================================================ // Fallback de loading para Suspense // ============================================================================ const PageLoadingFallback = () => (
Carregando...
); // ============================================================================ // Cache de componentes lazy para evitar re-criação a cada render // ============================================================================ const lazyComponentCache = new Map>>(); function getLazyComponent(route: RouteDefinition): React.LazyExoticComponent> { const key = route.path; if (!lazyComponentCache.has(key)) { lazyComponentCache.set(key, lazy(route.component)); } return lazyComponentCache.get(key)!; } // ============================================================================ // Funções de wrapping por tipo de guard // ============================================================================ function wrapWithGuard( element: React.ReactNode, guard: RouteDefinition['guard'], resourceKey?: string ): React.ReactNode { switch (guard) { case 'public': return element; case 'protected': return ( {element} ); case 'admin': return ( {element} ); case 'resource': return ( {element} ); default: return element; } } // ============================================================================ // Componente principal de rotas // ============================================================================ export function AppRoutes() { const routes = useMemo( () => routeConfig.map((route) => { const LazyComponent = getLazyComponent(route); const element = wrapWithGuard( }> , route.guard, route.resourceKey ); return ; }), [] ); // Lazy load da página NotFound const LazyNotFound = useMemo(() => lazy(() => import('@/pages/NotFound')), []); return ( {routes} }> } /> ); }