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

Match.tsx

326 lines9.9 KB

1'use client'
2​
3import * as React from 'react'
4import { useSelector } from '@tanstack/react-store'
5import { isNotFound, rootRouteId } from '@tanstack/router-core'
6import { isServer } from '@tanstack/router-core/isServer'
7import { CatchBoundary, ErrorComponent } from './CatchBoundary'
8import { useRouter } from './useRouter'
9import { CatchNotFound } from './not-found'
10import { matchContext } from './matchContext'
11import { SafeFragment } from './SafeFragment'
12import { renderRouteNotFound } from './renderRouteNotFound'
13import { ScrollRestoration } from './scroll-restoration'
14import { ClientOnly } from './ClientOnly'
15import {
16 nonRouteComponentContext,
17 wrapInNonRouteComponentContext,
18} from './nonRouteComponentContext'
19import type {
20 AnyRoute,
21 AnyRouteMatch,
22 RootRouteOptions,
23} from '@tanstack/router-core'
24​
25export function renderPending(
26 router: ReturnType<typeof useRouter>,
27 route?: AnyRoute,
28) {
29 const PendingComponent =
30 route?.options.pendingComponent ?? router.options.defaultPendingComponent
31 if (!PendingComponent) {
32 return null
33 }
34​
35 const pendingElement = <PendingComponent />
36 return process.env.NODE_ENV !== 'production'
37 ? wrapInNonRouteComponentContext(pendingElement, 'pendingComponent')
38 : pendingElement
40​
41type OutletMatchSelection = [
42 parentGlobalNotFound: boolean,
43 parentNotFoundError: unknown,
45​
46const outletMatchSelectionEqual = (
47 a: OutletMatchSelection,
48 b: OutletMatchSelection,
49) => a[0] === b[0] && a[1] === b[1]
50​
51const canWrapInSuspense = (
52 router: ReturnType<typeof useRouter>,
53 route: AnyRoute,
54 ssr: AnyRouteMatch['ssr'],
55) =>
56 !route.isRoot ||
57 (route.options as RootRouteOptions).shellComponent ||
58 route.options.wrapInSuspense ||
59 ssr === false ||
60 ssr === 'data-only' ||
61 !((isServer ?? router.isServer) || router.ssr)
62​
63export const Match = React.memo(function MatchImpl({
64 routeId,
65}: {
66 routeId: string
67}) {
68 const router = useRouter()
69​
70 if (isServer ?? router.isServer) {
71 const match = router.stores.byRoute.get(routeId)!.get()!
72 return <MatchView router={router} match={match} />
73 }
74​
75 const matchStore = router.stores.getMatchStore(routeId)
76 // eslint-disable-next-line react-hooks/rules-of-hooks
77 const match = useSelector(matchStore)
78 return <MatchView router={router} match={match!} />
79})
80​
81function MatchView({
82 router,
83 match,
84}: {
85 router: ReturnType<typeof useRouter>
86 match: AnyRouteMatch
87}) {
88 const route: AnyRoute = router.routesById[match.routeId]
89​
90 const pendingElement = renderPending(router, route)
91​
92 const routeErrorComponent =
93 route.options.errorComponent ?? router.options.defaultErrorComponent
94​
95 const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch
96​
97 const routeNotFoundComponent = route.isRoot
98 ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component
99 (route.options.notFoundComponent ??
100 router.options.notFoundRoute?.options.component)
101 : route.options.notFoundComponent
102​
103 const resolvedNoSsr = match.ssr === false || match.ssr === 'data-only'
104 // A root component may render the document itself. Only place its Suspense
105 // boundary in pure CSR, inside an explicit shell, or when explicitly opted in.
106 const ResolvedSuspenseBoundary =
107 canWrapInSuspense(router, route, match.ssr) &&
108 (route.options.wrapInSuspense ??
109 pendingElement ??
110 ((route.options.errorComponent as any)?.preload || resolvedNoSsr))
111 ? React.Suspense
112 : SafeFragment
113​
114 const ResolvedCatchBoundary = routeErrorComponent
115 ? CatchBoundary
116 : SafeFragment
117​
118 const ResolvedNotFoundBoundary = routeNotFoundComponent
119 ? CatchNotFound
120 : SafeFragment
121​
122 const ShellComponent = route.isRoot
123 ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)
124 : SafeFragment
125 return (
126 <ShellComponent>
127 <matchContext.Provider value={match.routeId}>
128 <ResolvedSuspenseBoundary fallback={pendingElement}>
129 <ResolvedCatchBoundary
130 getResetKey={() => match}
131 errorComponent={routeErrorComponent as any}
132 onCatch={(error, errorInfo) => {
133 // Forward not found errors (we don't want to show the error component for these)
134 if (isNotFound(error)) {
135 error.routeId ??= match.routeId
136 throw error
137 }
138 if (process.env.NODE_ENV !== 'production') {
139 console.warn(`Warning: Error in route match: ${match.id}`)
140 }
141 routeOnCatch?.(error, errorInfo)
142 }}
143 >
144 <ResolvedNotFoundBoundary
145 fallback={(error) => {
146 error.routeId ??= match.routeId
147​
148 if (error.routeId !== match.routeId) {
149 throw error
150 }
151​
152 const notFoundElement = React.createElement(
153 routeNotFoundComponent!,
154 error as any,
155 )
156 return process.env.NODE_ENV !== 'production'
157 ? wrapInNonRouteComponentContext(
158 notFoundElement,
159 'notFoundComponent',
160 )
161 : notFoundElement
162 }}
163 >
164 {resolvedNoSsr ? (
165 <ClientOnly fallback={pendingElement}>
166 <MatchInner match={match} />
167 </ClientOnly>
168 ) : (
169 <MatchInner match={match} />
170 )}
171 </ResolvedNotFoundBoundary>
172 </ResolvedCatchBoundary>
173 </ResolvedSuspenseBoundary>
174 </matchContext.Provider>
175 {(isServer ?? router.isServer) &&
176 route.parentRoute?.id === rootRouteId &&
177 router.options.scrollRestoration ? (
178 <ScrollRestoration />
179 ) : null}
180 </ShellComponent>
181 )
183​
184export const MatchInner = React.memo(function MatchInnerImpl({
185 match,
186}: {
187 match: AnyRouteMatch
188}): any {
189 const router = useRouter()
190 const routeId = match.routeId
191 const route = router.routesById[routeId] as AnyRoute
192 const key = React.useMemo(() => {
193 const remountFn =
194 route.options.remountDeps ?? router.options.defaultRemountDeps
195 const remountDeps = remountFn?.({
196 routeId,
197 loaderDeps: match.loaderDeps,
198 params: match._strictParams,
199 search: match._strictSearch,
200 })
201 return remountDeps ? JSON.stringify(remountDeps) : undefined
202 }, [
203 routeId,
204 match.loaderDeps,
205 match._strictParams,
206 match._strictSearch,
207 route.options.remountDeps,
208 router.options.defaultRemountDeps,
209 ])
210 const out = React.useMemo(() => {
211 const Comp = route.options.component ?? router.options.defaultComponent
212 return Comp ? <Comp key={key} /> : <Outlet />
213 }, [key, route.options.component, router.options.defaultComponent])
214​
215 if (match.status === 'pending') {
216 if (router.ssr && !canWrapInSuspense(router, route, match.ssr)) {
217 // Replacing an SSR document root with pending UI would remove <html>.
218 // Hydrated matches retain their prior data, so keep rendering it.
219 return out
220 }
221 if (router._tx) {
222 throw router._tx[5]
223 }
224 return renderPending(router, route)
225 }
226​
227 if (match.status === 'notFound') {
228 return renderRouteNotFound(router, route, match.error)
229 }
230​
231 if (match.status === 'error') {
232 if (isServer ?? router.isServer) {
233 const RouteErrorComponent =
234 (route.options.errorComponent ??
235 router.options.defaultErrorComponent) ||
236 ErrorComponent
237 const errorElement = (
238 <RouteErrorComponent
239 error={match.error}
240 reset={undefined as any}
241 info={{
242 componentStack: '',
243 }}
244 />
245 )
246 return process.env.NODE_ENV !== 'production'
247 ? wrapInNonRouteComponentContext(errorElement, 'errorComponent')
248 : errorElement
249 }
250 throw match.error
251 }
252​
253 return out
254})
255​
256/**
257 * Render the next child match in the route tree. Typically used inside
258 * a route component to render nested routes.
259 *
260 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent
261 */
262export const Outlet = React.memo(function OutletImpl() {
263 if (process.env.NODE_ENV !== 'production') {
264 // eslint-disable-next-line react-hooks/rules-of-hooks
265 const nonRouteComponent = React.useContext(nonRouteComponentContext!)
266 if (nonRouteComponent) {
267 console.warn(
268 `Warning: An <Outlet /> was rendered inside a ${nonRouteComponent}. <Outlet /> should only be rendered inside a route component.`,
269 )
270 }
271 }
272​
273 const router = useRouter()
274 const routeId = React.useContext(matchContext)!
275​
276 let parentGlobalNotFound: boolean
277 let parentNotFoundError: unknown
278 let childRouteId: string | undefined
279​
280 if (isServer ?? router.isServer) {
281 const matches = router.stores.matches.get()
282 const parentIndex = matches.findIndex((match) => match.routeId === routeId)
283 const parentMatch = matches[parentIndex]!
284 parentGlobalNotFound = !!parentMatch._notFound
285 parentNotFoundError = parentMatch.error
286 childRouteId = matches[parentIndex + 1]?.routeId
287 } else {
288 const parentMatchStore = router.stores.getMatchStore(routeId)
289​
290 // eslint-disable-next-line react-hooks/rules-of-hooks
291 ;[parentGlobalNotFound, parentNotFoundError] = useSelector(
292 parentMatchStore,
293 (match): OutletMatchSelection => [!!match!._notFound, match!.error],
294 { compare: outletMatchSelectionEqual },
295 )
296​
297 // eslint-disable-next-line react-hooks/rules-of-hooks
298 childRouteId = useSelector(router.stores.ids, (ids) => {
299 return ids[ids.indexOf(routeId) + 1]
300 })
301 }
302​
303 if (parentGlobalNotFound) {
304 return renderRouteNotFound(
305 router,
306 router.routesById[routeId],
307 parentNotFoundError,
308 )
309 }
310​
311 if (!childRouteId) {
312 return null
313 }
314​
315 const nextMatch = <Match routeId={childRouteId} />
316​
317 if (routeId === rootRouteId) {
318 return (
319 <React.Suspense fallback={renderPending(router)}>
320 {nextMatch}
321 </React.Suspense>
322 )
323 }
324​
325 return nextMatch
326})