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

BaseController.ts

362 lines9.6 KB

1import { ContextEvent } from '@lit/context'
2import {
3 createMissingQueryClientError,
4 queryClientContext,
5} from '../context.js'
6import type { QueryClient } from '@tanstack/query-core'
7import type { ReactiveController, ReactiveControllerHost } from 'lit'
8​
9type QueryClientResolutionState =
10 | 'pre-connect'
11 | 'awaiting-context'
12 | 'bound'
13 | 'missing'
14​
15/**
16 * Base class of the query controllers. It resolves the `QueryClient`, either
17 * passed explicitly or provided through context by a `QueryClientProvider`,
18 * follows the host's lifecycle, and requests a host update when the result
19 * changes.
20 */
21export abstract class BaseController<TResult> implements ReactiveController {
22 protected result: TResult
23​
24 private readonly explicitClient?: QueryClient
25 private contextClient: QueryClient | undefined
26 private contextUnsubscribe: (() => void) | undefined
27​
28 private connected = false
29 private destroyed = false
30 private updateQueued = false
31 private clientChangeQueued = false
32 private connectionAttempt = 0
33 private isHostUpdating = false
34 private queryClientResolutionState: QueryClientResolutionState
35​
36 protected constructor(
37 protected readonly host: ReactiveControllerHost,
38 initialResult: TResult,
39 queryClient?: QueryClient,
40 ) {
41 this.explicitClient = queryClient
42 this.result = initialResult
43 this.queryClientResolutionState = queryClient ? 'bound' : 'pre-connect'
44​
45 host.addController(this)
46 }
47​
48 /**
49 * Starts resolving the `QueryClient` from context, unless one was passed
50 * explicitly, and calls `onConnected` in a microtask so subclass fields are
51 * initialized first.
52 */
53 hostConnected(): void {
54 if (this.connected || this.destroyed) {
55 return
56 }
57​
58 this.connected = true
59 let contextResolutionAttempt: number | undefined
60​
61 if (this.explicitClient) {
62 this.queryClientResolutionState = 'bound'
63 } else {
64 contextResolutionAttempt = ++this.connectionAttempt
65 this.beginContextResolution()
66 }
67​
68 // Defer onConnected to ensure subclass constructors complete before
69 // lifecycle callbacks access subclass state. This handles the case where
70 // addController is called on an already-connected host (e.g., during
71 // willUpdate), which synchronously triggers hostConnected before
72 // subclass field initialization.
73 queueMicrotask(() => {
74 if (this.connected && !this.destroyed) {
75 this.onConnected()
76 }
77 })
78​
79 if (contextResolutionAttempt !== undefined) {
80 // Provider-backed controllers on already-connected hosts should finish
81 // their deferred onConnected pass before a context client binds.
82 this.queueContextResolution(contextResolutionAttempt)
83 }
84 }
85​
86 /**
87 * Releases the context `QueryClient`, unless one was passed explicitly, and
88 * calls `onDisconnected`.
89 */
90 hostDisconnected(): void {
91 if (!this.connected) {
92 return
93 }
94​
95 this.connected = false
96​
97 if (!this.explicitClient) {
98 this.connectionAttempt += 1
99 this.clearContextClient()
100 this.updateQueryClientResolutionState('pre-connect')
101 }
102​
103 this.onDisconnected()
104 }
105​
106 /**
107 * Calls `onHostUpdate` before the host renders. Results set during this call
108 * don't request another update.
109 */
110 hostUpdate(): void {
111 if (this.destroyed) {
112 return
113 }
114​
115 this.isHostUpdating = true
116 try {
117 this.onHostUpdate()
118 } finally {
119 this.isHostUpdating = false
120 }
121 }
122​
123 /**
124 * Permanently disconnects the controller and removes it from its host, if
125 * the host supports `removeController`. The controller ignores later
126 * lifecycle callbacks.
127 */
128 destroy(): void {
129 if (this.destroyed) {
130 return
131 }
132​
133 this.destroyed = true
134 this.connected = false
135 this.connectionAttempt += 1
136 this.clearContextClient()
137 this.queryClientResolutionState = this.explicitClient
138 ? 'bound'
139 : 'pre-connect'
140 this.onDisconnected()
141​
142 if ('removeController' in this.host) {
143 this.host.removeController(this)
144 }
145 }
146​
147 /**
148 * Returns the `QueryClient` without throwing when none is available.
149 * @returns The explicitly passed client, otherwise the client from context,
150 * or `undefined` if neither is available.
151 */
152 protected tryGetQueryClient(): QueryClient | undefined {
153 return this.explicitClient ?? this.contextClient
154 }
155​
156 /**
157 * Returns the `QueryClient`, throwing when none is available.
158 * @returns The explicitly passed client, otherwise the client from context.
159 * @throws {Error} If no `QueryClient` is available.
160 */
161 protected getQueryClient(): QueryClient {
162 const client = this.tryGetQueryClient()
163 if (!client) {
164 throw createMissingQueryClientError()
165 }
166​
167 return client
168 }
169​
170 /**
171 * Stores a new result and requests a host update, unless it is the same
172 * result or the host is already updating.
173 * @param next - The new result.
174 */
175 protected setResult(next: TResult): void {
176 if (Object.is(this.result, next)) {
177 return
178 }
179​
180 this.result = next
181 if (!this.isHostUpdating) {
182 this.queueUpdate()
183 }
184 }
185​
186 /**
187 * The latest result of the controller.
188 * @returns The latest result.
189 * @throws {Error} If no `QueryClient` could be resolved from context.
190 */
191 get current(): TResult {
192 if (this.queryClientResolutionState === 'missing') {
193 throw createMissingQueryClientError()
194 }
195​
196 return this.result
197 }
198​
199 /**
200 * Whether the controller's host is connected.
201 * @returns `true` while the host is connected.
202 */
203 protected get connectedState(): boolean {
204 return this.connected
205 }
206​
207 /**
208 * Requests a host update in a microtask, batching multiple calls into one.
209 */
210 protected queueUpdate(): void {
211 if (this.updateQueued) {
212 return
213 }
214​
215 this.updateQueued = true
216 queueMicrotask(() => {
217 this.updateQueued = false
218 if (!this.destroyed) {
219 this.host.requestUpdate()
220 }
221 })
222 }
223​
224 private queueQueryClientChanged(): void {
225 if (this.clientChangeQueued) {
226 return
227 }
228​
229 this.clientChangeQueued = true
230 queueMicrotask(() => {
231 this.clientChangeQueued = false
232 if (!this.destroyed) {
233 this.onQueryClientChanged()
234 }
235 })
236 }
237​
238 private beginContextResolution(): void {
239 this.clearContextClient()
240 this.updateQueryClientResolutionState('awaiting-context')
241 }
242​
243 private queueContextResolution(attempt: number): void {
244 queueMicrotask(() => {
245 if (
246 this.destroyed ||
247 !this.connected ||
248 attempt !== this.connectionAttempt ||
249 this.queryClientResolutionState !== 'awaiting-context'
250 ) {
251 return
252 }
253​
254 this.dispatchContextRequest(attempt)
255 this.queueInitialContextResolutionCompletion(attempt)
256 })
257 }
258​
259 private dispatchContextRequest(attempt: number): void {
260 if (!('dispatchEvent' in this.host)) {
261 return
262 }
263​
264 const contextTarget = this.host as ReactiveControllerHost & EventTarget
265 contextTarget.dispatchEvent(
266 new ContextEvent(
267 queryClientContext,
268 contextTarget as unknown as Element,
269 (value, unsubscribe) => {
270 if (
271 this.destroyed ||
272 !this.connected ||
273 attempt !== this.connectionAttempt
274 ) {
275 unsubscribe?.()
276 return
277 }
278​
279 if (
280 this.contextUnsubscribe &&
281 this.contextUnsubscribe !== unsubscribe
282 ) {
283 this.contextUnsubscribe()
284 }
285​
286 const resolutionChanged = this.updateQueryClientResolutionState(
287 // oxlint-disable-next-line typescript/no-unnecessary-condition -- the provider sends 'undefined' when its 'client' is removed
288 value === undefined ? 'missing' : 'bound',
289 )
290 const clientChanged = this.contextClient !== value
291​
292 this.contextClient = value
293 this.contextUnsubscribe = unsubscribe
294​
295 if (resolutionChanged || clientChanged) {
296 this.queueUpdate()
297 this.queueQueryClientChanged()
298 }
299 },
300 true,
301 ),
302 )
303 }
304​
305 private queueInitialContextResolutionCompletion(attempt: number): void {
306 queueMicrotask(() => {
307 if (
308 this.destroyed ||
309 !this.connected ||
310 attempt !== this.connectionAttempt ||
311 this.queryClientResolutionState !== 'awaiting-context'
312 ) {
313 return
314 }
315​
316 if (this.updateQueryClientResolutionState('missing')) {
317 this.queueUpdate()
318 this.queueQueryClientChanged()
319 }
320 })
321 }
322​
323 private clearContextClient(): void {
324 this.contextUnsubscribe?.()
325 this.contextUnsubscribe = undefined
326 this.contextClient = undefined
327 }
328​
329 private updateQueryClientResolutionState(
330 nextState: QueryClientResolutionState,
331 ): boolean {
332 if (this.queryClientResolutionState === nextState) {
333 return false
334 }
335​
336 this.queryClientResolutionState = nextState
337 return true
338 }
339​
340 /**
341 * Called in a microtask after the host connects, once the subclass fields
342 * are initialized. Subclasses subscribe to the `QueryClient` here, if one is
343 * available.
344 */
345 protected abstract onConnected(): void
346 /**
347 * Called when the host disconnects or the controller is destroyed.
348 * Subclasses unsubscribe here.
349 */
350 protected abstract onDisconnected(): void
351 /**
352 * Called before each host update. Subclasses refresh their options here.
353 */
354 protected abstract onHostUpdate(): void
355 /**
356 * Called in a microtask when the `QueryClient` from context changes, or when
357 * resolving it finishes without finding one (`tryGetQueryClient` then returns
358 * `undefined`). Subclasses resubscribe to the new client here, if there is
359 * one.
360 */
361 protected abstract onQueryClientChanged(): void