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