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
61export interface InjectLiveQueryResultWithCollection<
62 TResult extends object = any,
63 TKey extends string | number = string | number,
64 TUtils extends Record<string, any> = {},
65> {
66 state: Signal<Map<TKey, TResult>>
67 data: Signal<Array<TResult>>
68 collection: Signal<Collection<TResult, TKey, TUtils> | null>
69 status: Signal<CollectionStatus | `disabled`>
70 isLoading: Signal<boolean>
71 isReady: Signal<boolean>
72 isIdle: Signal<boolean>
73 isError: Signal<boolean>
74 isCleanedUp: Signal<boolean>
75}
76
77export interface InjectLiveQueryResultWithSingleResultCollection<
78 TResult extends object = any,
79 TKey extends string | number = string | number,
80 TUtils extends Record<string, any> = {},
81> {
82 state: Signal<Map<TKey, TResult>>
83 data: Signal<TResult | undefined>
84 collection: Signal<(Collection<TResult, TKey, TUtils> & SingleResult) | null>
85 status: Signal<CollectionStatus | `disabled`>
86 isLoading: Signal<boolean>
87 isReady: Signal<boolean>
88 isIdle: Signal<boolean>
89 isError: Signal<boolean>
90 isCleanedUp: Signal<boolean>
91}
92
93export function injectLiveQuery<
94 TContext extends Context,
95 TParams extends any,
96>(options: {
97 params: () => TParams
98 query: (args: {
99 params: TParams
100 q: InitialQueryBuilder
101 }) => QueryBuilder<TContext>
102}): InjectLiveQueryResult<TContext>
103export function injectLiveQuery<
104 TContext extends Context,
105 TParams extends any,
106>(options: {
107 params: () => TParams
108 query: (args: {
109 params: TParams
110 q: InitialQueryBuilder
111 }) => QueryBuilder<TContext> | undefined | null
112}): InjectLiveQueryResult<TContext>
113export function injectLiveQuery<TContext extends Context>(
114 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
115): InjectLiveQueryResult<TContext>
116export function injectLiveQuery<TContext extends Context>(
117 queryFn: (
118 q: InitialQueryBuilder,
119 ) => QueryBuilder<TContext> | undefined | null,
120): InjectLiveQueryResult<TContext>
121export function injectLiveQuery<TContext extends Context>(
122 config: LiveQueryCollectionConfig<TContext>,
123): InjectLiveQueryResult<TContext>
124// Pre-created collection without singleResult
125export function injectLiveQuery<
126 TResult extends object,
127 TKey extends string | number,
128 TUtils extends Record<string, any>,
129>(
130 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
131): InjectLiveQueryResultWithCollection<TResult, TKey, TUtils>
132// Pre-created collection with singleResult
133export function injectLiveQuery<
134 TResult extends object,
135 TKey extends string | number,
136 TUtils extends Record<string, any>,
137>(
138 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
139): InjectLiveQueryResultWithSingleResultCollection<TResult, TKey, TUtils>
140export function injectLiveQuery(opts: any) {
141 assertInInjectionContext(injectLiveQuery)
142 const destroyRef = inject(DestroyRef)
143
144 const collection = computed(() => {
145 // Check if it's an existing collection
146 if (isCollection(opts)) {
147 return opts
148 }
149
150 if (typeof opts === `function`) {
151 // Check if query function returns null/undefined (disabled query)
152 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
153 const result = opts(queryBuilder)
154
155 if (result === undefined || result === null) {
156 // Disabled query - return null
157 return null
158 }
159
160 return createLiveQueryCollection({
161 query: opts,
162 startSync: true,
163 gcTime: 0,
164 })
165 }
166
167 // Check if it's reactive query options
168 const isReactiveQueryOptions =
169 opts &&
170 typeof opts === `object` &&
171 typeof opts.query === `function` &&
172 typeof opts.params === `function`
173
174 if (isReactiveQueryOptions) {
175 const { params, query } = opts
176 const currentParams = params()
177
178 // Check if query function returns null/undefined (disabled query)
179 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
180 const result = query({ params: currentParams, q: queryBuilder })
181
182 if (result === undefined || result === null) {
183 // Disabled query - return null
184 return null
185 }
186
187 return createLiveQueryCollection({
188 query: () => result,
189 startSync: true,
190 gcTime: 0,
191 })
192 }
193
194 // Handle LiveQueryCollectionConfig objects. Default startSync/gcTime to
195 // match the query-fn and reactive-options paths, but let an explicit value
196 // in the config win — otherwise a bare `{ query }` never syncs.
197 if (opts && typeof opts === `object` && typeof opts.query === `function`) {
198 return createLiveQueryCollection({ startSync: true, gcTime: 0, ...opts })
199 }
200
201 throw new Error(`Invalid options provided to injectLiveQuery`)
202 })
203
204 const state = signal(new Map<string | number, any>())
205 const internalData = signal<Array<any>>([])
206 const status = signal<CollectionStatus | `disabled`>(
207 collection() ? `idle` : `disabled`,
208 )
209
210 // Returns single item for singleResult collections, array otherwise
211 const data = computed(() => {
212 const currentCollection = collection()
213 if (!currentCollection) {
214 return internalData()
215 }
216 return isSingleResultCollection(currentCollection)
217 ? internalData()[0]
218 : internalData()
219 })
220
221 const syncDataFromCollection = (
222 currentCollection: Collection<any, any, any>,
223 ) => {
224 const newState = new Map(currentCollection.entries())
225 const newData = Array.from(currentCollection.values())
226
227 state.set(newState)
228 internalData.set(newData)
229 status.set(currentCollection.status)
230 }
231
232 let unsub: (() => void) | null = null
233 const cleanup = () => {
234 unsub?.()
235 unsub = null
236 }
237
238 effect((onCleanup) => {
239 const currentCollection = collection()
240
241 // Handle null collection (disabled query)
242 if (!currentCollection) {
243 status.set(`disabled` as const)
244 state.set(new Map())
245 internalData.set([])
246 cleanup()
247 return
248 }
249
250 cleanup()
251
252 // The shared observer owns sync start, subscription, the ready-race, and
253 // status transitions; Angular re-reads the whole collection on each notify
254 // (wholesale) into its signals.
255 // Angular re-reads the collection on notify; wholesale mode preserves its
256 // pre-observer loading policy (no initial-state snapshot request).
257 const observer = createLiveQueryObserver(currentCollection, {
258 mode: `wholesale`,
259 })
260
261 const unsubscribe = observer.subscribe(() => {
262 syncDataFromCollection(currentCollection)
263 })
264 // Wholesale attach suppresses listener calls raised by synchronous sync
265 // startup. Read once after subscribe returns to capture that final state.
266 syncDataFromCollection(currentCollection)
267 unsub = () => {
268 unsubscribe()
269 observer.dispose()
270 }
271
272 onCleanup(cleanup)
273 })
274
275 destroyRef.onDestroy(cleanup)
276
277 return {
278 state,
279 data,
280 // Loosely typed so the impl return stays compatible with every overload
281 // (the shared `isCollection` guard narrows the computed to `Collection | null`).
282 collection: collection as Signal<any>,
283 status,
284 isLoading: computed(() => status() === `loading`),
285 isReady: computed(() => status() === `ready` || status() === `disabled`),
286 isIdle: computed(() => status() === `idle`),
287 isError: computed(() => status() === `error`),
288 isCleanedUp: computed(() => status() === `cleaned-up`),
289 }
290}