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