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

useLiveInfiniteQuery.svelte.ts

187 lines5.3 KB

1import {
2 bindLiveQueryWindow,
3 fetchNextLiveQueryWindowPage,
4 readLiveQueryWindowPageShape,
5} from '@tanstack/db'
6import { tick, untrack } from 'svelte'
7// Type-only: used in `ReturnType<typeof useLiveQuery>` below.
8import type {
9 UseLiveQueryReturnWithCollection,
10 useLiveQuery,
11} from './useLiveQuery.svelte.js'
12import type {
13 Collection,
14 Context,
15 InferResultType,
16 InitialQueryBuilder,
17 LiveQueryWindowBinding,
18 NonSingleResult,
19 QueryBuilder,
20} from '@tanstack/db'
21​
22type MaybeGetter<T> = T | (() => T)
23​
24type InfiniteQueryOptions = {
25 pageSize?: number
26 /** First result-page label, not a server cursor or remote offset. */
27 initialPageParam?: number
29​
30// Keep the generic parameter for existing typed config wrappers.
31export type LiveInfiniteQueryConfig<_TRow> = InfiniteQueryOptions
32​
33export type UseLiveInfiniteQueryConfig<TContext extends Context> =
34 LiveInfiniteQueryConfig<InferResultType<TContext>[number]>
35​
36export type UseLiveInfiniteQueryReturn<TContext extends Context> = Omit<
37 ReturnType<typeof useLiveQuery<TContext>>,
38 `data`
39> & {
40 data: InferResultType<TContext>
41 pages: Array<Array<InferResultType<TContext>[number]>>
42 pageParams: Array<number>
43 fetchNextPage: () => Promise<void>
44 hasNextPage: boolean
45 isFetchingNextPage: boolean
47​
48export type UseLiveInfiniteQueryReturnWithCollection<
49 TResult extends object,
50 TKey extends string | number,
51 TUtils extends Record<string, any>,
52> = Omit<
53 UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, Array<TResult>>,
54 `data`
55> & {
56 data: Array<TResult>
57 pages: Array<Array<TResult>>
58 pageParams: Array<number>
59 fetchNextPage: () => Promise<void>
60 hasNextPage: boolean
61 isFetchingNextPage: boolean
63​
64type EnabledLiveQueryReturn<TContext extends Context> = ReturnType<
65 typeof useLiveQuery<TContext>
67​
68/**
69 * Create a Svelte-native reactive view over the shared live-query window
70 * controller. The query must include an `orderBy` clause.
71 */
72export function useLiveInfiniteQuery<
73 TResult extends object,
74 TKey extends string | number,
75 TUtils extends Record<string, any>,
76>(
77 liveQueryCollection: MaybeGetter<
78 Collection<TResult, TKey, TUtils> & NonSingleResult
79 >,
80 config: LiveInfiniteQueryConfig<TResult>,
81): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
82​
83export function useLiveInfiniteQuery<TContext extends Context>(
84 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
85 config: UseLiveInfiniteQueryConfig<TContext>,
86 deps?: Array<() => unknown>,
87): UseLiveInfiniteQueryReturn<TContext>
88​
89export function useLiveInfiniteQuery<TContext extends Context>(
90 queryFnOrCollection: unknown,
91 config: InfiniteQueryOptions,
92 deps: Array<() => unknown> = [],
93): UseLiveInfiniteQueryReturn<TContext> {
94 // Reject an unsupported config at construction, not on first read.
95 readLiveQueryWindowPageShape(config)
96 let binding: LiveQueryWindowBinding | null = null
97​
98 // Svelte reruns this only when something it reads changed: a dependency,
99 // the page shape, or state the query callback reads.
100 const controller = $derived.by(() => {
101 const previous = binding
102 binding = bindLiveQueryWindow(previous, {
103 ...readLiveQueryWindowPageShape(config),
104 input: queryFnOrCollection,
105 dependencies: deps.map((dependency) => dependency()),
106 recompile: `always`,
107 })
108 if (binding !== previous && binding.warning) console.warn(binding.warning)
109 return binding.controller
110 })
111​
112 let snapshot = $state.raw(untrack(() => controller.getSnapshot()))
113​
114 $effect(() => {
115 const currentController = controller
116 snapshot = currentController.getSnapshot()
117 const unsubscribe = currentController.subscribe(() => {
118 snapshot = currentController.getSnapshot()
119 })
120 snapshot = currentController.getSnapshot()
121​
122 return () => {
123 unsubscribe()
124 currentController.dispose()
125 }
126 })
127​
128 const fetchNextPage = async () => {
129 // A dependency can invalidate the derived controller before Svelte runs the
130 // effect that subscribes it. Queue the imperative call until that handoff
131 // has completed so it cannot target an inactive controller.
132 await tick()
133 await fetchNextLiveQueryWindowPage(controller)
134 }
135​
136 return {
137 get state() {
138 return snapshot.state as EnabledLiveQueryReturn<TContext>[`state`]
139 },
140 get data() {
141 return snapshot.data as InferResultType<TContext>
142 },
143 get collection() {
144 return snapshot.collection as EnabledLiveQueryReturn<TContext>[`collection`]
145 },
146 get status() {
147 return snapshot.status as EnabledLiveQueryReturn<TContext>[`status`]
148 },
149 get isLoading() {
150 return snapshot.isLoading
151 },
152 get isReady() {
153 return snapshot.isReady
154 },
155 get isIdle() {
156 return snapshot.isIdle
157 },
158 get isLoadingError() {
159 return snapshot.isLoadingError
160 },
161 get isCrashed() {
162 return snapshot.isCrashed
163 },
164 get isCleanedUp() {
165 return snapshot.isCleanedUp
166 },
167 get isSyncError() {
168 return snapshot.isSyncError
169 },
170 get pages() {
171 return snapshot.pages as Array<Array<InferResultType<TContext>[number]>>
172 },
173 get pageParams() {
174 return snapshot.pageParams as Array<number>
175 },
176 get hasNextPage() {
177 return snapshot.hasNextPage
178 },
179 get isFetchingNextPage() {
180 return snapshot.isFetchingNextPage
181 },
182 get health() {
183 return snapshot.health
184 },
185 fetchNextPage,
186 }