Open History to see the last commit
1/**
2 * React reference driver for the shared live-query conformance suite.
3 *
4 * Everything realm-sensitive — collection creation and query operators — is
5 * imported here (React package's `@tanstack/db`) and handed to the shared
6 * scenarios, so instances match what this package's `useLiveQuery` expects.
7 *
8 * All registered laws must pass; the driver has no whole-test waivers.
9 */
10import { act, renderHook } from '@testing-library/react'
11import { useLayoutEffect } from 'react'
12import {
13 coalesce,
14 count,
15 createCollection,
16 createLiveQueryCollection,
17 createOptimisticAction,
18 eq,
19 gt,
20 sum,
21} from '@tanstack/db'
22import { expect, it } from 'vitest'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
30import { expectResultSurface } from '../../db/tests/conformance/result-laws'
31import type { RenderHookResult } from '@testing-library/react'
32import type {
33 ConformanceResult,
34 ControllableHandle,
35 DeferredSourceHandle,
36 LiveQueryDriver,
37 QueryBuild,
38} from '../../db/tests/conformance/contract'
39
40let sourceSeq = 0
41
42function writer<T extends { id: string }>(collection: any) {
43 return (type: `insert` | `update` | `delete`, value: T) => {
44 collection.utils.begin()
45 collection.utils.write({ type, value })
46 collection.utils.commit()
47 }
48}
49
50function makeSource<T extends { id: string }>(initialData: ReadonlyArray<T>) {
51 const collection = createCollection(
52 mockSyncCollectionOptions<T>({
53 id: `conformance-react-${sourceSeq++}`,
54 getKey: (r) => r.id,
55 initialData: [...initialData],
56 }),
57 )
58 const write = writer<T>(collection)
59 return {
60 collection,
61 insert: (row: T) => write(`insert`, row),
62 update: (row: T) => write(`update`, row),
63 remove: (row: T) => write(`delete`, row),
64 }
65}
66
67function makeDeferredSource<
68 T extends { id: string },
69>(): DeferredSourceHandle<T> {
70 const collection = createCollection(
71 mockSyncCollectionOptionsNoInitialState<T>({
72 id: `conformance-react-${sourceSeq++}`,
73 getKey: (r) => r.id,
74 }),
75 )
76 // Start sync so the sync fn binds utils and the collection sits in `loading`
77 // (NoInitialState never calls markReady on its own).
78 collection.startSyncImmediate()
79 const write = writer<T>(collection)
80 return {
81 collection,
82 insert: (row) => write(`insert`, row),
83 update: (row) => write(`update`, row),
84 remove: (row) => write(`delete`, row),
85 emit: (rows) => {
86 collection.utils.begin()
87 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
88 collection.utils.commit()
89 },
90 markReady: () => collection.utils.markReady(),
91 }
92}
93
94function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
95 const collection = createLiveQueryCollection({
96 query: build as any,
97 startSync: opts?.startSync ?? true,
98 })
99 return { collection }
100}
101
102function makeErrorSource() {
103 const expectedError = new Error(`conformance: sync failure`)
104 let startup: { returned: true } | { returned: false; error: unknown } = {
105 returned: true,
106 }
107 const collection = createCollection<{ id: string }>({
108 id: `conformance-react-err-${sourceSeq++}`,
109 getKey: (r) => r.id,
110 startSync: false,
111 sync: {
112 sync: () => {
113 throw expectedError
114 },
115 },
116 })
117 // Starting sync throws → engine catches and sets status to `error`.
118 try {
119 collection.startSyncImmediate()
120 } catch (error) {
121 startup = { returned: false, error }
122 }
123 return { collection, expectedError, startup }
124}
125
126function mount(build: QueryBuild) {
127 const hook = renderHook(() => useLiveQuery(build as any))
128 return makeHandle(hook)
129}
130
131function mountCollection(collection: any) {
132 const hook = renderHook(() => useLiveQuery(collection))
133 return makeHandle(hook)
134}
135
136function mountConfig(build: QueryBuild) {
137 const hook = renderHook(() => useLiveQuery({ query: build as any }))
138 return makeHandle(hook)
139}
140
141function mountDisabled() {
142 // React's disabled convention: the query callback returns null.
143 const hook = renderHook(() => useLiveQuery(() => null as any))
144 return makeHandle(hook)
145}
146
147function mountControllable<P>(
148 build: (q: any, param: P) => any,
149 initial: P,
150): ControllableHandle<P> {
151 const hook = renderHook(
152 ({ param }: { param: P }) =>
153 // Param goes in the dependency list so the hook recompiles when it changes.
154 useLiveQuery((q: any) => build(q, param), [param]),
155 { initialProps: { param: initial } },
156 )
157 const handle = makeHandle(hook)
158 return {
159 ...handle,
160 async setParam(param: P) {
161 await act(async () => {
162 hook.rerender({ param })
163 })
164 await handle.flush()
165 },
166 }
167}
168
169function makeHandle(hook: RenderHookResult<any, any>) {
170 return {
171 current(): ConformanceResult {
172 const r: any = hook.result.current
173 return expectResultSurface({
174 data: r?.data,
175 state: r?.state,
176 status: r?.status,
177 isReady: r?.isReady,
178 persistedStatus: r?.persistedStatus,
179 isPersistedReady: r?.isPersistedReady,
180 persistedError: r?.persistedError,
181 isError: r?.isError,
182 // Read react-db's real `isEnabled` field so the suite catches a broken
183 // one (deriving from status would mask it).
184 isEnabled: r?.isEnabled,
185 })
186 },
187 async flush() {
188 await act(async () => {
189 await new Promise((resolve) => setTimeout(resolve, 0))
190 })
191 },
192 async apply(fn: () => void) {
193 await act(async () => {
194 fn()
195 await new Promise((resolve) => setTimeout(resolve, 0))
196 })
197 },
198 unmount() {
199 hook.unmount()
200 },
201 }
202}
203
204const reactDriver: LiveQueryDriver = {
205 name: `react`,
206 disabledRepresentation: `absent`,
207 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
208 makeSource,
209 makeDeferredSource,
210 makeLaggingSource: <T extends { id: string }>() =>
211 makeLaggingSource<T>(
212 createCollection,
213 `conformance-react-lagging-${sourceSeq++}`,
214 ),
215 makePrecreated,
216 makeErrorSource,
217 mount,
218 mountControllable,
219 mountCollection,
220 mountConfig,
221 mountDisabled,
222 knownGaps: [],
223 features: { serverSnapshot: true, suspense: true, pooledEqFilters: true },
224}
225
226runSuite(reactDriver)
227it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
228 const source = makeSource([
229 { id: `1`, rank: 1 },
230 { id: `2`, rank: 2 },
231 { id: `3`, rank: 3 },
232 ])
233 const commits: Array<{ ids: Array<string>; status: string }> = []
234 const hook = renderHook(() => {
235 const result = useLiveQuery((q) =>
236 q
237 .from({ row: source.collection })
238 .orderBy(({ row }) => row.rank)
239 .limit(2),
240 )
241 useLayoutEffect(() => {
242 commits.push({
243 ids: result.data.map(({ id }) => id),
244 status: result.status,
245 })
246 })
247 return result
248 })
249
250 try {
251 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
252 } finally {
253 const liveQueryCollection = hook.result.current.collection
254 hook.unmount()
255 await liveQueryCollection.cleanup()
256 await source.collection.cleanup()
257 }
258})
259
260it(`publishes a synchronous full-source ordered limit in the first layout commit`, async () => {
261 // A function filter makes the plan load its whole source; that initial load
262 // shares the synchronous readiness cut with an ordinary ordered request.
263 const source = makeSource([
264 { id: `1`, rank: 1 },
265 { id: `2`, rank: 2 },
266 { id: `3`, rank: 3 },
267 ])
268 const commits: Array<{ ids: Array<string>; status: string }> = []
269 const hook = renderHook(() => {
270 const result = useLiveQuery((q) =>
271 q
272 .from({ row: source.collection })
273 .fn.where(({ row }) => row.rank > 0)
274 .orderBy(({ row }) => row.rank)
275 .limit(2),
276 )
277 useLayoutEffect(() => {
278 commits.push({
279 ids: result.data.map(({ id }) => id),
280 status: result.status,
281 })
282 })
283 return result
284 })
285
286 try {
287 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
288 } finally {
289 const liveQueryCollection = hook.result.current.collection
290 hook.unmount()
291 await liveQueryCollection.cleanup()
292 await source.collection.cleanup()
293 }
294})
295
296it(`preserves raw result types through the actual driver reader`, () => {
297 const raw: Record<string, unknown> = {
298 data: [{ id: `a`, value: undefined }],
299 state: new Map(),
300 status: `disabled`,
301 isReady: false,
302 isError: false,
303 isEnabled: false,
304 }
305 const hook = renderHook(() => raw)
306 const handle = makeHandle(hook)
307 try {
308 const healthy = handle.current()
309 expect(healthy.data).toBe(raw.data)
310 expect(healthy.state).toBe(raw.state)
311 expect(healthy.isReady).toBe(false)
312 expect(healthy.isError).toBe(false)
313 expect(healthy.isEnabled).toBe(false)
314 for (const key of [`status`, `isReady`, `isError`, `isEnabled`]) {
315 const original = raw[key]
316 delete raw[key]
317 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
318 for (const invalid of key === `status`
319 ? [undefined, 0]
320 : [undefined, 0, ``]) {
321 raw[key] = invalid
322 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
323 }
324 raw[key] = original
325 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
326 }
327 } finally {
328 handle.unmount()
329 }
330})