Open History to see the last commit
1import * as React from 'react'
2import invariant from 'tiny-invariant'
3import warning from 'tiny-warning'
4import {
5 createControlledPromise,
6 getLocationChangeInfo,
7 isNotFound,
8 isRedirect,
9 rootRouteId,
10} from '@tanstack/router-core'
11import { CatchBoundary, ErrorComponent } from './CatchBoundary'
12import { useRouterState } from './useRouterState'
13import { useRouter } from './useRouter'
14import { CatchNotFound } from './not-found'
15import { matchContext } from './matchContext'
16import { SafeFragment } from './SafeFragment'
17import { renderRouteNotFound } from './renderRouteNotFound'
18import { ScrollRestoration } from './scroll-restoration'
19import { ClientOnly } from './ClientOnly'
20import type {
21 AnyRoute,
22 ParsedLocation,
23 RootRouteOptions,
24} from '@tanstack/router-core'
25β
26export const Match = React.memo(function MatchImpl({
27 matchId,
28}: {
29 matchId: string
30}) {
31 const router = useRouter()
32 const matchState = useRouterState({
33 select: (s) => {
34 const match = s.matches.find((d) => d.id === matchId)
35 invariant(
36 match,
37 `Could not find match for matchId "${matchId}". Please file an issue!`,
38 )
39 return {
40 routeId: match.routeId,
41 ssr: match.ssr,
42 _displayPending: match._displayPending,
43 }
44 },
45 structuralSharing: true as any,
46 })
47β
48 const route: AnyRoute = router.routesById[matchState.routeId]
49β
50 const PendingComponent =
51 route.options.pendingComponent ?? router.options.defaultPendingComponent
52β
53 const pendingElement = PendingComponent ? <PendingComponent /> : null
54β
55 const routeErrorComponent =
56 route.options.errorComponent ?? router.options.defaultErrorComponent
57β
58 const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch
59β
60 const routeNotFoundComponent = route.isRoot
61 ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
62 (route.options.notFoundComponent ??
63 router.options.notFoundRoute?.options.component)
64 : route.options.notFoundComponent
65β
66 const resolvedNoSsr =
67 matchState.ssr === false || matchState.ssr === 'data-only'
68 const ResolvedSuspenseBoundary =
69 // If we're on the root route, allow forcefully wrapping in suspense
70 (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&
71 (route.options.wrapInSuspense ??
72 PendingComponent ??
73 ((route.options.errorComponent as any)?.preload || resolvedNoSsr))
74 ? React.Suspense
75 : SafeFragment
76β
77 const ResolvedCatchBoundary = routeErrorComponent
78 ? CatchBoundary
79 : SafeFragment
80β
81 const ResolvedNotFoundBoundary = routeNotFoundComponent
82 ? CatchNotFound
83 : SafeFragment
84β
85 const resetKey = useRouterState({
86 select: (s) => s.loadedAt,
87 })
88β
89 const parentRouteId = useRouterState({
90 select: (s) => {
91 const index = s.matches.findIndex((d) => d.id === matchId)
92 return s.matches[index - 1]?.routeId as string
93 },
94 })
95β
96 const ShellComponent = route.isRoot
97 ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)
98 : SafeFragment
99 return (
100 <ShellComponent>
101 <matchContext.Provider value={matchId}>
102 <ResolvedSuspenseBoundary fallback={pendingElement}>
103 <ResolvedCatchBoundary
104 getResetKey={() => resetKey}
105 errorComponent={routeErrorComponent || ErrorComponent}
106 onCatch={(error, errorInfo) => {
107 // Forward not found errors (we don't want to show the error component for these)
108 if (isNotFound(error)) throw error
109 warning(false, `Error in route match: ${matchId}`)
110 routeOnCatch?.(error, errorInfo)
111 }}
112 >
113 <ResolvedNotFoundBoundary
114 fallback={(error) => {
115 // If the current not found handler doesn't exist or it has a
116 // route ID which doesn't match the current route, rethrow the error
117 if (
118 !routeNotFoundComponent ||
119 (error.routeId && error.routeId !== matchState.routeId) ||
120 (!error.routeId && !route.isRoot)
121 )
122 throw error
123β
124 return React.createElement(routeNotFoundComponent, error as any)
125 }}
126 >
127 {resolvedNoSsr || matchState._displayPending ? (
128 <ClientOnly fallback={pendingElement}>
129 <MatchInner matchId={matchId} />
130 </ClientOnly>
131 ) : (
132 <MatchInner matchId={matchId} />
133 )}
134 </ResolvedNotFoundBoundary>
135 </ResolvedCatchBoundary>
136 </ResolvedSuspenseBoundary>
137 </matchContext.Provider>
138 {parentRouteId === rootRouteId && router.options.scrollRestoration ? (
139 <>
140 <OnRendered />
141 <ScrollRestoration />
142 </>
143 ) : null}
144 </ShellComponent>
145 )
146})
147β
148// On Rendered can't happen above the root layout because it actually
149// renders a dummy dom element to track the rendered state of the app.
150// We render a script tag with a key that changes based on the current
151// location state.__TSR_key. Also, because it's below the root layout, it
152// allows us to fire onRendered events even after a hydration mismatch
153// error that occurred above the root layout (like bad head/link tags,
154// which is common).
155function OnRendered() {
156 const router = useRouter()
157β
158 const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(
159 undefined,
160 )
161β
162 return (
163 <script
164 key={router.latestLocation.state.__TSR_key}
165 suppressHydrationWarning
166 ref={(el) => {
167 if (
168 el &&
169 (prevLocationRef.current === undefined ||
170 prevLocationRef.current.href !== router.latestLocation.href)
171 ) {
172 router.emit({
173 type: 'onRendered',
174 ...getLocationChangeInfo(router.state),
175 })
176 prevLocationRef.current = router.latestLocation
177 }
178 }}
179 />
180 )
181}
182β
183export const MatchInner = React.memo(function MatchInnerImpl({
184 matchId,
185}: {
186 matchId: string
187}): any {
188 const router = useRouter()
189β
190 const { match, key, routeId } = useRouterState({
191 select: (s) => {
192 const match = s.matches.find((d) => d.id === matchId)!
193 const routeId = match.routeId as string
194β
195 const remountFn =
196 (router.routesById[routeId] as AnyRoute).options.remountDeps ??
197 router.options.defaultRemountDeps
198 const remountDeps = remountFn?.({
199 routeId,
200 loaderDeps: match.loaderDeps,
201 params: match._strictParams,
202 search: match._strictSearch,
203 })
204 const key = remountDeps ? JSON.stringify(remountDeps) : undefined
205β
206 return {
207 key,
208 routeId,
209 match: {
210 id: match.id,
211 status: match.status,
212 error: match.error,
213 _forcePending: match._forcePending,
214 _displayPending: match._displayPending,
215 },
216 }
217 },
218 structuralSharing: true as any,
219 })
220β
221 const route = router.routesById[routeId] as AnyRoute
222β
223 const out = React.useMemo(() => {
224 const Comp = route.options.component ?? router.options.defaultComponent
225 if (Comp) {
226 return <Comp key={key} />
227 }
228 return <Outlet />
229 }, [key, route.options.component, router.options.defaultComponent])
230β
231 if (match._displayPending) {
232 throw router.getMatch(match.id)?._nonReactive.displayPendingPromise
233 }
234β
235 if (match._forcePending) {
236 throw router.getMatch(match.id)?._nonReactive.minPendingPromise
237 }
238β
239 // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts
240 if (match.status === 'pending') {
241 // We're pending, and if we have a minPendingMs, we need to wait for it
242 const pendingMinMs =
243 route.options.pendingMinMs ?? router.options.defaultPendingMinMs
244 if (pendingMinMs) {
245 const routerMatch = router.getMatch(match.id)
246 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
247 // Create a promise that will resolve after the minPendingMs
248 if (!router.isServer) {
249 const minPendingPromise = createControlledPromise<void>()
250β
251 routerMatch._nonReactive.minPendingPromise = minPendingPromise
252β
253 setTimeout(() => {
254 minPendingPromise.resolve()
255 // We've handled the minPendingPromise, so we can delete it
256 routerMatch._nonReactive.minPendingPromise = undefined
257 }, pendingMinMs)
258 }
259 }
260 }
261 throw router.getMatch(match.id)?._nonReactive.loadPromise
262 }
263β
264 if (match.status === 'notFound') {
265 invariant(isNotFound(match.error), 'Expected a notFound error')
266 return renderRouteNotFound(router, route, match.error)
267 }
268β
269 if (match.status === 'redirected') {
270 // Redirects should be handled by the router transition. If we happen to
271 // encounter a redirect here, it's a bug. Let's warn, but render nothing.
272 invariant(isRedirect(match.error), 'Expected a redirect error')
273β
274 // warning(
275 // false,
276 // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!',
277 // )
278 throw router.getMatch(match.id)?._nonReactive.loadPromise
279 }
280β
281 if (match.status === 'error') {
282 // If we're on the server, we need to use React's new and super
283 // wonky api for throwing errors from a server side render inside
284 // of a suspense boundary. This is the only way to get
285 // renderToPipeableStream to not hang indefinitely.
286 // We'll serialize the error and rethrow it on the client.
287 if (router.isServer) {
288 const RouteErrorComponent =
289 (route.options.errorComponent ??
290 router.options.defaultErrorComponent) ||
291 ErrorComponent
292 return (
293 <RouteErrorComponent
294 error={match.error as any}
295 reset={undefined as any}
296 info={{
297 componentStack: '',
298 }}
299 />
300 )
301 }
302β
303 throw match.error
304 }
305β
306 return out
307})
308β
309/**
310 * Render the next child match in the route tree. Typically used inside
311 * a route component to render nested routes.
312 *
313 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent
314 */
315export const Outlet = React.memo(function OutletImpl() {
316 const router = useRouter()
317 const matchId = React.useContext(matchContext)
318 const routeId = useRouterState({
319 select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,
320 })
321β
322 const route = router.routesById[routeId]!
323β
324 const parentGlobalNotFound = useRouterState({
325 select: (s) => {
326 const matches = s.matches
327 const parentMatch = matches.find((d) => d.id === matchId)
328 invariant(
329 parentMatch,
330 `Could not find parent match for matchId "${matchId}"`,
331 )
332 return parentMatch.globalNotFound
333 },
334 })
335β
336 const childMatchId = useRouterState({
337 select: (s) => {
338 const matches = s.matches
339 const index = matches.findIndex((d) => d.id === matchId)
340 return matches[index + 1]?.id
341 },
342 })
343β
344 const pendingElement = router.options.defaultPendingComponent ? (
345 <router.options.defaultPendingComponent />
346 ) : null
347β
348 if (parentGlobalNotFound) {
349 return renderRouteNotFound(router, route, undefined)
350 }
351β
352 if (!childMatchId) {
353 return null
354 }
355β
356 const nextMatch = <Match matchId={childMatchId} />
357β
358 if (matchId === rootRouteId) {
359 return (
360 <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>
361 )
362 }
363β
364 return nextMatch
365})