refactor: recursiveRouteRenderer params update and comments

This commit is contained in:
enes 2024-07-31 13:48:57 +02:00
parent 1070c9a8f9
commit 5d415a2359
2 changed files with 25 additions and 32 deletions

View File

@ -50,22 +50,12 @@ const App = () => {
return `${appPublicRoutes.login}?callbackPath=${callbackPathEncoded}`
}
const publicRoutesList = recursiveRouteRenderer({
routes: publicRoutes,
renderConditionCallback: (r) => {
if (authState?.loggedIn) {
if (!r.hiddenWhenLoggedIn) {
return true
}
} else {
return true
}
return false
}
// Hide route only if loggedIn and r.hiddenWhenLoggedIn are both true
const publicRoutesList = recursiveRouteRenderer(publicRoutes, (r) => {
return !authState.loggedIn || !r.hiddenWhenLoggedIn
})
const privateRouteList = recursiveRouteRenderer({ routes: privateRoutes })
const privateRouteList = recursiveRouteRenderer(privateRoutes)
return (
<Routes>

View File

@ -41,42 +41,45 @@ export const getProfileRoute = (hexKey: string) =>
export const getProfileSettingsRoute = (hexKey: string) =>
appPrivateRoutes.profileSettings.replace(':npub', hexToNpub(hexKey))
/**
* Helper type allows for extending react-router-dom's **RouteProps** with generic type
*/
type CustomRouteProps<T> = T &
Omit<RouteProps, 'children'> & {
children?: Array<CustomRouteProps<T>>
}
interface CustomRoutes<T> {
routes?: CustomRouteProps<T>[]
renderConditionCallback?: (route: CustomRouteProps<T>) => boolean
}
type PublicRouteProps = CustomRouteProps<{
hiddenWhenLoggedIn?: boolean
}>
export function recursiveRouteRenderer<T>({
routes,
renderConditionCallback = () => true
}: CustomRoutes<T>) {
/**
* This function maps over nested routes with optional condition for rendering
* @param {CustomRouteProps<T>[]} routes - routes list
* @param {RenderConditionCallbackFn} renderConditionCallbackFn - render condition callback (default true)
*/
export function recursiveRouteRenderer<T>(
routes?: CustomRouteProps<T>[],
renderConditionCallbackFn: (route: CustomRouteProps<T>) => boolean = () =>
true
) {
if (!routes) return null
// Callback allows us to pass arbitrary conditions for each route's rendering
// Skipping the callback will by default evaluate to true (show route)
return routes.map((route, index) =>
renderConditionCallback(route) ? (
renderConditionCallbackFn(route) ? (
<Route
key={`${route.path}${index}`}
path={route.path}
element={route.element}
>
{recursiveRouteRenderer({
routes: route.children,
renderConditionCallback
})}
{recursiveRouteRenderer(route.children, renderConditionCallbackFn)}
</Route>
) : null
)
}
type PublicRouteProps = CustomRouteProps<{
hiddenWhenLoggedIn?: boolean
}>
export const publicRoutes: PublicRouteProps[] = [
{
path: appPublicRoutes.landingPage,