-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathuseLiveQuery.ts
More file actions
482 lines (447 loc) · 16.5 KB
/
useLiveQuery.ts
File metadata and controls
482 lines (447 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import {
computed,
getCurrentScope,
onScopeDispose,
ref,
shallowReactive,
shallowRef,
toValue,
watchEffect,
} from 'vue'
import {
BaseQueryBuilder,
CollectionImpl,
createLiveQueryCollection,
} from '@tanstack/db'
import type {
ChangeMessage,
Collection,
CollectionConfigSingleRowOption,
CollectionStatus,
Context,
GetResult,
InferResultType,
InitialQueryBuilder,
LiveQueryCollectionConfig,
NonSingleResult,
QueryBuilder,
SingleResult,
} from '@tanstack/db'
import type { ComputedRef, MaybeRefOrGetter } from 'vue'
const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
/**
* Return type for useLiveQuery hook
* @property state - Reactive Map of query results (key → item)
* @property data - Reactive array of query results in order, or single result for findOne queries
* @property collection - The underlying query collection instance
* @property status - Current query status
* @property isLoading - True while initial query data is loading
* @property isReady - True when query has received first data and is ready
* @property isIdle - True when query hasn't started yet
* @property isError - True when query encountered an error
* @property isCleanedUp - True when query has been cleaned up
* @property isEnabled - True when query is active, false when disabled
*/
export interface UseLiveQueryReturn<TContext extends Context> {
state: ComputedRef<Map<string | number, GetResult<TContext>>>
data: ComputedRef<InferResultType<TContext>>
collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>
status: ComputedRef<CollectionStatus>
isLoading: ComputedRef<boolean>
isReady: ComputedRef<boolean>
isIdle: ComputedRef<boolean>
isError: ComputedRef<boolean>
isCleanedUp: ComputedRef<boolean>
isEnabled: ComputedRef<boolean>
}
export interface UseLiveQueryReturnWithCollection<
T extends object,
TKey extends string | number,
TUtils extends Record<string, any>,
> {
state: ComputedRef<Map<TKey, T>>
data: ComputedRef<Array<T>>
collection: ComputedRef<Collection<T, TKey, TUtils>>
status: ComputedRef<CollectionStatus>
isLoading: ComputedRef<boolean>
isReady: ComputedRef<boolean>
isIdle: ComputedRef<boolean>
isError: ComputedRef<boolean>
isCleanedUp: ComputedRef<boolean>
isEnabled: ComputedRef<boolean>
}
export interface UseLiveQueryReturnWithSingleResultCollection<
T extends object,
TKey extends string | number,
TUtils extends Record<string, any>,
> {
state: ComputedRef<Map<TKey, T>>
data: ComputedRef<T | undefined>
collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>
status: ComputedRef<CollectionStatus>
isLoading: ComputedRef<boolean>
isReady: ComputedRef<boolean>
isIdle: ComputedRef<boolean>
isError: ComputedRef<boolean>
isCleanedUp: ComputedRef<boolean>
isEnabled: ComputedRef<boolean>
}
/**
* Create a live query using a query function
* @param queryFn - Query function that defines what data to fetch
* @param deps - Array of reactive dependencies that trigger query re-execution when changed
* @returns Reactive object with query data, state, and status information
* @example
* // Basic query with object syntax
* const { data, isLoading } = useLiveQuery((q) =>
* q.from({ todos: todosCollection })
* .where(({ todos }) => eq(todos.completed, false))
* .select(({ todos }) => ({ id: todos.id, text: todos.text }))
* )
*
* @example
* // With reactive dependencies
* const minPriority = ref(5)
* const { data, state } = useLiveQuery(
* (q) => q.from({ todos: todosCollection })
* .where(({ todos }) => gt(todos.priority, minPriority.value)),
* [minPriority] // Re-run when minPriority changes
* )
*
* @example
* // Join pattern
* const { data } = useLiveQuery((q) =>
* q.from({ issues: issueCollection })
* .join({ persons: personCollection }, ({ issues, persons }) =>
* eq(issues.userId, persons.id)
* )
* .select(({ issues, persons }) => ({
* id: issues.id,
* title: issues.title,
* userName: persons.name
* }))
* )
*
* @example
* // Handle loading and error states in template
* const { data, isLoading, isError, status } = useLiveQuery((q) =>
* q.from({ todos: todoCollection })
* )
*
* // In template:
* // <div v-if="isLoading">Loading...</div>
* // <div v-else-if="isError">Error: {{ status }}</div>
* // <ul v-else>
* // <li v-for="todo in data" :key="todo.id">{{ todo.text }}</li>
* // </ul>
*/
// Overload 1: Accept query function that always returns QueryBuilder
export function useLiveQuery<TContext extends Context>(
queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
deps?: Array<MaybeRefOrGetter<unknown>>,
): UseLiveQueryReturn<TContext>
// Overload 1b: Accept query function that can return undefined/null
export function useLiveQuery<TContext extends Context>(
queryFn: (
q: InitialQueryBuilder,
) => QueryBuilder<TContext> | undefined | null,
deps?: Array<MaybeRefOrGetter<unknown>>,
): UseLiveQueryReturn<TContext>
/**
* Create a live query using configuration object
* @param config - Configuration object with query and options
* @param deps - Array of reactive dependencies that trigger query re-execution when changed
* @returns Reactive object with query data, state, and status information
* @example
* // Basic config object usage
* const { data, status } = useLiveQuery({
* query: (q) => q.from({ todos: todosCollection }),
* gcTime: 60000
* })
*
* @example
* // With reactive dependencies
* const filter = ref('active')
* const { data, isReady } = useLiveQuery({
* query: (q) => q.from({ todos: todosCollection })
* .where(({ todos }) => eq(todos.status, filter.value))
* }, [filter])
*
* @example
* // Handle all states uniformly
* const { data, isLoading, isReady, isError } = useLiveQuery({
* query: (q) => q.from({ items: itemCollection })
* })
*
* // In template:
* // <div v-if="isLoading">Loading...</div>
* // <div v-else-if="isError">Something went wrong</div>
* // <div v-else-if="!isReady">Preparing...</div>
* // <div v-else>{{ data.length }} items loaded</div>
*/
// Overload 2: Accept config object
export function useLiveQuery<TContext extends Context>(
config: LiveQueryCollectionConfig<TContext>,
deps?: Array<MaybeRefOrGetter<unknown>>,
): UseLiveQueryReturn<TContext>
/**
* Subscribe to an existing query collection (can be reactive)
* @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)
* @returns Reactive object with query data, state, and status information
* @example
* // Using pre-created query collection
* const myLiveQuery = createLiveQueryCollection((q) =>
* q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
* )
* const { data, collection } = useLiveQuery(myLiveQuery)
*
* @example
* // Reactive query collection reference
* const selectedQuery = ref(todosQuery)
* const { data, collection } = useLiveQuery(selectedQuery)
*
* // Switch queries reactively
* selectedQuery.value = archiveQuery
*
* @example
* // Access query collection methods directly
* const { data, collection, isReady } = useLiveQuery(existingQuery)
*
* // Use underlying collection for mutations
* const handleToggle = (id) => {
* collection.value.update(id, draft => { draft.completed = !draft.completed })
* }
*
* @example
* // Handle states consistently
* const { data, isLoading, isError } = useLiveQuery(sharedQuery)
*
* // In template:
* // <div v-if="isLoading">Loading...</div>
* // <div v-else-if="isError">Error loading data</div>
* // <div v-else>
* // <Item v-for="item in data" :key="item.id" v-bind="item" />
* // </div>
*/
// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result
export function useLiveQuery<
TResult extends object,
TKey extends string | number,
TUtils extends Record<string, any>,
>(
liveQueryCollection: MaybeRefOrGetter<
Collection<TResult, TKey, TUtils> & NonSingleResult
>,
): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>
// Overload 4: Accept pre-created live query collection with singleResult: true
export function useLiveQuery<
TResult extends object,
TKey extends string | number,
TUtils extends Record<string, any>,
>(
liveQueryCollection: MaybeRefOrGetter<
Collection<TResult, TKey, TUtils> & SingleResult
>,
): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>
// Implementation
export function useLiveQuery(
configOrQueryOrCollection: any,
deps: Array<MaybeRefOrGetter<unknown>> = [],
): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
const collection = computed(() => {
// First check if the original parameter might be a ref/getter
// by seeing if toValue returns something different than the original
// NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!
let unwrappedParam = configOrQueryOrCollection
if (typeof configOrQueryOrCollection !== `function`) {
try {
const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
if (potentiallyUnwrapped !== configOrQueryOrCollection) {
unwrappedParam = potentiallyUnwrapped
}
} catch {
// If toValue fails, use original parameter
unwrappedParam = configOrQueryOrCollection
}
}
// Check if it's already a collection instance
if (unwrappedParam instanceof CollectionImpl) {
// Warn when passing a collection directly with on-demand sync mode
// In on-demand mode, data is only loaded when queries with predicates request it
// Passing the collection directly doesn't provide any predicates, so no data loads
const syncMode = (unwrappedParam as { config?: { syncMode?: string } })
.config?.syncMode
if (syncMode === `on-demand`) {
console.warn(
`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
`will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
`Instead, use a query builder function:\n` +
` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
`Or switch to syncMode "eager" if you want all data to sync automatically.`,
)
}
// It's already a collection, ensure sync is started for Vue hooks
// Only start sync if the collection is in idle state
if (unwrappedParam.status === `idle`) {
unwrappedParam.startSyncImmediate()
}
return unwrappedParam
}
// Reference deps to make computed reactive to them
deps.forEach((dep) => toValue(dep))
// Ensure we always start sync for Vue hooks
if (typeof unwrappedParam === `function`) {
// Probe the query function to check if it returns null/undefined (disabled query)
// This matches the pattern used by React and Solid adapters
const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
const result = unwrappedParam(queryBuilder)
if (result === undefined || result === null) {
return null
}
return createLiveQueryCollection({
query: unwrappedParam,
startSync: true,
gcTime: DEFAULT_GC_TIME_MS,
})
} else {
return createLiveQueryCollection({
gcTime: DEFAULT_GC_TIME_MS,
...unwrappedParam,
startSync: true,
})
}
})
// Reactive state that gets updated granularly through change events
// shallowReactive tracks Map operations (set/delete/has/get/size) without
// deeply proxying stored values — collection items are immutable snapshots
const state = shallowReactive(new Map<string | number, any>())
// Reactive data array — shallowRef avoids deep proxying of array elements
// and triggers a single notification on .value assignment (vs reactive array's
// double trigger from length=0 + push)
const internalData = shallowRef<Array<any>>([])
// Computed wrapper for the data to match expected return type
// Returns single item for singleResult collections, array otherwise
const data = computed(() => {
const currentCollection = collection.value
if (!currentCollection) {
return internalData.value
}
const config: CollectionConfigSingleRowOption<any, any, any> =
currentCollection.config
return config.singleResult ? internalData.value[0] : internalData.value
})
// Track collection status reactively
const status = ref(
collection.value ? collection.value.status : (`disabled` as const),
)
// Helper to sync data array from collection in correct order
const syncDataFromCollection = (
currentCollection: Collection<any, any, any>,
) => {
internalData.value = Array.from(currentCollection.values())
}
// Track current unsubscribe function
let currentUnsubscribe: (() => void) | null = null
// Watch for collection changes and subscribe to updates
watchEffect((onInvalidate) => {
const currentCollection = collection.value
// Handle null collection (disabled query)
if (!currentCollection) {
status.value = `disabled` as const
state.clear()
internalData.value = []
if (currentUnsubscribe) {
currentUnsubscribe()
currentUnsubscribe = null
}
return
}
// Update status ref whenever the effect runs
status.value = currentCollection.status
// Clean up previous subscription
if (currentUnsubscribe) {
currentUnsubscribe()
}
// Initialize state with current collection data
state.clear()
for (const [key, value] of currentCollection.entries()) {
state.set(key, value)
}
// Initialize data array in correct order
syncDataFromCollection(currentCollection)
// Listen for the first ready event to catch status transitions
// that might not trigger change events (fixes async status transition bug).
// Guard: if the collection has changed by the time the callback fires,
// skip the update — the new collection's own callback will handle it.
const collectionAtRegistration = currentCollection
currentCollection.onFirstReady(() => {
if (collection.value === collectionAtRegistration) {
status.value = currentCollection.status
}
})
// Subscribe to collection changes with granular updates
const subscription = currentCollection.subscribeChanges(
(changes: Array<ChangeMessage<any>>) => {
// Apply each change individually to the reactive state
for (const change of changes) {
switch (change.type) {
case `insert`:
case `update`:
state.set(change.key, change.value)
break
case `delete`:
state.delete(change.key)
break
}
}
// Update the data array to maintain sorted order
syncDataFromCollection(currentCollection)
// Update status ref on every change
status.value = currentCollection.status
},
{
includeInitialState: true,
},
)
currentUnsubscribe = subscription.unsubscribe.bind(subscription)
// Preload collection data if not already started
if (currentCollection.status === `idle`) {
currentCollection.preload().catch(console.error)
}
// Cleanup when effect is invalidated
onInvalidate(() => {
if (currentUnsubscribe) {
currentUnsubscribe()
currentUnsubscribe = null
}
})
})
// Cleanup on scope disposal — works in components, composables, and standalone effectScope.
// Guard with getCurrentScope() since useLiveQuery may be called outside any reactive scope
// (e.g., in tests or standalone utility code). watchEffect's onInvalidate handles cleanup
// when the effect is stopped, but onScopeDispose provides defense-in-depth for scope disposal.
if (getCurrentScope()) {
onScopeDispose(() => {
if (currentUnsubscribe) {
currentUnsubscribe()
currentUnsubscribe = null
}
})
}
return {
state: computed(() => state),
data,
collection: computed(
() => collection.value as Collection<any, any, any>,
),
status: computed(() => status.value as CollectionStatus),
isLoading: computed(() => status.value === `loading`),
isReady: computed(
() => status.value === `ready` || status.value === `disabled`,
),
isIdle: computed(() => status.value === `idle`),
isError: computed(() => status.value === `error`),
isCleanedUp: computed(() => status.value === `cleaned-up`),
isEnabled: computed(() => status.value !== `disabled`),
}
}