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 { 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 {
6 BaseQueryBuilder,
7 UnhashableQueryIRError,
8 createLiveQueryCollection,
9 createLiveQueryObserver,
10 getLiveQueryHash,
11 getPublicCollection,
12 getStableValueHash,
13 isCollection,
14 isSingleResultCollection,
15 prepareLiveQueryValue,
16 resolveLiveQueryValue,
17 resumeDeferredLiveQueryCollections,
18} from '@tanstack/db'
19import { useOptionalDbClient } from './db-context.js'
20import type {
21 ChangeMessage,
22 Collection,
23 CollectionStatus,
24 Context,
25 DbClient,
26 DeferredLiveQueryCollections,
27 GetResult,
28 InferResultType,
29 InitialQueryBuilder,
30 LiveQueryCollectionConfig,
31 LiveQueryKey,
32 LiveQueryObserver,
33 LiveQueryPersistedStatus,
34 NonSingleResult,
35 QueryBuilder,
36 SingleResult,
37} from '@tanstack/db'
38
39/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */
40function snapshotRows(data: unknown): Array<any> {
41 if (Array.isArray(data)) return [...data]
42 return data === undefined ? [] : [data]
43}
44
45/**
46 * Return type for useLiveQuery hook
47 * @property state - Reactive Map of query results (key → item)
48 * @property data - Reactive array of query results in order, or single item when using findOne()
49 * @property collection - The underlying query collection instance
50 * @property status - Current query status
51 * @property isLoading - True while initial query data is loading
52 * @property isReady - True when query has received first data and is ready
53 * @property isIdle - True when query hasn't started yet
54 * @property isError - True when query encountered an error
55 * @property isCleanedUp - True when query has been cleaned up
56 */
57export interface UseLiveQueryReturn<T extends object, TData = Array<T>> {
58 state: Map<string | number, T>
59 data: TData
60 collection: Collection<T, string | number, {}>
61 status: CollectionStatus
62 isLoading: boolean
63 isReady: boolean
64 persistedStatus: LiveQueryPersistedStatus
65 isPersistedReady: boolean
66 persistedError: unknown | undefined
67 isIdle: boolean
68 isError: boolean
69 isCleanedUp: boolean
70}
71
72type InferConditionalResultType<TContext extends Context> =
73 TContext extends SingleResult
74 ? InferResultType<TContext> | []
75 : InferResultType<TContext>
76
77export type ConditionalUseLiveQueryReturn<
78 T extends object,
79 TData = Array<T>,
80> = Omit<UseLiveQueryReturn<T, TData>, `collection` | `status`> & {
81 collection: Collection<T, string | number, {}> | null
82 status: CollectionStatus | `disabled`
83}
84
85export interface UseLiveQueryReturnWithCollection<
86 T extends object,
87 TKey extends string | number,
88 TUtils extends Record<string, any>,
89 TData = Array<T>,
90> {
91 state: Map<TKey, T>
92 data: TData
93 collection: Collection<T, TKey, TUtils>
94 status: CollectionStatus
95 isLoading: boolean
96 isReady: boolean
97 persistedStatus: LiveQueryPersistedStatus
98 isPersistedReady: boolean
99 persistedError: unknown | undefined
100 isIdle: boolean
101 isError: boolean
102 isCleanedUp: boolean
103}
104
105type MaybeGetter<T> = T | (() => T)
106
107export type UseLiveQueryConfig<TContext extends Context> =
108 LiveQueryCollectionConfig<TContext> & {
109 queryKey?: MaybeGetter<LiveQueryKey>
110 client?: DbClient
111 }
112
113function toValue<T>(value: MaybeGetter<T>): T {
114 if (typeof value === `function`) {
115 return (value as () => T)()
116 }
117 return value
118}
119
120/**
121 * Create a live query using a query function
122 * @param queryFn - Query function that defines what data to fetch
123 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
124 * @returns Reactive object with query data, state, and status information
125 *
126 * @remarks
127 * **IMPORTANT - Destructuring in Svelte 5:**
128 * Direct destructuring breaks reactivity. To destructure, wrap with `$derived`:
129 *
130 * ❌ **Incorrect** - Loses reactivity:
131 * ```ts
132 * const { data, isLoading } = useLiveQuery(...)
133 * ```
134 *
135 * ✅ **Correct** - Maintains reactivity:
136 * ```ts
137 * // Option 1: Use dot notation (recommended)
138 * const query = useLiveQuery(...)
139 * // Access: query.data, query.isLoading
140 *
141 * // Option 2: Wrap with $derived for destructuring
142 * const query = useLiveQuery(...)
143 * const { data, isLoading } = $derived(query)
144 * ```
145 *
146 * This is a fundamental Svelte 5 limitation, not a library bug. See:
147 * https://github.com/sveltejs/svelte/issues/11002
148 *
149 * @example
150 * // Basic query with object syntax (recommended pattern)
151 * const todosQuery = useLiveQuery((q) =>
152 * q.from({ todos: todosCollection })
153 * .where(({ todos }) => eq(todos.completed, false))
154 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
155 * )
156 * // Access via: todosQuery.data, todosQuery.isLoading, etc.
157 *
158 * @example
159 * // With reactive dependencies
160 * let minPriority = $state(5)
161 * const todosQuery = useLiveQuery(
162 * (q) => q.from({ todos: todosCollection })
163 * .where(({ todos }) => gt(todos.priority, minPriority)),
164 * [() => minPriority] // Re-run when minPriority changes
165 * )
166 *
167 * @example
168 * // Destructuring with $derived (if needed)
169 * const query = useLiveQuery((q) =>
170 * q.from({ todos: todosCollection })
171 * )
172 * const { data, isLoading, isError } = $derived(query)
173 * // Now data, isLoading, and isError maintain reactivity
174 *
175 * @example
176 * // Join pattern
177 * const issuesQuery = useLiveQuery((q) =>
178 * q.from({ issues: issueCollection })
179 * .join({ persons: personCollection }, ({ issues, persons }) =>
180 * eq(issues.userId, persons.id)
181 * )
182 * .select(({ issues, persons }) => ({
183 * id: issues.id,
184 * title: issues.title,
185 * userName: persons.name
186 * }))
187 * )
188 *
189 * @example
190 * // Handle loading and error states in template
191 * const todosQuery = useLiveQuery((q) =>
192 * q.from({ todos: todoCollection })
193 * )
194 *
195 * // In template:
196 * // {#if todosQuery.isLoading}
197 * // <div>Loading...</div>
198 * // {:else if todosQuery.isError}
199 * // <div>Error: {todosQuery.status}</div>
200 * // {:else}
201 * // <ul>
202 * // {#each todosQuery.data as todo (todo.id)}
203 * // <li>{todo.text}</li>
204 * // {/each}
205 * // </ul>
206 * // {/if}
207 */
208// Overload 1: Accept query function that always returns QueryBuilder
209export function useLiveQuery<TContext extends Context>(
210 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
211 deps?: Array<() => unknown>,
212): UseLiveQueryReturn<GetResult<TContext>, InferResultType<TContext>>
213
214// Overload 1b: Accept query function that can return undefined/null
215export function useLiveQuery<TContext extends Context>(
216 queryFn: (
217 q: InitialQueryBuilder,
218 ) => QueryBuilder<TContext> | undefined | null,
219 deps?: Array<() => unknown>,
220): ConditionalUseLiveQueryReturn<
221 GetResult<TContext>,
222 InferConditionalResultType<TContext>
223>
224
225/**
226 * Create a live query using configuration object
227 * @param config - Configuration object with query and options
228 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
229 * @returns Reactive object with query data, state, and status information
230 * @example
231 * // Basic config object usage
232 * const todosQuery = useLiveQuery({
233 * query: (q) => q.from({ todos: todosCollection }),
234 * gcTime: 60000
235 * })
236 *
237 * @example
238 * // With reactive dependencies
239 * let filter = $state('active')
240 * const todosQuery = useLiveQuery({
241 * query: (q) => q.from({ todos: todosCollection })
242 * .where(({ todos }) => eq(todos.status, filter))
243 * }, [() => filter])
244 *
245 * @example
246 * // Handle all states uniformly
247 * const itemsQuery = useLiveQuery({
248 * query: (q) => q.from({ items: itemCollection })
249 * })
250 *
251 * // In template:
252 * // {#if itemsQuery.isLoading}
253 * // <div>Loading...</div>
254 * // {:else if itemsQuery.isError}
255 * // <div>Something went wrong</div>
256 * // {:else if !itemsQuery.isReady}
257 * // <div>Preparing...</div>
258 * // {:else}
259 * // <div>{itemsQuery.data.length} items loaded</div>
260 * // {/if}
261 */
262// Overload 2: Accept config object
263export function useLiveQuery<TContext extends Context>(
264 config: UseLiveQueryConfig<TContext>,
265 deps?: Array<() => unknown>,
266): UseLiveQueryReturn<GetResult<TContext>, InferResultType<TContext>>
267
268/**
269 * Subscribe to an existing query collection (can be reactive)
270 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a getter)
271 * @returns Reactive object with query data, state, and status information
272 * @example
273 * // Using pre-created query collection
274 * const myLiveQuery = createLiveQueryCollection((q) =>
275 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
276 * )
277 * const queryResult = useLiveQuery(myLiveQuery)
278 *
279 * @example
280 * // Reactive query collection reference
281 * let selectedQuery = $state(todosQuery)
282 * const queryResult = useLiveQuery(() => selectedQuery)
283 *
284 * // Switch queries reactively
285 * selectedQuery = archiveQuery
286 *
287 * @example
288 * // Access query collection methods directly
289 * const queryResult = useLiveQuery(existingQuery)
290 *
291 * // Use underlying collection for mutations
292 * const handleToggle = (id) => {
293 * queryResult.collection.update(id, draft => { draft.completed = !draft.completed })
294 * }
295 *
296 * @example
297 * // Handle states consistently
298 * const queryResult = useLiveQuery(sharedQuery)
299 *
300 * // In template:
301 * // {#if queryResult.isLoading}
302 * // <div>Loading...</div>
303 * // {:else if queryResult.isError}
304 * // <div>Error loading data</div>
305 * // {:else}
306 * // {#each queryResult.data as item (item.id)}
307 * // <Item {...item} />
308 * // {/each}
309 * // {/if}
310 */
311// Overload 3: Accept pre-created live query collection WITHOUT SingleResult (returns array)
312export function useLiveQuery<
313 TResult extends object,
314 TKey extends string | number,
315 TUtils extends Record<string, any>,
316>(
317 liveQueryCollection: MaybeGetter<
318 Collection<TResult, TKey, TUtils> & NonSingleResult
319 >,
320): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, Array<TResult>>
321
322// Overload 4: Accept pre-created live query collection WITH SingleResult (returns single item)
323export function useLiveQuery<
324 TResult extends object,
325 TKey extends string | number,
326 TUtils extends Record<string, any>,
327>(
328 liveQueryCollection: MaybeGetter<
329 Collection<TResult, TKey, TUtils> & SingleResult
330 >,
331): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, TResult | undefined>
332
333// Implementation
334export function useLiveQuery(
335 configOrQueryOrCollection: any,
336 deps: Array<() => unknown> = [],
337): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
338 const contextDbClient = useOptionalDbClient()
339
340 const resolved = $derived.by(() => {
341 // First check if the original parameter might be a getter
342 // by seeing if toValue returns something different than the original
343 let unwrappedParam = configOrQueryOrCollection
344 try {
345 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
346 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
347 unwrappedParam = potentiallyUnwrapped
348 }
349 } catch {
350 // If toValue fails, use original parameter
351 unwrappedParam = configOrQueryOrCollection
352 }
353
354 // Check if it's already a collection by checking for specific collection methods
355 const inputIsCollection = isCollection(unwrappedParam)
356 const dbClient = inputIsCollection
357 ? contextDbClient
358 : ((unwrappedParam as { client?: DbClient } | null)?.client ??
359 contextDbClient)
360
361 if (inputIsCollection) {
362 // Warn when passing a collection directly with on-demand sync mode
363 // In on-demand mode, data is only loaded when queries with predicates request it
364 // Passing the collection directly doesn't provide any predicates, so no data loads
365 const syncMode = (unwrappedParam as { config?: { syncMode?: string } })
366 .config?.syncMode
367 if (syncMode === `on-demand`) {
368 console.warn(
369 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
370 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
371 `Instead, use a query builder function:\n` +
372 ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
373 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
374 )
375 }
376 // It's already a collection, ensure sync is started for Svelte helpers
377 // Only start sync if the collection is in idle state
378 if (unwrappedParam.status === `idle`) {
379 unwrappedParam.startSyncImmediate()
380 }
381 return {
382 collection: unwrappedParam,
383 client: dbClient,
384 queryHash: getStableValueHash(
385 [`collection`, unwrappedParam.id],
386 `queryKey`,
387 ),
388 resumeDeferredCollections: () => {},
389 }
390 }
391
392 // Reference deps to make computed reactive to them
393 const dependencyValues = deps.map((dep) => toValue(dep))
394 const deferredCollections: DeferredLiveQueryCollections = new Set()
395 const preparedValue = prepareLiveQueryValue(
396 unwrappedParam,
397 dbClient,
398 deferredCollections,
399 )
400 const configuredQueryKey = (
401 unwrappedParam as { queryKey?: MaybeGetter<LiveQueryKey> } | null
402 )?.queryKey
403 const queryKey = configuredQueryKey
404 ? toValue(configuredQueryKey)
405 : undefined
406
407 let queryHash: string | undefined
408 try {
409 queryHash =
410 deps.length > 0 && !queryKey
411 ? getStableValueHash(
412 [`deps`, dependencyValues, getLiveQueryHash(preparedValue)],
413 `queryKey`,
414 )
415 : getLiveQueryHash(preparedValue, queryKey)
416 } catch (error) {
417 if (!(error instanceof UnhashableQueryIRError)) throw error
418 if (queryKey !== undefined) throw error
419 }
420
421 let collection: Collection<any, any, any> | null
422 if (preparedValue === undefined || preparedValue === null) {
423 collection = null
424 } else if (isCollection(preparedValue)) {
425 collection = preparedValue
426 } else if (preparedValue instanceof BaseQueryBuilder) {
427 // Hydration keys the live-query Collection by identity.
428 collection = resolveLiveQueryValue(preparedValue, { pool: !dbClient })
429 } else {
430 collection = createLiveQueryCollection({
431 ...(preparedValue as LiveQueryCollectionConfig<any>),
432 startSync: true,
433 })
434 }
435
436 return {
437 collection,
438 client: dbClient,
439 queryHash,
440 resumeDeferredCollections: () =>
441 resumeDeferredLiveQueryCollections(deferredCollections),
442 }
443 })
444
445 let currentResolved = untrack(() => resolved)
446 let currentObserver = createLiveQueryObserver(currentResolved.collection, {
447 client: currentResolved.client,
448 queryHash: currentResolved.queryHash,
449 onPreload: currentResolved.resumeDeferredCollections,
450 })
451 const initialSnapshot = currentObserver.getServerSnapshot()
452
453 // Reactive state that gets updated granularly through change events
454 const state = new SvelteMap<string | number, any>(initialSnapshot.state ?? [])
455
456 // Reactive data array that maintains sorted order
457 let internalData = $state<Array<any>>(snapshotRows(initialSnapshot.data))
458
459 // Track collection status reactively
460 let status = $state(initialSnapshot.status)
461 let persistedStatus = $state(initialSnapshot.persistedStatus)
462 let persistedError = $state.raw<unknown>(initialSnapshot.persistedError)
463
464 const syncFromObserver = (
465 observer: LiveQueryObserver<any, any>,
466 changes?: Array<ChangeMessage<any>>,
467 ) => {
468 const snapshot = observer.getSnapshot()
469 status = snapshot.status as CollectionStatus
470 persistedStatus = snapshot.persistedStatus
471 persistedError = snapshot.persistedError
472 untrack(() => {
473 if (changes && changes.length > 0) {
474 for (const change of changes) {
475 switch (change.type) {
476 case `insert`:
477 case `update`:
478 state.set(change.key, change.value)
479 break
480 case `delete`:
481 state.delete(change.key)
482 break
483 }
484 }
485 } else {
486 state.clear()
487 for (const [key, value] of snapshot.state ?? []) {
488 state.set(key, value)
489 }
490 }
491 internalData = snapshotRows(snapshot.data)
492 })
493 }
494
495 // Watch for collection changes and subscribe to updates
496 $effect(() => {
497 const nextResolved = resolved
498
499 if (nextResolved !== currentResolved) {
500 currentObserver.dispose()
501 currentResolved = nextResolved
502 currentObserver = createLiveQueryObserver(nextResolved.collection, {
503 client: nextResolved.client,
504 queryHash: nextResolved.queryHash,
505 onPreload: nextResolved.resumeDeferredCollections,
506 })
507 syncFromObserver(currentObserver)
508 }
509
510 const observer = currentObserver
511
512 const unsubscribe = observer.subscribe(
513 (changes: Array<ChangeMessage<any>> | undefined) => {
514 syncFromObserver(observer, changes)
515 },
516 )
517 try {
518 currentResolved.resumeDeferredCollections()
519 syncFromObserver(observer)
520 } catch (error) {
521 unsubscribe()
522 observer.dispose()
523 throw error
524 }
525
526 // Cleanup when effect is invalidated
527 return () => {
528 unsubscribe()
529 if (observer === currentObserver) observer.dispose()
530 }
531 })
532
533 return {
534 get state() {
535 return state
536 },
537 get data() {
538 const currentCollection = resolved.collection
539 if (currentCollection && isSingleResultCollection(currentCollection)) {
540 return internalData[0]
541 }
542 return internalData
543 },
544 get collection() {
545 return getPublicCollection(resolved.collection)
546 },
547 get status() {
548 return status as CollectionStatus
549 },
550 get isLoading() {
551 return status === `loading`
552 },
553 get isReady() {
554 return status === `ready` || status === `disabled`
555 },
556 get persistedStatus() {
557 return persistedStatus
558 },
559 get isPersistedReady() {
560 return persistedStatus === `ready`
561 },
562 get persistedError() {
563 return persistedError
564 },
565 get isIdle() {
566 return status === `idle`
567 },
568 get isError() {
569 return status === `error`
570 },
571 get isCleanedUp() {
572 return status === `cleaned-up`
573 },
574 }
575}