Open History to see the last commit
1import {
2 DestroyRef,
3 assertInInjectionContext,
4 computed,
5 effect,
6 inject,
7 signal,
8} from '@angular/core'
9import {
10 BaseQueryBuilder,
11 createLiveQueryCollection,
12 createLiveQueryObserver,
13 isCollection,
14 isSingleResultCollection,
15} from '@tanstack/db'
16import type {
17 Collection,
18 CollectionStatus,
19 Context,
20 GetResult,
21 InferResultType,
22 InitialQueryBuilder,
23 LiveQueryCollectionConfig,
24 NonSingleResult,
25 QueryBuilder,
26 SingleResult,
27} from '@tanstack/db'
28import type { Signal } from '@angular/core'
29
30export * from '@tanstack/db'
31
32/**
33 * The result of calling `injectLiveQuery`.
34 * Contains reactive signals for the query state and data.
35 */
36export interface InjectLiveQueryResult<TContext extends Context> {
37 /** A signal containing the complete state map of results keyed by their ID */
38 state: Signal<Map<string | number, GetResult<TContext>>>
39 /** A signal containing the results as an array, or single result for findOne queries */
40 data: Signal<InferResultType<TContext>>
41 /** A signal containing the underlying collection instance (null for disabled queries) */
42 collection: Signal<Collection<
43 GetResult<TContext>,
44 string | number,
45 {}
46 > | null>
47 /** A signal containing the current status of the collection */
48 status: Signal<CollectionStatus | `disabled`>
49 /** A signal indicating whether the collection is currently loading */
50 isLoading: Signal<boolean>
51 /** A signal indicating whether the collection is ready */
52 isReady: Signal<boolean>
53 /** A signal indicating whether the collection is idle */
54 isIdle: Signal<boolean>
55 /** A signal indicating whether the collection has an error */
56 isError: Signal<boolean>
57 /** A signal indicating whether the collection has been cleaned up */
58 isCleanedUp: Signal<boolean>
59}
60
61type InferConditionalResultType<TContext extends Context> =
62 TContext extends SingleResult
63 ? InferResultType<TContext> | []
64 : InferResultType<TContext>
65
66export type InjectConditionalLiveQueryResult<TContext extends Context> = Omit<
67 InjectLiveQueryResult<TContext>,
68 `data`
69> & {
70 data: Signal<InferConditionalResultType<TContext>>
71}
72
73export interface InjectLiveQueryResultWithCollection<
74 TResult extends object = any,
75 TKey extends string | number = string | number,
76 TUtils extends Record<string, any> = {},
77> {
78 state: Signal<Map<TKey, TResult>>
79 data: Signal<Array<TResult>>
80 collection: Signal<Collection<TResult, TKey, TUtils> | null>
81 status: Signal<CollectionStatus | `disabled`>
82 isLoading: Signal<boolean>
83 isReady: Signal<boolean>
84 isIdle: Signal<boolean>
85 isError: Signal<boolean>
86 isCleanedUp: Signal<boolean>
87}
88
89export interface InjectLiveQueryResultWithSingleResultCollection<
90 TResult extends object = any,
91 TKey extends string | number = string | number,
92 TUtils extends Record<string, any> = {},
93> {
94 state: Signal<Map<TKey, TResult>>
95 data: Signal<TResult | undefined>
96 collection: Signal<(Collection<TResult, TKey, TUtils> & SingleResult) | null>
97 status: Signal<CollectionStatus | `disabled`>
98 isLoading: Signal<boolean>
99 isReady: Signal<boolean>
100 isIdle: Signal<boolean>
101 isError: Signal<boolean>
102 isCleanedUp: Signal<boolean>
103}
104
105export function injectLiveQuery<
106 TContext extends Context,
107 TParams extends any,
108>(options: {
109 params: () => TParams
110 query: (args: {
111 params: TParams
112 q: InitialQueryBuilder
113 }) => QueryBuilder<TContext>
114}): InjectLiveQueryResult<TContext>
115export function injectLiveQuery<
116 TContext extends Context,
117 TParams extends any,
118>(options: {
119 params: () => TParams
120 query: (args: {
121 params: TParams
122 q: InitialQueryBuilder
123 }) => QueryBuilder<TContext> | undefined | null
124}): InjectConditionalLiveQueryResult<TContext>
125export function injectLiveQuery<TContext extends Context>(
126 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
127): InjectLiveQueryResult<TContext>
128export function injectLiveQuery<TContext extends Context>(
129 queryFn: (
130 q: InitialQueryBuilder,
131 ) => QueryBuilder<TContext> | undefined | null,
132): InjectConditionalLiveQueryResult<TContext>
133export function injectLiveQuery<TContext extends Context>(
134 config: LiveQueryCollectionConfig<TContext>,
135): InjectLiveQueryResult<TContext>
136// Pre-created collection without singleResult
137export function injectLiveQuery<
138 TResult extends object,
139 TKey extends string | number,
140 TUtils extends Record<string, any>,
141>(
142 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
143): InjectLiveQueryResultWithCollection<TResult, TKey, TUtils>
144// Pre-created collection with singleResult
145export function injectLiveQuery<
146 TResult extends object,
147 TKey extends string | number,
148 TUtils extends Record<string, any>,
149>(
150 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
151): InjectLiveQueryResultWithSingleResultCollection<TResult, TKey, TUtils>
152export function injectLiveQuery(opts: any) {
153 assertInInjectionContext(injectLiveQuery)
154 const destroyRef = inject(DestroyRef)
155
156 const collection = computed(() => {
157 // Check if it's an existing collection
158 if (isCollection(opts)) {
159 return opts
160 }
161
162 if (typeof opts === `function`) {
163 // Check if query function returns null/undefined (disabled query)
164 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
165 const result = opts(queryBuilder)
166
167 if (result === undefined || result === null) {
168 // Disabled query - return null
169 return null
170 }
171
172 return createLiveQueryCollection({
173 query: opts,
174 startSync: true,
175 gcTime: 0,
176 })
177 }
178
179 // Check if it's reactive query options
180 const isReactiveQueryOptions =
181 opts &&
182 typeof opts === `object` &&
183 typeof opts.query === `function` &&
184 typeof opts.params === `function`
185
186 if (isReactiveQueryOptions) {
187 const { params, query } = opts
188 const currentParams = params()
189
190 // Check if query function returns null/undefined (disabled query)
191 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
192 const result = query({ params: currentParams, q: queryBuilder })
193
194 if (result === undefined || result === null) {
195 // Disabled query - return null
196 return null
197 }
198
199 return createLiveQueryCollection({
200 query: () => result,
201 startSync: true,
202 gcTime: 0,
203 })
204 }
205
206 // Handle LiveQueryCollectionConfig objects. Default startSync/gcTime to
207 // match the query-fn and reactive-options paths, but let an explicit value
208 // in the config win — otherwise a bare `{ query }` never syncs.
209 if (opts && typeof opts === `object` && typeof opts.query === `function`) {
210 return createLiveQueryCollection({ startSync: true, gcTime: 0, ...opts })
211 }
212
213 throw new Error(`Invalid options provided to injectLiveQuery`)
214 })
215
216 const state = signal(new Map<string | number, any>())
217 const internalData = signal<Array<any>>([])
218 const status = signal<CollectionStatus | `disabled`>(
219 collection() ? `idle` : `disabled`,
220 )
221
222 // Returns single item for singleResult collections, array otherwise
223 const data = computed(() => {
224 const currentCollection = collection()
225 if (!currentCollection) {
226 return internalData()
227 }
228 return isSingleResultCollection(currentCollection)
229 ? internalData()[0]
230 : internalData()
231 })
232
233 const syncDataFromCollection = (
234 currentCollection: Collection<any, any, any>,
235 ) => {
236 const newState = new Map(currentCollection.entries())
237 const newData = Array.from(currentCollection.values())
238
239 state.set(newState)
240 internalData.set(newData)
241 status.set(currentCollection.status)
242 }
243
244 let unsub: (() => void) | null = null
245 const cleanup = () => {
246 unsub?.()
247 unsub = null
248 }
249
250 effect((onCleanup) => {
251 const currentCollection = collection()
252
253 // Handle null collection (disabled query)
254 if (!currentCollection) {
255 status.set(`disabled` as const)
256 state.set(new Map())
257 internalData.set([])
258 cleanup()
259 return
260 }
261
262 cleanup()
263
264 // The shared observer owns sync start, subscription, the ready-race, and
265 // status transitions; Angular re-reads the whole collection on each notify
266 // (wholesale) into its signals.
267 // Angular re-reads the collection on notify; wholesale mode preserves its
268 // pre-observer loading policy (no initial-state snapshot request).
269 const observer = createLiveQueryObserver(currentCollection, {
270 mode: `wholesale`,
271 })
272
273 const unsubscribe = observer.subscribe(() => {
274 syncDataFromCollection(currentCollection)
275 })
276 // Wholesale attach suppresses listener calls raised by synchronous sync
277 // startup. Read once after subscribe returns to capture that final state.
278 syncDataFromCollection(currentCollection)
279 unsub = () => {
280 unsubscribe()
281 observer.dispose()
282 }
283
284 onCleanup(cleanup)
285 })
286
287 destroyRef.onDestroy(cleanup)
288
289 return {
290 state,
291 data,
292 // Loosely typed so the impl return stays compatible with every overload
293 // (the shared `isCollection` guard narrows the computed to `Collection | null`).
294 collection: collection as Signal<any>,
295 status,
296 isLoading: computed(() => status() === `loading`),
297 isReady: computed(() => status() === `ready` || status() === `disabled`),
298 isIdle: computed(() => status() === `idle`),
299 isError: computed(() => status() === `error`),
300 isCleanedUp: computed(() => status() === `cleaned-up`),
301 }
302}