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 groupKeys,
20 gt,
21 sum,
22} from '@tanstack/db'
23import { expect, it } from 'vitest'
24import {
25 mockSyncCollectionOptions,
26 mockSyncCollectionOptionsNoInitialState,
27} from '../../db/tests/utils'
28import { useLiveQuery } from '../src/useLiveQuery'
29import { runSuite } from '../../db/tests/conformance/suite'
30import { createPublicationLog } from '../../db/tests/conformance/publication-log'
31import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
32import { makeSyncSource } from '../../db/tests/conformance/sync-source'
33import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
34import { expectResultSurface } from '../../db/tests/conformance/result-laws'
35import { rejectReadsAfterRenderError } from './rejected-binding'
36import type { RenderHookResult } from '@testing-library/react'
37import type { PooledLiveQueries } from '@tanstack/db'
38import type {
39 ConformanceResult,
40 ControllableHandle,
41 DeferredSourceHandle,
42 LiveQueryDriver,
43 QueryBuild,
44} from '../../db/tests/conformance/contract'
45
46let sourceSeq = 0
47
48function writer<T extends { id: string }>(collection: any) {
49 return (type: `insert` | `update` | `delete`, value: T) => {
50 collection.utils.begin()
51 collection.utils.write({ type, value })
52 collection.utils.commit()
53 }
54}
55
56function makeSource<T extends { id: string }>(
57 initialData: ReadonlyArray<T>,
58 collectionId?: string,
59) {
60 const collection = createCollection(
61 mockSyncCollectionOptions<T>({
62 id: collectionId ?? `conformance-react-${sourceSeq++}`,
63 getKey: (r) => r.id,
64 initialData: [...initialData],
65 }),
66 )
67 const write = writer<T>(collection)
68 return {
69 collection,
70 insert: (row: T) => write(`insert`, row),
71 update: (row: T) => write(`update`, row),
72 remove: (row: T) => write(`delete`, row),
73 }
74}
75
76function makeDeferredSource<
77 T extends { id: string },
78>(): DeferredSourceHandle<T> {
79 const collection = createCollection(
80 mockSyncCollectionOptionsNoInitialState<T>({
81 id: `conformance-react-${sourceSeq++}`,
82 getKey: (r) => r.id,
83 }),
84 )
85 // Start sync so the sync fn binds utils and the collection sits in `loading`
86 // (NoInitialState never calls markReady on its own).
87 collection.startSyncImmediate()
88 const write = writer<T>(collection)
89 return {
90 collection,
91 insert: (row) => write(`insert`, row),
92 update: (row) => write(`update`, row),
93 remove: (row) => write(`delete`, row),
94 emit: (rows) => {
95 collection.utils.begin()
96 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
97 collection.utils.commit()
98 },
99 markReady: () => collection.utils.markReady(),
100 }
101}
102
103function makePrecreated(
104 build: QueryBuild,
105 opts?: { startSync?: boolean; gcTime?: number },
106) {
107 const collection = createLiveQueryCollection({
108 query: build as any,
109 startSync: opts?.startSync ?? true,
110 gcTime: opts?.gcTime,
111 })
112 return { collection }
113}
114
115function makeErrorSource(kind: `fail` | `crash`) {
116 return makeSharedErrorSource(
117 createCollection,
118 `conformance-react-err-${sourceSeq++}`,
119 kind,
120 )
121}
122
123function mount(build: QueryBuild) {
124 const hook = renderHook(() => useLiveQuery(build as any))
125 return makeHandle(hook)
126}
127
128function mountCollection(collection: any) {
129 const hook = renderHook(() => useLiveQuery(collection))
130 return makeHandle(hook)
131}
132
133function mountConfig(
134 build: QueryBuild,
135 opts?: { gcTime?: number; pool?: PooledLiveQueries },
136) {
137 const hook = renderHook(() => useLiveQuery({ query: build as any, ...opts }))
138 return makeHandle(hook)
139}
140
141// An empty dependency list compiles the query once, at mount, where the hook
142// checks its identity and claims its sources.
143function mountWithDependencyList(build: QueryBuild) {
144 const hook = renderHook(() => useLiveQuery(build as any, []))
145 return makeHandle(hook)
146}
147
148function mountConfigWithDependencyList(
149 build: QueryBuild,
150 opts?: { gcTime?: number; pool?: PooledLiveQueries },
151) {
152 const hook = renderHook(() =>
153 useLiveQuery({ query: build as any, ...opts } as any, []),
154 )
155 return makeHandle(hook)
156}
157
158function mountDisabled() {
159 // React's disabled convention: the query callback returns null.
160 const hook = renderHook(() => useLiveQuery(() => null as any))
161 return makeHandle(hook)
162}
163
164// React compares query identity on two production paths: the identity derived
165// from the query IR on every render (the 1.0 form), and a deprecated
166// dependency list, which decides reuse and checks identity when the query
167// compiles. The suite runs once per path.
168type IdentityPath = `derived` | `dependency list`
169
170const mountControllableWith = (path: IdentityPath) =>
171 function mountControllable<P>(
172 build: (q: any, param: P) => any,
173 initial: P,
174 opts?: { pool?: PooledLiveQueries },
175 ): ControllableHandle<P> {
176 const published = createPublicationLog()
177 const hook = renderHook(
178 ({ param }: { param: P }) => {
179 const query = (q: any) => build(q, param)
180 // A pooled query uses the config form, on either identity path.
181 const result =
182 opts?.pool !== undefined
183 ? path === `derived`
184 ? useLiveQuery({ query, pool: opts.pool })
185 : useLiveQuery({ query, pool: opts.pool }, [param])
186 : path === `derived`
187 ? // The callback captures param, so its IR identity changes with it.
188 useLiveQuery(query)
189 : useLiveQuery(query, [param])
190 // A layout effect records each committed value.
191 useLayoutEffect(() => {
192 published.record(result.data, result.state)
193 })
194 return result
195 },
196 { initialProps: { param: initial } },
197 )
198 const guard = rejectReadsAfterRenderError(hook)
199 const handle = makeHandle(hook)
200 return {
201 ...handle,
202 publications: published.values,
203 statePublications: published.stateValues,
204 async setParam(param: P) {
205 await guard(() =>
206 act(async () => {
207 hook.rerender({ param })
208 }),
209 )
210 await handle.flush()
211 },
212 }
213 }
214
215function makeHandle(hook: RenderHookResult<any, any>) {
216 return {
217 collection: () => hook.result.current?.collection ?? null,
218 current(): ConformanceResult {
219 const r: any = hook.result.current
220 return expectResultSurface({
221 data: r?.data,
222 state: r?.state,
223 status: r?.status,
224 isReady: r?.isReady,
225 isLoadingError: r?.isLoadingError,
226 isCrashed: r?.isCrashed,
227 isSyncError: r?.isSyncError,
228 // Read react-db's real `isEnabled` field so the suite catches a broken
229 // one (deriving from status would mask it).
230 isEnabled: r?.isEnabled,
231 health: r?.health,
232 })
233 },
234 async flush() {
235 await act(async () => {
236 await new Promise((resolve) => setTimeout(resolve, 0))
237 })
238 },
239 async apply(fn: () => void) {
240 await act(async () => {
241 fn()
242 await new Promise((resolve) => setTimeout(resolve, 0))
243 })
244 },
245 unmount() {
246 hook.unmount()
247 },
248 }
249}
250
251// The config-object form with a queryKey chosen per step; an undefined key
252// leaves the hook to derive the identity, or to follow the dependency list.
253const mountKeyedControllableWith = (path: IdentityPath) =>
254 function mountKeyedControllable<P>(
255 build: (q: any, param: P) => any,
256 key: (param: P) => ReadonlyArray<unknown> | undefined,
257 initial: P,
258 ): ControllableHandle<P> {
259 const published = createPublicationLog()
260 const hook = renderHook(
261 ({ param }: { param: P }) => {
262 const config = {
263 query: (q: any) => build(q, param),
264 queryKey: key(param),
265 } as any
266 const result =
267 path === `derived`
268 ? useLiveQuery(config)
269 : useLiveQuery(config, [param])
270 useLayoutEffect(() => {
271 published.record(result.data, result.state)
272 })
273 return result
274 },
275 { initialProps: { param: initial } },
276 )
277 const guard = rejectReadsAfterRenderError(hook)
278 const handle = makeHandle(hook)
279 return {
280 ...handle,
281 publications: published.values,
282 statePublications: published.stateValues,
283 async setParam(param: P) {
284 await guard(() =>
285 act(async () => {
286 hook.rerender({ param })
287 }),
288 )
289 await handle.flush()
290 },
291 }
292 }
293
294const reactDriver: LiveQueryDriver = {
295 name: `react`,
296 // Each render re-runs the query input and compares its identity.
297 comparesQueryIdentity: true,
298 disabledRepresentation: `absent`,
299 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
300 makeSource,
301 makeDeferredSource,
302 makeLaggingSource: <T extends { id: string }>() =>
303 makeLaggingSource<T>(
304 createCollection,
305 `conformance-react-lagging-${sourceSeq++}`,
306 ),
307 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
308 makeSyncSource<T>(
309 createCollection,
310 `conformance-react-health-${sourceSeq++}`,
311 data,
312 ),
313 makePrecreated,
314 makeErrorSource,
315 mount,
316 mountControllable: mountControllableWith(`derived`),
317 mountKeyedControllable: mountKeyedControllableWith(`derived`),
318 mountCollection,
319 mountConfig,
320 mountDisabled,
321 knownGaps: [],
322 features: { serverSnapshot: true, suspense: true, pooledEqFilters: true },
323}
324
325runSuite(reactDriver)
326runSuite({
327 ...reactDriver,
328 name: `react (dependency list)`,
329 mount: mountWithDependencyList,
330 mountConfig: mountConfigWithDependencyList,
331 mountControllable: mountControllableWith(`dependency list`),
332 mountKeyedControllable: mountKeyedControllableWith(`dependency list`),
333})
334it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
335 const source = makeSource([
336 { id: `1`, rank: 1 },
337 { id: `2`, rank: 2 },
338 { id: `3`, rank: 3 },
339 ])
340 const commits: Array<{ ids: Array<string>; status: string }> = []
341 const hook = renderHook(() => {
342 const result = useLiveQuery((q) =>
343 q
344 .from({ row: source.collection })
345 .orderBy(({ row }) => row.rank)
346 .limit(2),
347 )
348 useLayoutEffect(() => {
349 commits.push({
350 ids: result.data.map(({ id }) => id),
351 status: result.status,
352 })
353 })
354 return result
355 })
356
357 try {
358 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
359 } finally {
360 const liveQueryCollection = hook.result.current.collection
361 hook.unmount()
362 await liveQueryCollection.cleanup()
363 await source.collection.cleanup()
364 }
365})
366
367it(`publishes a synchronous full-source ordered limit in the first layout commit`, async () => {
368 // A function filter makes the plan load its whole source; that initial load
369 // shares the synchronous readiness cut with an ordinary ordered request.
370 const source = makeSource([
371 { id: `1`, rank: 1 },
372 { id: `2`, rank: 2 },
373 { id: `3`, rank: 3 },
374 ])
375 const commits: Array<{ ids: Array<string>; status: string }> = []
376 const hook = renderHook(() => {
377 const result = useLiveQuery({
378 queryKey: [`full-source-ordered-limit`],
379 query: (q) =>
380 q
381 .from({ row: source.collection })
382 .fn.where(({ row }) => row.rank > 0)
383 .orderBy(({ row }) => row.rank)
384 .limit(2),
385 })
386 useLayoutEffect(() => {
387 commits.push({
388 ids: result.data.map(({ id }) => id),
389 status: result.status,
390 })
391 })
392 return result
393 })
394
395 try {
396 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
397 } finally {
398 const liveQueryCollection = hook.result.current.collection
399 hook.unmount()
400 await liveQueryCollection.cleanup()
401 await source.collection.cleanup()
402 }
403})
404
405it(`publishes a locale-string findOne fallback in the first layout commit`, async () => {
406 // A locale string cannot form a provider cursor. Both acquisitions return
407 // literal true from this eager source, so the first window is ready at the
408 // initial render's layout commit.
409 const source = createCollection(
410 mockSyncCollectionOptions({
411 id: `conformance-react-locale-fallback-${sourceSeq++}`,
412 getKey: (row: { id: string; at: string }) => row.id,
413 initialData: [
414 { id: `1`, at: `2026-10-01` },
415 { id: `2`, at: `2026-10-02` },
416 ],
417 autoIndex: `eager`,
418 defaultStringCollation: { stringSort: `locale` },
419 }),
420 )
421 const commits: Array<{ id: string | undefined; status: string }> = []
422 const hook = renderHook(() => {
423 const result = useLiveQuery((q) =>
424 q
425 .from({ row: source })
426 .orderBy(({ row }) => row.at, `desc`)
427 .findOne(),
428 )
429 useLayoutEffect(() => {
430 commits.push({
431 id: result.data?.id,
432 status: result.status,
433 })
434 })
435 return result
436 })
437
438 try {
439 expect(commits[0]).toEqual({ id: `2`, status: `ready` })
440 } finally {
441 const liveQueryCollection = hook.result.current.collection
442 hook.unmount()
443 await liveQueryCollection.cleanup()
444 await source.cleanup()
445 }
446})
447
448it(`preserves raw result types through the actual driver reader`, () => {
449 const raw: Record<string, unknown> = {
450 data: [{ id: `a`, value: undefined }],
451 state: new Map(),
452 status: `disabled`,
453 isReady: false,
454 isLoadingError: false,
455 isCrashed: false,
456 isSyncError: false,
457 isEnabled: false,
458 }
459 const hook = renderHook(() => raw)
460 const handle = makeHandle(hook)
461 try {
462 const healthy = handle.current()
463 expect(healthy.data).toBe(raw.data)
464 expect(healthy.state).toBe(raw.state)
465 expect(healthy.isReady).toBe(false)
466 expect(healthy.isLoadingError).toBe(false)
467 expect(healthy.isEnabled).toBe(false)
468 for (const key of [`status`, `isReady`, `isLoadingError`, `isEnabled`]) {
469 const original = raw[key]
470 delete raw[key]
471 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
472 for (const invalid of key === `status`
473 ? [undefined, 0]
474 : [undefined, 0, ``]) {
475 raw[key] = invalid
476 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
477 }
478 raw[key] = original
479 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
480 }
481 } finally {
482 handle.unmount()
483 }
484})