Open History to see the last commit
1/**
2 * Vue driver for the shared infinite-query conformance suite.
3 *
4 * The effect scope owns the hook, and `nextTick` defines Vue's observation cut.
5 * Sources and query operators stay in this package's module realm. The shared
6 * suite, not this bridge, owns the ordered-prefix and page-ledger model.
7 */
8import {
9 BTreeIndex,
10 createCollection,
11 createLiveQueryCollection,
12 createLiveQueryWindowController,
13 eq,
14 gt,
15} from '@tanstack/db'
16import {
17 effectScope,
18 nextTick,
19 onScopeDispose,
20 reactive,
21 ref,
22 shallowRef,
23 watch,
24} from 'vue'
25import { describe, expect, it } from 'vitest'
26import { mockSyncCollectionOptions } from '../../db/tests/utils'
27import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite-oracle'
28import { registerInfiniteQueryUnitScenarios } from '../../db/tests/conformance/infinite-suite-cases'
29import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
30import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
31import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
32import type {
33 InfiniteQueryConfig,
34 InfiniteQueryDriver,
35 InfiniteQueryHandle,
36 InfiniteQueryObservation,
37} from '../../db/tests/conformance/infinite-contract'
38import type {
39 QueryBuild,
40 SourceHandle,
41} from '../../db/tests/conformance/contract'
42
43let sourceSequence = 0
44
45function makeSource<T extends { id: string }>(
46 initialData: ReadonlyArray<T>,
47 collectionId?: string,
48): SourceHandle<T> {
49 const collection = createCollection(
50 mockSyncCollectionOptions<T>({
51 autoIndex: `eager`,
52 id: collectionId ?? `infinite-conformance-vue-${sourceSequence++}`,
53 getKey: (row) => row.id,
54 initialData: [...initialData],
55 }),
56 )
57 const write = (type: `insert` | `update` | `delete`, value: T) => {
58 collection.utils.begin()
59 collection.utils.write({ type, value })
60 collection.utils.commit()
61 }
62 return {
63 collection,
64 insert: (row) => write(`insert`, row),
65 update: (row) => write(`update`, row),
66 remove: (row) => write(`delete`, row),
67 }
68}
69
70function makePrecreated(build: QueryBuild) {
71 return {
72 collection: createLiveQueryCollection({ query: build as any }),
73 }
74}
75
76async function settle(): Promise<void> {
77 await nextTick()
78 await new Promise((resolve) => setTimeout(resolve, 0))
79}
80
81function runInScope<R>(fn: () => R) {
82 const scope = effectScope()
83 let result!: R
84 withScopeSetup(
85 () =>
86 scope.run(() => {
87 result = fn()
88 }),
89 () => scope.stop(),
90 )
91 return { result, scope }
92}
93
94type Observations = Array<InfiniteQueryObservation>
95
96function observe(result: any): InfiniteQueryObservation {
97 return {
98 status: result.status.value,
99 ids: result.data.value.map((row: { id: string }) => row.id),
100 pages: result.pages.value.map((page: Array<{ id: string }>) =>
101 page.map((row) => row.id),
102 ),
103 hasNextPage: result.hasNextPage.value,
104 }
105}
106
107// Vue renders the value present after setup, then at each pre-flush. A
108// pre-flush watcher sees what a component would render, not each synchronous
109// intermediate write that the same tick overwrites.
110function recordPublications<R>(result: R, log: Observations): R {
111 log.push(observe(result))
112 watch(
113 () => observe(result),
114 (observation) => {
115 log.push(observation)
116 },
117 { flush: `pre` },
118 )
119 return result
120}
121
122function makeHandle(
123 result: any,
124 scope: ReturnType<typeof effectScope>,
125 log: Observations,
126): InfiniteQueryHandle {
127 return {
128 observations: () => log,
129 current() {
130 return {
131 data: result.data.value,
132 pages: result.pages.value,
133 pageParams: result.pageParams.value,
134 hasNextPage: result.hasNextPage.value,
135 isFetchingNextPage: result.isFetchingNextPage.value,
136 isLoadingError: result.isLoadingError.value,
137 status: result.status.value,
138 collection: result.collection.value,
139 }
140 },
141 fetchNextPage: () => result.fetchNextPage(),
142 flush: settle,
143 async apply(fn) {
144 fn()
145 await settle()
146 },
147 unmount() {
148 scope.stop()
149 },
150 }
151}
152
153function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
154 const log: Observations = []
155 const { result, scope } = runInScope(() =>
156 recordPublications(useLiveInfiniteQuery(build as any, config as any), log),
157 )
158 return makeHandle(result, scope, log)
159}
160
161function mountControllable<P>(
162 build: (q: any, param: P) => any,
163 initial: P,
164 config: InfiniteQueryConfig = {},
165) {
166 const param = ref(initial) as { value: P }
167 const log: Observations = []
168 const { result, scope } = runInScope(() =>
169 recordPublications(
170 useLiveInfiniteQuery((q: any) => build(q, param.value), config as any, [
171 param,
172 ]),
173 log,
174 ),
175 )
176 const handle = makeHandle(result, scope, log)
177 return {
178 ...handle,
179 setParamSync(next: P) {
180 param.value = next
181 },
182 }
183}
184
185function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
186 const log: Observations = []
187 const { result, scope } = runInScope(() =>
188 recordPublications(useLiveInfiniteQuery(collection, config as any), log),
189 )
190 return makeHandle(result, scope, log)
191}
192
193function mountCollectionControllable(
194 initial: any,
195 config: InfiniteQueryConfig = {},
196) {
197 const collection = shallowRef(initial)
198 const log: Observations = []
199 const { result, scope } = runInScope(() =>
200 recordPublications(useLiveInfiniteQuery(collection, config as any), log),
201 )
202 const handle = makeHandle(result, scope, log)
203 return {
204 ...handle,
205 replaceCollectionSync(next: any) {
206 collection.value = next
207 },
208 }
209}
210
211function mountConfigControllable(
212 build: QueryBuild,
213 initial: InfiniteQueryConfig,
214) {
215 const config = reactive({ ...initial })
216 const log: Observations = []
217 const { result, scope } = runInScope(() =>
218 recordPublications(useLiveInfiniteQuery(build as any, config as any), log),
219 )
220 const handle = makeHandle(result, scope, log)
221 return {
222 ...handle,
223 setConfigSync(next: InfiniteQueryConfig) {
224 delete config.pageSize
225 delete config.initialPageParam
226 Object.assign(config, next)
227 },
228 }
229}
230
231function mountInputControllable(
232 collection: any,
233 build: QueryBuild,
234 config: InfiniteQueryConfig = {},
235) {
236 const kind = ref<`collection` | `query`>(`collection`)
237 const log: Observations = []
238 const { result, scope } = runInScope(() =>
239 recordPublications(
240 useLiveInfiniteQuery(
241 (q: any) => (kind.value === `collection` ? collection : build(q)),
242 config as any,
243 [kind],
244 ),
245 log,
246 ),
247 )
248 const handle = makeHandle(result, scope, log)
249 return {
250 ...handle,
251 setInputKindSync(next: `collection` | `query`) {
252 kind.value = next
253 },
254 }
255}
256
257const vueInfiniteDriver: InfiniteQueryDriver = {
258 name: `vue`,
259 // Reactive reads decide when the query compiles again.
260 comparesQueryIdentity: false,
261 gt,
262 eq,
263 makeSource,
264 makeOnDemandSource: (data, delay) =>
265 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
266 makeLaggingOnDemandSource: (data) =>
267 makeInfiniteOnDemandSource(
268 { createCollection, BTreeIndex },
269 data,
270 undefined,
271 `lagging`,
272 ),
273 makePrecreated,
274 makeWindowController: createLiveQueryWindowController,
275 mount,
276 mountControllable,
277 mountCollection,
278 mountCollectionControllable,
279 mountConfigControllable,
280 mountInputControllable,
281 knownGaps: [],
282}
283
284runInfiniteQuerySuite(vueInfiniteDriver, registerInfiniteQueryUnitScenarios)
285
286describe(`infinite driver scope ownership`, () => {
287 it(`retains successful scope until its owner disposes`, () => {
288 let calls = 0
289 const { scope } = runInScope(() =>
290 onScopeDispose(() => {
291 calls++
292 }),
293 )
294 expect(calls).toBe(0)
295 scope.stop()
296 expect(calls).toBe(1)
297 })
298 it.each([false, true])(
299 `cleans failed setup, cleanupFails=%s`,
300 (cleanupFails) => {
301 const primary = new Error(`setup`)
302 const secondary = new Error(`cleanup`)
303 let calls = 0
304 let caught: unknown
305 try {
306 runInScope(() => {
307 onScopeDispose(() => {
308 calls++
309 if (cleanupFails) throw secondary
310 })
311 throw primary
312 })
313 } catch (error) {
314 caught = error
315 }
316 expect(calls).toBe(1)
317 if (cleanupFails) {
318 expect(caught).toBeInstanceOf(AggregateError)
319 expect((caught as AggregateError).errors).toEqual([primary, secondary])
320 expect((caught as AggregateError).cause).toBe(primary)
321 } else expect(caught).toBe(primary)
322 },
323 )
324})