Open History to see the last commit
1import * as Solid from 'solid-js'
2import invariant from 'tiny-invariant'
3import { useRouterState } from './useRouterState'
4import { dummyMatchContext, matchContext } from './matchContext'
5import type {
6 AnyRouter,
7 MakeRouteMatch,
8 MakeRouteMatchUnion,
9 RegisteredRouter,
10 StrictOrFrom,
11 ThrowConstraint,
12 ThrowOrOptional,
13} from '@tanstack/router-core'
14β
15export interface UseMatchBaseOptions<
16 TRouter extends AnyRouter,
17 TFrom,
18 TStrict extends boolean,
19 TThrow extends boolean,
20 TSelected,
21> {
22 select?: (
23 match: MakeRouteMatch<TRouter['routeTree'], TFrom, TStrict>,
24 ) => TSelected
25 shouldThrow?: TThrow
26}
27β
28export type UseMatchRoute<out TFrom> = <
29 TRouter extends AnyRouter = RegisteredRouter,
30 TSelected = unknown,
31>(
32 opts?: UseMatchBaseOptions<TRouter, TFrom, true, true, TSelected>,
33) => Solid.Accessor<UseMatchResult<TRouter, TFrom, true, TSelected>>
34β
35export type UseMatchOptions<
36 TRouter extends AnyRouter,
37 TFrom extends string | undefined,
38 TStrict extends boolean,
39 TThrow extends boolean,
40 TSelected,
41> = StrictOrFrom<TRouter, TFrom, TStrict> &
42 UseMatchBaseOptions<TRouter, TFrom, TStrict, TThrow, TSelected>
43β
44export type UseMatchResult<
45 TRouter extends AnyRouter,
46 TFrom,
47 TStrict extends boolean,
48 TSelected,
49> = unknown extends TSelected
50 ? TStrict extends true
51 ? MakeRouteMatch<TRouter['routeTree'], TFrom, TStrict>
52 : MakeRouteMatchUnion<TRouter>
53 : TSelected
54β
55export function useMatch<
56 TRouter extends AnyRouter = RegisteredRouter,
57 const TFrom extends string | undefined = undefined,
58 TStrict extends boolean = true,
59 TThrow extends boolean = true,
60 TSelected = unknown,
61>(
62 opts: UseMatchOptions<
63 TRouter,
64 TFrom,
65 TStrict,
66 ThrowConstraint<TStrict, TThrow>,
67 TSelected
68 >,
69): Solid.Accessor<
70 ThrowOrOptional<UseMatchResult<TRouter, TFrom, TStrict, TSelected>, TThrow>
71> {
72 const nearestMatchId = Solid.useContext(
73 opts.from ? dummyMatchContext : matchContext,
74 )
75β
76 const matchSelection = useRouterState({
77 select: (state: any) => {
78 const match = state.matches.find((d: any) =>
79 opts.from ? opts.from === d.routeId : d.id === nearestMatchId(),
80 )
81β
82 invariant(
83 !((opts.shouldThrow ?? true) && !match),
84 `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`,
85 )
86β
87 if (match === undefined) {
88 return undefined
89 }
90β
91 return opts.select ? opts.select(match) : match
92 },
93 } as any)
94β
95 return matchSelection as any
96}