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

matchContext.tsx

74 lines2.4 KB

1'use client'
2​
3import * as React from 'react'
4import { _isRouteDeparting } from '@tanstack/router-core'
5import type { AnyRoute, AnyRouter, ParsedLocation } from '@tanstack/router-core'
6​
7declare module '@tanstack/router-core' {
8 // Declaration merging requires the original type parameters.
9 // eslint-disable-next-line unused-imports/no-unused-vars
10 interface RouterStores<in out TRouteTree extends AnyRoute> {
11 /**
12 * The link scope of each route id that rendered links, keyed `undefined`
13 * for links outside every match (route ids start with `/` or are the
14 * root id). A scope without links holds no location.
15 */
16 _linkScopes?: Record<string, LinkScope>
17 }
19​
20/**
21 * The location source shared by the links of one route. It holds one location
22 * subscription for all of them while any is subscribed, and skips a
23 * publication whose navigation removes the route: those links keep the
24 * location their route still presents until it unmounts or a newer
25 * publication keeps it. Without subscribers it holds nothing and reads the
26 * live location.
27 */
28export type LinkScope = [
29 getSource: () => ParsedLocation,
30 subscribe: (listener: () => void) => () => void,
32​
33export function createLinkScope(
34 router: AnyRouter,
35 routeId?: string,
36): LinkScope {
37 // Stores are created once per router.
38 const store = router.stores.location
39 const listeners = new Set<() => void>()
40 let source: ParsedLocation | undefined
41 let unsubscribe: () => void
42 // Defined outside `subscribe` so the store's subscription does not share a
43 // closure with, and retain, the first listener after it unsubscribes.
44 const update = (location: ParsedLocation) => {
45 if (!_isRouteDeparting(router, routeId, location)) {
46 source = location
47 listeners.forEach((listener) => listener())
48 }
49 }
50 return [
51 () => source ?? store.get(),
52 (listener) => {
53 if (!listeners.size) {
54 source = store.get()
55 unsubscribe = store.subscribe(update).unsubscribe
56 }
57 listeners.add(listener)
58 return () => {
59 listeners.delete(listener)
60 if (!listeners.size) {
61 unsubscribe()
62 source = undefined
63 }
64 }
65 },
66 ]
68​
69export const matchContext = React.createContext<string | undefined>(undefined)
70​
71// N.B. this only exists so we can conditionally call useContext on it when we are not interested in the nearest match
72export const dummyMatchContext = React.createContext<string | undefined>(
73 undefined,