Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

Match.tsx

356 lines11.3 KB

1import * as Solid from 'solid-js'
2import { rootRouteId } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { Dynamic } from 'solid-js/web'
5import { CatchBoundary, ErrorComponent } from './CatchBoundary'
6import { useRouter } from './useRouter'
7import { CatchNotFound, getNotFound } from './not-found'
8import { nearestMatchContext } from './matchContext'
9import { SafeFragment } from './SafeFragment'
10import { renderRouteNotFound } from './renderRouteNotFound'
11import { ScrollRestoration } from './scroll-restoration'
12import { ClientOnly } from './ClientOnly'
13import {
14 nonRouteComponentContext,
15 renderInNonRouteComponentContext,
16} from './nonRouteComponentContext'
17import type {
18 AnyRoute,
19 AnyRouter,
20 RootRouteOptions,
21} from '@tanstack/router-core'
22​
23// Keep the client constant undefined so the server-only script can be dropped.
24const renderScrollRestoration =
25 isServer === false
26 ? undefined
27 : (router: AnyRouter, route: AnyRoute) =>
28 (isServer ?? router.isServer) &&
29 route.parentRoute?.id === rootRouteId &&
30 router.options.scrollRestoration ? (
31 <ScrollRestoration />
32 ) : null
33​
34export const Match = (props: { routeId: string }) => {
35 const router = useRouter()
36​
37 const currentMatch = Solid.createMemo(
38 () => router.stores.byRoute.get(props.routeId)!.get()!,
39 )
40​
41 const nearestMatch = [() => props.routeId, currentMatch] as const
42​
43 const route: AnyRoute = router.routesById[props.routeId]
44​
45 // Lazy route option mutations become observable with the next client match
46 // publication. Server stores are non-reactive and options load before render.
47 const routeOptions =
48 (isServer ?? router.isServer)
49 ? () => route.options
50 : () => {
51 currentMatch()
52 return route.options
53 }
54​
55 const resolvePendingComponent = () =>
56 routeOptions().pendingComponent ?? router.options.defaultPendingComponent
57​
58 const routeErrorComponent = () =>
59 routeOptions().errorComponent ?? router.options.defaultErrorComponent
60​
61 const routeNotFoundComponent = () =>
62 route.isRoot
63 ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component
64 (routeOptions().notFoundComponent ??
65 router.options.notFoundRoute?.options.component)
66 : routeOptions().notFoundComponent
67​
68 const resolvedNoSsr = () =>
69 currentMatch().ssr === false || currentMatch().ssr === 'data-only'
70​
71 const shouldSkipSuspenseFallback = () =>
72 (isServer ?? router.isServer)
73 ? resolvedNoSsr()
74 : currentMatch().ssr === 'data-only'
75​
76 const ShellComponent = route.isRoot
77 ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)
78 : SafeFragment
79​
80 const MatchContent = () => (
81 <Solid.Show
82 when={currentMatch().status !== 'pending'}
83 fallback={(() => {
84 if (process.env.NODE_ENV !== 'production') {
85 return renderInNonRouteComponentContext(
86 () => <Dynamic component={resolvePendingComponent()} />,
87 'pendingComponent',
88 )
89 }
90 return <Dynamic component={resolvePendingComponent()} />
91 })()}
92 >
93 <MatchInner />
94 </Solid.Show>
95 )
96​
97 return (
98 <ShellComponent>
99 <nearestMatchContext.Provider value={nearestMatch}>
100 <Solid.Suspense
101 fallback={(() => {
102 // Data-only SSR renders the inner fallback on the server, so
103 // avoid adding an extra suspense fallback on the client.
104 if (shouldSkipSuspenseFallback()) {
105 return undefined
106 }
107 if (process.env.NODE_ENV !== 'production') {
108 return renderInNonRouteComponentContext(
109 () => <Dynamic component={resolvePendingComponent()} />,
110 'pendingComponent',
111 )
112 }
113 return <Dynamic component={resolvePendingComponent()} />
114 })()}
115 >
116 <Dynamic
117 component={routeErrorComponent() ? CatchBoundary : SafeFragment}
118 getResetKey={currentMatch}
119 errorComponent={routeErrorComponent() as any}
120 onCatch={(error: Error) => {
121 // Forward not found errors (we don't want to show the error component for these)
122 const notFoundError = getNotFound(error)
123 if (notFoundError) {
124 notFoundError.routeId ??= currentMatch().routeId
125 throw notFoundError
126 }
127 if (process.env.NODE_ENV !== 'production') {
128 console.warn(
129 `Warning: Error in route match: ${currentMatch().routeId}`,
130 )
131 }
132 ;(route.options.onCatch ?? router.options.defaultOnCatch)?.(error)
133 }}
134 >
135 <Dynamic
136 component={
137 routeNotFoundComponent() ? CatchNotFound : SafeFragment
138 }
139 fallback={(error: any) => {
140 const notFoundError = getNotFound(error) ?? error
141​
142 notFoundError.routeId ??= currentMatch().routeId
143​
144 if (notFoundError.routeId !== currentMatch().routeId) {
145 throw notFoundError
146 }
147​
148 return process.env.NODE_ENV !== 'production' ? (
149 renderInNonRouteComponentContext(
150 () => (
151 <Dynamic
152 component={routeNotFoundComponent()}
153 {...notFoundError}
154 />
155 ),
156 'notFoundComponent',
157 )
158 ) : (
159 <Dynamic
160 component={routeNotFoundComponent()}
161 {...notFoundError}
162 />
163 )
164 }}
165 >
166 <Solid.Switch>
167 <Solid.Match when={resolvedNoSsr()}>
168 <ClientOnly
169 fallback={(() => {
170 if (process.env.NODE_ENV !== 'production') {
171 return renderInNonRouteComponentContext(
172 () => (
173 <Dynamic component={resolvePendingComponent()} />
174 ),
175 'pendingComponent',
176 )
177 }
178 return <Dynamic component={resolvePendingComponent()} />
179 })()}
180 >
181 <MatchContent />
182 </ClientOnly>
183 </Solid.Match>
184 <Solid.Match when={!resolvedNoSsr()}>
185 <MatchContent />
186 </Solid.Match>
187 </Solid.Switch>
188 </Dynamic>
189 </Dynamic>
190 </Solid.Suspense>
191 </nearestMatchContext.Provider>
192​
193 {renderScrollRestoration?.(router, route)}
194 </ShellComponent>
195 )
197​
198export const MatchInner = (): any => {
199 const router = useRouter()
200 const nearestMatch = Solid.useContext(nearestMatchContext)
201 const match = nearestMatch[1 /* match */]
202 const routeId = nearestMatch[0 /* route id */]
203 const route = router.routesById[routeId()!]!
204 const currentMatch = () => match()!
205​
206 const componentKey = () => {
207 const current = currentMatch()
208 const remount =
209 route.options.remountDeps ?? router.options.defaultRemountDeps
210 if (!remount) {
211 return routeId()
212 }
213 const deps = remount({
214 routeId: routeId()!,
215 loaderDeps: current.loaderDeps,
216 params: current._strictParams,
217 search: current._strictSearch,
218 })
219 return JSON.stringify(deps) ?? routeId()
220 }
221​
222 const out = () => {
223 const Comp = route.options.component ?? router.options.defaultComponent
224 if (Comp) {
225 return <Comp />
226 }
227 return <Outlet />
228 }
229​
230 const keyedOut = () => (
231 <Solid.Show when={componentKey()} keyed>
232 {(_key) => out()}
233 </Solid.Show>
234 )
235​
236 return (
237 <Solid.Switch>
238 <Solid.Match when={currentMatch().status === 'notFound'}>
239 {(_) => renderRouteNotFound(router, route, currentMatch().error)}
240 </Solid.Match>
241 <Solid.Match when={currentMatch().status === 'error'}>
242 {(_) => {
243 if (isServer ?? router.isServer) {
244 // Match Solid.ErrorBoundary's normalization without changing router state.
245 const thrown = currentMatch().error
246 const error =
247 thrown instanceof Error
248 ? thrown
249 : new Error(
250 typeof thrown === 'string' ? thrown : 'Unknown error',
251 {
252 cause: thrown,
253 },
254 )
255 const RouteErrorComponent =
256 (route.options.errorComponent ??
257 router.options.defaultErrorComponent) ||
258 ErrorComponent
259​
260 return process.env.NODE_ENV !== 'production' ? (
261 renderInNonRouteComponentContext(
262 () => (
263 <RouteErrorComponent
264 error={error}
265 info={{
266 componentStack: '',
267 }}
268 />
269 ),
270 'errorComponent',
271 )
272 ) : (
273 <RouteErrorComponent
274 error={error}
275 info={{
276 componentStack: '',
277 }}
278 />
279 )
280 }
281​
282 throw currentMatch().error
283 }}
284 </Solid.Match>
285 <Solid.Match when={currentMatch().status === 'success'}>
286 {keyedOut()}
287 </Solid.Match>
288 </Solid.Switch>
289 )
291​
292export const Outlet = () => {
293 if (process.env.NODE_ENV !== 'production') {
294 const nonRouteComponent = Solid.useContext(nonRouteComponentContext!)
295 if (nonRouteComponent) {
296 console.warn(
297 `Warning: An <Outlet /> was rendered inside a ${nonRouteComponent}. <Outlet /> should only be rendered inside a route component.`,
298 )
299 }
300 }
301​
302 const router = useRouter()
303 const nearestParentMatch = Solid.useContext(nearestMatchContext)
304 const parentMatch = nearestParentMatch[1 /* match */]
305 const routeId = nearestParentMatch[0 /* route id */]
306 const route = router.routesById[routeId()!]!
307​
308 const childRouteId = () => {
309 if (parentMatch()!._notFound) {
310 return
311 }
312 const ids = router.stores.ids.get()
313 return ids[ids.indexOf(routeId()!) + 1]
314 }
315​
316 return (
317 <Solid.Show
318 when={childRouteId()}
319 keyed
320 fallback={
321 parentMatch()!._notFound
322 ? renderRouteNotFound(router, route, parentMatch()!.error)
323 : undefined
324 }
325 >
326 {(_routeKey: string) => {
327 return (
328 <Solid.Show
329 when={routeId() === rootRouteId}
330 fallback={<Match routeId={childRouteId()!} />}
331 >
332 <Solid.Suspense
333 fallback={(() => {
334 if (process.env.NODE_ENV !== 'production') {
335 return renderInNonRouteComponentContext(
336 () => (
337 <Dynamic
338 component={router.options.defaultPendingComponent}
339 />
340 ),
341 'pendingComponent',
342 )
343 }
344 return (
345 <Dynamic component={router.options.defaultPendingComponent} />
346 )
347 })()}
348 >
349 <Match routeId={childRouteId()!} />
350 </Solid.Suspense>
351 </Solid.Show>
352 )
353 }}
354 </Solid.Show>
355 )