Open History to see the last commit
1'use client'
2
3import { useCallback, useRef, useSyncExternalStore } from 'react'
4import {
5 assertLiveQueryWindowManyResult,
6 canStartLiveQueryWindowSyncInRender,
7 compareLiveQueryWindowDependencies,
8 createLiveQueryCollection,
9 createLiveQueryWindowController,
10 fetchNextLiveQueryWindowPage,
11 getLiveQueryWindowCollectionWarning,
12 getLiveQueryWindowInputKind,
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
123/**
124 * Create an infinite query using a query function with live updates.
125 *
126 * Uses `utils.setWindow()` to dynamically adjust the limit/offset window
127 * without recreating the live query collection on each page change.
128 *
129 * @param queryFn - Query function that defines what data to fetch. Must include `.orderBy()` for setWindow to work.
130 * @param config - Configuration including pageSize and an optional initial page label
131 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
132 * @returns Object with pages, data, and pagination controls
133 */
134
135// Overload for pre-created collection (non-single result)
136export function useLiveInfiniteQuery<
137 TResult extends object,
138 TKey extends string | number,
139 TUtils extends Record<string, any>,
140>(
141 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
142 config: UseLiveInfiniteQueryConfig<any>,
143): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
144
145// Overload for query function
146export function useLiveInfiniteQuery<TContext extends Context>(
147 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
148 config: UseLiveInfiniteQueryConfig<TContext>,
149 deps?: Array<unknown>,
150): UseLiveInfiniteQueryReturn<TContext>
151
152// Implementation
153export function useLiveInfiniteQuery<TContext extends Context>(
154 queryFnOrCollection: any,
155 config: UseLiveInfiniteQueryConfig<TContext>,
156 deps?: Array<unknown>,
157): UseLiveInfiniteQueryReturn<TContext> {
158 if (`getNextPageParam` in config) {
159 throw new Error(
160 `getNextPageParam is not supported by useLiveInfiniteQuery. Use an on-demand collection and fulfill meta.loadSubsetOptions in queryFn for server pagination.`,
161 )
162 }
163 const pageSize = normalizeLiveQueryWindowPageSize(config.pageSize)
164 const initialPageParam = config.initialPageParam ?? 0
165 const contextDbClient = useOptionalDbClient()
166 const dbClient = config.client ?? contextDbClient
167
168 const inputIsCollection =
169 getLiveQueryWindowInputKind(queryFnOrCollection) === `collection`
170
171 const committedRef = useRef<InfiniteQueryRenderState | null>(null)
172 const committed = committedRef.current
173 const inputKind = inputIsCollection ? `collection` : `query`
174 const derivedIdentityProfilerRef = useRef<DerivedIdentityProfiler>({
175 renderCount: 0,
176 totalMs: 0,
177 maxMs: 0,
178 warned: false,
179 })
180 const legacyUnhashableIdentityRef = useRef<Array<unknown>>([
181 `legacy-unhashable`,
182 ])
183 const deferredCollections = new Set<
184 CollectionImplType<any, string | number, any, any, any>
185 >()
186
187 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
188 unpreparedQueryValue
189 let identityDeps: ReadonlyArray<unknown> = []
190 let identityMode: InfiniteQueryRenderState[`identityMode`] = `collection`
191
192 if (!inputIsCollection) {
193 if (config.queryKey !== undefined) {
194 identityMode = `queryKey`
195 identityDeps = config.queryKey
196 } else if (deps !== undefined) {
197 identityMode = `legacyDeps`
198 identityDeps = deps
199 warnDeprecatedDepsArray(`useLiveInfiniteQuery`)
200 } else if (
201 committed?.identityMode === `derived` &&
202 committed.inputQuery === queryFnOrCollection &&
203 committed.client === dbClient
204 ) {
205 identityMode = `derived`
206 identityDeps = committed.dependencies ?? []
207 } else {
208 identityMode = `derived`
209 const preparation = prepareDerivedQuery(
210 queryFnOrCollection,
211 dbClient,
212 derivedIdentityProfilerRef.current,
213 deferredCollections,
214 )
215 preparedQueryValue = preparation.value
216 if (preparation.status === `hashable`) {
217 identityDeps = preparation.identityDeps
218 } else {
219 warnUnhashableDerivedIdentity(preparation.error)
220 identityDeps = legacyUnhashableIdentityRef.current
221 }
222 }
223 }
224
225 const usesLegacyDeps =
226 !inputIsCollection && config.queryKey === undefined && deps !== undefined
227 const dependencyComparison = compareLiveQueryWindowDependencies(
228 committed?.dependencies,
229 identityDeps,
230 )
231 const sameClient = committed?.client === dbClient
232 const dependenciesChanged =
233 !inputIsCollection &&
234 (!sameClient ||
235 (usesLegacyDeps
236 ? dependencyComparison.changed
237 : !dependencyComparison.structurallyEqual))
238 const dependenciesStructurallyEqual =
239 usesLegacyDeps && sameClient && dependencyComparison.structurallyEqual
240 const needsNewCollection =
241 committed === null ||
242 committed.inputKind !== inputKind ||
243 (inputIsCollection && committed.inputCollection !== queryFnOrCollection) ||
244 dependenciesChanged
245 const pageShapeChanged =
246 committed === null ||
247 committed.pageSize !== pageSize ||
248 committed.initialPageParam !== initialPageParam
249 const needsNewController =
250 committed === null || needsNewCollection || pageShapeChanged
251
252 let renderState = committed
253 if (needsNewController) {
254 let collection = committed?.collection
255 let warning: string | null = null
256
257 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
258 hasPreviousController: committed !== null,
259 previousInputKind: committed?.inputKind,
260 inputKind,
261 sameCollection:
262 inputIsCollection && committed?.inputCollection === queryFnOrCollection,
263 dependenciesChanged,
264 dependenciesStructurallyEqual,
265 pageShapeChanged,
266 })
267 const previousPageCount = committed
268 ? Math.max(1, committed.controller.getSnapshot().pages.length)
269 : 1
270 const initialPageCount = canPreservePageCount ? previousPageCount : 1
271
272 if (needsNewCollection) {
273 let inputValue = queryFnOrCollection
274 if (!inputIsCollection) {
275 if (preparedQueryValue === unpreparedQueryValue) {
276 preparedQueryValue = prepareQueryValue(
277 queryFnOrCollection,
278 dbClient,
279 deferredCollections,
280 )
281 }
282 inputValue = () => preparedQueryValue
283 }
284 const input = resolveLiveQueryWindowInput<TContext>(inputValue)
285 if (input.kind === `collection`) {
286 collection = input.collection
287 } else {
288 // Wrap the query with the peek-ahead window for every retained page, so
289 // a collection that starts syncing now never publishes fewer rows than
290 // the controller's pages. The controller grows the limit via setWindow.
291 collection = createLiveQueryCollection({
292 query: input.query.limit(initialPageCount * pageSize + 1).offset(0),
293 // Like useLiveQuery, start sync during render so a synchronously
294 // loaded source is published on the first commit instead of an empty
295 // idle commit. GC reclaims a render that never commits. On-demand
296 // sources wait for the subscription, so an abandoned or duplicate
297 // render does not send a page request.
298 startSync: canStartLiveQueryWindowSyncInRender(input.query),
299 gcTime: DEFAULT_GC_TIME_MS,
300 })
301 }
302 }
303
304 if (!collection) {
305 throw new Error(`useLiveInfiniteQuery: Failed to create a collection.`)
306 }
307
308 if (inputIsCollection) {
309 warning =
310 getLiveQueryWindowCollectionWarning(collection, pageSize + 1) ?? null
311 } else {
312 assertLiveQueryWindowManyResult(collection)
313 }
314
315 renderState = {
316 inputKind,
317 inputCollection: inputIsCollection ? collection : null,
318 inputQuery: inputIsCollection ? null : queryFnOrCollection,
319 client: dbClient,
320 identityMode,
321 dependencies: inputIsCollection ? null : [...identityDeps],
322 pageSize,
323 initialPageParam,
324 collection,
325 controller: createLiveQueryWindowController(collection, {
326 pageSize,
327 initialPageParam,
328 initialPageCount,
329 }),
330 warning,
331 warned: false,
332 deferredCollections,
333 }
334 }
335 const currentRenderState = renderState!
336 const controller = currentRenderState.controller
337
338 const subscribe = useCallback(
339 (onStoreChange: () => void) => {
340 const unsubscribe = controller.subscribe(onStoreChange)
341 committedRef.current = currentRenderState
342 if (currentRenderState.warning && !currentRenderState.warned) {
343 currentRenderState.warned = true
344 console.warn(currentRenderState.warning)
345 }
346 for (const collection of currentRenderState.deferredCollections) {
347 collection._resumeSyncStart()
348 }
349 currentRenderState.deferredCollections.clear()
350 return unsubscribe
351 },
352 [controller, currentRenderState],
353 )
354 const getSnapshot = useCallback(() => controller.getSnapshot(), [controller])
355 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
356
357 const fetchNextPage = useCallback(
358 () => fetchNextLiveQueryWindowPage(controller),
359 [controller],
360 )
361
362 return {
363 data: snapshot.data as InferResultType<TContext>,
364 state: snapshot.state as EnabledLiveQueryReturn<TContext>[`state`],
365 status: snapshot.status as EnabledLiveQueryReturn<TContext>[`status`],
366 isLoading: snapshot.isLoading,
367 isReady: snapshot.isReady,
368 persistedStatus: snapshot.persistedStatus,
369 isPersistedReady: snapshot.isPersistedReady,
370 persistedError: snapshot.persistedError,
371 isIdle: snapshot.isIdle,
372 isError: snapshot.isError,
373 isCleanedUp: snapshot.isCleanedUp,
374 collection:
375 snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`],
376 isEnabled: snapshot.isEnabled,
377 pages: snapshot.pages as Array<Array<InferResultType<TContext>[number]>>,
378 pageParams: snapshot.pageParams as Array<number>,
379 fetchNextPage,
380 hasNextPage: snapshot.hasNextPage,
381 isFetchingNextPage: snapshot.isFetchingNextPage,
382 error: snapshot.error,
383 }
384}