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(
95 build: QueryBuild,
96 opts?: { startSync?: boolean; gcTime?: number },
97) {
98 const collection = createLiveQueryCollection({
99 query: build as any,
100 startSync: opts?.startSync ?? true,
101 gcTime: opts?.gcTime,
102 })
103 return { collection }
104}
105
106function makeErrorSource() {
107 const expectedError = new Error(`conformance: sync failure`)
108 let startup: { returned: true } | { returned: false; error: unknown } = {
109 returned: true,
110 }
111 const collection = createCollection<{ id: string }>({
112 id: `conformance-react-err-${sourceSeq++}`,
113 getKey: (r) => r.id,
114 startSync: false,
115 sync: {
116 sync: () => {
117 throw expectedError
118 },
119 },
120 })
121 // Starting sync throws → engine catches and sets status to `error`.
122 try {
123 collection.startSyncImmediate()
124 } catch (error) {
125 startup = { returned: false, error }
126 }
127 return { collection, expectedError, startup }
128}
129
130function mount(build: QueryBuild) {
131 const hook = renderHook(() => useLiveQuery(build as any))
132 return makeHandle(hook)
133}
134
135function mountCollection(collection: any) {
136 const hook = renderHook(() => useLiveQuery(collection))
137 return makeHandle(hook)
138}
139
140function mountConfig(build: QueryBuild, opts?: { gcTime?: number }) {
141 const hook = renderHook(() => useLiveQuery({ query: build as any, ...opts }))
142 return makeHandle(hook)
143}
144
145function mountDisabled() {
146 // React's disabled convention: the query callback returns null.
147 const hook = renderHook(() => useLiveQuery(() => null as any))
148 return makeHandle(hook)
149}
150
151function mountControllable<P>(
152 build: (q: any, param: P) => any,
153 initial: P,
154): ControllableHandle<P> {
155 const hook = renderHook(
156 ({ param }: { param: P }) =>
157 // Param goes in the dependency list so the hook recompiles when it changes.
158 useLiveQuery((q: any) => build(q, param), [param]),
159 { initialProps: { param: initial } },
160 )
161 const handle = makeHandle(hook)
162 return {
163 ...handle,
164 async setParam(param: P) {
165 await act(async () => {
166 hook.rerender({ param })
167 })
168 await handle.flush()
169 },
170 }
171}
172
173function makeHandle(hook: RenderHookResult<any, any>) {
174 return {
175 collection: () => hook.result.current?.collection ?? null,
176 current(): ConformanceResult {
177 const r: any = hook.result.current
178 return expectResultSurface({
179 data: r?.data,
180 state: r?.state,
181 status: r?.status,
182 isReady: r?.isReady,
183 persistedStatus: r?.persistedStatus,
184 isPersistedReady: r?.isPersistedReady,
185 persistedError: r?.persistedError,
186 isError: r?.isError,
187 // Read react-db's real `isEnabled` field so the suite catches a broken
188 // one (deriving from status would mask it).
189 isEnabled: r?.isEnabled,
190 })
191 },
192 async flush() {
193 await act(async () => {
194 await new Promise((resolve) => setTimeout(resolve, 0))
195 })
196 },
197 async apply(fn: () => void) {
198 await act(async () => {
199 fn()
200 await new Promise((resolve) => setTimeout(resolve, 0))
201 })
202 },
203 unmount() {
204 hook.unmount()
205 },
206 }
207}
208
209const reactDriver: LiveQueryDriver = {
210 name: `react`,
211 disabledRepresentation: `absent`,
212 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
213 makeSource,
214 makeDeferredSource,
215 makeLaggingSource: <T extends { id: string }>() =>
216 makeLaggingSource<T>(
217 createCollection,
218 `conformance-react-lagging-${sourceSeq++}`,
219 ),
220 makePrecreated,
221 makeErrorSource,
222 mount,
223 mountControllable,
224 mountCollection,
225 mountConfig,
226 mountDisabled,
227 knownGaps: [],
228 features: { serverSnapshot: true, suspense: true, pooledEqFilters: true },
229}
230
231runSuite(reactDriver)
232it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
233 const source = makeSource([
234 { id: `1`, rank: 1 },
235 { id: `2`, rank: 2 },
236 { id: `3`, rank: 3 },
237 ])
238 const commits: Array<{ ids: Array<string>; status: string }> = []
239 const hook = renderHook(() => {
240 const result = useLiveQuery((q) =>
241 q
242 .from({ row: source.collection })
243 .orderBy(({ row }) => row.rank)
244 .limit(2),
245 )
246 useLayoutEffect(() => {
247 commits.push({
248 ids: result.data.map(({ id }) => id),
249 status: result.status,
250 })
251 })
252 return result
253 })
254
255 try {
256 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
257 } finally {
258 const liveQueryCollection = hook.result.current.collection
259 hook.unmount()
260 await liveQueryCollection.cleanup()
261 await source.collection.cleanup()
262 }
263})
264
265it(`publishes a synchronous full-source ordered limit in the first layout commit`, async () => {
266 // A function filter makes the plan load its whole source; that initial load
267 // shares the synchronous readiness cut with an ordinary ordered request.
268 const source = makeSource([
269 { id: `1`, rank: 1 },
270 { id: `2`, rank: 2 },
271 { id: `3`, rank: 3 },
272 ])
273 const commits: Array<{ ids: Array<string>; status: string }> = []
274 const hook = renderHook(() => {
275 const result = useLiveQuery((q) =>
276 q
277 .from({ row: source.collection })
278 .fn.where(({ row }) => row.rank > 0)
279 .orderBy(({ row }) => row.rank)
280 .limit(2),
281 )
282 useLayoutEffect(() => {
283 commits.push({
284 ids: result.data.map(({ id }) => id),
285 status: result.status,
286 })
287 })
288 return result
289 })
290
291 try {
292 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
293 } finally {
294 const liveQueryCollection = hook.result.current.collection
295 hook.unmount()
296 await liveQueryCollection.cleanup()
297 await source.collection.cleanup()
298 }
299})
300
301it(`publishes a locale-string findOne fallback in the first layout commit`, async () => {
302 // A locale string cannot form a provider cursor. Both acquisitions return
303 // literal true from this eager source, so the first window is ready at the
304 // initial render's layout commit.
305 const source = createCollection(
306 mockSyncCollectionOptions({
307 id: `conformance-react-locale-fallback-${sourceSeq++}`,
308 getKey: (row: { id: string; at: string }) => row.id,
309 initialData: [
310 { id: `1`, at: `2026-10-01` },
311 { id: `2`, at: `2026-10-02` },
312 ],
313 autoIndex: `eager`,
314 defaultStringCollation: { stringSort: `locale` },
315 }),
316 )
317 const commits: Array<{ id: string | undefined; status: string }> = []
318 const hook = renderHook(() => {
319 const result = useLiveQuery((q) =>
320 q
321 .from({ row: source })
322 .orderBy(({ row }) => row.at, `desc`)
323 .findOne(),
324 )
325 useLayoutEffect(() => {
326 commits.push({
327 id: result.data?.id,
328 status: result.status,
329 })
330 })
331 return result
332 })
333
334 try {
335 expect(commits[0]).toEqual({ id: `2`, status: `ready` })
336 } finally {
337 const liveQueryCollection = hook.result.current.collection
338 hook.unmount()
339 await liveQueryCollection.cleanup()
340 await source.cleanup()
341 }
342})
343
344it(`preserves raw result types through the actual driver reader`, () => {
345 const raw: Record<string, unknown> = {
346 data: [{ id: `a`, value: undefined }],
347 state: new Map(),
348 status: `disabled`,
349 isReady: false,
350 isError: false,
351 isEnabled: false,
352 }
353 const hook = renderHook(() => raw)
354 const handle = makeHandle(hook)
355 try {
356 const healthy = handle.current()
357 expect(healthy.data).toBe(raw.data)
358 expect(healthy.state).toBe(raw.state)
359 expect(healthy.isReady).toBe(false)
360 expect(healthy.isError).toBe(false)
361 expect(healthy.isEnabled).toBe(false)
362 for (const key of [`status`, `isReady`, `isError`, `isEnabled`]) {
363 const original = raw[key]
364 delete raw[key]
365 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
366 for (const invalid of key === `status`
367 ? [undefined, 0]
368 : [undefined, 0, ``]) {
369 raw[key] = invalid
370 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
371 }
372 raw[key] = original
373 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
374 }
375 } finally {
376 handle.unmount()
377 }
378})