Open History to see the last commit
1// eslint-disable-next-line import/no-duplicates -- See https://github.com/un-ts/eslint-plugin-import-x/issues/308
2import { flushSync, untrack } from "svelte"
3// eslint-disable-next-line import/no-duplicates -- See https://github.com/un-ts/eslint-plugin-import-x/issues/308
4import { SvelteMap } from "svelte/reactivity"
5import { createLiveQueryCollection } from "@tanstack/db"
6import type {
7 ChangeMessage,
8 Collection,
9 CollectionStatus,
10 Context,
11 GetResult,
12 InitialQueryBuilder,
13 LiveQueryCollectionConfig,
14 QueryBuilder,
15} from "@tanstack/db"
16
17/**
18 * Return type for useLiveQuery hook
19 * @property state - Reactive Map of query results (key → item)
20 * @property data - Reactive array of query results in order
21 * @property collection - The underlying query collection instance
22 * @property status - Current query status
23 * @property isLoading - True while initial query data is loading
24 * @property isReady - True when query has received first data and is ready
25 * @property isIdle - True when query hasn't started yet
26 * @property isError - True when query encountered an error
27 * @property isCleanedUp - True when query has been cleaned up
28 */
29export interface UseLiveQueryReturn<T extends object> {
30 state: Map<string | number, T>
31 data: Array<T>
32 collection: Collection<T, string | number, {}>
33 status: CollectionStatus
34 isLoading: boolean
35 isReady: boolean
36 isIdle: boolean
37 isError: boolean
38 isCleanedUp: boolean
39}
40
41export interface UseLiveQueryReturnWithCollection<
42 T extends object,
43 TKey extends string | number,
44 TUtils extends Record<string, any>,
45> {
46 state: Map<TKey, T>
47 data: Array<T>
48 collection: Collection<T, TKey, TUtils>
49 status: CollectionStatus
50 isLoading: boolean
51 isReady: boolean
52 isIdle: boolean
53 isError: boolean
54 isCleanedUp: boolean
55}
56
57type MaybeGetter<T> = T | (() => T)
58
59function toValue<T>(value: MaybeGetter<T>): T {
60 if (typeof value === `function`) {
61 return (value as () => T)()
62 }
63 return value
64}
65
66/**
67 * Create a live query using a query function
68 * @param queryFn - Query function that defines what data to fetch
69 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
70 * @returns Reactive object with query data, state, and status information
71 * @example
72 * // Basic query with object syntax
73 * const todosQuery = useLiveQuery((q) =>
74 * q.from({ todos: todosCollection })
75 * .where(({ todos }) => eq(todos.completed, false))
76 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
77 * )
78 *
79 * @example
80 * // With reactive dependencies
81 * let minPriority = $state(5)
82 * const todosQuery = useLiveQuery(
83 * (q) => q.from({ todos: todosCollection })
84 * .where(({ todos }) => gt(todos.priority, minPriority)),
85 * [() => minPriority] // Re-run when minPriority changes
86 * )
87 *
88 * @example
89 * // Join pattern
90 * const issuesQuery = useLiveQuery((q) =>
91 * q.from({ issues: issueCollection })
92 * .join({ persons: personCollection }, ({ issues, persons }) =>
93 * eq(issues.userId, persons.id)
94 * )
95 * .select(({ issues, persons }) => ({
96 * id: issues.id,
97 * title: issues.title,
98 * userName: persons.name
99 * }))
100 * )
101 *
102 * @example
103 * // Handle loading and error states in template
104 * const todosQuery = useLiveQuery((q) =>
105 * q.from({ todos: todoCollection })
106 * )
107 *
108 * // In template:
109 * // {#if todosQuery.isLoading}
110 * // <div>Loading...</div>
111 * // {:else if todosQuery.isError}
112 * // <div>Error: {todosQuery.status}</div>
113 * // {:else}
114 * // <ul>
115 * // {#each todosQuery.data as todo (todo.id)}
116 * // <li>{todo.text}</li>
117 * // {/each}
118 * // </ul>
119 * // {/if}
120 */
121// Overload 1: Accept just the query function
122export function useLiveQuery<TContext extends Context>(
123 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
124 deps?: Array<() => unknown>
125): UseLiveQueryReturn<GetResult<TContext>>
126
127/**
128 * Create a live query using configuration object
129 * @param config - Configuration object with query and options
130 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
131 * @returns Reactive object with query data, state, and status information
132 * @example
133 * // Basic config object usage
134 * const todosQuery = useLiveQuery({
135 * query: (q) => q.from({ todos: todosCollection }),
136 * gcTime: 60000
137 * })
138 *
139 * @example
140 * // With reactive dependencies
141 * let filter = $state('active')
142 * const todosQuery = useLiveQuery({
143 * query: (q) => q.from({ todos: todosCollection })
144 * .where(({ todos }) => eq(todos.status, filter))
145 * }, [() => filter])
146 *
147 * @example
148 * // Handle all states uniformly
149 * const itemsQuery = useLiveQuery({
150 * query: (q) => q.from({ items: itemCollection })
151 * })
152 *
153 * // In template:
154 * // {#if itemsQuery.isLoading}
155 * // <div>Loading...</div>
156 * // {:else if itemsQuery.isError}
157 * // <div>Something went wrong</div>
158 * // {:else if !itemsQuery.isReady}
159 * // <div>Preparing...</div>
160 * // {:else}
161 * // <div>{itemsQuery.data.length} items loaded</div>
162 * // {/if}
163 */
164// Overload 2: Accept config object
165export function useLiveQuery<TContext extends Context>(
166 config: LiveQueryCollectionConfig<TContext>,
167 deps?: Array<() => unknown>
168): UseLiveQueryReturn<GetResult<TContext>>
169
170/**
171 * Subscribe to an existing query collection (can be reactive)
172 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a getter)
173 * @returns Reactive object with query data, state, and status information
174 * @example
175 * // Using pre-created query collection
176 * const myLiveQuery = createLiveQueryCollection((q) =>
177 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
178 * )
179 * const queryResult = useLiveQuery(myLiveQuery)
180 *
181 * @example
182 * // Reactive query collection reference
183 * let selectedQuery = $state(todosQuery)
184 * const queryResult = useLiveQuery(() => selectedQuery)
185 *
186 * // Switch queries reactively
187 * selectedQuery = archiveQuery
188 *
189 * @example
190 * // Access query collection methods directly
191 * const queryResult = useLiveQuery(existingQuery)
192 *
193 * // Use underlying collection for mutations
194 * const handleToggle = (id) => {
195 * queryResult.collection.update(id, draft => { draft.completed = !draft.completed })
196 * }
197 *
198 * @example
199 * // Handle states consistently
200 * const queryResult = useLiveQuery(sharedQuery)
201 *
202 * // In template:
203 * // {#if queryResult.isLoading}
204 * // <div>Loading...</div>
205 * // {:else if queryResult.isError}
206 * // <div>Error loading data</div>
207 * // {:else}
208 * // {#each queryResult.data as item (item.id)}
209 * // <Item {...item} />
210 * // {/each}
211 * // {/if}
212 */
213// Overload 3: Accept pre-created live query collection (can be reactive)
214export function useLiveQuery<
215 TResult extends object,
216 TKey extends string | number,
217 TUtils extends Record<string, any>,
218>(
219 liveQueryCollection: MaybeGetter<Collection<TResult, TKey, TUtils>>
220): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>
221
222// Implementation
223export function useLiveQuery(
224 configOrQueryOrCollection: any,
225 deps: Array<() => unknown> = []
226): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
227 const collection = $derived.by(() => {
228 // First check if the original parameter might be a getter
229 // by seeing if toValue returns something different than the original
230 let unwrappedParam = configOrQueryOrCollection
231 try {
232 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
233 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
234 unwrappedParam = potentiallyUnwrapped
235 }
236 } catch {
237 // If toValue fails, use original parameter
238 unwrappedParam = configOrQueryOrCollection
239 }
240
241 // Check if it's already a collection by checking for specific collection methods
242 const isCollection =
243 unwrappedParam &&
244 typeof unwrappedParam === `object` &&
245 typeof unwrappedParam.subscribeChanges === `function` &&
246 typeof unwrappedParam.startSyncImmediate === `function` &&
247 typeof unwrappedParam.id === `string`
248
249 if (isCollection) {
250 // It's already a collection, ensure sync is started for Svelte helpers
251 // Only start sync if the collection is in idle state
252 if (unwrappedParam.status === `idle`) {
253 unwrappedParam.startSyncImmediate()
254 }
255 return unwrappedParam
256 }
257
258 // Reference deps to make computed reactive to them
259 deps.forEach((dep) => toValue(dep))
260
261 // Ensure we always start sync for Svelte helpers
262 if (typeof unwrappedParam === `function`) {
263 return createLiveQueryCollection({
264 query: unwrappedParam,
265 startSync: true,
266 })
267 } else {
268 return createLiveQueryCollection({
269 ...unwrappedParam,
270 startSync: true,
271 })
272 }
273 })
274
275 // Reactive state that gets updated granularly through change events
276 const state = new SvelteMap<string | number, any>()
277
278 // Reactive data array that maintains sorted order
279 let internalData = $state<Array<any>>([])
280
281 // Track collection status reactively
282 let status = $state(collection.status)
283
284 // Helper to sync data array from collection in correct order
285 const syncDataFromCollection = (
286 currentCollection: Collection<any, any, any>
287 ) => {
288 untrack(() => {
289 internalData = []
290 internalData.push(...Array.from(currentCollection.values()))
291 })
292 }
293
294 // Track current unsubscribe function
295 let currentUnsubscribe: (() => void) | null = null
296
297 // Watch for collection changes and subscribe to updates
298 $effect(() => {
299 const currentCollection = collection
300
301 // Update status state whenever the effect runs
302 status = currentCollection.status
303
304 // Clean up previous subscription
305 if (currentUnsubscribe) {
306 currentUnsubscribe()
307 }
308
309 // Initialize state with current collection data
310 untrack(() => {
311 state.clear()
312 for (const [key, value] of currentCollection.entries()) {
313 state.set(key, value)
314 }
315 })
316
317 // Initialize data array in correct order
318 syncDataFromCollection(currentCollection)
319
320 // Listen for the first ready event to catch status transitions
321 // that might not trigger change events (fixes async status transition bug)
322 currentCollection.onFirstReady(() => {
323 // Use flushSync to ensure Svelte reactivity updates properly
324 flushSync(() => {
325 status = currentCollection.status
326 })
327 })
328
329 // Subscribe to collection changes with granular updates
330 const subscription = currentCollection.subscribeChanges(
331 (changes: Array<ChangeMessage<any>>) => {
332 // Apply each change individually to the reactive state
333 untrack(() => {
334 for (const change of changes) {
335 switch (change.type) {
336 case `insert`:
337 case `update`:
338 state.set(change.key, change.value)
339 break
340 case `delete`:
341 state.delete(change.key)
342 break
343 }
344 }
345 })
346
347 // Update the data array to maintain sorted order
348 syncDataFromCollection(currentCollection)
349 // Update status state on every change
350 status = currentCollection.status
351 },
352 {
353 includeInitialState: true,
354 }
355 )
356
357 currentUnsubscribe = subscription.unsubscribe.bind(subscription)
358
359 // Preload collection data if not already started
360 if (currentCollection.status === `idle`) {
361 currentCollection.preload().catch(console.error)
362 }
363
364 // Cleanup when effect is invalidated
365 return () => {
366 if (currentUnsubscribe) {
367 currentUnsubscribe()
368 currentUnsubscribe = null
369 }
370 }
371 })
372
373 return {
374 get state() {
375 return state
376 },
377 get data() {
378 return internalData
379 },
380 get collection() {
381 return collection
382 },
383 get status() {
384 return status
385 },
386 get isLoading() {
387 return status === `loading` || status === `initialCommit`
388 },
389 get isReady() {
390 return status === `ready`
391 },
392 get isIdle() {
393 return status === `idle`
394 },
395 get isError() {
396 return status === `error`
397 },
398 get isCleanedUp() {
399 return status === `cleaned-up`
400 },
401 }
402}