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

stores.ts

180 lines4.9 KB

1import { arraysEqual, functionalUpdate } from './utils'
2​
3import type { AnyRoute } from './route'
4import type { RouterState } from './router'
5import type { FullSearchSchema } from './routeInfo'
6import type { ParsedLocation } from './location'
7import type { AnyRouteMatch } from './Matches'
8​
9export interface RouterReadableStore<TValue> {
10 get: () => TValue
12​
13export interface RouterWritableStore<
14 TValue,
15> extends RouterReadableStore<TValue> {
16 set: ((updater: (prev: TValue) => TValue) => void) & ((value: TValue) => void)
18​
19export type RouterBatchFn = (fn: () => void) => void
20​
21export type MutableStoreFactory = <TValue>(
22 initialValue: TValue,
23) => RouterWritableStore<TValue>
24​
25export type ReadonlyStoreFactory = <TValue>(
26 read: () => TValue,
27) => RouterReadableStore<TValue>
28​
29export type GetStoreConfig = (opts: { isServer?: boolean }) => StoreConfig
30​
31export type StoreConfig = {
32 createMutableStore: MutableStoreFactory
33 createReadonlyStore: ReadonlyStoreFactory
34 batch: RouterBatchFn
36​
37type MatchStore = RouterWritableStore<AnyRouteMatch | undefined>
38type ReadableStore<TValue> = RouterReadableStore<TValue>
39​
40/** SSR non-reactive createMutableStore */
41export function createNonReactiveMutableStore<TValue>(
42 initialValue: TValue,
43): RouterWritableStore<TValue> {
44 let value = initialValue
45​
46 return {
47 get() {
48 return value
49 },
50 set(nextOrUpdater: TValue | ((prev: TValue) => TValue)) {
51 value = functionalUpdate(nextOrUpdater, value)
52 },
53 }
55​
56/** SSR non-reactive createReadonlyStore */
57export function createNonReactiveReadonlyStore<TValue>(
58 read: () => TValue,
59): RouterReadableStore<TValue> {
60 return {
61 get() {
62 return read()
63 },
64 }
66​
67export interface RouterStores<in out TRouteTree extends AnyRoute> {
68 status: RouterWritableStore<RouterState<TRouteTree>['status']>
69 location: RouterWritableStore<ParsedLocation<FullSearchSchema<TRouteTree>>>
70 resolvedLocation: RouterWritableStore<
71 ParsedLocation<FullSearchSchema<TRouteTree>> | undefined
72 >
73 ids: RouterWritableStore<Array<string>>
74 matches: ReadableStore<Array<AnyRouteMatch>>
75 __store: RouterReadableStore<RouterState<TRouteTree>>
76​
77 byRoute: Map<string, MatchStore>
78​
79 /**
80 * Get the stable atom for a route's presented match. The atom remains in the
81 * pool when the route leaves and contains `undefined` until it re-enters.
82 */
83 getMatchStore: (
84 routeId: string,
85 ) => RouterReadableStore<AnyRouteMatch | undefined>
86​
87 setMatches: (nextMatches: Array<AnyRouteMatch>) => void
89​
90export function createRouterStores<TRouteTree extends AnyRoute>(
91 initialLocation: RouterState<TRouteTree>['location'],
92 config: StoreConfig,
93): RouterStores<TRouteTree> {
94 const { createMutableStore, createReadonlyStore, batch } = config
95​
96 // non reactive utilities
97 const byRoute = new Map<string, MatchStore>()
98​
99 // atoms
100 const status = createMutableStore<RouterState<TRouteTree>['status']>('idle')
101 const location = createMutableStore(initialLocation)
102 const resolvedLocation =
103 createMutableStore<RouterState<TRouteTree>['resolvedLocation']>(undefined)
104 const ids = createMutableStore<Array<string>>([])
105​
106 // 1st order derived stores
107 const matches = createReadonlyStore(() =>
108 ids.get().map((id) => byRoute.get(id)!.get()!),
109 )
110​
111 // compatibility "big" state store
112 const __store = createReadonlyStore(() => ({
113 status: status.get(),
114 isLoading: status.get() === 'pending',
115 matches: matches.get(),
116 location: location.get(),
117 resolvedLocation: resolvedLocation.get(),
118 }))
119​
120 function getMatchStore(routeId: string): MatchStore {
121 let matchStore = byRoute.get(routeId)
122 if (!matchStore) {
123 matchStore = createMutableStore<AnyRouteMatch | undefined>(undefined)
124 byRoute.set(routeId, matchStore)
125 }
126 return matchStore
127 }
128​
129 const store = {
130 // atoms
131 status,
132 location,
133 resolvedLocation,
134 ids,
135​
136 // derived
137 matches,
138​
139 // non-reactive state
140 byRoute,
141​
142 // compatibility "big" state
143 __store,
144​
145 // stable per-route presentation atoms
146 getMatchStore,
147​
148 // methods
149 setMatches,
150 }
151​
152 // setters to update non-reactive utilities in sync with the reactive stores
153 function setMatches(nextMatches: Array<AnyRouteMatch>) {
154 const previousIds = ids.get()
155 const nextIds = nextMatches.map((match) => match.routeId)
156​
157 batch(() => {
158 // Publish lane membership first so framework trees reconcile departures
159 // before observers of a leaving route receive its tombstone.
160 if (!arraysEqual(previousIds, nextIds)) {
161 ids.set(nextIds)
162 }
163​
164 for (const id of previousIds) {
165 if (!nextIds.includes(id)) {
166 byRoute.get(id)!.set(() => undefined)
167 }
168 }
169​
170 for (const nextMatch of nextMatches) {
171 const matchStore = getMatchStore(nextMatch.routeId)
172 if (matchStore.get() !== nextMatch) {
173 matchStore.set(nextMatch)
174 }
175 }
176 })
177 }
178​
179 return store