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 gt,
17} from '@tanstack/db'
18import { mockSyncCollectionOptions } from '../../db/tests/utils'
19import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite'
20import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
21import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
22import type { RenderHookResult } from '@testing-library/react'
23import type {
24 InfiniteQueryConfig,
25 InfiniteQueryDriver,
26 InfiniteQueryHandle,
27} from '../../db/tests/conformance/infinite-contract'
28import type { QueryBuild } from '../../db/tests/conformance/contract'
29
30let sourceSequence = 0
31
32function makeSource<T extends { id: string }>(initialData: ReadonlyArray<T>) {
33 const collection = createCollection(
34 mockSyncCollectionOptions<T>({
35 autoIndex: `eager`,
36 id: `infinite-conformance-react-${sourceSequence++}`,
37 getKey: (row) => row.id,
38 initialData: [...initialData],
39 }),
40 )
41 const write = (type: `insert` | `update` | `delete`, value: T) => {
42 collection.utils.begin()
43 collection.utils.write({ type, value })
44 collection.utils.commit()
45 }
46 return {
47 collection,
48 insert: (row: T) => write(`insert`, row),
49 update: (row: T) => write(`update`, row),
50 remove: (row: T) => write(`delete`, row),
51 }
52}
53
54function makePrecreated(build: QueryBuild) {
55 return {
56 collection: createLiveQueryCollection({ query: build as any }),
57 }
58}
59
60function makeHandle(hook: RenderHookResult<any, any>): InfiniteQueryHandle {
61 return {
62 current() {
63 const result = hook.result.current
64 return {
65 data: result.data,
66 pages: result.pages,
67 pageParams: result.pageParams,
68 hasNextPage: result.hasNextPage,
69 isFetchingNextPage: result.isFetchingNextPage,
70 error: result.error,
71 status: result.status,
72 collection: result.collection,
73 }
74 },
75 fetchNextPage() {
76 let request!: Promise<void>
77 act(() => {
78 request = hook.result.current.fetchNextPage()
79 })
80 return request
81 },
82 async flush() {
83 await act(async () => {
84 await new Promise((resolve) => setTimeout(resolve, 0))
85 })
86 },
87 async apply(fn) {
88 await act(async () => {
89 fn()
90 await Promise.resolve()
91 })
92 },
93 unmount() {
94 hook.unmount()
95 },
96 }
97}
98
99function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
100 return makeHandle(
101 renderHook(() => useLiveInfiniteQuery(build as any, config as any)),
102 )
103}
104
105function mountControllable<P>(
106 build: (q: any, param: P) => any,
107 initial: P,
108 config: InfiniteQueryConfig = {},
109) {
110 const hook = renderHook(
111 ({ param }: { param: P }) =>
112 useLiveInfiniteQuery((q: any) => build(q, param), config as any, [param]),
113 { initialProps: { param: initial } },
114 )
115 const handle = makeHandle(hook)
116 return {
117 ...handle,
118 setParamSync(param: P) {
119 act(() => hook.rerender({ param }))
120 },
121 }
122}
123
124function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
125 return makeHandle(
126 renderHook(() => useLiveInfiniteQuery(collection, config as any)),
127 )
128}
129
130function mountCollectionControllable(
131 initial: any,
132 config: InfiniteQueryConfig = {},
133) {
134 const hook = renderHook(
135 ({ collection }) => useLiveInfiniteQuery(collection, config as any),
136 { initialProps: { collection: initial } },
137 )
138 const handle = makeHandle(hook)
139 return {
140 ...handle,
141 replaceCollectionSync(collection: any) {
142 act(() => hook.rerender({ collection }))
143 },
144 }
145}
146
147function mountConfigControllable(
148 build: QueryBuild,
149 initial: InfiniteQueryConfig,
150) {
151 const hook = renderHook(
152 ({ config }: { config: InfiniteQueryConfig }) =>
153 useLiveInfiniteQuery(build as any, config as any),
154 { initialProps: { config: initial } },
155 )
156 const handle = makeHandle(hook)
157 return {
158 ...handle,
159 setConfigSync(config: InfiniteQueryConfig) {
160 act(() => hook.rerender({ config }))
161 },
162 }
163}
164
165function mountInputControllable(
166 collection: any,
167 build: QueryBuild,
168 config: InfiniteQueryConfig = {},
169) {
170 const hook = renderHook(
171 ({ kind }: { kind: `collection` | `query` }) =>
172 useLiveInfiniteQuery(
173 kind === `collection` ? collection : build,
174 config as any,
175 [kind],
176 ),
177 {
178 initialProps: {
179 kind: `collection` as `collection` | `query`,
180 },
181 },
182 )
183 const handle = makeHandle(hook)
184 return {
185 ...handle,
186 setInputKindSync(kind: `collection` | `query`) {
187 act(() => hook.rerender({ kind }))
188 },
189 }
190}
191
192const reactInfiniteDriver: InfiniteQueryDriver = {
193 name: `react`,
194 gt,
195 makeSource,
196 makeOnDemandSource: (data, delay) =>
197 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
198 makePrecreated,
199 mount,
200 mountControllable,
201 mountCollection,
202 mountCollectionControllable,
203 mountConfigControllable,
204 mountInputControllable,
205 knownGaps: [],
206}
207
208runInfiniteQuerySuite(reactInfiniteDriver)
209
210it(`publishes query-function pages in the first non-idle layout commit after mount and dependency replacement`, async () => {
211 const source = makeSource(
212 Array.from({ length: 10 }, (_, index) => ({
213 id: String(index + 1),
214 rank: index + 1,
215 })),
216 )
217 const commits: Array<{ ranks: Array<number>; status: string }> = []
218 const liveQueryCollections = new Set<{ cleanup: () => Promise<void> }>()
219 const hook = renderHook(
220 ({ minimum }: { minimum: number }) => {
221 const result = useLiveInfiniteQuery(
222 (q) =>
223 q
224 .from({ row: source.collection })
225 .where(({ row }) => gt(row.rank, minimum))
226 .orderBy(({ row }) => row.rank, `desc`),
227 { pageSize: 3 },
228 [minimum],
229 )
230 useLayoutEffect(() => {
231 if (!result.collection) {
232 throw new Error(`Expected an enabled infinite-query collection`)
233 }
234 liveQueryCollections.add(result.collection)
235 commits.push({
236 ranks: result.data.map(({ rank }) => rank),
237 status: result.status,
238 })
239 })
240 return result
241 },
242 { initialProps: { minimum: 0 } },
243 )
244
245 try {
246 await waitFor(() => expect(hook.result.current.status).toBe(`ready`))
247 expect(commits.find(({ status }) => status !== `idle`)).toEqual({
248 ranks: [10, 9, 8],
249 status: `ready`,
250 })
251 commits.length = 0
252 act(() => hook.rerender({ minimum: 8 }))
253 await waitFor(() =>
254 expect(hook.result.current.data.map(({ rank }) => rank)).toEqual([10, 9]),
255 )
256 expect(commits.find(({ status }) => status !== `idle`)).toEqual({
257 ranks: [10, 9],
258 status: `ready`,
259 })
260 } finally {
261 hook.unmount()
262 await Promise.all(
263 Array.from(liveQueryCollections, (collection) => collection.cleanup()),
264 )
265 await source.collection.cleanup()
266 }
267})