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 isError: r?.isError,
178 // Read react-db's real `isEnabled` field so the suite catches a broken
179 // one (deriving from status would mask it).
180 isEnabled: r?.isEnabled,
181 })
182 },
183 async flush() {
184 await act(async () => {
185 await new Promise((resolve) => setTimeout(resolve, 0))
186 })
187 },
188 async apply(fn: () => void) {
189 await act(async () => {
190 fn()
191 await new Promise((resolve) => setTimeout(resolve, 0))
192 })
193 },
194 unmount() {
195 hook.unmount()
196 },
197 }
198}
199
200const reactDriver: LiveQueryDriver = {
201 name: `react`,
202 disabledRepresentation: `absent`,
203 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
204 makeSource,
205 makeDeferredSource,
206 makePrecreated,
207 makeErrorSource,
208 mount,
209 mountControllable,
210 mountCollection,
211 mountConfig,
212 mountDisabled,
213 knownGaps: [],
214 features: { serverSnapshot: true, suspense: true },
215}
216
217runSuite(reactDriver)
218it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
219 const source = makeSource([
220 { id: `1`, rank: 1 },
221 { id: `2`, rank: 2 },
222 { id: `3`, rank: 3 },
223 ])
224 const commits: Array<{ ids: Array<string>; status: string }> = []
225 const hook = renderHook(() => {
226 const result = useLiveQuery((q) =>
227 q
228 .from({ row: source.collection })
229 .orderBy(({ row }) => row.rank)
230 .limit(2),
231 )
232 useLayoutEffect(() => {
233 commits.push({
234 ids: result.data.map(({ id }) => id),
235 status: result.status,
236 })
237 })
238 return result
239 })
240
241 try {
242 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
243 } finally {
244 const liveQueryCollection = hook.result.current.collection
245 hook.unmount()
246 await liveQueryCollection.cleanup()
247 await source.collection.cleanup()
248 }
249})
250
251it(`preserves raw result types through the actual driver reader`, () => {
252 const raw: Record<string, unknown> = {
253 data: [{ id: `a`, value: undefined }],
254 state: new Map(),
255 status: `disabled`,
256 isReady: false,
257 isError: false,
258 isEnabled: false,
259 }
260 const hook = renderHook(() => raw)
261 const handle = makeHandle(hook)
262 try {
263 const healthy = handle.current()
264 expect(healthy.data).toBe(raw.data)
265 expect(healthy.state).toBe(raw.state)
266 expect(healthy.isReady).toBe(false)
267 expect(healthy.isError).toBe(false)
268 expect(healthy.isEnabled).toBe(false)
269 for (const key of [`status`, `isReady`, `isError`, `isEnabled`]) {
270 const original = raw[key]
271 delete raw[key]
272 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
273 for (const invalid of key === `status`
274 ? [undefined, 0]
275 : [undefined, 0, ``]) {
276 raw[key] = invalid
277 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
278 }
279 raw[key] = original
280 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
281 }
282 } finally {
283 handle.unmount()
284 }
285})