UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

1 lines 2.63 kB
{"version":3,"sources":["../src/components/ModuleProtectedRoute.tsx"],"sourcesContent":["import React from 'react';\nimport { Navigate } from 'react-router-dom';\nimport { useModules } from '../hooks/useModules';\nimport type { ModulesConfig } from '../types/modulesConfig';\n\ntype ModuleKey = keyof ModulesConfig;\n\n/** Keys of ModulesConfig whose value is a boolean (i.e. gateable modules). */\ntype BooleanModuleKey = {\n [K in ModuleKey]: ModulesConfig[K] extends boolean ? K : never;\n}[ModuleKey];\n\ninterface BaseModuleProtectedRouteProps {\n children: React.ReactNode;\n redirectTo?: string;\n}\n\n/**\n * Gate on a boolean module key (`module`) OR on an explicit `enabled` flag\n * (for derived/nested gates such as the Simulados master, `simulations.enabled`).\n * At least one of the two is required, so a route can never be left ungated.\n */\nexport type ModuleProtectedRouteProps = BaseModuleProtectedRouteProps &\n (\n | { module: BooleanModuleKey; enabled?: boolean }\n | { module?: BooleanModuleKey; enabled: boolean }\n );\n\n/**\n * Route guard component that redirects if the specified module is disabled\n * Use this component to wrap routes that should only be accessible when the module is enabled\n *\n * @example\n * <Route path=\"simulador-sisu\" element={\n * <ModuleProtectedRoute module=\"simulator\">\n * <SimuladorSisu />\n * </ModuleProtectedRoute>\n * } />\n *\n * @example\n * <Route path=\"simulados\" element={\n * <ModuleProtectedRoute enabled={hasSimulations}>\n * <Simulados />\n * </ModuleProtectedRoute>\n * } />\n */\nexport const ModuleProtectedRoute = ({\n module,\n enabled,\n children,\n redirectTo = '/painel',\n}: ModuleProtectedRouteProps) => {\n const { modules, loading } = useModules();\n\n // While loading, render nothing to prevent flash of content\n if (loading) {\n return null;\n }\n\n // `enabled` wins when provided; otherwise gate on the boolean module key.\n // Fail closed when neither is supplied (the types prevent this, defensive).\n const isEnabled = enabled ?? (module ? Boolean(modules[module]) : false);\n\n // If disabled, redirect\n if (!isEnabled) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n"],"mappings":";;;;;AACA,SAAS,gBAAgB;AAgEd,SAGF,UAHE;AAnBJ,IAAM,uBAAuB,CAAC;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AACf,MAAiC;AAC/B,QAAM,EAAE,SAAS,QAAQ,IAAI,WAAW;AAGxC,MAAI,SAAS;AACX,WAAO;AAAA,EACT;AAIA,QAAM,YAAY,YAAY,SAAS,QAAQ,QAAQ,MAAM,CAAC,IAAI;AAGlE,MAAI,CAAC,WAAW;AACd,WAAO,oBAAC,YAAS,IAAI,YAAY,SAAO,MAAC;AAAA,EAC3C;AAEA,SAAO,gCAAG,UAAS;AACrB;","names":[]}