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