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