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

useLiveInfiniteQuery.svelte.ts

276 lines8.3 KB

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