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

Match.tsx

387 lines12.0 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={<Dynamic component={PendingComponent()} />}
100 >
101 <Dynamic
102 component={ResolvedCatchBoundary()}
103 getResetKey={() => resetKey()}
104 errorComponent={routeErrorComponent() || ErrorComponent}
105 onCatch={(error: Error) => {
106 // Forward not found errors (we don't want to show the error component for these)
107 if (isNotFound(error)) throw error
108 warning(false, `Error in route match: ${props.matchId}`)
109 routeOnCatch()?.(error)
110 }}
111 >
112 <Dynamic
113 component={ResolvedNotFoundBoundary()}
114 fallback={(error: any) => {
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 (
125 <Dynamic component={routeNotFoundComponent()} {...error} />
126 )
127 }}
128 >
129 <Solid.Switch>
130 <Solid.Match when={resolvedNoSsr}>
131 <Solid.Show
132 when={!router.isServer}
133 fallback={<Dynamic component={PendingComponent()} />}
134 >
135 <MatchInner matchId={props.matchId} />
136 </Solid.Show>
137 </Solid.Match>
138 <Solid.Match when={!resolvedNoSsr}>
139 <MatchInner matchId={props.matchId} />
140 </Solid.Match>
141 </Solid.Switch>
142 </Dynamic>
143 </Dynamic>
144 </Dynamic>
145 </matchContext.Provider>
146​
147 {parentRouteId() === rootRouteId ? (
148 <>
149 <OnRendered />
150 <ScrollRestoration />
151 </>
152 ) : null}
153 </ShellComponent>
154 )
156​
157// On Rendered can't happen above the root layout because it actually
158// renders a dummy dom element to track the rendered state of the app.
159// We render a script tag with a key that changes based on the current
160// location state.__TSR_key. Also, because it's below the root layout, it
161// allows us to fire onRendered events even after a hydration mismatch
162// error that occurred above the root layout (like bad head/link tags,
163// which is common).
164function OnRendered() {
165 const router = useRouter()
166​
167 const location = useRouterState({
168 select: (s) => {
169 return s.resolvedLocation?.state.__TSR_key
170 },
171 })
172 Solid.createEffect(
173 Solid.on([location], () => {
174 router.emit({
175 type: 'onRendered',
176 ...getLocationChangeInfo(router.state),
177 })
178 }),
179 )
180 return null
182​
183export const MatchInner = (props: { matchId: string }): any => {
184 const router = useRouter()
185​
186 const matchState = useRouterState({
187 select: (s) => {
188 const match = s.matches.find((d) => d.id === props.matchId)!
189 const routeId = match.routeId as string
190​
191 const remountFn =
192 (router.routesById[routeId] as AnyRoute).options.remountDeps ??
193 router.options.defaultRemountDeps
194 const remountDeps = remountFn?.({
195 routeId,
196 loaderDeps: match.loaderDeps,
197 params: match._strictParams,
198 search: match._strictSearch,
199 })
200 const key = remountDeps ? JSON.stringify(remountDeps) : undefined
201​
202 return {
203 key,
204 routeId,
205 match: {
206 id: match.id,
207 status: match.status,
208 error: match.error,
209 _forcePending: match._forcePending,
210 _displayPending: match._displayPending,
211 },
212 }
213 },
214 })
215​
216 const route = () => router.routesById[matchState().routeId]!
217​
218 const match = () => matchState().match
219​
220 const out = () => {
221 const Comp = route().options.component ?? router.options.defaultComponent
222 if (Comp) {
223 const key = matchState().key ?? matchState().match.id
224 return (
225 <Solid.Show when={key} keyed>
226 <Comp />
227 </Solid.Show>
228 )
229 }
230 return <Outlet />
231 }
232​
233 return (
234 <Solid.Switch>
235 <Solid.Match when={match()._displayPending}>
236 {(_) => {
237 const [displayPendingResult] = Solid.createResource(
238 () =>
239 router.getMatch(match().id)?._nonReactive.displayPendingPromise,
240 )
241​
242 return <>{displayPendingResult()}</>
243 }}
244 </Solid.Match>
245 <Solid.Match when={match()._forcePending}>
246 {(_) => {
247 const [minPendingResult] = Solid.createResource(
248 () => router.getMatch(match().id)?._nonReactive.minPendingPromise,
249 )
250​
251 return <>{minPendingResult()}</>
252 }}
253 </Solid.Match>
254 <Solid.Match when={match().status === 'pending'}>
255 {(_) => {
256 const pendingMinMs =
257 route().options.pendingMinMs ?? router.options.defaultPendingMinMs
258​
259 if (pendingMinMs) {
260 const routerMatch = router.getMatch(match().id)
261 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
262 // Create a promise that will resolve after the minPendingMs
263 if (!router.isServer) {
264 const minPendingPromise = createControlledPromise<void>()
265​
266 routerMatch._nonReactive.minPendingPromise = minPendingPromise
267​
268 setTimeout(() => {
269 minPendingPromise.resolve()
270 // We've handled the minPendingPromise, so we can delete it
271 routerMatch._nonReactive.minPendingPromise = undefined
272 }, pendingMinMs)
273 }
274 }
275 }
276​
277 const [loaderResult] = Solid.createResource(async () => {
278 await new Promise((r) => setTimeout(r, 0))
279 return router.getMatch(match().id)?._nonReactive.loadPromise
280 })
281​
282 return <>{loaderResult()}</>
283 }}
284 </Solid.Match>
285 <Solid.Match when={match().status === 'notFound'}>
286 {(_) => {
287 invariant(isNotFound(match().error), 'Expected a notFound error')
288​
289 return renderRouteNotFound(router, route(), match().error)
290 }}
291 </Solid.Match>
292 <Solid.Match when={match().status === 'redirected'}>
293 {(_) => {
294 invariant(isRedirect(match().error), 'Expected a redirect error')
295​
296 const [loaderResult] = Solid.createResource(async () => {
297 await new Promise((r) => setTimeout(r, 0))
298 return router.getMatch(match().id)?._nonReactive.loadPromise
299 })
300​
301 return <>{loaderResult()}</>
302 }}
303 </Solid.Match>
304 <Solid.Match when={match().status === 'error'}>
305 {(_) => {
306 if (router.isServer) {
307 const RouteErrorComponent =
308 (route().options.errorComponent ??
309 router.options.defaultErrorComponent) ||
310 ErrorComponent
311​
312 return (
313 <RouteErrorComponent
314 error={match().error}
315 info={{
316 componentStack: '',
317 }}
318 />
319 )
320 }
321​
322 throw match().error
323 }}
324 </Solid.Match>
325 <Solid.Match when={match().status === 'success'}>{out()}</Solid.Match>
326 </Solid.Switch>
327 )
329​
330export const Outlet = () => {
331 const router = useRouter()
332 const matchId = Solid.useContext(matchContext)
333 const routeId = useRouterState({
334 select: (s) => s.matches.find((d) => d.id === matchId())?.routeId as string,
335 })
336​
337 const route = () => router.routesById[routeId()]!
338​
339 const parentGlobalNotFound = useRouterState({
340 select: (s) => {
341 const matches = s.matches
342 const parentMatch = matches.find((d) => d.id === matchId())
343 invariant(
344 parentMatch,
345 `Could not find parent match for matchId "${matchId()}"`,
346 )
347 return parentMatch.globalNotFound
348 },
349 })
350​
351 const childMatchId = useRouterState({
352 select: (s) => {
353 const matches = s.matches
354 const index = matches.findIndex((d) => d.id === matchId())
355 const v = matches[index + 1]?.id
356 return v
357 },
358 })
359​
360 return (
361 <Solid.Switch>
362 <Solid.Match when={parentGlobalNotFound()}>
363 {renderRouteNotFound(router, route(), undefined)}
364 </Solid.Match>
365 <Solid.Match when={childMatchId()}>
366 {(matchId) => {
367 // const nextMatch = <Match matchId={matchId()} />
368​
369 return (
370 <Solid.Show
371 when={matchId() === rootRouteId}
372 fallback={<Match matchId={matchId()} />}
373 >
374 <Solid.Suspense
375 fallback={
376 <Dynamic component={router.options.defaultPendingComponent} />
377 }
378 >
379 <Match matchId={matchId()} />
380 </Solid.Suspense>
381 </Solid.Show>
382 )
383 }}
384 </Solid.Match>
385 </Solid.Switch>
386 )