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

Match.tsx

392 lines12.2 KB

1import * as Solid from 'solid-js'
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 { Dynamic } from 'solid-js/web'
12import { CatchBoundary, ErrorComponent } from './CatchBoundary'
13import { useRouterState } from './useRouterState'
14import { useRouter } from './useRouter'
15import { CatchNotFound } from './not-found'
16import { matchContext } from './matchContext'
17import { SafeFragment } from './SafeFragment'
18import { renderRouteNotFound } from './renderRouteNotFound'
19import { ScrollRestoration } from './scroll-restoration'
20import type { AnyRoute, RootRouteOptions } from '@tanstack/router-core'
21​
22export const Match = (props: { matchId: string }) => {
23 const router = useRouter()
24 const matchState = useRouterState({
25 select: (s) => {
26 const match = s.matches.find((d) => d.id === props.matchId)
27​
28 invariant(
29 match,
30 `Could not find match for matchId "${props.matchId}". Please file an issue!`,
31 )
32 return {
33 routeId: match.routeId,
34 ssr: match.ssr,
35 _displayPending: match._displayPending,
36 }
37 },
38 })
39​
40 const route: () => AnyRoute = () => router.routesById[matchState().routeId]
41​
42 const PendingComponent = () =>
43 route().options.pendingComponent ?? router.options.defaultPendingComponent
44​
45 const routeErrorComponent = () =>
46 route().options.errorComponent ?? router.options.defaultErrorComponent
47​
48 const routeOnCatch = () =>
49 route().options.onCatch ?? router.options.defaultOnCatch
50​
51 const routeNotFoundComponent = () =>
52 route().isRoot
53 ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
54 (route().options.notFoundComponent ??
55 router.options.notFoundRoute?.options.component)
56 : route().options.notFoundComponent
57​
58 const resolvedNoSsr =
59 matchState().ssr === false || matchState().ssr === 'data-only'
60​
61 const ResolvedSuspenseBoundary = () =>
62 // If we're on the root route, allow forcefully wrapping in suspense
63 (!route().isRoot ||
64 route().options.wrapInSuspense ||
65 resolvedNoSsr ||
66 matchState()._displayPending) &&
67 (route().options.wrapInSuspense ??
68 PendingComponent() ??
69 ((route().options.errorComponent as any)?.preload || resolvedNoSsr))
70 ? Solid.Suspense
71 : SafeFragment
72​
73 const ResolvedCatchBoundary = () =>
74 routeErrorComponent() ? CatchBoundary : SafeFragment
75​
76 const ResolvedNotFoundBoundary = () =>
77 routeNotFoundComponent() ? CatchNotFound : SafeFragment
78​
79 const resetKey = useRouterState({
80 select: (s) => s.loadedAt,
81 })
82​
83 const parentRouteId = useRouterState({
84 select: (s) => {
85 const index = s.matches.findIndex((d) => d.id === props.matchId)
86 return s.matches[index - 1]?.routeId as string
87 },
88 })
89​
90 const ShellComponent = route().isRoot
91 ? ((route().options as RootRouteOptions).shellComponent ?? SafeFragment)
92 : SafeFragment
93​
94 return (
95 <ShellComponent>
96 <matchContext.Provider value={() => props.matchId}>
97 <Dynamic
98 component={ResolvedSuspenseBoundary()}
99 fallback={
100 // Don't show fallback on server when using no-ssr mode to avoid hydration mismatch
101 router.isServer || resolvedNoSsr ? undefined : (
102 <Dynamic component={PendingComponent()} />
103 )
104 }
105 >
106 <Dynamic
107 component={ResolvedCatchBoundary()}
108 getResetKey={() => resetKey()}
109 errorComponent={routeErrorComponent() || ErrorComponent}
110 onCatch={(error: Error) => {
111 // Forward not found errors (we don't want to show the error component for these)
112 if (isNotFound(error)) throw error
113 warning(false, `Error in route match: ${props.matchId}`)
114 routeOnCatch()?.(error)
115 }}
116 >
117 <Dynamic
118 component={ResolvedNotFoundBoundary()}
119 fallback={(error: any) => {
120 // If the current not found handler doesn't exist or it has a
121 // route ID which doesn't match the current route, rethrow the error
122 if (
123 !routeNotFoundComponent() ||
124 (error.routeId && error.routeId !== matchState().routeId) ||
125 (!error.routeId && !route().isRoot)
126 )
127 throw error
128​
129 return (
130 <Dynamic component={routeNotFoundComponent()} {...error} />
131 )
132 }}
133 >
134 <Solid.Switch>
135 <Solid.Match when={resolvedNoSsr}>
136 <Solid.Show
137 when={!router.isServer}
138 fallback={<Dynamic component={PendingComponent()} />}
139 >
140 <MatchInner matchId={props.matchId} />
141 </Solid.Show>
142 </Solid.Match>
143 <Solid.Match when={!resolvedNoSsr}>
144 <MatchInner matchId={props.matchId} />
145 </Solid.Match>
146 </Solid.Switch>
147 </Dynamic>
148 </Dynamic>
149 </Dynamic>
150 </matchContext.Provider>
151​
152 {parentRouteId() === rootRouteId ? (
153 <>
154 <OnRendered />
155 <ScrollRestoration />
156 </>
157 ) : null}
158 </ShellComponent>
159 )
161​
162// On Rendered can't happen above the root layout because it actually
163// renders a dummy dom element to track the rendered state of the app.
164// We render a script tag with a key that changes based on the current
165// location state.__TSR_key. Also, because it's below the root layout, it
166// allows us to fire onRendered events even after a hydration mismatch
167// error that occurred above the root layout (like bad head/link tags,
168// which is common).
169function OnRendered() {
170 const router = useRouter()
171​
172 const location = useRouterState({
173 select: (s) => {
174 return s.resolvedLocation?.state.__TSR_key
175 },
176 })
177 Solid.createEffect(
178 Solid.on([location], () => {
179 router.emit({
180 type: 'onRendered',
181 ...getLocationChangeInfo(router.state),
182 })
183 }),
184 )
185 return null
187​
188export const MatchInner = (props: { matchId: string }): any => {
189 const router = useRouter()
190​
191 const matchState = useRouterState({
192 select: (s) => {
193 const match = s.matches.find((d) => d.id === props.matchId)!
194 const routeId = match.routeId as string
195​
196 const remountFn =
197 (router.routesById[routeId] as AnyRoute).options.remountDeps ??
198 router.options.defaultRemountDeps
199 const remountDeps = remountFn?.({
200 routeId,
201 loaderDeps: match.loaderDeps,
202 params: match._strictParams,
203 search: match._strictSearch,
204 })
205 const key = remountDeps ? JSON.stringify(remountDeps) : undefined
206​
207 return {
208 key,
209 routeId,
210 match: {
211 id: match.id,
212 status: match.status,
213 error: match.error,
214 _forcePending: match._forcePending,
215 _displayPending: match._displayPending,
216 },
217 }
218 },
219 })
220​
221 const route = () => router.routesById[matchState().routeId]!
222​
223 const match = () => matchState().match
224​
225 const out = () => {
226 const Comp = route().options.component ?? router.options.defaultComponent
227 if (Comp) {
228 const key = matchState().key ?? matchState().match.id
229 return (
230 <Solid.Show when={key} keyed>
231 <Comp />
232 </Solid.Show>
233 )
234 }
235 return <Outlet />
236 }
237​
238 return (
239 <Solid.Switch>
240 <Solid.Match when={match()._displayPending}>
241 {(_) => {
242 const [displayPendingResult] = Solid.createResource(
243 () =>
244 router.getMatch(match().id)?._nonReactive.displayPendingPromise,
245 )
246​
247 return <>{displayPendingResult()}</>
248 }}
249 </Solid.Match>
250 <Solid.Match when={match()._forcePending}>
251 {(_) => {
252 const [minPendingResult] = Solid.createResource(
253 () => router.getMatch(match().id)?._nonReactive.minPendingPromise,
254 )
255​
256 return <>{minPendingResult()}</>
257 }}
258 </Solid.Match>
259 <Solid.Match when={match().status === 'pending'}>
260 {(_) => {
261 const pendingMinMs =
262 route().options.pendingMinMs ?? router.options.defaultPendingMinMs
263​
264 if (pendingMinMs) {
265 const routerMatch = router.getMatch(match().id)
266 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
267 // Create a promise that will resolve after the minPendingMs
268 if (!router.isServer) {
269 const minPendingPromise = createControlledPromise<void>()
270​
271 routerMatch._nonReactive.minPendingPromise = minPendingPromise
272​
273 setTimeout(() => {
274 minPendingPromise.resolve()
275 // We've handled the minPendingPromise, so we can delete it
276 routerMatch._nonReactive.minPendingPromise = undefined
277 }, pendingMinMs)
278 }
279 }
280 }
281​
282 const [loaderResult] = Solid.createResource(async () => {
283 await new Promise((r) => setTimeout(r, 0))
284 return router.getMatch(match().id)?._nonReactive.loadPromise
285 })
286​
287 return <>{loaderResult()}</>
288 }}
289 </Solid.Match>
290 <Solid.Match when={match().status === 'notFound'}>
291 {(_) => {
292 invariant(isNotFound(match().error), 'Expected a notFound error')
293​
294 return renderRouteNotFound(router, route(), match().error)
295 }}
296 </Solid.Match>
297 <Solid.Match when={match().status === 'redirected'}>
298 {(_) => {
299 invariant(isRedirect(match().error), 'Expected a redirect error')
300​
301 const [loaderResult] = Solid.createResource(async () => {
302 await new Promise((r) => setTimeout(r, 0))
303 return router.getMatch(match().id)?._nonReactive.loadPromise
304 })
305​
306 return <>{loaderResult()}</>
307 }}
308 </Solid.Match>
309 <Solid.Match when={match().status === 'error'}>
310 {(_) => {
311 if (router.isServer) {
312 const RouteErrorComponent =
313 (route().options.errorComponent ??
314 router.options.defaultErrorComponent) ||
315 ErrorComponent
316​
317 return (
318 <RouteErrorComponent
319 error={match().error}
320 info={{
321 componentStack: '',
322 }}
323 />
324 )
325 }
326​
327 throw match().error
328 }}
329 </Solid.Match>
330 <Solid.Match when={match().status === 'success'}>{out()}</Solid.Match>
331 </Solid.Switch>
332 )
334​
335export const Outlet = () => {
336 const router = useRouter()
337 const matchId = Solid.useContext(matchContext)
338 const routeId = useRouterState({
339 select: (s) => s.matches.find((d) => d.id === matchId())?.routeId as string,
340 })
341​
342 const route = () => router.routesById[routeId()]!
343​
344 const parentGlobalNotFound = useRouterState({
345 select: (s) => {
346 const matches = s.matches
347 const parentMatch = matches.find((d) => d.id === matchId())
348 invariant(
349 parentMatch,
350 `Could not find parent match for matchId "${matchId()}"`,
351 )
352 return parentMatch.globalNotFound
353 },
354 })
355​
356 const childMatchId = useRouterState({
357 select: (s) => {
358 const matches = s.matches
359 const index = matches.findIndex((d) => d.id === matchId())
360 const v = matches[index + 1]?.id
361 return v
362 },
363 })
364​
365 return (
366 <Solid.Switch>
367 <Solid.Match when={parentGlobalNotFound()}>
368 {renderRouteNotFound(router, route(), undefined)}
369 </Solid.Match>
370 <Solid.Match when={childMatchId()}>
371 {(matchId) => {
372 // const nextMatch = <Match matchId={matchId()} />
373​
374 return (
375 <Solid.Show
376 when={matchId() === rootRouteId}
377 fallback={<Match matchId={matchId()} />}
378 >
379 <Solid.Suspense
380 fallback={
381 <Dynamic component={router.options.defaultPendingComponent} />
382 }
383 >
384 <Match matchId={matchId()} />
385 </Solid.Suspense>
386 </Solid.Show>
387 )
388 }}
389 </Solid.Match>
390 </Solid.Switch>
391 )