1 import { ComponentType } from "react"
2 import { LoaderFunction, RouteObject } from "react-router-dom"
3 import { ErrorBoundary } from "../../components/utilities/error-boundary"
4 import { RouteExtension, RouteModule } from "../types"
5
6 /**
7 * Used to test if a route is a settings route.
8 */
9 const settingsRouteRegex = /^\/settings\//
10
11 export const getRouteExtensions = (
12 module: RouteModule,
13 type: "settings" | "core"
14 ) => {
15 return module.routes.filter((route) => {
16 if (type === "settings") {
17 return settingsRouteRegex.test(route.path)
18 }
19
20 return !settingsRouteRegex.test(route.path)
21 })
22 }
23
24 /**
25 * Creates a route object for a branch node in the route tree
26 * @param segment - The path segment for this branch
27 */
28 const createBranchRoute = (segment: string): RouteObject => ({
29 path: segment,
30 children: [],
31 })
32
33 /**
34 * Creates a route object for a leaf node with its component
35 * @param Component - The React component to render at this route
36 */
37 const createLeafRoute = (
38 Component: ComponentType,
39 loader?: LoaderFunction,
40 handle?: object,
41 path: string = ""
42 ): RouteObject => ({
43 path,
44 ErrorBoundary: ErrorBoundary,
45 async lazy() {
46 const result: {
47 Component: ComponentType
48 loader?: LoaderFunction
49 handle?: object
50 } = { Component }
51
52 if (loader) {
53 result.loader = loader
54 }
55
56 if (handle) {
57 result.handle = handle
58 }
59
60 return result
61 },
62 })
63
64 /**
65 * Creates a parallel route configuration
66 * @param path - The route path
67 * @param Component - The React component to render
68 */
69 const createParallelRoute = (
70 path: string,
71 Component: ComponentType,
72 loader?: LoaderFunction,
73 handle?: object
74 ) => ({
75 path,
76 async lazy() {
77 const result: {
78 Component: ComponentType
79 loader?: LoaderFunction
80 handle?: object
81 } = { Component }
82
83 if (loader) {
84 result.loader = loader
85 }
86
87 if (handle) {
88 result.handle = handle
89 }
90
91 return result
92 },
93 })
94
95 /**
96 * Processes parallel routes by cleaning their paths relative to the current path
97 * @param parallelRoutes - Array of parallel route extensions
98 * @param currentFullPath - The full path of the current route
99 */
100 const processParallelRoutes = (
101 parallelRoutes: RouteExtension[] | undefined,
102 currentFullPath: string
103 ): RouteObject[] | undefined => {
104 return parallelRoutes
105 ?.map(({ path, Component, loader, handle }) => {
106 const childPath = path?.replace(currentFullPath, "").replace(/^\/+/, "")
107 if (!childPath) {
108 return null
109 }
110 return createParallelRoute(childPath, Component, loader, handle)
111 })
112 .filter(Boolean) as RouteObject[]
113 }
114
115 /**
116 * Recursively builds the route tree by adding routes at the correct level
117 * @param pathSegments - Array of remaining path segments to process
118 * @param Component - The React component for the route
119 * @param currentLevel - Current level in the route tree
120 * @param parallelRoutes - Optional parallel routes to add
121 * @param fullPath - The full path up to the current level
122 */
123 const addRoute = (
124 pathSegments: string[],
125 Component: ComponentType,
126 currentLevel: RouteObject[],
127 loader?: LoaderFunction,
128 handle?: object,
129 parallelRoutes?: RouteExtension[],
130 fullPath?: string,
131 componentPath?: string
132 ) => {
133 if (!pathSegments.length) {
134 return
135 }
136
137 const [currentSegment, ...remainingSegments] = pathSegments
138 let route = currentLevel.find((r) => r.path === currentSegment)
139
140 if (!route) {
141 route = createBranchRoute(currentSegment)
142 currentLevel.push(route)
143 }
144
145 const currentFullPath = fullPath
146 ? `${fullPath}/${currentSegment}`
147 : currentSegment
148
149 const isComponentSegment = currentFullPath === componentPath
150
151 if (isComponentSegment || remainingSegments.length === 0) {
152 route.children ||= []
153
154 if (handle) {
155 route.handle = handle
156 }
157
158 if (loader) {
159 route.loader = loader
160 }
161
162 // Since splat segments must occur at the end of a route, react-router enforces the segment to be a leaf.
163 // Therefore we can't create a child leaf route with `path: ""` and must instead modify the route itself
164 if (currentSegment === "*?" || currentSegment === "*") {
165 const leaf = createLeafRoute(Component, loader, handle, currentSegment)
166 leaf.children = processParallelRoutes(parallelRoutes, currentFullPath)
167 Object.assign(route, leaf)
168 } else {
169 const leaf = createLeafRoute(Component, loader)
170 leaf.children = processParallelRoutes(parallelRoutes, currentFullPath)
171 route.children.push(leaf)
172 }
173 if (remainingSegments.length > 0) {
174 addRoute(
175 remainingSegments,
176 Component,
177 route.children,
178 undefined,
179 undefined,
180 undefined,
181 currentFullPath
182 )
183 }
184 } else {
185 route.children ||= []
186 addRoute(
187 remainingSegments,
188 Component,
189 route.children,
190 loader,
191 handle,
192 parallelRoutes,
193 currentFullPath,
194 componentPath
195 )
196 }
197 }
198
199 /**
200 * Creates a complete route map from route extensions
201 * @param routes - Array of route extensions to process
202 * @param ignore - Optional path prefix to ignore when processing routes
203 * @returns An array of route objects forming a route tree
204 */
205 export const createRouteMap = (
206 routes: RouteExtension[],
207 ignore?: string
208 ): RouteObject[] => {
209 const root: RouteObject[] = []
210
211 routes.forEach(({ path, Component, loader, handle, children }) => {
212 const cleanedPath = ignore
213 ? path.replace(ignore, "").replace(/^\/+/, "")
214 : path.replace(/^\/+/, "")
215 const pathSegments = cleanedPath.split("/").filter(Boolean)
216 addRoute(
217 pathSegments,
218 Component,
219 root,
220 loader,
221 handle,
222 children,
223 undefined,
224 path
225 )
226 })
227
228 return root
229 }