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 * `knownGaps` is populated empirically from the run below, NOT from the coverage
9 * matrix: only keys that actually fail belong here. Today that's just the
10 * universal order-only-move case (handled by the shared suite), so the list is empty.
11 */
12import { act, renderHook } from '@testing-library/react'
13import {
14 coalesce,
15 count,
16 createCollection,
17 createLiveQueryCollection,
18 createOptimisticAction,
19 eq,
20 gt,
21 sum,
22} from '@tanstack/db'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import type { RenderHookResult } from '@testing-library/react'
30import type {
31 ConformanceResult,
32 ControllableHandle,
33 DeferredSourceHandle,
34 LiveQueryDriver,
35 QueryBuild,
36 SourceHandle,
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 }>(
50 initialData: ReadonlyArray<T>,
51): SourceHandle<T> {
52 const collection = createCollection(
53 mockSyncCollectionOptions<T>({
54 id: `conformance-react-${sourceSeq++}`,
55 getKey: (r) => r.id,
56 initialData: [...initialData],
57 }),
58 )
59 const write = writer<T>(collection)
60 return {
61 collection,
62 insert: (row) => write(`insert`, row),
63 update: (row) => write(`update`, row),
64 remove: (row) => write(`delete`, row),
65 }
66}
67
68function makeDeferredSource<
69 T extends { id: string },
70>(): DeferredSourceHandle<T> {
71 const collection = createCollection(
72 mockSyncCollectionOptionsNoInitialState<T>({
73 id: `conformance-react-${sourceSeq++}`,
74 getKey: (r) => r.id,
75 }),
76 )
77 // Start sync so the sync fn binds utils and the collection sits in `loading`
78 // (NoInitialState never calls markReady on its own).
79 collection.startSyncImmediate()
80 const write = writer<T>(collection)
81 return {
82 collection,
83 insert: (row) => write(`insert`, row),
84 update: (row) => write(`update`, row),
85 remove: (row) => write(`delete`, row),
86 emit: (rows) => {
87 collection.utils.begin()
88 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
89 collection.utils.commit()
90 },
91 markReady: () => collection.utils.markReady(),
92 }
93}
94
95function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
96 const collection = createLiveQueryCollection({
97 query: build as any,
98 startSync: opts?.startSync ?? true,
99 })
100 return { collection }
101}
102
103function makeErrorSource() {
104 const collection = createCollection<{ id: string }>({
105 id: `conformance-react-err-${sourceSeq++}`,
106 getKey: (r) => r.id,
107 startSync: false,
108 sync: {
109 sync: () => {
110 throw new Error(`conformance: sync failure`)
111 },
112 },
113 })
114 // Starting sync throws → engine catches and sets status to `error`.
115 try {
116 collection.startSyncImmediate()
117 } catch {
118 // expected: the rethrown sync error; status is already `error`
119 }
120 return { collection }
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(build: QueryBuild) {
134 const hook = renderHook(() => useLiveQuery({ query: build as any }))
135 return makeHandle(hook)
136}
137
138function mountDisabled() {
139 // React's disabled convention: the query callback returns null.
140 const hook = renderHook(() => useLiveQuery(() => null as any))
141 return makeHandle(hook)
142}
143
144function mountControllable<P>(
145 build: (q: any, param: P) => any,
146 initial: P,
147): ControllableHandle<P> {
148 const hook = renderHook(
149 ({ param }: { param: P }) =>
150 // Param goes in the dependency list so the hook recompiles when it changes.
151 useLiveQuery((q: any) => build(q, param), [param]),
152 { initialProps: { param: initial } },
153 )
154 const handle = makeHandle(hook)
155 return {
156 ...handle,
157 async setParam(param: P) {
158 await act(async () => {
159 hook.rerender({ param })
160 })
161 await handle.flush()
162 },
163 }
164}
165
166function makeHandle(hook: RenderHookResult<any, any>) {
167 return {
168 current(): ConformanceResult {
169 const r: any = hook.result.current
170 return {
171 data: r?.data,
172 state: r?.state,
173 status: r?.status ?? `idle`,
174 isReady: Boolean(r?.isReady),
175 isError: Boolean(r?.isError),
176 // Read react-db's real `isEnabled` field so the suite catches a broken
177 // one (deriving from status would mask it).
178 isEnabled: Boolean(r?.isEnabled),
179 }
180 },
181 async flush() {
182 await act(async () => {
183 await new Promise((resolve) => setTimeout(resolve, 0))
184 })
185 },
186 async apply(fn: () => void) {
187 await act(async () => {
188 fn()
189 await new Promise((resolve) => setTimeout(resolve, 0))
190 })
191 },
192 unmount() {
193 hook.unmount()
194 },
195 }
196}
197
198const reactDriver: LiveQueryDriver = {
199 name: `react`,
200 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
201 makeSource,
202 makeDeferredSource,
203 makePrecreated,
204 makeErrorSource,
205 mount,
206 mountControllable,
207 mountCollection,
208 mountConfig,
209 mountDisabled,
210 knownGaps: [],
211 features: { serverSnapshot: true, suspense: true },
212}
213
214runSuite(reactDriver)