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

Matches.tsx

319 lines10.0 KB

1import * as React from 'react'
2import warning from 'tiny-warning'
3import { rootRouteId } from '@tanstack/router-core'
4import { CatchBoundary, ErrorComponent } from './CatchBoundary'
5import { useRouterState } from './useRouterState'
6import { useRouter } from './useRouter'
7import { Transitioner } from './Transitioner'
8import { matchContext } from './matchContext'
9import { Match } from './Match'
10import { SafeFragment } from './SafeFragment'
11import type {
12 StructuralSharingOption,
13 ValidateSelected,
14} from './structuralSharing'
15import type {
16 AnyRoute,
17 AnyRouter,
18 DeepPartial,
19 Expand,
20 MakeOptionalPathParams,
21 MakeOptionalSearchParams,
22 MakeRouteMatchUnion,
23 MaskOptions,
24 MatchRouteOptions,
25 NoInfer,
26 RegisteredRouter,
27 ResolveRelativePath,
28 ResolveRoute,
29 RouteByPath,
30 RouterState,
31 ToSubOptionsProps,
32} from '@tanstack/router-core'
33​
34declare module '@tanstack/router-core' {
35 export interface RouteMatchExtensions {
36 meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>
37 links?: Array<React.JSX.IntrinsicElements['link'] | undefined>
38 scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
39 styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>
40 headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>
41 }
43​
44/**
45 * Internal component that renders the router's active match tree with
46 * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
47 */
48/**
49 * Internal component that renders the router's active match tree with
50 * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
51 */
52export function Matches() {
53 const router = useRouter()
54 const rootRoute: AnyRoute = router.routesById[rootRouteId]
55​
56 const PendingComponent =
57 rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent
58​
59 const pendingElement = PendingComponent ? <PendingComponent /> : null
60​
61 // Do not render a root Suspense during SSR or hydrating from SSR
62 const ResolvedSuspense =
63 router.isServer || (typeof document !== 'undefined' && router.ssr)
64 ? SafeFragment
65 : React.Suspense
66​
67 const inner = (
68 <ResolvedSuspense fallback={pendingElement}>
69 {!router.isServer && <Transitioner />}
70 <MatchesInner />
71 </ResolvedSuspense>
72 )
73​
74 return router.options.InnerWrap ? (
75 <router.options.InnerWrap>{inner}</router.options.InnerWrap>
76 ) : (
77 inner
78 )
80​
81function MatchesInner() {
82 const router = useRouter()
83 const matchId = useRouterState({
84 select: (s) => {
85 return s.matches[0]?.id
86 },
87 })
88​
89 const resetKey = useRouterState({
90 select: (s) => s.loadedAt,
91 })
92​
93 const matchComponent = matchId ? <Match matchId={matchId} /> : null
94​
95 return (
96 <matchContext.Provider value={matchId}>
97 {router.options.disableGlobalCatchBoundary ? (
98 matchComponent
99 ) : (
100 <CatchBoundary
101 getResetKey={() => resetKey}
102 errorComponent={ErrorComponent}
103 onCatch={(error) => {
104 warning(
105 false,
106 `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,
107 )
108 warning(false, error.message || error.toString())
109 }}
110 >
111 {matchComponent}
112 </CatchBoundary>
113 )}
114 </matchContext.Provider>
115 )
117​
118export type UseMatchRouteOptions<
119 TRouter extends AnyRouter = RegisteredRouter,
120 TFrom extends string = string,
121 TTo extends string | undefined = undefined,
122 TMaskFrom extends string = TFrom,
123 TMaskTo extends string = '',
124> = ToSubOptionsProps<TRouter, TFrom, TTo> &
125 DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &
126 DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &
127 MaskOptions<TRouter, TMaskFrom, TMaskTo> &
128 MatchRouteOptions
129​
130/**
131 * Create a matcher function for testing locations against route definitions.
132 *
133 * The returned function accepts standard navigation options (`to`, `params`,
134 * `search`, etc.) and returns either `false` (no match) or the matched params
135 * object when the route matches the current or pending location.
136 *
137 * Useful for conditional rendering and active UI states.
138 *
139 * @returns A `matchRoute(options)` function that returns `false` or params.
140 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook
141 */
142export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {
143 const router = useRouter()
144​
145 useRouterState({
146 select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],
147 structuralSharing: true as any,
148 })
149​
150 return React.useCallback(
151 <
152 const TFrom extends string = string,
153 const TTo extends string | undefined = undefined,
154 const TMaskFrom extends string = TFrom,
155 const TMaskTo extends string = '',
156 >(
157 opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
158 ):
159 | false
160 | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {
161 const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts
162​
163 return router.matchRoute(rest as any, {
164 pending,
165 caseSensitive,
166 fuzzy,
167 includeSearch,
168 })
169 },
170 [router],
171 )
173​
174export type MakeMatchRouteOptions<
175 TRouter extends AnyRouter = RegisteredRouter,
176 TFrom extends string = string,
177 TTo extends string | undefined = undefined,
178 TMaskFrom extends string = TFrom,
179 TMaskTo extends string = '',
180> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
181 // 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
182 children?:
183 | ((
184 params?: RouteByPath<
185 TRouter['routeTree'],
186 ResolveRelativePath<TFrom, NoInfer<TTo>>
187 >['types']['allParams'],
188 ) => React.ReactNode)
189 | React.ReactNode
191​
192/**
193 * Component that conditionally renders its children based on whether a route
194 * matches the provided `from`/`to` options. If `children` is a function, it
195 * receives the matched params object.
196 *
197 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent
198 */
199export function MatchRoute<
200 TRouter extends AnyRouter = RegisteredRouter,
201 const TFrom extends string = string,
202 const TTo extends string | undefined = undefined,
203 const TMaskFrom extends string = TFrom,
204 const TMaskTo extends string = '',
205>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {
206 const matchRoute = useMatchRoute()
207 const params = matchRoute(props as any) as boolean
208​
209 if (typeof props.children === 'function') {
210 return (props.children as any)(params)
211 }
212​
213 return params ? props.children : null
215​
216export interface UseMatchesBaseOptions<
217 TRouter extends AnyRouter,
218 TSelected,
219 TStructuralSharing,
220> {
221 select?: (
222 matches: Array<MakeRouteMatchUnion<TRouter>>,
223 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
225​
226export type UseMatchesResult<
227 TRouter extends AnyRouter,
228 TSelected,
229> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected
230​
231export function useMatches<
232 TRouter extends AnyRouter = RegisteredRouter,
233 TSelected = unknown,
234 TStructuralSharing extends boolean = boolean,
235>(
236 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
237 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
238): UseMatchesResult<TRouter, TSelected> {
239 return useRouterState({
240 select: (state: RouterState<TRouter['routeTree']>) => {
241 const matches = state.matches
242 return opts?.select
243 ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)
244 : matches
245 },
246 structuralSharing: opts?.structuralSharing,
247 } as any) as UseMatchesResult<TRouter, TSelected>
249​
250/**
251 * Read the full array of active route matches or select a derived subset.
252 *
253 * Useful for debugging, breadcrumbs, or aggregating metadata across matches.
254 *
255 * @returns The array of matches (or the selected value).
256 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook
257 */
258​
259/**
260 * Read the full array of active route matches or select a derived subset.
261 *
262 * Useful for debugging, breadcrumbs, or aggregating metadata across matches.
263 *
264 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook
265 */
266/**
267 * Read the full array of active route matches or select a derived subset
268 * from the parent boundary up to (but not including) the current match.
269 */
270export function useParentMatches<
271 TRouter extends AnyRouter = RegisteredRouter,
272 TSelected = unknown,
273 TStructuralSharing extends boolean = boolean,
274>(
275 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
276 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
277): UseMatchesResult<TRouter, TSelected> {
278 const contextMatchId = React.useContext(matchContext)
279​
280 return useMatches({
281 select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {
282 matches = matches.slice(
283 0,
284 matches.findIndex((d) => d.id === contextMatchId),
285 )
286 return opts?.select ? opts.select(matches) : matches
287 },
288 structuralSharing: opts?.structuralSharing,
289 } as any)
291​
292/**
293 * Read the array of active route matches that are children of the current
294 * match (or selected parent) in the match tree.
295 */
296/**
297 * Read the array of active route matches that are children of the current
298 * match (or selected parent) in the match tree.
299 */
300export function useChildMatches<
301 TRouter extends AnyRouter = RegisteredRouter,
302 TSelected = unknown,
303 TStructuralSharing extends boolean = boolean,
304>(
305 opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &
306 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
307): UseMatchesResult<TRouter, TSelected> {
308 const contextMatchId = React.useContext(matchContext)
309​
310 return useMatches({
311 select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {
312 matches = matches.slice(
313 matches.findIndex((d) => d.id === contextMatchId) + 1,
314 )
315 return opts?.select ? opts.select(matches) : matches
316 },
317 structuralSharing: opts?.structuralSharing,
318 } as any)