Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useLiveInfiniteQuery.svelte.ts

290 lines9.1 KB

1import {
2 assertLiveQueryWindowManyResult,
3 compareLiveQueryWindowDependencies,
4 createLiveQueryCollection,
5 createLiveQueryWindowController,
6 fetchNextLiveQueryWindowPage,
7 getLiveQueryWindowCollectionWarning,
8 liveQueryWindowMatches,
9 normalizeLiveQueryWindowPageSize,
10 resolveLiveQueryWindowInput,
11 shouldPreserveLiveQueryWindowPageCount,
12} from '@tanstack/db'
13import { tick, untrack } from 'svelte'
14// Type-only: used in `ReturnType<typeof useLiveQuery>` below.
15import type {
16 UseLiveQueryReturnWithCollection,
17 useLiveQuery,
18} from './useLiveQuery.svelte.js'
19import type {
20 Collection,
21 Context,
22 InferResultType,
23 InitialQueryBuilder,
24 NonSingleResult,
25 QueryBuilder,
26 UtilsRecord,
27} from '@tanstack/db'
28​
29const DEFAULT_GC_TIME_MS = 1
30​
31type MaybeGetter<T> = T | (() => T)
32​
33type InternalCollection = Collection<object, string | number, UtilsRecord>
34​
35type PreviousController = {
36 getSnapshot: () => { pages: ReadonlyArray<ReadonlyArray<unknown>> }
38​
39type InfiniteQueryOptions = {
40 pageSize?: number
41 /** First result-page label, not a server cursor or remote offset. */
42 initialPageParam?: number
44​
45// Keep the generic parameter for existing typed config wrappers.
46export type LiveInfiniteQueryConfig<_TRow> = InfiniteQueryOptions
47​
48export type UseLiveInfiniteQueryConfig<TContext extends Context> =
49 LiveInfiniteQueryConfig<InferResultType<TContext>[number]>
50​
51export type UseLiveInfiniteQueryReturn<TContext extends Context> = Omit<
52 ReturnType<typeof useLiveQuery<TContext>>,
53 `data`
54> & {
55 data: InferResultType<TContext>
56 pages: Array<Array<InferResultType<TContext>[number]>>
57 pageParams: Array<number>
58 fetchNextPage: () => Promise<void>
59 hasNextPage: boolean
60 isFetchingNextPage: boolean
61 error: unknown
63​
64export type UseLiveInfiniteQueryReturnWithCollection<
65 TResult extends object,
66 TKey extends string | number,
67 TUtils extends Record<string, any>,
68> = Omit<
69 UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, Array<TResult>>,
70 `data`
71> & {
72 data: Array<TResult>
73 pages: Array<Array<TResult>>
74 pageParams: Array<number>
75 fetchNextPage: () => Promise<void>
76 hasNextPage: boolean
77 isFetchingNextPage: boolean
78 error: unknown
80​
81type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
82 typeof useLiveQuery<TContext>
84​
85/**
86 * Create a Svelte-native reactive view over the shared live-query window
87 * controller. The query must include an `orderBy` clause.
88 */
89export function useLiveInfiniteQuery<
90 TResult extends object,
91 TKey extends string | number,
92 TUtils extends Record<string, any>,
93>(
94 liveQueryCollection: MaybeGetter<
95 Collection<TResult, TKey, TUtils> & NonSingleResult
96 >,
97 config: LiveInfiniteQueryConfig<TResult>,
98): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
99​
100export function useLiveInfiniteQuery<TContext extends Context>(
101 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
102 config: UseLiveInfiniteQueryConfig<TContext>,
103 deps?: Array<() => unknown>,
104): UseLiveInfiniteQueryReturn<TContext>
105​
106export function useLiveInfiniteQuery<TContext extends Context>(
107 queryFnOrCollection: unknown,
108 config: InfiniteQueryOptions,
109 deps: Array<() => unknown> = [],
110): UseLiveInfiniteQueryReturn<TContext> {
111 if (`getNextPageParam` in config) {
112 throw new Error(
113 `getNextPageParam is not supported by useLiveInfiniteQuery. Use an on-demand collection and fulfill meta.loadSubsetOptions in queryFn for server pagination.`,
114 )
115 }
116 let validatedCollection: InternalCollection | null = null
117 let previousController: PreviousController | null = null
118 let previousInput: ReturnType<
119 typeof resolveLiveQueryWindowInput<TContext>
120 > | null = null
121 let previousDependencies: Array<unknown> | null = null
122 let previousPageSize: number | null = null
123 let previousInitialPageParam: number | null = null
124​
125 const pageSize = $derived(normalizeLiveQueryWindowPageSize(config.pageSize))
126 const initialPageParam = $derived(config.initialPageParam ?? 0)
127​
128 const controller = $derived.by(() => {
129 const dependencies = deps.map((dependency) => dependency())
130​
131 const input = resolveLiveQueryWindowInput<TContext>(queryFnOrCollection)
132 const dependencyComparison = compareLiveQueryWindowDependencies(
133 previousDependencies,
134 dependencies,
135 )
136 const dependenciesChanged = dependencyComparison.changed
137 const dependenciesStructurallyEqual = dependencyComparison.structurallyEqual
138 const pageShapeChanged =
139 previousPageSize !== pageSize ||
140 previousInitialPageParam !== initialPageParam
141 const sameCollection =
142 input.kind === `collection` &&
143 previousInput?.kind === `collection` &&
144 previousInput.collection === input.collection
145 const canPreservePageCount = shouldPreserveLiveQueryWindowPageCount({
146 hasPreviousController: previousController !== null,
147 previousInputKind: previousInput?.kind,
148 inputKind: input.kind,
149 sameCollection,
150 dependenciesChanged,
151 dependenciesStructurallyEqual,
152 pageShapeChanged,
153 })
154 const previousPageCount = previousController
155 ? Math.max(1, previousController.getSnapshot().pages.length)
156 : 1
157 const initialPageCount = canPreservePageCount ? previousPageCount : 1
158 // The peek-ahead window for every retained page.
159 const requiredLimit = initialPageCount * pageSize + 1
160​
161 previousInput = input
162 previousDependencies = [...dependencies]
163 previousPageSize = pageSize
164 previousInitialPageParam = initialPageParam
165​
166 if (input.kind === `collection`) {
167 const collection = input.collection
168 const warning = getLiveQueryWindowCollectionWarning(
169 collection,
170 pageSize + 1,
171 )
172​
173 if (validatedCollection !== collection) {
174 validatedCollection = collection
175 if (warning) console.warn(warning)
176 }
177 // Like useLiveQuery, start a supplied collection during construction when
178 // its rows are already correct. A window the controller must still adjust
179 // waits for the subscription.
180 if (liveQueryWindowMatches(collection, requiredLimit)) {
181 collection.startSyncImmediate()
182 }
183 const currentController = createLiveQueryWindowController(collection, {
184 pageSize,
185 initialPageParam,
186 initialPageCount,
187 })
188 previousController = currentController
189 return currentController
190 }
191​
192 const collection = createLiveQueryCollection({
193 // Size the window for every retained page, so a collection that starts
194 // syncing now never publishes fewer rows than the controller's pages.
195 query: input.query.limit(requiredLimit).offset(0),
196 gcTime: DEFAULT_GC_TIME_MS,
197 })
198 assertLiveQueryWindowManyResult(collection)
199 // Like useLiveQuery, start sync during construction once the query is
200 // valid, so a synchronously loaded source is published on the first render
201 // instead of an empty idle snapshot before the subscribing effect attaches.
202 collection.startSyncImmediate()
203 const currentController = createLiveQueryWindowController(collection, {
204 pageSize,
205 initialPageParam,
206 initialPageCount,
207 })
208 previousController = currentController
209 return currentController
210 })
211​
212 let snapshot = $state.raw(untrack(() => controller.getSnapshot()))
213​
214 $effect(() => {
215 const currentController = controller
216 snapshot = currentController.getSnapshot()
217 const unsubscribe = currentController.subscribe(() => {
218 snapshot = currentController.getSnapshot()
219 })
220 snapshot = currentController.getSnapshot()
221​
222 return () => {
223 unsubscribe()
224 currentController.dispose()
225 }
226 })
227​
228 const fetchNextPage = async () => {
229 // A dependency can invalidate the derived controller before Svelte runs the
230 // effect that subscribes it. Queue the imperative call until that handoff
231 // has completed so it cannot target an inactive controller.
232 await tick()
233 await fetchNextLiveQueryWindowPage(controller)
234 }
235​
236 return {
237 get state() {
238 return snapshot.state as EnabledLiveQueryReturn<TContext>[`state`]
239 },
240 get data() {
241 return snapshot.data as InferResultType<TContext>
242 },
243 get collection() {
244 return snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`]
245 },
246 get status() {
247 return snapshot.status as EnabledLiveQueryReturn<TContext>[`status`]
248 },
249 get isLoading() {
250 return snapshot.isLoading
251 },
252 get isReady() {
253 return snapshot.isReady
254 },
255 get persistedStatus() {
256 return snapshot.persistedStatus
257 },
258 get isPersistedReady() {
259 return snapshot.isPersistedReady
260 },
261 get persistedError() {
262 return snapshot.persistedError
263 },
264 get isIdle() {
265 return snapshot.isIdle
266 },
267 get isError() {
268 return snapshot.isError
269 },
270 get isCleanedUp() {
271 return snapshot.isCleanedUp
272 },
273 get pages() {
274 return snapshot.pages as Array<Array<InferResultType<TContext>[number]>>
275 },
276 get pageParams() {
277 return snapshot.pageParams as Array<number>
278 },
279 get hasNextPage() {
280 return snapshot.hasNextPage
281 },
282 get isFetchingNextPage() {
283 return snapshot.isFetchingNextPage
284 },
285 get error() {
286 return snapshot.error
287 },
288 fetchNextPage,
289 }