Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4import { useSelector } from '@tanstack/react-store'
5import { rootRouteId } from '@tanstack/router-core'
6import { isServer } from '@tanstack/router-core/isServer'
7import { CatchBoundary } from './CatchBoundary'
8import { useRouter } from './useRouter'
9import { useStructuralSharing } from './useMatch'
10import { useLayoutEffect } from './utils'
11import { Transitioner, settleOwner } from './Transitioner'
12import { matchContext } from './matchContext'
13import { Match, renderPending } from './Match'
14import type {
15 StructuralSharingOption,
16 ValidateSelected,
17} from './structuralSharing'
18import type {
19 AnyRoute,
20 AnyRouter,
21 DeepPartial,
22 Expand,
23 MakeOptionalPathParams,
24 MakeOptionalSearchParams,
25 MakeRouteMatchUnion,
26 MaskOptions,
27 MatchRouteOptions,
28 RegisteredRouter,
29 ResolveRoute,
30 ToSubOptionsProps,
31} from '@tanstack/router-core'
32β
33declare module '@tanstack/router-core' {
34 export interface RouteMatchExtensions {
35 meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>
36 links?: Array<React.JSX.IntrinsicElements['link'] | undefined>
37 scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
38 styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>
39 headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
40 }
41}
42β
43/**
44 * Internal component that renders the router's active match tree with
45 * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
46 */
47export function Matches() {
48 const router = useRouter()
49 const rootRoute: AnyRoute = router.routesById[rootRouteId]
50β
51 const pendingElement = renderPending(router, rootRoute)
52β
53 const inner = (
54 <>
55 {!(isServer ?? router.isServer) && (
56 <Transitioner
57 // The initial load publishes matches before MatchesInner's store
58 // subscription is active. Storing the router here forces Matches to render
59 // that first publication before paint. Later publications store the same
60 // router object, so React skips the update.
61 // eslint-disable-next-line react-hooks/rules-of-hooks -- server only, condition is static
62 t={React.useState<AnyRouter>()[1]}
63 />
64 )}
65 {(isServer ?? router.isServer) || router.ssr ? (
66 <MatchesInner />
67 ) : (
68 <React.Suspense fallback={pendingElement}>
69 <MatchesInner />
70 </React.Suspense>
71 )}
72 </>
73 )
74β
75 return router.options.InnerWrap ? (
76 <router.options.InnerWrap>{inner}</router.options.InnerWrap>
77 ) : (
78 inner
79 )
80}
81β
82function MatchesInner() {
83 const router = useRouter()
84 const acknowledgement = router._rendered!
85 const matches =
86 (isServer ?? router.isServer)
87 ? router.stores.matches.get()
88 : // eslint-disable-next-line react-hooks/rules-of-hooks
89 useSelector(
90 router.stores.matches,
91 (value) => acknowledgement[0 /* offered */] ?? value,
92 )
93 const match = matches[0]
94 const routeId = match?.routeId
95β
96 useLayoutEffect(() => {
97 if (acknowledgement[0 /* offered */] === matches) {
98 settleOwner(acknowledgement, true)
99 }
100 }, [acknowledgement, matches])
101β
102 const matchComponent = routeId ? <Match routeId={routeId} /> : null
103β
104 return router.options.disableGlobalCatchBoundary ? (
105 matchComponent
106 ) : (
107 <CatchBoundary
108 getResetKey={() => match}
109 onCatch={
110 process.env.NODE_ENV !== 'production'
111 ? (error) => {
112 console.warn(
113 `Warning: The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,
114 )
115 console.warn('Warning:', error)
116 }
117 : undefined
118 }
119 >
120 {matchComponent}
121 </CatchBoundary>
122 )
123}
124β
125export type UseMatchRouteOptions<
126 TRouter extends AnyRouter = RegisteredRouter,
127 TFrom extends string = string,
128 TTo extends string | undefined = undefined,
129 TMaskFrom extends string = TFrom,
130 TMaskTo extends string = '',
131> = ToSubOptionsProps<TRouter, TFrom, TTo> &
132 DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &
133 DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &
134 MaskOptions<TRouter, TMaskFrom, TMaskTo> &
135 MatchRouteOptions
136β
137/**
138 * Create a matcher function for testing locations against route definitions.
139 *
140 * The returned function accepts standard navigation options (`to`, `params`,
141 * `search`, etc.) and returns either `false` (no match) or the matched params
142 * object when the route matches the current or pending location.
143 *
144 * Useful for conditional rendering and active UI states because it subscribes
145 * the component to the router state used for matching. The returned function's
146 * identity changes when that state changes. For imperative checks in event
147 * handlers, get the router with `useRouter` and call `router.matchRoute(...)`
148 * to avoid that subscription.
149 *
150 * @returns A `matchRoute(options)` function that returns `false` or params.
151 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook
152 */
153export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>(): <
154 const TFrom extends string = string,
155 const TTo extends string | undefined = undefined,
156 const TMaskFrom extends string = TFrom,
157 const TMaskTo extends string = '',
158>(
159 opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
160) => false | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> {
161 const router = useRouter()
162 if (isServer ?? router.isServer) {
163 return (opts) => {
164 const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts
165β
166 return router.matchRoute(rest as any, {
167 pending,
168 caseSensitive,
169 fuzzy,
170 includeSearch,
171 })
172 }
173 }
174β
175 // eslint-disable-next-line react-hooks/rules-of-hooks
176 return React.useCallback(
177 (opts) => {
178 const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts
179β
180 return router.matchRoute(rest as any, {
181 pending,
182 caseSensitive,
183 fuzzy,
184 includeSearch,
185 })
186 },
187 [
188 router,
189 // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps
190 useSelector(router.stores.location, (location) => location.href),
191 // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps
192 useSelector(router.stores.resolvedLocation, (location) => location?.href),
193 // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps
194 useSelector(router.stores.status),
195 ],
196 )
197}
198β
199export type MakeMatchRouteOptions<
200 TRouter extends AnyRouter = RegisteredRouter,
201 TFrom extends string = string,
202 TTo extends string | undefined = undefined,
203 TMaskFrom extends string = TFrom,
204 TMaskTo extends string = '',
205> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
206 // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns
207 children?:
208 | ((
209 params?: Expand<
210 ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']
211 >,
212 ) => React.ReactNode)
213 | React.ReactNode
214}
215β
216/**
217 * Component that conditionally renders its children based on whether a route
218 * matches the provided `from`/`to` options. If `children` is a function, it
219 * receives the matched params object.
220 *
221 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent
222 */
223export function MatchRoute<
224 TRouter extends AnyRouter = RegisteredRouter,
225 const TFrom extends string = string,
226 const TTo extends string | undefined = undefined,
227 const TMaskFrom extends string = TFrom,
228 const TMaskTo extends string = '',
229>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {
230 const matchRoute = useMatchRoute()
231 const params = matchRoute(props as any) as boolean
232β
233 if (typeof props.children === 'function') {
234 return (props.children as any)(params)
235 }
236β
237 return params ? props.children : null
238}
239β
240export interface UseMatchesBaseOptions<
241 TRouter extends AnyRouter,
242 TSelected,
243 TStructuralSharing,
244> {
245 select?: (
246 matches: Array<MakeRouteMatchUnion<TRouter>>,
247 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
248}
249β
250export type UseMatchesResult<
251 TRouter extends AnyRouter,
252 TSelected,
253> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected
254β
255export function useMatches<
256 TRouter extends AnyRouter = RegisteredRouter,
257 TSelected = unknown,
258 TStructuralSharing extends boolean = boolean,
259>(
260 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
261 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
262): UseMatchesResult<TRouter, TSelected> {
263 const router = useRouter<TRouter>()
264β
265 if (isServer ?? router.isServer) {
266 const matches = router.stores.matches.get() as Array<
267 MakeRouteMatchUnion<TRouter>
268 >
269 return (opts?.select ? opts.select(matches) : matches) as UseMatchesResult<
270 TRouter,
271 TSelected
272 >
273 }
274β
275 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
276 return useSelector(
277 router.stores.matches,
278 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
279 useStructuralSharing(opts, router),
280 ) as UseMatchesResult<TRouter, TSelected>
281}
282β
283/**
284 * Read the presented route matches above the current match, or select a
285 * derived value from them.
286 */
287export function useParentMatches<
288 TRouter extends AnyRouter = RegisteredRouter,
289 TSelected = unknown,
290 TStructuralSharing extends boolean = boolean,
291>(
292 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
293 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
294): UseMatchesResult<TRouter, TSelected> {
295 const contextRouteId = React.useContext(matchContext)
296β
297 return useMatches({
298 select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {
299 matches = matches.slice(
300 0,
301 matches.findIndex((d) => d.routeId === contextRouteId),
302 )
303 return opts?.select ? opts.select(matches) : matches
304 },
305 structuralSharing: opts?.structuralSharing,
306 } as any)
307}
308β
309/**
310 * Read the presented route matches below the current match, or select a
311 * derived value from them.
312 */
313export function useChildMatches<
314 TRouter extends AnyRouter = RegisteredRouter,
315 TSelected = unknown,
316 TStructuralSharing extends boolean = boolean,
317>(
318 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
319 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
320): UseMatchesResult<TRouter, TSelected> {
321 const contextRouteId = React.useContext(matchContext)
322β
323 return useMatches({
324 select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {
325 matches = matches.slice(
326 matches.findIndex((d) => d.routeId === contextRouteId) + 1,
327 )
328 return opts?.select ? opts.select(matches) : matches
329 },
330 structuralSharing: opts?.structuralSharing,
331 } as any)
332}