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