Open History to see the last commit
1import { notifyManager } from './notifyManager'
2import { QueryObserver } from './queryObserver'
3import { Subscribable } from './subscribable'
4import { replaceEqualDeep, shallowEqualObjects } from './utils'
5import type {
6 DefaultedQueryObserverOptions,
7 QueryObserverOptions,
8 QueryObserverResult,
9} from './types'
10import type { QueryClient } from './queryClient'
11β
12function difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {
13 const excludeSet = new Set(array2)
14 return array1.filter((x) => !excludeSet.has(x))
15}
16β
17type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
18β
19type CombineFn<TCombinedResult> = (
20 result: Array<QueryObserverResult>,
21) => TCombinedResult
22β
23export interface QueriesObserverOptions<
24 TCombinedResult = Array<QueryObserverResult>,
25> {
26 combine?: CombineFn<TCombinedResult>
27}
28β
29export class QueriesObserver<
30 TCombinedResult = Array<QueryObserverResult>,
31> extends Subscribable<QueriesObserverListener> {
32 #client: QueryClient
33 #result!: Array<QueryObserverResult>
34 #queries: Array<QueryObserverOptions>
35 #options?: QueriesObserverOptions<TCombinedResult>
36 #observers: Array<QueryObserver>
37 #combinedResult!: TCombinedResult
38 #lastCombine?: CombineFn<TCombinedResult>
39 #lastResult?: Array<QueryObserverResult>
40 #lastQueryHashes?: Array<string>
41 #observerMatches: Array<QueryObserverMatch> = []
42β
43 constructor(
44 client: QueryClient,
45 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
46 options?: QueriesObserverOptions<TCombinedResult>,
47 ) {
48 super()
49β
50 this.#client = client
51 this.#options = options
52 this.#queries = []
53 this.#observers = []
54 this.#result = []
55β
56 this.setQueries(queries)
57 }
58β
59 protected onSubscribe(): void {
60 if (this.listeners.size === 1) {
61 this.#observers.forEach((observer) => {
62 observer.subscribe((result) => {
63 this.#onUpdate(observer, result)
64 })
65 })
66 }
67 }
68β
69 protected onUnsubscribe(): void {
70 if (!this.listeners.size) {
71 this.destroy()
72 }
73 }
74β
75 destroy(): void {
76 this.listeners = new Set()
77 this.#observers.forEach((observer) => {
78 observer.destroy()
79 })
80 }
81β
82 setQueries(
83 queries: Array<QueryObserverOptions>,
84 options?: QueriesObserverOptions<TCombinedResult>,
85 ): void {
86 this.#queries = queries
87 this.#options = options
88β
89 if (process.env.NODE_ENV !== 'production') {
90 const queryHashes = queries.map(
91 (query) => this.#client.defaultQueryOptions(query).queryHash,
92 )
93 if (new Set(queryHashes).size !== queryHashes.length) {
94 console.warn(
95 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
96 )
97 }
98 }
99β
100 notifyManager.batch(() => {
101 const prevObservers = this.#observers
102β
103 const newObserverMatches = this.#findMatchingObservers(this.#queries)
104β
105 // set options for the new observers to notify of changes
106 newObserverMatches.forEach((match) =>
107 match.observer.setOptions(match.defaultedQueryOptions),
108 )
109β
110 const newObservers = newObserverMatches.map((match) => match.observer)
111 const newResult = newObservers.map((observer) =>
112 observer.getCurrentResult(),
113 )
114β
115 const hasLengthChange = prevObservers.length !== newObservers.length
116 const hasIndexChange = newObservers.some(
117 (observer, index) => observer !== prevObservers[index],
118 )
119 const hasStructuralChange = hasLengthChange || hasIndexChange
120β
121 const hasResultChange = hasStructuralChange
122 ? true
123 : newResult.some((result, index) => {
124 const prev = this.#result[index]
125 return !prev || !shallowEqualObjects(result, prev)
126 })
127β
128 if (!hasStructuralChange && !hasResultChange) return
129β
130 if (hasStructuralChange) {
131 this.#observerMatches = newObserverMatches
132 this.#observers = newObservers
133 }
134β
135 this.#result = newResult
136β
137 if (!this.hasListeners()) return
138β
139 if (hasStructuralChange) {
140 difference(prevObservers, newObservers).forEach((observer) => {
141 observer.destroy()
142 })
143 difference(newObservers, prevObservers).forEach((observer) => {
144 observer.subscribe((result) => {
145 this.#onUpdate(observer, result)
146 })
147 })
148 }
149β
150 this.#notify()
151 })
152 }
153β
154 getCurrentResult(): Array<QueryObserverResult> {
155 return this.#result
156 }
157β
158 getQueries() {
159 return this.#observers.map((observer) => observer.getCurrentQuery())
160 }
161β
162 getObservers() {
163 return this.#observers
164 }
165β
166 getOptimisticResult(
167 queries: Array<QueryObserverOptions>,
168 combine: CombineFn<TCombinedResult> | undefined,
169 ): [
170 rawResult: Array<QueryObserverResult>,
171 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
172 trackResult: () => Array<QueryObserverResult>,
173 ] {
174 const matches = this.#findMatchingObservers(queries)
175 const result = matches.map((match) =>
176 match.observer.getOptimisticResult(match.defaultedQueryOptions),
177 )
178 const queryHashes = matches.map(
179 (match) => match.defaultedQueryOptions.queryHash,
180 )
181β
182 return [
183 result,
184 (r?: Array<QueryObserverResult>) => {
185 return this.#combineResult(r ?? result, combine, queryHashes)
186 },
187 () => {
188 return this.#trackResult(result, matches)
189 },
190 ]
191 }
192β
193 #trackResult(
194 result: Array<QueryObserverResult>,
195 matches: Array<QueryObserverMatch>,
196 ) {
197 const trackedProps = new Set<keyof QueryObserverResult>()
198β
199 return matches.map((match, index) => {
200 const observerResult = result[index]!
201 return !match.defaultedQueryOptions.notifyOnChangeProps
202 ? match.observer.trackResult(observerResult, (accessedProp) => {
203 // track property on all observers to ensure proper (synchronized) tracking (#7000)
204 if (!trackedProps.has(accessedProp)) {
205 trackedProps.add(accessedProp)
206 matches.forEach((m) => {
207 m.observer.trackProp(accessedProp)
208 })
209 }
210 })
211 : observerResult
212 })
213 }
214β
215 #combineResult(
216 input: Array<QueryObserverResult>,
217 combine: CombineFn<TCombinedResult> | undefined,
218 queryHashes?: Array<string>,
219 ): TCombinedResult {
220 if (combine) {
221 const lastHashes = this.#lastQueryHashes
222 const queryHashesChanged =
223 queryHashes !== undefined &&
224 lastHashes !== undefined &&
225 (lastHashes.length !== queryHashes.length ||
226 queryHashes.some((hash, i) => hash !== lastHashes[i]))
227β
228 if (
229 this.#result !== this.#lastResult ||
230 queryHashesChanged ||
231 combine !== this.#lastCombine
232 ) {
233 this.#lastCombine = combine
234 this.#lastResult = this.#result
235β
236 if (queryHashes !== undefined) {
237 this.#lastQueryHashes = queryHashes
238 }
239 this.#combinedResult = replaceEqualDeep(
240 this.#combinedResult,
241 combine(input),
242 )
243 }
244β
245 return this.#combinedResult
246 }
247 return input as any
248 }
249β
250 #shouldSkipCombine(): boolean {
251 return (
252 !this.#options?.combine ||
253 this.#observers.some((observer, index) => {
254 return (
255 observer.options.suspense && this.#result[index]?.data === undefined
256 )
257 })
258 )
259 }
260β
261 #findMatchingObservers(
262 queries: Array<QueryObserverOptions>,
263 ): Array<QueryObserverMatch> {
264 const prevObserversMap = new Map<string, Array<QueryObserver>>()
265β
266 this.#observers.forEach((observer) => {
267 const key = observer.options.queryHash
268 if (!key) return
269β
270 const previousObservers = prevObserversMap.get(key)
271β
272 if (previousObservers) {
273 previousObservers.push(observer)
274 } else {
275 prevObserversMap.set(key, [observer])
276 }
277 })
278β
279 const observers: Array<QueryObserverMatch> = []
280β
281 queries.forEach((options) => {
282 const defaultedOptions = this.#client.defaultQueryOptions(options)
283 const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()
284 const observer =
285 match ?? new QueryObserver(this.#client, defaultedOptions)
286β
287 observers.push({
288 defaultedQueryOptions: defaultedOptions,
289 observer,
290 })
291 })
292β
293 return observers
294 }
295β
296 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
297 const index = this.#observers.indexOf(observer)
298 if (index !== -1) {
299 this.#result = this.#result.slice()
300 this.#result[index] = result
301 this.#notify()
302 }
303 }
304β
305 #notify(): void {
306 if (this.hasListeners()) {
307 const shouldSkipCombine = this.#shouldSkipCombine()
308 const previousResult = this.#combinedResult
309 const newResult = shouldSkipCombine
310 ? previousResult
311 : this.#combineResult(
312 this.#trackResult(this.#result, this.#observerMatches),
313 this.#options?.combine,
314 )
315β
316 if (shouldSkipCombine || previousResult !== newResult) {
317 notifyManager.batch(() => {
318 this.listeners.forEach((listener) => {
319 listener(this.#result)
320 })
321 })
322 }
323 }
324 }
325}
326β
327type QueryObserverMatch = {
328 defaultedQueryOptions: DefaultedQueryObserverOptions
329 observer: QueryObserver
330}