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

BaseController.ts

292 lines7.1 KB

1import { ContextEvent } from '@lit/context'
2import type { QueryClient } from '@tanstack/query-core'
3import type { ReactiveController, ReactiveControllerHost } from 'lit'
4import {
5 createMissingQueryClientError,
6 queryClientContext,
7} from '../context.js'
8​
9type QueryClientResolutionState =
10 | 'pre-connect'
11 | 'awaiting-context'
12 | 'bound'
13 | 'missing'
14​
15export abstract class BaseController<TResult> implements ReactiveController {
16 protected result: TResult
17​
18 private readonly explicitClient?: QueryClient
19 private contextClient: QueryClient | undefined
20 private contextUnsubscribe: (() => void) | undefined
21​
22 private connected = false
23 private destroyed = false
24 private updateQueued = false
25 private clientChangeQueued = false
26 private connectionAttempt = 0
27 private isHostUpdating = false
28 private queryClientResolutionState: QueryClientResolutionState
29​
30 protected constructor(
31 protected readonly host: ReactiveControllerHost,
32 initialResult: TResult,
33 queryClient?: QueryClient,
34 ) {
35 this.explicitClient = queryClient
36 this.result = initialResult
37 this.queryClientResolutionState = queryClient ? 'bound' : 'pre-connect'
38​
39 host.addController(this)
40 }
41​
42 hostConnected(): void {
43 if (this.connected || this.destroyed) {
44 return
45 }
46​
47 this.connected = true
48 let contextResolutionAttempt: number | undefined
49​
50 if (this.explicitClient) {
51 this.queryClientResolutionState = 'bound'
52 } else {
53 contextResolutionAttempt = ++this.connectionAttempt
54 this.beginContextResolution()
55 }
56​
57 // Defer onConnected to ensure subclass constructors complete before
58 // lifecycle callbacks access subclass state. This handles the case where
59 // addController is called on an already-connected host (e.g., during
60 // willUpdate), which synchronously triggers hostConnected before
61 // subclass field initialization.
62 queueMicrotask(() => {
63 if (this.connected && !this.destroyed) {
64 this.onConnected()
65 }
66 })
67​
68 if (contextResolutionAttempt !== undefined) {
69 // Provider-backed controllers on already-connected hosts should finish
70 // their deferred onConnected pass before a context client binds.
71 this.queueContextResolution(contextResolutionAttempt)
72 }
73 }
74​
75 hostDisconnected(): void {
76 if (!this.connected) {
77 return
78 }
79​
80 this.connected = false
81​
82 if (!this.explicitClient) {
83 this.connectionAttempt += 1
84 this.clearContextClient()
85 this.updateQueryClientResolutionState('pre-connect')
86 }
87​
88 this.onDisconnected()
89 }
90​
91 hostUpdate(): void {
92 if (this.destroyed) {
93 return
94 }
95​
96 this.isHostUpdating = true
97 try {
98 this.onHostUpdate()
99 } finally {
100 this.isHostUpdating = false
101 }
102 }
103​
104 destroy(): void {
105 if (this.destroyed) {
106 return
107 }
108​
109 this.destroyed = true
110 this.connected = false
111 this.connectionAttempt += 1
112 this.clearContextClient()
113 this.queryClientResolutionState = this.explicitClient
114 ? 'bound'
115 : 'pre-connect'
116 this.onDisconnected()
117​
118 if ('removeController' in this.host) {
119 this.host.removeController(this)
120 }
121 }
122​
123 protected tryGetQueryClient(): QueryClient | undefined {
124 return this.explicitClient ?? this.contextClient
125 }
126​
127 protected getQueryClient(): QueryClient {
128 const client = this.tryGetQueryClient()
129 if (!client) {
130 throw createMissingQueryClientError()
131 }
132​
133 return client
134 }
135​
136 protected setResult(next: TResult): void {
137 if (Object.is(this.result, next)) {
138 return
139 }
140​
141 this.result = next
142 if (!this.isHostUpdating) {
143 this.queueUpdate()
144 }
145 }
146​
147 get current(): TResult {
148 if (this.queryClientResolutionState === 'missing') {
149 throw createMissingQueryClientError()
150 }
151​
152 return this.result
153 }
154​
155 protected get connectedState(): boolean {
156 return this.connected
157 }
158​
159 protected queueUpdate(): void {
160 if (this.updateQueued) {
161 return
162 }
163​
164 this.updateQueued = true
165 queueMicrotask(() => {
166 this.updateQueued = false
167 if (!this.destroyed) {
168 this.host.requestUpdate()
169 }
170 })
171 }
172​
173 private queueQueryClientChanged(): void {
174 if (this.clientChangeQueued) {
175 return
176 }
177​
178 this.clientChangeQueued = true
179 queueMicrotask(() => {
180 this.clientChangeQueued = false
181 if (!this.destroyed) {
182 this.onQueryClientChanged()
183 }
184 })
185 }
186​
187 private beginContextResolution(): void {
188 this.clearContextClient()
189 this.updateQueryClientResolutionState('awaiting-context')
190 }
191​
192 private queueContextResolution(attempt: number): void {
193 queueMicrotask(() => {
194 if (
195 this.destroyed ||
196 !this.connected ||
197 attempt !== this.connectionAttempt ||
198 this.queryClientResolutionState !== 'awaiting-context'
199 ) {
200 return
201 }
202​
203 this.dispatchContextRequest(attempt)
204 this.queueInitialContextResolutionCompletion(attempt)
205 })
206 }
207​
208 private dispatchContextRequest(attempt: number): void {
209 if (!('dispatchEvent' in this.host)) {
210 return
211 }
212​
213 const contextTarget = this.host as ReactiveControllerHost & EventTarget
214 contextTarget.dispatchEvent(
215 new ContextEvent(
216 queryClientContext,
217 contextTarget as unknown as Element,
218 (value, unsubscribe) => {
219 if (
220 this.destroyed ||
221 !this.connected ||
222 attempt !== this.connectionAttempt
223 ) {
224 unsubscribe?.()
225 return
226 }
227​
228 if (
229 this.contextUnsubscribe &&
230 this.contextUnsubscribe !== unsubscribe
231 ) {
232 this.contextUnsubscribe()
233 }
234​
235 const resolutionChanged = this.updateQueryClientResolutionState(
236 value === undefined ? 'missing' : 'bound',
237 )
238 const clientChanged = this.contextClient !== value
239​
240 this.contextClient = value
241 this.contextUnsubscribe = unsubscribe
242​
243 if (resolutionChanged || clientChanged) {
244 this.queueUpdate()
245 this.queueQueryClientChanged()
246 }
247 },
248 true,
249 ),
250 )
251 }
252​
253 private queueInitialContextResolutionCompletion(attempt: number): void {
254 queueMicrotask(() => {
255 if (
256 this.destroyed ||
257 !this.connected ||
258 attempt !== this.connectionAttempt ||
259 this.queryClientResolutionState !== 'awaiting-context'
260 ) {
261 return
262 }
263​
264 if (this.updateQueryClientResolutionState('missing')) {
265 this.queueUpdate()
266 this.queueQueryClientChanged()
267 }
268 })
269 }
270​
271 private clearContextClient(): void {
272 this.contextUnsubscribe?.()
273 this.contextUnsubscribe = undefined
274 this.contextClient = undefined
275 }
276​
277 private updateQueryClientResolutionState(
278 nextState: QueryClientResolutionState,
279 ): boolean {
280 if (this.queryClientResolutionState === nextState) {
281 return false
282 }
283​
284 this.queryClientResolutionState = nextState
285 return true
286 }
287​
288 protected abstract onConnected(): void
289 protected abstract onDisconnected(): void
290 protected abstract onHostUpdate(): void
291 protected abstract onQueryClientChanged(): void