Open History to see the last commit
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 // During navigation transitions, matches can be temporarily removed
29 // Return null to avoid errors - the component will handle this gracefully
30 if (!match) {
31 return null
32 }
33β
34 return {
35 routeId: match.routeId,
36 ssr: match.ssr,
37 _displayPending: match._displayPending,
38 }
39 },
40 })
41β
42 // If match doesn't exist yet, return null (component is being unmounted or not ready)
43 if (!matchState()) return null
44β
45 const route: () => AnyRoute = () => router.routesById[matchState()!.routeId]
46β
47 const resolvePendingComponent = () =>
48 route().options.pendingComponent ?? router.options.defaultPendingComponent
49β
50 const routeErrorComponent = () =>
51 route().options.errorComponent ?? router.options.defaultErrorComponent
52β
53 const routeOnCatch = () =>
54 route().options.onCatch ?? router.options.defaultOnCatch
55β
56 const routeNotFoundComponent = () =>
57 route().isRoot
58 ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
59 (route().options.notFoundComponent ??
60 router.options.notFoundRoute?.options.component)
61 : route().options.notFoundComponent
62β
63 const resolvedNoSsr =
64 matchState()!.ssr === false || matchState()!.ssr === 'data-only'
65β
66 const ResolvedSuspenseBoundary = () => Solid.Suspense
67β
68 const ResolvedCatchBoundary = () =>
69 routeErrorComponent() ? CatchBoundary : SafeFragment
70β
71 const ResolvedNotFoundBoundary = () =>
72 routeNotFoundComponent() ? CatchNotFound : SafeFragment
73β
74 const resetKey = useRouterState({
75 select: (s) => s.loadedAt,
76 })
77β
78 const parentRouteId = useRouterState({
79 select: (s) => {
80 const index = s.matches.findIndex((d) => d.id === props.matchId)
81 return s.matches[index - 1]?.routeId as string
82 },
83 })
84β
85 const ShellComponent = route().isRoot
86 ? ((route().options as RootRouteOptions).shellComponent ?? SafeFragment)
87 : SafeFragment
88β
89 return (
90 <ShellComponent>
91 <matchContext.Provider value={() => props.matchId}>
92 <Dynamic
93 component={ResolvedSuspenseBoundary()}
94 fallback={
95 // Don't show fallback on server when using no-ssr mode to avoid hydration mismatch
96 router.isServer || resolvedNoSsr ? undefined : (
97 <Dynamic component={resolvePendingComponent()} />
98 )
99 }
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={resolvePendingComponent()} />}
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 )
155}
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
181}
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β
190 // During navigation transitions, matches can be temporarily removed
191 if (!match) {
192 return null
193 }
194β
195 const routeId = match.routeId as string
196β
197 const remountFn =
198 (router.routesById[routeId] as AnyRoute).options.remountDeps ??
199 router.options.defaultRemountDeps
200 const remountDeps = remountFn?.({
201 routeId,
202 loaderDeps: match.loaderDeps,
203 params: match._strictParams,
204 search: match._strictSearch,
205 })
206 const key = remountDeps ? JSON.stringify(remountDeps) : undefined
207β
208 return {
209 key,
210 routeId,
211 match: {
212 id: match.id,
213 status: match.status,
214 error: match.error,
215 _forcePending: match._forcePending,
216 _displayPending: match._displayPending,
217 },
218 }
219 },
220 })
221β
222 if (!matchState()) return null
223β
224 const route = () => router.routesById[matchState()!.routeId]!
225β
226 const match = () => matchState()!.match
227β
228 const componentKey = () => matchState()!.key ?? matchState()!.match.id
229β
230 const out = () => {
231 const Comp = route().options.component ?? router.options.defaultComponent
232 if (Comp) {
233 return <Comp />
234 }
235 return <Outlet />
236 }
237β
238 const keyedOut = () => (
239 <Solid.Show when={componentKey()} keyed>
240 {(_key) => out()}
241 </Solid.Show>
242 )
243β
244 return (
245 <Solid.Switch>
246 <Solid.Match when={match()._displayPending}>
247 {(_) => {
248 const [displayPendingResult] = Solid.createResource(
249 () =>
250 router.getMatch(match().id)?._nonReactive.displayPendingPromise,
251 )
252β
253 return <>{displayPendingResult()}</>
254 }}
255 </Solid.Match>
256 <Solid.Match when={match()._forcePending}>
257 {(_) => {
258 const [minPendingResult] = Solid.createResource(
259 () => router.getMatch(match().id)?._nonReactive.minPendingPromise,
260 )
261β
262 return <>{minPendingResult()}</>
263 }}
264 </Solid.Match>
265 <Solid.Match when={match().status === 'pending'}>
266 {(_) => {
267 const pendingMinMs =
268 route().options.pendingMinMs ?? router.options.defaultPendingMinMs
269β
270 if (pendingMinMs) {
271 const routerMatch = router.getMatch(match().id)
272 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
273 // Create a promise that will resolve after the minPendingMs
274 if (!router.isServer) {
275 const minPendingPromise = createControlledPromise<void>()
276β
277 routerMatch._nonReactive.minPendingPromise = minPendingPromise
278β
279 setTimeout(() => {
280 minPendingPromise.resolve()
281 // We've handled the minPendingPromise, so we can delete it
282 routerMatch._nonReactive.minPendingPromise = undefined
283 }, pendingMinMs)
284 }
285 }
286 }
287β
288 const [loaderResult] = Solid.createResource(async () => {
289 await new Promise((r) => setTimeout(r, 0))
290 return router.getMatch(match().id)?._nonReactive.loadPromise
291 })
292β
293 const FallbackComponent =
294 route().options.pendingComponent ??
295 router.options.defaultPendingComponent
296β
297 return (
298 <>
299 {FallbackComponent && pendingMinMs > 0 ? (
300 <Dynamic component={FallbackComponent} />
301 ) : null}
302 {loaderResult()}
303 </>
304 )
305 }}
306 </Solid.Match>
307 <Solid.Match when={match().status === 'notFound'}>
308 {(_) => {
309 invariant(isNotFound(match().error), 'Expected a notFound error')
310β
311 return renderRouteNotFound(router, route(), match().error)
312 }}
313 </Solid.Match>
314 <Solid.Match when={match().status === 'redirected'}>
315 {(_) => {
316 invariant(isRedirect(match().error), 'Expected a redirect error')
317β
318 const [loaderResult] = Solid.createResource(async () => {
319 await new Promise((r) => setTimeout(r, 0))
320 return router.getMatch(match().id)?._nonReactive.loadPromise
321 })
322β
323 return <>{loaderResult()}</>
324 }}
325 </Solid.Match>
326 <Solid.Match when={match().status === 'error'}>
327 {(_) => {
328 if (router.isServer) {
329 const RouteErrorComponent =
330 (route().options.errorComponent ??
331 router.options.defaultErrorComponent) ||
332 ErrorComponent
333β
334 return (
335 <RouteErrorComponent
336 error={match().error}
337 info={{
338 componentStack: '',
339 }}
340 />
341 )
342 }
343β
344 throw match().error
345 }}
346 </Solid.Match>
347 <Solid.Match when={match().status === 'success'}>
348 {keyedOut()}
349 </Solid.Match>
350 </Solid.Switch>
351 )
352}
353β
354export const Outlet = () => {
355 const router = useRouter()
356 const matchId = Solid.useContext(matchContext)
357 const routeId = useRouterState({
358 select: (s) => s.matches.find((d) => d.id === matchId())?.routeId as string,
359 })
360β
361 const route = () => router.routesById[routeId()]!
362β
363 const parentGlobalNotFound = useRouterState({
364 select: (s) => {
365 const matches = s.matches
366 const parentMatch = matches.find((d) => d.id === matchId())
367β
368 // During navigation transitions, parent match can be temporarily removed
369 // Return false to avoid errors - the component will handle this gracefully
370 if (!parentMatch) {
371 return false
372 }
373β
374 return parentMatch.globalNotFound
375 },
376 })
377β
378 const childMatchId = useRouterState({
379 select: (s) => {
380 const matches = s.matches
381 const index = matches.findIndex((d) => d.id === matchId())
382 const v = matches[index + 1]?.id
383 return v
384 },
385 })
386β
387 const childMatchStatus = useRouterState({
388 select: (s) => {
389 const matches = s.matches
390 const index = matches.findIndex((d) => d.id === matchId())
391 return matches[index + 1]?.status
392 },
393 })
394β
395 // Only show not-found if we're not in a redirected state
396 const shouldShowNotFound = () =>
397 childMatchStatus() !== 'redirected' && parentGlobalNotFound()
398β
399 return (
400 <Solid.Show
401 when={!shouldShowNotFound() && childMatchId()}
402 fallback={
403 <Solid.Show when={shouldShowNotFound()}>
404 {renderRouteNotFound(router, route(), undefined)}
405 </Solid.Show>
406 }
407 >
408 {(matchIdAccessor) => {
409 // Use a memo to avoid stale accessor errors while keeping reactivity
410 const currentMatchId = Solid.createMemo(() => matchIdAccessor())
411β
412 return (
413 <Solid.Show
414 when={currentMatchId() === rootRouteId}
415 fallback={<Match matchId={currentMatchId()} />}
416 >
417 <Solid.Suspense
418 fallback={
419 <Dynamic component={router.options.defaultPendingComponent} />
420 }
421 >
422 <Match matchId={currentMatchId()} />
423 </Solid.Suspense>
424 </Solid.Show>
425 )
426 }}
427 </Solid.Show>
428 )
429}