Open History to see the last commit
1/**
2 * React driver for the shared infinite-query conformance suite.
3 *
4 * `renderHook`, `act`, and the hook result are the only React-specific layer.
5 * Sources and query operators come from this package's module realm. The shared
6 * suite owns the page model and histories; this driver defines when React has
7 * committed enough work for those public observations to be read.
8 */
9import { act, renderHook, waitFor } from '@testing-library/react'
10import { useLayoutEffect } from 'react'
11import { expect, it } from 'vitest'
12import {
13 BTreeIndex,
14 createCollection,
15 createLiveQueryCollection,
16 createLiveQueryWindowController,
17 gt,
18} from '@tanstack/db'
19import { mockSyncCollectionOptions } from '../../db/tests/utils'
20import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite-oracle'
21import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
22import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
23import type { RenderHookResult } from '@testing-library/react'
24import type {
25 InfiniteQueryConfig,
26 InfiniteQueryDriver,
27 InfiniteQueryHandle,
28 InfiniteQueryObservation,
29} from '../../db/tests/conformance/infinite-contract'
30import type { QueryBuild } from '../../db/tests/conformance/contract'
31
32let sourceSequence = 0
33
34function makeSource<T extends { id: string }>(initialData: ReadonlyArray<T>) {
35 const collection = createCollection(
36 mockSyncCollectionOptions<T>({
37 autoIndex: `eager`,
38 id: `infinite-conformance-react-${sourceSequence++}`,
39 getKey: (row) => row.id,
40 initialData: [...initialData],
41 }),
42 )
43 const write = (type: `insert` | `update` | `delete`, value: T) => {
44 collection.utils.begin()
45 collection.utils.write({ type, value })
46 collection.utils.commit()
47 }
48 return {
49 collection,
50 insert: (row: T) => write(`insert`, row),
51 update: (row: T) => write(`update`, row),
52 remove: (row: T) => write(`delete`, row),
53 }
54}
55
56function makePrecreated(build: QueryBuild) {
57 return {
58 collection: createLiveQueryCollection({ query: build as any }),
59 }
60}
61
62type Observations = Array<InfiniteQueryObservation>
63
64function observe(result: any): InfiniteQueryObservation {
65 return {
66 status: result.status,
67 ids: result.data.map((row: { id: string }) => row.id),
68 pages: result.pages.map((page: Array<{ id: string }>) =>
69 page.map((row) => row.id),
70 ),
71 hasNextPage: result.hasNextPage,
72 }
73}
74
75// React publishes at each layout commit. renderHook can coalesce a commit
76// before it returns, so only a layout effect sees every published value.
77function useRecorded<T>(result: T, log: Observations): T {
78 useLayoutEffect(() => {
79 log.push(observe(result))
80 })
81 return result
82}
83
84function makeHandle(
85 hook: RenderHookResult<any, any>,
86 log: Observations,
87): InfiniteQueryHandle {
88 return {
89 current() {
90 const result = hook.result.current
91 return {
92 data: result.data,
93 pages: result.pages,
94 pageParams: result.pageParams,
95 hasNextPage: result.hasNextPage,
96 isFetchingNextPage: result.isFetchingNextPage,
97 error: result.error,
98 status: result.status,
99 collection: result.collection,
100 }
101 },
102 observations: () => log,
103 fetchNextPage() {
104 let request!: Promise<void>
105 act(() => {
106 request = hook.result.current.fetchNextPage()
107 })
108 return request
109 },
110 async flush() {
111 await act(async () => {
112 await new Promise((resolve) => setTimeout(resolve, 0))
113 })
114 },
115 async apply(fn) {
116 await act(async () => {
117 fn()
118 await Promise.resolve()
119 })
120 },
121 unmount() {
122 hook.unmount()
123 },
124 }
125}
126
127function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
128 const log: Observations = []
129 return makeHandle(
130 renderHook(() =>
131 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
132 ),
133 log,
134 )
135}
136
137function mountControllable<P>(
138 build: (q: any, param: P) => any,
139 initial: P,
140 config: InfiniteQueryConfig = {},
141) {
142 const log: Observations = []
143 const hook = renderHook(
144 ({ param }: { param: P }) =>
145 useRecorded(
146 useLiveInfiniteQuery((q: any) => build(q, param), config as any, [
147 param,
148 ]),
149 log,
150 ),
151 { initialProps: { param: initial } },
152 )
153 const handle = makeHandle(hook, log)
154 return {
155 ...handle,
156 setParamSync(param: P) {
157 act(() => hook.rerender({ param }))
158 },
159 }
160}
161
162function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
163 const log: Observations = []
164 return makeHandle(
165 renderHook(() =>
166 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
167 ),
168 log,
169 )
170}
171
172function mountCollectionControllable(
173 initial: any,
174 config: InfiniteQueryConfig = {},
175) {
176 const log: Observations = []
177 const hook = renderHook(
178 ({ collection }) =>
179 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
180 { initialProps: { collection: initial } },
181 )
182 const handle = makeHandle(hook, log)
183 return {
184 ...handle,
185 replaceCollectionSync(collection: any) {
186 act(() => hook.rerender({ collection }))
187 },
188 }
189}
190
191function mountConfigControllable(
192 build: QueryBuild,
193 initial: InfiniteQueryConfig,
194) {
195 const log: Observations = []
196 const hook = renderHook(
197 ({ config }: { config: InfiniteQueryConfig }) =>
198 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
199 { initialProps: { config: initial } },
200 )
201 const handle = makeHandle(hook, log)
202 return {
203 ...handle,
204 setConfigSync(config: InfiniteQueryConfig) {
205 act(() => hook.rerender({ config }))
206 },
207 }
208}
209
210function mountInputControllable(
211 collection: any,
212 build: QueryBuild,
213 config: InfiniteQueryConfig = {},
214) {
215 const log: Observations = []
216 const hook = renderHook(
217 ({ kind }: { kind: `collection` | `query` }) =>
218 useRecorded(
219 useLiveInfiniteQuery(
220 kind === `collection` ? collection : build,
221 config as any,
222 [kind],
223 ),
224 log,
225 ),
226 {
227 initialProps: {
228 kind: `collection` as `collection` | `query`,
229 },
230 },
231 )
232 const handle = makeHandle(hook, log)
233 return {
234 ...handle,
235 setInputKindSync(kind: `collection` | `query`) {
236 act(() => hook.rerender({ kind }))
237 },
238 }
239}
240
241const reactInfiniteDriver: InfiniteQueryDriver = {
242 name: `react`,
243 gt,
244 makeSource,
245 makeOnDemandSource: (data, delay) =>
246 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
247 makePrecreated,
248 makeWindowController: createLiveQueryWindowController,
249 mount,
250 mountControllable,
251 mountCollection,
252 mountCollectionControllable,
253 mountConfigControllable,
254 mountInputControllable,
255 knownGaps: [],
256}
257
258runInfiniteQuerySuite(reactInfiniteDriver)
259
260it(`publishes query-function pages on the first layout commit after mount and dependency replacement`, async () => {
261 const source = makeSource(
262 Array.from({ length: 10 }, (_, index) => ({
263 id: String(index + 1),
264 rank: index + 1,
265 })),
266 )
267 const commits: Array<{ ranks: Array<number>; status: string }> = []
268 const liveQueryCollections = new Set<{ cleanup: () => Promise<void> }>()
269 const hook = renderHook(
270 ({ minimum }: { minimum: number }) => {
271 const result = useLiveInfiniteQuery(
272 (q) =>
273 q
274 .from({ row: source.collection })
275 .where(({ row }) => gt(row.rank, minimum))
276 .orderBy(({ row }) => row.rank, `desc`),
277 { pageSize: 3 },
278 [minimum],
279 )
280 useLayoutEffect(() => {
281 if (!result.collection) {
282 throw new Error(`Expected an enabled infinite-query collection`)
283 }
284 liveQueryCollections.add(result.collection)
285 commits.push({
286 ranks: result.data.map(({ rank }) => rank),
287 status: result.status,
288 })
289 })
290 return result
291 },
292 { initialProps: { minimum: 0 } },
293 )
294
295 try {
296 await waitFor(() => expect(hook.result.current.status).toBe(`ready`))
297 // The very first commit already carries data: no empty idle flash precedes
298 // it, matching useLiveQuery for a synchronously loaded source.
299 expect(commits[0]).toEqual({
300 ranks: [10, 9, 8],
301 status: `ready`,
302 })
303 commits.length = 0
304 act(() => hook.rerender({ minimum: 8 }))
305 await waitFor(() =>
306 expect(hook.result.current.data.map(({ rank }) => rank)).toEqual([10, 9]),
307 )
308 // Replacing the dependency builds a fresh eager collection, so its first
309 // commit is ready too — no idle flash on re-query.
310 expect(commits[0]).toEqual({
311 ranks: [10, 9],
312 status: `ready`,
313 })
314 } finally {
315 hook.unmount()
316 await Promise.all(
317 Array.from(liveQueryCollections, (collection) => collection.cleanup()),
318 )
319 await source.collection.cleanup()
320 }
321})