Open History to see the last commit
1import { useCallback, useLayoutEffect, useRef, useState } from 'preact/hooks'
2import {
3 bindLiveQueryWindow,
4 createLiveQuerySourceIdClaims,
5 fetchNextLiveQueryWindowPage,
6 getLiveQueryHash,
7 getLiveQueryKey,
8 identifyLiveQuery,
9 prepareLiveQueryValue,
10 readLiveQueryWindowPageShape,
11} from '@tanstack/db'
12import type {
13 Collection,
14 CollectionStatus,
15 Context,
16 InferResultType,
17 InitialQueryBuilder,
18 LiveQueryKey,
19 LiveQuerySourceIdClaims,
20 LiveQueryWindowBinding,
21 NonSingleResult,
22 QueryBuilder,
23} from '@tanstack/db'
24import type { UseLiveQueryResult } from './useLiveQuery'
25
26// Keep the generic parameter for typed config wrappers.
27export type UseLiveInfiniteQueryConfig<_TContext extends Context> = {
28 /**
29 * Explicit identity for a query whose IR cannot derive one, such as a query
30 * with functional variants. Structured queries should omit it.
31 */
32 queryKey?: LiveQueryKey
33 pageSize?: number
34 /** First result-page label, not a server cursor or remote offset. */
35 initialPageParam?: number
36}
37
38interface InfiniteQueryPagination<TRow> {
39 pages: Array<Array<TRow>>
40 pageParams: Array<number>
41 fetchNextPage: () => Promise<void>
42 hasNextPage: boolean
43 isFetchingNextPage: boolean
44}
45
46export type UseLiveInfiniteQueryReturn<TContext extends Context> =
47 UseLiveQueryResult<
48 InferResultType<TContext>[number],
49 string | number,
50 InferResultType<TContext>,
51 Collection<InferResultType<TContext>[number], string | number, {}>
52 > &
53 InfiniteQueryPagination<InferResultType<TContext>[number]>
54
55export type UseLiveInfiniteQueryReturnWithCollection<
56 TResult extends object,
57 TKey extends string | number,
58 TUtils extends Record<string, any>,
59> = UseLiveQueryResult<
60 TResult,
61 TKey,
62 Array<TResult>,
63 Collection<TResult, TKey, TUtils> & NonSingleResult
64> &
65 InfiniteQueryPagination<TResult>
66
67/** What one hook instance renders until its input or page shape changes. */
68/**
69 * Page through an ordered live query, growing one live-query Collection's
70 * window with `utils.setWindow()` instead of recreating it per page.
71 *
72 * The query must include `.orderBy()`. Its identity follows `useLiveQuery`:
73 * derived from the query IR, or named by `queryKey`. A query whose IR cannot be
74 * hashed throws `UnhashableQueryIRError` unless `queryKey` is supplied.
75 *
76 * @example
77 * const { pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
78 * (q) =>
79 * q
80 * .from({ posts: postsCollection })
81 * .orderBy(({ posts }) => posts.createdAt, `desc`),
82 * { pageSize: 20 },
83 * )
84 */
85export function useLiveInfiniteQuery<
86 TResult extends object,
87 TKey extends string | number,
88 TUtils extends Record<string, any>,
89>(
90 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
91 config: UseLiveInfiniteQueryConfig<any>,
92): UseLiveInfiniteQueryReturnWithCollection<TResult, TKey, TUtils>
93
94export function useLiveInfiniteQuery<TContext extends Context>(
95 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
96 config: UseLiveInfiniteQueryConfig<TContext>,
97): UseLiveInfiniteQueryReturn<TContext>
98
99export function useLiveInfiniteQuery(
100 queryFnOrCollection: unknown,
101 config: UseLiveInfiniteQueryConfig<any>,
102): UseLiveInfiniteQueryReturn<any> {
103 const pageShape = readLiveQueryWindowPageShape(config)
104 const claimsRef = useRef<LiveQuerySourceIdClaims | null>(null)
105 const bindingRef = useRef<LiveQueryWindowBinding | null>(null)
106
107 // A query input's identity is a hash, so a structurally equal query keeps
108 // its loaded pages and a changed one compiles again.
109 let preparedValue: unknown
110 let identity: string | undefined
111 if (typeof queryFnOrCollection === `function`) {
112 const queryKey = getLiveQueryKey(config)
113 if (queryKey) {
114 identity = getLiveQueryHash(undefined, queryKey)
115 } else {
116 preparedValue = prepareLiveQueryValue(queryFnOrCollection, undefined)
117 identity = identifyLiveQuery(
118 preparedValue,
119 {
120 claims: (claimsRef.current ??= createLiveQuerySourceIdClaims()),
121 client: undefined,
122 bindingName: `useLiveInfiniteQuery`,
123 },
124 getLiveQueryHash,
125 )
126 }
127 }
128
129 const binding = (bindingRef.current = bindLiveQueryWindow(
130 bindingRef.current,
131 {
132 ...pageShape,
133 // Compile what this render prepared, so the callback runs once.
134 input:
135 preparedValue === undefined ? queryFnOrCollection : () => preparedValue,
136 dependencies: identity === undefined ? undefined : [identity],
137 recompile: `identity`,
138 },
139 ))
140
141 const { controller } = binding
142 const snapshot = controller.getSnapshot()
143 const [, setRevision] = useState(0)
144
145 useLayoutEffect(() => {
146 const rerender = () => setRevision((revision) => revision + 1)
147 controller.subscribe(rerender)
148 // The query can publish between this render and its subscription.
149 if (controller.getSnapshot() !== snapshot) rerender()
150 if (binding.warning) console.warn(binding.warning)
151 // Each binding owns its controller, so disposal also detaches this
152 // subscription and releases its window lease.
153 return () => controller.dispose()
154 }, [controller])
155
156 const fetchNextPage = useCallback(
157 () => fetchNextLiveQueryWindowPage(controller),
158 [controller],
159 )
160
161 return {
162 data: snapshot.data,
163 get state() {
164 return snapshot.state
165 },
166 status: snapshot.status as CollectionStatus,
167 isLoading: snapshot.isLoading,
168 isReady: snapshot.isReady,
169 isIdle: snapshot.isIdle,
170 isLoadingError: snapshot.isLoadingError,
171 isCrashed: snapshot.isCrashed,
172 isCleanedUp: snapshot.isCleanedUp,
173 isSyncError: snapshot.isSyncError,
174 collection: snapshot.collection,
175 isEnabled: true,
176 pages: snapshot.pages,
177 pageParams: snapshot.pageParams,
178 fetchNextPage,
179 hasNextPage: snapshot.hasNextPage,
180 isFetchingNextPage: snapshot.isFetchingNextPage,
181 health: snapshot.health,
182 } as UseLiveInfiniteQueryReturn<any>
183}