Open History to see the last commit
1'use client'
2
3import { useCallback, useRef, useSyncExternalStore } from 'react'
4import {
5 assertLiveQueryWindowManyResult,
6 compareLiveQueryWindowDependencies,
7 createLiveQueryCollection,
8 createLiveQueryWindowController,
9 fetchNextLiveQueryWindowPage,
10 getLiveQueryWindowCollectionWarning,
11 getLiveQueryWindowInputKind,
12 liveQueryWindowHoldsRows,
13 normalizeLiveQueryWindowPageSize,
14 resolveLiveQueryWindowInput,
15 shouldPreserveLiveQueryWindowPageCount,
16} from '@tanstack/db'
17import { useOptionalDbClient } from './DbProvider'
18import {
19 prepareDerivedQuery,
20 prepareQueryValue,
21 warnDeprecatedDepsArray,
22 warnUnhashableDerivedIdentity,
23} from './useLiveQuery'
24import type {
25 DerivedIdentityProfiler,
26 LiveQueryKey,
27 useLiveQuery,
28} from './useLiveQuery'
29import type {
30 Collection,
31 CollectionImpl as CollectionImplType,
32 CollectionStatus,
33 Context,
34 DbClient,
35 InferResultType,
36 InitialQueryBuilder,
37 LiveQueryPersistedStatus,
38 LiveQueryWindowController,
39 NonSingleResult,
40 QueryBuilder,
41} from '@tanstack/db'
42
43// Live queries created here are cleaned up immediately (0 disables GC).
44const DEFAULT_GC_TIME_MS = 1
45const unpreparedQueryValue = Symbol(`unpreparedQueryValue`)
46
47// Keep the generic parameter for existing typed config wrappers.
48export type UseLiveInfiniteQueryConfig<_TContext extends Context> = {
49 /**
50 * Explicit identity for queries that contain opaque functional variants or
51 * are hot enough that deriving identity from structured IR is too expensive.
52 * Structured queries should omit this so DB can derive identity directly.
53 */
54 queryKey?: LiveQueryKey
55 /** Override the nearest DbProvider for this query. */
56 client?: DbClient
57 pageSize?: number
58 /** First result-page label, not a server cursor or remote offset. */
59 initialPageParam?: number
60}
61
62export type UseLiveInfiniteQueryReturn<TContext extends Context> = Omit<
63 ReturnType<typeof useLiveQuery<TContext>>,
64 `data`
65> & {
66 data: InferResultType<TContext>
67 pages: Array<Array<InferResultType<TContext>[number]>>
68 pageParams: Array<number>
69 fetchNextPage: () => Promise<void>
70 hasNextPage: boolean
71 isFetchingNextPage: boolean
72 error: unknown
73}
74
75export type UseLiveInfiniteQueryReturnWithCollection<
76 TResult extends object,
77 TKey extends string | number,
78 TUtils extends Record<string, any>,
79> = {
80 data: Array<TResult>
81 state: Map<TKey, TResult>
82 collection: Collection<TResult, TKey, TUtils> & NonSingleResult
83 status: CollectionStatus
84 isLoading: boolean
85 isReady: boolean
86 persistedStatus: LiveQueryPersistedStatus
87 isPersistedReady: boolean
88 persistedError: unknown | undefined
89 isIdle: boolean
90 isError: boolean
91 isCleanedUp: boolean
92 isEnabled: true
93 pages: Array<Array<TResult>>
94 pageParams: Array<number>
95 fetchNextPage: () => Promise<void>
96 hasNextPage: boolean
97 isFetchingNextPage: boolean
98 error: unknown
99}
100
101type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
102 typeof useLiveQuery<TContext>
103>
104
105type InfiniteQueryRenderState = {
106 inputKind: `collection` | `query`
107 inputCollection: Collection<any, any, any> | null
108 inputQuery: unknown
109 client: DbClient | undefined
110 identityMode: `collection` | `queryKey` | `legacyDeps` | `derived`
111 dependencies: Array<unknown> | null
112 pageSize: number
113 initialPageParam: number
114 collection: Collection<any, any, any>
115 controller: LiveQueryWindowController<any, any>
116 warning: string | null
117 warned: boolean
118 deferredCollections: Set<
119 CollectionImplType<any, string | number, any, any, any>
120 >
121}
122
123type RenderedWindowCollection = {
124 client: DbClient | undefined
125 dependencies: Array<unknown>
126 collection: Collection<any, any, any>
127 deferredCollections: Set<
128 CollectionImplType<any, string | number, any, any, any>
129 >
130}
131
132/**
133 * Whether a recorded query identity matches the current one. Legacy deps
134 * compare by reference. Derived identities and query keys compare by structure.
135 */
136function queryIdentityMatches(
137 comparison: { changed: boolean; structurallyEqual: boolean },
138 sameClient: boolean,
139 usesLegacyDeps: boolean,
140): boolean {
141 return (
142 sameClient &&
143 (usesLegacyDeps ? !comparison.changed : comparison.structurallyEqual)
144 )
145}
146
147/**
148 * Create an infinite query using a query function with live updates.
149 *
150 * Uses `utils.setWindow()` to dynamically adjust the limit/offset window
151 * without recreating the live query collection on each page change.
152 *
153 * @param queryFn - Query function that defines what data to fetch. Must include `.orderBy()` for setWindow to work.
154 * @param config - Configuration including pageSize and an optional initial page label
155 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
156 * @returns Object with pages, data, and pagination controls
157 */
158
159// Overload for pre-created collection (non-single result)
160export function useLiveInfiniteQuery<
161 TResult extends object,
162 TKey extends string | number,
163 TUtils extends Record<string, any>,
164>(
165 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
166 config: UseLiveInfiniteQueryConfig<any>,
167): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
168
169// Overload for query function
170export function useLiveInfiniteQuery<TContext extends Context>(
171 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
172 config: UseLiveInfiniteQueryConfig<TContext>,
173 deps?: Array<unknown>,
174): UseLiveInfiniteQueryReturn<TContext>
175
176// Implementation
177export function useLiveInfiniteQuery<TContext extends Context>(
178 queryFnOrCollection: any,
179 config: UseLiveInfiniteQueryConfig<TContext>,
180 deps?: Array<unknown>,
181): UseLiveInfiniteQueryReturn<TContext> {
182 if (`getNextPageParam` in config) {
183 throw new Error(
184 `getNextPageParam is not supported by useLiveInfiniteQuery. Use an on-demand collection and fulfill meta.loadSubsetOptions in queryFn for server pagination.`,
185 )
186 }
187 const pageSize = normalizeLiveQueryWindowPageSize(config.pageSize)
188 const initialPageParam = config.initialPageParam ?? 0
189 const contextDbClient = useOptionalDbClient()
190 const dbClient = config.client ?? contextDbClient
191
192 const inputIsCollection =
193 getLiveQueryWindowInputKind(queryFnOrCollection) === `collection`
194
195 const committedRef = useRef<InfiniteQueryRenderState | null>(null)
196 const committed = committedRef.current
197 // Like useLiveQuery's instance memo, keep the window collection built by the
198 // latest render. A second render before commit, such as a StrictMode double
199 // render, reuses it instead of starting another one. Only the collection is
200 // kept. Each render still builds its own controller and page count from the
201 // committed state, which an uncommitted render never changes.
202 const renderedCollectionRef = useRef<RenderedWindowCollection | null>(null)
203 const inputKind = inputIsCollection ? `collection` : `query`
204 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
205 renderCount: 0,
206 totalMs: 0,
207 maxMs: 0,
208 warned: false,
209 })
210 const legacyUnhashableIdentityRef = useRef<Array<unknown>>([
211 `legacy-unhashable`,
212 ])
213 const deferredCollections = new Set<
214 CollectionImplType<any, string | number, any, any, any>
215 >()
216
217 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
218 unpreparedQueryValue
219 let identityDeps: ReadonlyArray<unknown> = []
220 let identityMode: InfiniteQueryRenderState[`identityMode`] = `collection`
221
222 if (!inputIsCollection) {
223 if (config.queryKey !== undefined) {
224 identityMode = `queryKey`
225 identityDeps = config.queryKey
226 } else if (deps !== undefined) {
227 identityMode = `legacyDeps`
228 identityDeps = deps
229 warnDeprecatedDepsArray(`useLiveInfiniteQuery`)
230 } else if (
231 committed?.identityMode === `derived` &&
232 committed.inputQuery === queryFnOrCollection &&
233 committed.client === dbClient
234 ) {
235 identityMode = `derived`
236 identityDeps = committed.dependencies ?? []
237 } else {
238 identityMode = `derived`
239 const preparation = prepareDerivedQuery(
240 queryFnOrCollection,
241 dbClient,
242 derivedIdentityProfilerRef.current,
243 deferredCollections,
244 )
245 preparedQueryValue = preparation.value
246 if (preparation.status === `hashable`) {
247 identityDeps = preparation.identityDeps
248 } else {
249 warnUnhashableDerivedIdentity(preparation.error)
250 identityDeps = legacyUnhashableIdentityRef.current
251 }
252 }
253 }
254
255 const usesLegacyDeps =
256 !inputIsCollection && config.queryKey === undefined && deps !== undefined
257 const dependencyComparison = compareLiveQueryWindowDependencies(
258 committed?.dependencies,
259 identityDeps,
260 )
261 const sameClient = committed?.client === dbClient
262 const dependenciesChanged =
263 !inputIsCollection &&
264 !queryIdentityMatches(dependencyComparison, sameClient, usesLegacyDeps)
265 const dependenciesStructurallyEqual =
266 usesLegacyDeps && sameClient && dependencyComparison.structurallyEqual
267 const needsNewCollection =
268 committed === null ||
269 committed.inputKind !== inputKind ||
270 (inputIsCollection && committed.inputCollection !== queryFnOrCollection) ||
271 dependenciesChanged
272 const pageShapeChanged =
273 committed === null ||
274 committed.pageSize !== pageSize ||
275 committed.initialPageParam !== initialPageParam
276 const needsNewController =
277 committed === null || needsNewCollection || pageShapeChanged
278
279 let renderState = committed
280 if (needsNewController) {
281 let collection = committed?.collection
282 let warning: string | null = null
283 let startInRender = false
284 let suppliedCollection = false
285
286 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
287 hasPreviousController: committed !== null,
288 previousInputKind: committed?.inputKind,
289 inputKind,
290 sameCollection:
291 inputIsCollection && committed?.inputCollection === queryFnOrCollection,
292 dependenciesChanged,
293 dependenciesStructurallyEqual,
294 pageShapeChanged,
295 })
296 const previousPageCount = committed
297 ? Math.max(1, committed.controller.getSnapshot().pages.length)
298 : 1
299 const initialPageCount = canPreservePageCount ? previousPageCount : 1
300
301 if (needsNewCollection) {
302 let inputValue = queryFnOrCollection
303 if (!inputIsCollection) {
304 if (preparedQueryValue === unpreparedQueryValue) {
305 preparedQueryValue = prepareQueryValue(
306 queryFnOrCollection,
307 dbClient,
308 deferredCollections,
309 )
310 }
311 inputValue = () => preparedQueryValue
312 }
313 const rendered = renderedCollectionRef.current
314 const requiredLimit = initialPageCount * pageSize + 1
315 if (
316 !inputIsCollection &&
317 rendered !== null &&
318 queryIdentityMatches(
319 compareLiveQueryWindowDependencies(
320 rendered.dependencies,
321 identityDeps,
322 ),
323 rendered.client === dbClient,
324 usesLegacyDeps,
325 ) &&
326 rendered.collection.status !== `cleaned-up` &&
327 liveQueryWindowHoldsRows(rendered.collection, requiredLimit)
328 ) {
329 // An earlier render built this collection and nothing has committed
330 // since. Its window already holds the retained pages, so its first
331 // rows are correct. Sources it deferred still resume at commit.
332 collection = rendered.collection
333 for (const deferred of rendered.deferredCollections) {
334 deferredCollections.add(deferred)
335 }
336 } else {
337 const input = resolveLiveQueryWindowInput<TContext>(inputValue)
338 if (input.kind === `collection`) {
339 collection = input.collection
340 suppliedCollection = true
341 } else {
342 // Wrap the query with the peek-ahead window for every retained page,
343 // so a collection that starts syncing now never publishes fewer rows
344 // than the controller's pages. The controller grows the limit via
345 // setWindow.
346 collection = createLiveQueryCollection({
347 query: input.query.limit(requiredLimit).offset(0),
348 gcTime: DEFAULT_GC_TIME_MS,
349 })
350 startInRender = true
351 renderedCollectionRef.current = {
352 client: dbClient,
353 dependencies: [...identityDeps],
354 collection,
355 deferredCollections,
356 }
357 }
358 }
359 }
360
361 if (!collection) {
362 throw new Error(`useLiveInfiniteQuery: Failed to create a collection.`)
363 }
364
365 if (inputIsCollection) {
366 warning =
367 getLiveQueryWindowCollectionWarning(collection, pageSize + 1) ?? null
368 } else {
369 assertLiveQueryWindowManyResult(collection)
370 }
371 // Like useLiveQuery, start sync during render once the input is valid, so
372 // a synchronously loaded source is published on the first commit instead
373 // of an empty idle commit. GC reclaims a render that never commits. A
374 // supplied window that the controller must still adjust waits for the
375 // subscription.
376 if (suppliedCollection) {
377 startInRender = liveQueryWindowHoldsRows(
378 collection,
379 initialPageCount * pageSize + 1,
380 )
381 }
382 if (startInRender) collection.startSyncImmediate()
383
384 renderState = {
385 inputKind,
386 inputCollection: inputIsCollection ? collection : null,
387 inputQuery: inputIsCollection ? null : queryFnOrCollection,
388 client: dbClient,
389 identityMode,
390 dependencies: inputIsCollection ? null : [...identityDeps],
391 pageSize,
392 initialPageParam,
393 collection,
394 controller: createLiveQueryWindowController(collection, {
395 pageSize,
396 initialPageParam,
397 initialPageCount,
398 }),
399 warning,
400 warned: false,
401 deferredCollections,
402 }
403 }
404 const currentRenderState = renderState!
405 const controller = currentRenderState.controller
406
407 const subscribe = useCallback(
408 (onStoreChange: () => void) => {
409 const unsubscribe = controller.subscribe(onStoreChange)
410 committedRef.current = currentRenderState
411 if (currentRenderState.warning && !currentRenderState.warned) {
412 currentRenderState.warned = true
413 console.warn(currentRenderState.warning)
414 }
415 for (const collection of currentRenderState.deferredCollections) {
416 collection._resumeSyncStart()
417 }
418 currentRenderState.deferredCollections.clear()
419 return unsubscribe
420 },
421 [controller, currentRenderState],
422 )
423 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
424 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
425
426 const fetchNextPage = useCallback(
427 () => fetchNextLiveQueryWindowPage(controller),
428 [controller],
429 )
430
431 return {
432 data: snapshot.data as InferResultType<TContext>,
433 state: snapshot.state as EnabledLiveQueryReturn<TContext>[`state`],
434 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
435 isLoading: snapshot.isLoading,
436 isReady: snapshot.isReady,
437 persistedStatus: snapshot.persistedStatus,
438 isPersistedReady: snapshot.isPersistedReady,
439 persistedError: snapshot.persistedError,
440 isIdle: snapshot.isIdle,
441 isError: snapshot.isError,
442 isCleanedUp: snapshot.isCleanedUp,
443 collection:
444 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
445 isEnabled: snapshot.isEnabled,
446 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
447 pageParams: snapshot.pageParams as Array<number>,
448 fetchNextPage,
449 hasNextPage: snapshot.hasNextPage,
450 isFetchingNextPage: snapshot.isFetchingNextPage,
451 error: snapshot.error,
452 }
453}