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