Open History to see the last commit
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 the
125 * host supports `removeController`. The controller ignores later lifecycle
126 * 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 *
150 * @returns The explicitly passed client, otherwise the client from context,
151 * or `undefined` if neither is available.
152 */
153 protected tryGetQueryClient(): QueryClient | undefined {
154 return this.explicitClient ?? this.contextClient
155 }
156β
157 /**
158 * Returns the `QueryClient`, throwing when none is available.
159 *
160 * @returns The explicitly passed client, otherwise the client from context.
161 * @throws {Error} If no `QueryClient` is available.
162 */
163 protected getQueryClient(): QueryClient {
164 const client = this.tryGetQueryClient()
165 if (!client) {
166 throw createMissingQueryClientError()
167 }
168β
169 return client
170 }
171β
172 /**
173 * Stores a new result and requests a host update, unless it is the same
174 * result or the host is already updating.
175 *
176 * @param next - The new result.
177 */
178 protected setResult(next: TResult): void {
179 if (Object.is(this.result, next)) {
180 return
181 }
182β
183 this.result = next
184 if (!this.isHostUpdating) {
185 this.queueUpdate()
186 }
187 }
188β
189 /**
190 * The latest result of the controller.
191 *
192 * @returns The latest result.
193 * @throws {Error} If no `QueryClient` could be resolved from context.
194 */
195 get current(): TResult {
196 if (this.queryClientResolutionState === 'missing') {
197 throw createMissingQueryClientError()
198 }
199β
200 return this.result
201 }
202β
203 /**
204 * Whether the controller's host is connected.
205 *
206 * @returns `true` while the host is connected.
207 */
208 protected get connectedState(): boolean {
209 return this.connected
210 }
211β
212 /** Requests a host update in a microtask, batching multiple calls into one. */
213 protected queueUpdate(): void {
214 if (this.updateQueued) {
215 return
216 }
217β
218 this.updateQueued = true
219 queueMicrotask(() => {
220 this.updateQueued = false
221 if (!this.destroyed) {
222 this.host.requestUpdate()
223 }
224 })
225 }
226β
227 private queueQueryClientChanged(): void {
228 if (this.clientChangeQueued) {
229 return
230 }
231β
232 this.clientChangeQueued = true
233 queueMicrotask(() => {
234 this.clientChangeQueued = false
235 if (!this.destroyed) {
236 this.onQueryClientChanged()
237 }
238 })
239 }
240β
241 private beginContextResolution(): void {
242 this.clearContextClient()
243 this.updateQueryClientResolutionState('awaiting-context')
244 }
245β
246 private queueContextResolution(attempt: number): void {
247 queueMicrotask(() => {
248 if (
249 this.destroyed ||
250 !this.connected ||
251 attempt !== this.connectionAttempt ||
252 this.queryClientResolutionState !== 'awaiting-context'
253 ) {
254 return
255 }
256β
257 this.dispatchContextRequest(attempt)
258 this.queueInitialContextResolutionCompletion(attempt)
259 })
260 }
261β
262 private dispatchContextRequest(attempt: number): void {
263 if (!('dispatchEvent' in this.host)) {
264 return
265 }
266β
267 const contextTarget = this.host as ReactiveControllerHost & EventTarget
268 contextTarget.dispatchEvent(
269 new ContextEvent(
270 queryClientContext,
271 contextTarget as unknown as Element,
272 (value, unsubscribe) => {
273 if (
274 this.destroyed ||
275 !this.connected ||
276 attempt !== this.connectionAttempt
277 ) {
278 unsubscribe?.()
279 return
280 }
281β
282 if (
283 this.contextUnsubscribe &&
284 this.contextUnsubscribe !== unsubscribe
285 ) {
286 this.contextUnsubscribe()
287 }
288β
289 const resolutionChanged = this.updateQueryClientResolutionState(
290 // oxlint-disable-next-line typescript/no-unnecessary-condition
291 value === undefined ? 'missing' : 'bound',
292 )
293 const clientChanged = this.contextClient !== value
294β
295 this.contextClient = value
296 this.contextUnsubscribe = unsubscribe
297β
298 if (resolutionChanged || clientChanged) {
299 this.queueUpdate()
300 this.queueQueryClientChanged()
301 }
302 },
303 true,
304 ),
305 )
306 }
307β
308 private queueInitialContextResolutionCompletion(attempt: number): void {
309 queueMicrotask(() => {
310 if (
311 this.destroyed ||
312 !this.connected ||
313 attempt !== this.connectionAttempt ||
314 this.queryClientResolutionState !== 'awaiting-context'
315 ) {
316 return
317 }
318β
319 if (this.updateQueryClientResolutionState('missing')) {
320 this.queueUpdate()
321 this.queueQueryClientChanged()
322 }
323 })
324 }
325β
326 private clearContextClient(): void {
327 this.contextUnsubscribe?.()
328 this.contextUnsubscribe = undefined
329 this.contextClient = undefined
330 }
331β
332 private updateQueryClientResolutionState(
333 nextState: QueryClientResolutionState,
334 ): boolean {
335 if (this.queryClientResolutionState === nextState) {
336 return false
337 }
338β
339 this.queryClientResolutionState = nextState
340 return true
341 }
342β
343 /**
344 * Called in a microtask after the host connects, once the subclass fields are
345 * initialized. Subclasses subscribe to the `QueryClient` here, if one is
346 * available.
347 */
348 protected abstract onConnected(): void
349 /**
350 * Called when the host disconnects or the controller is destroyed. Subclasses
351 * unsubscribe here.
352 */
353 protected abstract onDisconnected(): void
354 /** Called before each host update. Subclasses refresh their options here. */
355 protected abstract onHostUpdate(): void
356 /**
357 * Called in a microtask when the `QueryClient` from context changes, or when
358 * resolving it finishes without finding one (`tryGetQueryClient` then returns
359 * `undefined`). Subclasses resubscribe to the new client here, if there is
360 * one.
361 */
362 protected abstract onQueryClientChanged(): void
363}