Skip to content

Commit

Permalink
refactor: add generate preserved routes utility
Browse files Browse the repository at this point in the history
  • Loading branch information
oedotme committed Sep 22, 2022
1 parent a672669 commit 017fb73
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 11 deletions.
7 changes: 2 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { Fragment } from 'react'
import { LoaderFn, Outlet, ReactLocation, Route, Router, RouterProps } from '@tanstack/react-location'

import { patterns } from './utils'
import { generatePreservedRoutes } from './utils'

type Element = () => JSX.Element
type Module = { default: Element; Loader: LoaderFn; Pending: Element; Failure: Element }

const PRESERVED = import.meta.glob<Module>('/src/pages/(_app|404).{jsx,tsx}', { eager: true })
const ROUTES = import.meta.glob<Module>(['/src/pages/**/[\\w[]*.{jsx,tsx}', '!**/(_app|404).*'])

const preservedRoutes: Partial<Record<string, () => JSX.Element>> = Object.keys(PRESERVED).reduce((routes, key) => {
const path = key.replace(...patterns.clean)
return { ...routes, [path]: PRESERVED[key]?.default }
}, {})
const preservedRoutes = generatePreservedRoutes<Element>(PRESERVED)

const regularRoutes = Object.keys(ROUTES).reduce<Route[]>((routes, key) => {
const module = ROUTES[key]
Expand Down
6 changes: 0 additions & 6 deletions src/utils.ts

This file was deleted.

15 changes: 15 additions & 0 deletions src/utils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const patterns = {
clean: [/\/src\/pages\/|\.(jsx|tsx)$/g, ''],
catch: [/\[\.{3}.+\]/, '*'],
param: [/\[([^\]]+)\]/g, ':$1'],
index: [/index|\./g, '/'],
} as const

type PreservedKey = '_app' | '404'

export const generatePreservedRoutes = <T,>(routes: Record<string, T | any>): Partial<Record<PreservedKey, T>> => {
return Object.keys(routes).reduce((result, current) => {
const path = current.replace(...patterns.clean)
return { ...result, [path]: routes[current]?.default }
}, {})
}

0 comments on commit 017fb73

Please sign in to comment.