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 { createLiveQueryCollection } from "@tanstack/db"
10import type {
11 ChangeMessage,
12 Collection,
13 CollectionStatus,
14 Context,
15 GetResult,
16 InitialQueryBuilder,
17 LiveQueryCollectionConfig,
18 QueryBuilder,
19} from "@tanstack/db"
20import type { Signal } from "@angular/core"
21
22/**
23 * The result of calling `injectLiveQuery`.
24 * Contains reactive signals for the query state and data.
25 */
26export interface InjectLiveQueryResult<
27 TResult extends object = any,
28 TKey extends string | number = string | number,
29 TUtils extends Record<string, any> = {},
30> {
31 /** A signal containing the complete state map of results keyed by their ID */
32 state: Signal<Map<TKey, TResult>>
33 /** A signal containing the results as an array */
34 data: Signal<Array<TResult>>
35 /** A signal containing the underlying collection instance */
36 collection: Signal<Collection<TResult, TKey, TUtils>>
37 /** A signal containing the current status of the collection */
38 status: Signal<CollectionStatus>
39 /** A signal indicating whether the collection is currently loading */
40 isLoading: Signal<boolean>
41 /** A signal indicating whether the collection is ready */
42 isReady: Signal<boolean>
43 /** A signal indicating whether the collection is idle */
44 isIdle: Signal<boolean>
45 /** A signal indicating whether the collection has an error */
46 isError: Signal<boolean>
47 /** A signal indicating whether the collection has been cleaned up */
48 isCleanedUp: Signal<boolean>
49}
50
51export function injectLiveQuery<
52 TContext extends Context,
53 TParams extends any,
54>(options: {
55 params: () => TParams
56 query: (args: {
57 params: TParams
58 q: InitialQueryBuilder
59 }) => QueryBuilder<TContext>
60}): InjectLiveQueryResult<GetResult<TContext>>
61export function injectLiveQuery<TContext extends Context>(
62 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>
63): InjectLiveQueryResult<GetResult<TContext>>
64export function injectLiveQuery<TContext extends Context>(
65 config: LiveQueryCollectionConfig<TContext>
66): InjectLiveQueryResult<GetResult<TContext>>
67export function injectLiveQuery<
68 TResult extends object,
69 TKey extends string | number,
70 TUtils extends Record<string, any>,
71>(
72 liveQueryCollection: Collection<TResult, TKey, TUtils>
73): InjectLiveQueryResult<TResult, TKey, TUtils>
74export function injectLiveQuery(opts: any) {
75 assertInInjectionContext(injectLiveQuery)
76 const destroyRef = inject(DestroyRef)
77
78 const collection = computed(() => {
79 // Check if it's an existing collection
80 const isExistingCollection =
81 opts &&
82 typeof opts === `object` &&
83 typeof opts.subscribeChanges === `function` &&
84 typeof opts.startSyncImmediate === `function` &&
85 typeof opts.id === `string`
86
87 if (isExistingCollection) {
88 return opts
89 }
90
91 if (typeof opts === `function`) {
92 return createLiveQueryCollection({
93 query: opts,
94 startSync: true,
95 gcTime: 0,
96 })
97 }
98
99 // Check if it's reactive query options
100 const isReactiveQueryOptions =
101 opts &&
102 typeof opts === `object` &&
103 typeof opts.query === `function` &&
104 typeof opts.params === `function`
105
106 if (isReactiveQueryOptions) {
107 const { params, query } = opts
108 const currentParams = params()
109 return createLiveQueryCollection({
110 query: (q) => query({ params: currentParams, q }),
111 startSync: true,
112 gcTime: 0,
113 })
114 }
115
116 // Handle LiveQueryCollectionConfig objects
117 if (opts && typeof opts === `object` && typeof opts.query === `function`) {
118 return createLiveQueryCollection(opts)
119 }
120
121 throw new Error(`Invalid options provided to injectLiveQuery`)
122 })
123
124 const state = signal(new Map<string | number, any>())
125 const data = signal<Array<any>>([])
126 const status = signal<CollectionStatus>(`idle`)
127
128 const syncDataFromCollection = (
129 currentCollection: Collection<any, any, any>
130 ) => {
131 const newState = new Map(currentCollection.entries())
132 const newData = Array.from(currentCollection.values())
133
134 state.set(newState)
135 data.set(newData)
136 status.set(currentCollection.status)
137 }
138
139 let unsub: (() => void) | null = null
140 const cleanup = () => {
141 unsub?.()
142 unsub = null
143 }
144
145 effect((onCleanup) => {
146 const currentCollection = collection()
147
148 if (!currentCollection) {
149 return
150 }
151
152 cleanup()
153
154 // Initialize immediately with current state
155 syncDataFromCollection(currentCollection)
156
157 // Start sync if idle
158 if (currentCollection.status === `idle`) {
159 currentCollection.startSyncImmediate()
160 // Update status after starting sync
161 status.set(currentCollection.status)
162 }
163
164 // Subscribe to changes
165 const subscription = currentCollection.subscribeChanges(
166 (_: Array<ChangeMessage<any>>) => {
167 syncDataFromCollection(currentCollection)
168 }
169 )
170 unsub = subscription.unsubscribe.bind(subscription)
171
172 // Handle ready state
173 currentCollection.onFirstReady(() => {
174 status.set(currentCollection.status)
175 })
176
177 onCleanup(cleanup)
178 })
179
180 destroyRef.onDestroy(cleanup)
181
182 return {
183 state,
184 data,
185 collection,
186 status,
187 isLoading: computed(
188 () => status() === `loading` || status() === `initialCommit`
189 ),
190 isReady: computed(() => status() === `ready`),
191 isIdle: computed(() => status() === `idle`),
192 isError: computed(() => status() === `error`),
193 isCleanedUp: computed(() => status() === `cleaned-up`),
194 }
195}