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 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 )
160}
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
186}
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 componentKey = () => matchState().key ?? matchState().match.id
226β
227 const out = () => {
228 const Comp = route().options.component ?? router.options.defaultComponent
229 if (Comp) {
230 return <Comp />
231 }
232 return <Outlet />
233 }
234β
235 const keyedOut = () => (
236 <Solid.Show when={componentKey()} keyed>
237 {(_key) => out()}
238 </Solid.Show>
239 )
240β
241 return (
242 <Solid.Switch>
243 <Solid.Match when={match()._displayPending}>
244 {(_) => {
245 const [displayPendingResult] = Solid.createResource(
246 () =>
247 router.getMatch(match().id)?._nonReactive.displayPendingPromise,
248 )
249β
250 return <>{displayPendingResult()}</>
251 }}
252 </Solid.Match>
253 <Solid.Match when={match()._forcePending}>
254 {(_) => {
255 const [minPendingResult] = Solid.createResource(
256 () => router.getMatch(match().id)?._nonReactive.minPendingPromise,
257 )
258β
259 return <>{minPendingResult()}</>
260 }}
261 </Solid.Match>
262 <Solid.Match when={match().status === 'pending'}>
263 {(_) => {
264 const pendingMinMs =
265 route().options.pendingMinMs ?? router.options.defaultPendingMinMs
266β
267 if (pendingMinMs) {
268 const routerMatch = router.getMatch(match().id)
269 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
270 // Create a promise that will resolve after the minPendingMs
271 if (!router.isServer) {
272 const minPendingPromise = createControlledPromise<void>()
273β
274 routerMatch._nonReactive.minPendingPromise = minPendingPromise
275β
276 setTimeout(() => {
277 minPendingPromise.resolve()
278 // We've handled the minPendingPromise, so we can delete it
279 routerMatch._nonReactive.minPendingPromise = undefined
280 }, pendingMinMs)
281 }
282 }
283 }
284β
285 const [loaderResult] = Solid.createResource(async () => {
286 await new Promise((r) => setTimeout(r, 0))
287 return router.getMatch(match().id)?._nonReactive.loadPromise
288 })
289β
290 return <>{loaderResult()}</>
291 }}
292 </Solid.Match>
293 <Solid.Match when={match().status === 'notFound'}>
294 {(_) => {
295 invariant(isNotFound(match().error), 'Expected a notFound error')
296β
297 return renderRouteNotFound(router, route(), match().error)
298 }}
299 </Solid.Match>
300 <Solid.Match when={match().status === 'redirected'}>
301 {(_) => {
302 invariant(isRedirect(match().error), 'Expected a redirect error')
303β
304 const [loaderResult] = Solid.createResource(async () => {
305 await new Promise((r) => setTimeout(r, 0))
306 return router.getMatch(match().id)?._nonReactive.loadPromise
307 })
308β
309 return <>{loaderResult()}</>
310 }}
311 </Solid.Match>
312 <Solid.Match when={match().status === 'error'}>
313 {(_) => {
314 if (router.isServer) {
315 const RouteErrorComponent =
316 (route().options.errorComponent ??
317 router.options.defaultErrorComponent) ||
318 ErrorComponent
319β
320 return (
321 <RouteErrorComponent
322 error={match().error}
323 info={{
324 componentStack: '',
325 }}
326 />
327 )
328 }
329β
330 throw match().error
331 }}
332 </Solid.Match>
333 <Solid.Match when={match().status === 'success'}>
334 {keyedOut()}
335 </Solid.Match>
336 </Solid.Switch>
337 )
338}
339β
340export const Outlet = () => {
341 const router = useRouter()
342 const matchId = Solid.useContext(matchContext)
343 const routeId = useRouterState({
344 select: (s) => s.matches.find((d) => d.id === matchId())?.routeId as string,
345 })
346β
347 const route = () => router.routesById[routeId()]!
348β
349 const parentGlobalNotFound = useRouterState({
350 select: (s) => {
351 const matches = s.matches
352 const parentMatch = matches.find((d) => d.id === matchId())
353 invariant(
354 parentMatch,
355 `Could not find parent match for matchId "${matchId()}"`,
356 )
357 return parentMatch.globalNotFound
358 },
359 })
360β
361 const childMatchId = useRouterState({
362 select: (s) => {
363 const matches = s.matches
364 const index = matches.findIndex((d) => d.id === matchId())
365 const v = matches[index + 1]?.id
366 return v
367 },
368 })
369β
370 const childMatchStatus = useRouterState({
371 select: (s) => {
372 const matches = s.matches
373 const index = matches.findIndex((d) => d.id === matchId())
374 return matches[index + 1]?.status
375 },
376 })
377β
378 // Only show not-found if we're not in a redirected state
379 const shouldShowNotFound = () =>
380 childMatchStatus() !== 'redirected' && parentGlobalNotFound()
381β
382 return (
383 <Solid.Show
384 when={!shouldShowNotFound() && childMatchId()}
385 fallback={
386 <Solid.Show when={shouldShowNotFound()}>
387 {renderRouteNotFound(router, route(), undefined)}
388 </Solid.Show>
389 }
390 >
391 {(matchId) => {
392 // const nextMatch = <Match matchId={matchId()} />
393β
394 return (
395 <Solid.Show
396 when={matchId() === rootRouteId}
397 fallback={<Match matchId={matchId()} />}
398 >
399 <Solid.Suspense
400 fallback={
401 <Dynamic component={router.options.defaultPendingComponent} />
402 }
403 >
404 <Match matchId={matchId()} />
405 </Solid.Suspense>
406 </Solid.Show>
407 )
408 }}
409 </Solid.Show>
410 )
411}