Open History to see the last commit
1/**
2 * Preact driver for the shared infinite-query conformance suite.
3 *
4 * The probe in `render-probe.ts`, `act`, and the hook result are the only
5 * Preact-specific layer. Sources and query operators come from this package's
6 * module realm. The shared suite owns the page model and histories; this
7 * driver defines when Preact has committed enough work for those public
8 * observations to be read.
9 *
10 * Publication cut: Preact publishes at each commit, and the probe records
11 * every committed value in a layout effect. Preact has no render that skips
12 * its commit, so the first observation is the first paint.
13 *
14 * Controllable mounts capture their parameter in the query callback. The hook
15 * derives identity from the query IR, so a changed parameter recompiles and a
16 * structurally equal one keeps the loaded pages. `setParamSync` rerenders
17 * inside `act`, which commits and attaches the replacement subscription before
18 * it returns.
19 */
20import { act } from 'preact/test-utils'
21import {
22 BTreeIndex,
23 createCollection,
24 createLiveQueryCollection,
25 createLiveQueryWindowController,
26 eq,
27 gt,
28} from '@tanstack/db'
29import { mockSyncCollectionOptions } from '../../db/tests/utils'
30import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite-oracle'
31import { registerInfiniteQueryUnitScenarios } from '../../db/tests/conformance/infinite-suite-cases'
32import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
33import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
34import { renderHook, settle } from './render-probe'
35import type { MountedHook } from './render-probe'
36import type {
37 InfiniteQueryConfig,
38 InfiniteQueryDriver,
39 InfiniteQueryHandle,
40 InfiniteQueryObservation,
41} from '../../db/tests/conformance/infinite-contract'
42import type { QueryBuild } from '../../db/tests/conformance/contract'
43
44let sourceSequence = 0
45
46function makeSource<T extends { id: string }>(
47 initialData: ReadonlyArray<T>,
48 collectionId?: string,
49) {
50 const collection = createCollection(
51 mockSyncCollectionOptions<T>({
52 autoIndex: `eager`,
53 id: collectionId ?? `infinite-conformance-preact-${sourceSequence++}`,
54 getKey: (row) => row.id,
55 initialData: [...initialData],
56 }),
57 )
58 const write = (type: `insert` | `update` | `delete`, value: T) => {
59 collection.utils.begin()
60 collection.utils.write({ type, value })
61 collection.utils.commit()
62 }
63 return {
64 collection,
65 insert: (row: T) => write(`insert`, row),
66 update: (row: T) => write(`update`, row),
67 remove: (row: T) => write(`delete`, row),
68 }
69}
70
71function makePrecreated(build: QueryBuild) {
72 return {
73 collection: createLiveQueryCollection({ query: build as any }),
74 }
75}
76
77type Observations = Array<InfiniteQueryObservation>
78
79function observe(result: any): InfiniteQueryObservation {
80 return {
81 status: result.status,
82 ids: result.data.map((row: { id: string }) => row.id),
83 pages: result.pages.map((page: Array<{ id: string }>) =>
84 page.map((row) => row.id),
85 ),
86 hasNextPage: result.hasNextPage,
87 }
88}
89
90/** Mount and record every committed value as an observation. */
91function mountRecorded<P>(
92 useResult: (props: P) => unknown,
93 initialProps?: P,
94): { hook: MountedHook<P>; log: Observations } {
95 const log: Observations = []
96 const hook = renderHook(useResult, {
97 initialProps,
98 onCommit: (result) => log.push(observe(result)),
99 })
100 return { hook, log }
101}
102
103function makeHandle(
104 hook: MountedHook<any>,
105 log: Observations,
106): InfiniteQueryHandle {
107 return {
108 current() {
109 const result = hook.result.current
110 return {
111 data: result.data,
112 pages: result.pages,
113 pageParams: result.pageParams,
114 hasNextPage: result.hasNextPage,
115 isFetchingNextPage: result.isFetchingNextPage,
116 isLoadingError: result.isLoadingError,
117 status: result.status,
118 collection: result.collection,
119 }
120 },
121 observations: () => log,
122 fetchNextPage() {
123 let request!: Promise<void>
124 act(() => {
125 request = hook.result.current.fetchNextPage()
126 })
127 return request
128 },
129 flush: settle,
130 async apply(fn) {
131 await act(async () => {
132 fn()
133 await Promise.resolve()
134 })
135 },
136 unmount() {
137 hook.unmount()
138 },
139 }
140}
141
142function rerenderSync<P>(hook: MountedHook<P>, props: P): void {
143 // The probe rerenders inside `act`, so the commit and the replacement
144 // subscription complete before this returns.
145 hook.rerender(props)
146}
147
148function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
149 const { hook, log } = mountRecorded(() =>
150 useLiveInfiniteQuery(build as any, config as any),
151 )
152 return makeHandle(hook, log)
153}
154
155function mountControllable<P>(
156 build: (q: any, param: P) => any,
157 initial: P,
158 config: InfiniteQueryConfig = {},
159) {
160 const { hook, log } = mountRecorded(
161 ({ param }: { param: P }) =>
162 useLiveInfiniteQuery((q: any) => build(q, param), config as any),
163 { param: initial },
164 )
165 return {
166 ...makeHandle(hook, log),
167 setParamSync: (param: P) => rerenderSync(hook, { param }),
168 }
169}
170
171// The keyed form: the config names a queryKey chosen per step, or none.
172function mountKeyedControllable<P>(
173 build: (q: any, param: P) => any,
174 key: (param: P) => ReadonlyArray<unknown> | undefined,
175 initial: P,
176 config: InfiniteQueryConfig = {},
177) {
178 const { hook, log } = mountRecorded(
179 ({ param }: { param: P }) =>
180 useLiveInfiniteQuery((q: any) => build(q, param), {
181 ...config,
182 queryKey: key(param),
183 } as any),
184 { param: initial },
185 )
186 return {
187 ...makeHandle(hook, log),
188 setParamSync: (param: P) => rerenderSync(hook, { param }),
189 }
190}
191
192function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
193 const { hook, log } = mountRecorded(() =>
194 useLiveInfiniteQuery(collection, config as any),
195 )
196 return makeHandle(hook, log)
197}
198
199function mountCollectionControllable(
200 initial: any,
201 config: InfiniteQueryConfig = {},
202) {
203 const { hook, log } = mountRecorded(
204 ({ collection }: { collection: any }) =>
205 useLiveInfiniteQuery(collection, config as any),
206 { collection: initial },
207 )
208 return {
209 ...makeHandle(hook, log),
210 replaceCollectionSync: (collection: any) =>
211 rerenderSync(hook, { collection }),
212 }
213}
214
215function mountConfigControllable(
216 build: QueryBuild,
217 initial: InfiniteQueryConfig,
218) {
219 const { hook, log } = mountRecorded(
220 ({ config }: { config: InfiniteQueryConfig }) =>
221 useLiveInfiniteQuery(build as any, config as any),
222 { config: initial },
223 )
224 return {
225 ...makeHandle(hook, log),
226 setConfigSync: (config: InfiniteQueryConfig) =>
227 rerenderSync(hook, { config }),
228 }
229}
230
231function mountInputControllable(
232 collection: any,
233 build: QueryBuild,
234 config: InfiniteQueryConfig = {},
235) {
236 type Kind = `collection` | `query`
237 const { hook, log } = mountRecorded(
238 ({ kind }: { kind: Kind }) =>
239 useLiveInfiniteQuery(
240 kind === `collection` ? collection : build,
241 config as any,
242 ),
243 { kind: `collection` as Kind },
244 )
245 return {
246 ...makeHandle(hook, log),
247 setInputKindSync: (kind: Kind) => rerenderSync(hook, { kind }),
248 }
249}
250
251const preactInfiniteDriver: InfiniteQueryDriver = {
252 name: `preact`,
253 // Each render re-runs the query input and compares its identity.
254 comparesQueryIdentity: true,
255 gt,
256 eq,
257 makeSource,
258 makeOnDemandSource: (data, delay) =>
259 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
260 makeLaggingOnDemandSource: (data) =>
261 makeInfiniteOnDemandSource(
262 { createCollection, BTreeIndex },
263 data,
264 undefined,
265 `lagging`,
266 ),
267 makePrecreated,
268 makeWindowController: createLiveQueryWindowController,
269 mount,
270 mountControllable,
271 mountKeyedControllable,
272 mountCollection,
273 mountCollectionControllable,
274 mountConfigControllable,
275 mountInputControllable,
276 knownGaps: [],
277}
278
279runInfiniteQuerySuite(preactInfiniteDriver, registerInfiniteQueryUnitScenarios)