Open History to see the last commit
1import { replaceEqualDeep } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { BaseController } from './controllers/BaseController.js'
4import type { Accessor, ValueAccessor } from './accessor.js'
5import type {
6 Mutation,
7 MutationFilters,
8 MutationState,
9 QueryClient,
10} from '@tanstack/query-core'
11import type { ReactiveControllerHost } from 'lit'
12β
13/** Options accepted by `useMutationState`. */
14export type MutationStateOptions<TResult> = {
15 /** Filters used to select mutations from the mutation cache. */
16 filters?: Accessor<MutationFilters>
17 /** Maps each matching mutation to the value returned by the accessor. */
18 select?: (mutation: Mutation) => TResult
19}
20β
21/**
22 * Accessor returned by `useMutationState`.
23 *
24 * Call the accessor or read its `current` property to get the selected state
25 * for matching mutations.
26 */
27export type MutationStateAccessor<TResult> = ValueAccessor<Array<TResult>> & {
28 /** Removes the controller from its Lit host and unsubscribes observers. */
29 destroy: () => void
30}
31β
32class MutationStateController<TResult> extends BaseController<Array<TResult>> {
33 private queryClient: QueryClient | undefined
34 private unsubscribe: (() => void) | undefined
35β
36 constructor(
37 host: ReactiveControllerHost,
38 private readonly options: MutationStateOptions<TResult>,
39 queryClient?: QueryClient,
40 ) {
41 super(host, [], queryClient)
42β
43 if (!queryClient) {
44 return
45 }
46β
47 this.queryClient = queryClient
48 this.result = this.computeState()
49 }
50β
51 protected override onConnected(): void {
52 if (!this.syncClient()) {
53 this.setMutationState([])
54 return
55 }
56β
57 this.subscribe()
58 this.setMutationState(this.computeState())
59 }
60β
61 protected override onDisconnected(): void {
62 this.unsubscribe?.()
63 this.unsubscribe = undefined
64 this.syncClient()
65 }
66β
67 protected override onHostUpdate(): void {
68 if (!this.shouldRefreshOnHostUpdate()) {
69 return
70 }
71β
72 this.setMutationState(this.syncClient() ? this.computeState() : [])
73 }
74β
75 protected override onQueryClientChanged(): void {
76 if (!this.syncClient()) {
77 this.setMutationState([])
78 return
79 }
80β
81 if (this.connectedState) {
82 this.subscribe()
83 this.setMutationState(this.computeState())
84 }
85 }
86β
87 private syncClient(): boolean {
88 const nextClient = this.tryGetQueryClient()
89 if (!nextClient) {
90 this.unsubscribe?.()
91 this.unsubscribe = undefined
92 this.queryClient = undefined
93 return false
94 }
95β
96 if (nextClient === this.queryClient) {
97 return true
98 }
99β
100 this.unsubscribe?.()
101 this.unsubscribe = undefined
102 this.queryClient = nextClient
103 return true
104 }
105β
106 private subscribe(): void {
107 if (!this.queryClient) {
108 return
109 }
110β
111 if (this.unsubscribe) {
112 return
113 }
114β
115 this.unsubscribe = this.queryClient.getMutationCache().subscribe(() => {
116 this.setMutationState(this.computeState())
117 })
118 }
119β
120 private setMutationState(next: Array<TResult>): void {
121 this.setResult(replaceEqualDeep(this.result, next))
122 }
123β
124 private shouldRefreshOnHostUpdate(): boolean {
125 return (
126 typeof this.options.filters === 'function' ||
127 typeof this.options.select === 'function'
128 )
129 }
130β
131 private computeState(): Array<TResult> {
132 if (!this.queryClient) {
133 return []
134 }
135β
136 const filters = this.options.filters
137 ? readAccessor(this.options.filters)
138 : undefined
139β
140 const select = this.options.select
141 const mutations = this.queryClient.getMutationCache().findAll(filters)
142β
143 return mutations.map((mutation) => {
144 if (select) {
145 return select(mutation)
146 }
147β
148 return mutation.state as TResult
149 })
150 }
151}
152β
153/**
154 * Creates a Lit reactive controller that selects state from matching mutations
155 * in the mutation cache.
156 *
157 * When `options.filters` is a function, it is re-read during host updates so
158 * the selection can follow reactive host state. If `queryClient` is omitted,
159 * the controller resolves the client from the nearest connected
160 * `QueryClientProvider`.
161 *
162 * @example
163 * ```ts
164 * import { LitElement, html } from 'lit'
165 * import { useMutationState } from '@tanstack/lit-query'
166 *
167 * class PendingUploads extends LitElement {
168 * private readonly uploads = useMutationState(this, {
169 * filters: { mutationKey: ['upload'], status: 'pending' },
170 * select: (mutation) => mutation.state.variables as File,
171 * })
172 *
173 * render() {
174 * return html`<span>${this.uploads().length} uploads pending</span>`
175 * }
176 * }
177 * ```
178 *
179 * @param host - The Lit reactive controller host that owns the mutation cache
180 * subscription.
181 * @param options - Mutation state filters and optional selector.
182 * @param queryClient - Optional explicit query client. Provide this for
183 * controllers that should not resolve a client from Lit context.
184 * @returns An accessor for the selected mutation state array.
185 */
186export function useMutationState<
187 TResult = MutationState<unknown, unknown, unknown, unknown>,
188>(
189 host: ReactiveControllerHost,
190 options: MutationStateOptions<TResult> = {},
191 queryClient?: QueryClient,
192): MutationStateAccessor<TResult> {
193 const controller = new MutationStateController(host, options, queryClient)
194 return Object.assign(
195 createValueAccessor(() => controller.current),
196 {
197 destroy: () => controller.destroy(),
198 },
199 )
200}