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