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