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

Match.tsx

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