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 gt,
13} from '@tanstack/db'
14import {
15 effectScope,
16 nextTick,
17 onScopeDispose,
18 reactive,
19 ref,
20 shallowRef,
21} from 'vue'
22import { describe, expect, it } from 'vitest'
23import { mockSyncCollectionOptions } from '../../db/tests/utils'
24import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite'
25import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
26import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
27import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
28import type {
29 InfiniteQueryConfig,
30 InfiniteQueryDriver,
31 InfiniteQueryHandle,
32} from '../../db/tests/conformance/infinite-contract'
33import type {
34 QueryBuild,
35 SourceHandle,
36} from '../../db/tests/conformance/contract'
37
38let sourceSequence = 0
39
40function makeSource<T extends { id: string }>(
41 initialData: ReadonlyArray<T>,
42): SourceHandle<T> {
43 const collection = createCollection(
44 mockSyncCollectionOptions<T>({
45 autoIndex: `eager`,
46 id: `infinite-conformance-vue-${sourceSequence++}`,
47 getKey: (row) => row.id,
48 initialData: [...initialData],
49 }),
50 )
51 const write = (type: `insert` | `update` | `delete`, value: T) => {
52 collection.utils.begin()
53 collection.utils.write({ type, value })
54 collection.utils.commit()
55 }
56 return {
57 collection,
58 insert: (row) => write(`insert`, row),
59 update: (row) => write(`update`, row),
60 remove: (row) => write(`delete`, row),
61 }
62}
63
64function makePrecreated(build: QueryBuild) {
65 return {
66 collection: createLiveQueryCollection({ query: build as any }),
67 }
68}
69
70async function settle(): Promise<void> {
71 await nextTick()
72 await new Promise((resolve) => setTimeout(resolve, 0))
73}
74
75function runInScope<R>(fn: () => R) {
76 const scope = effectScope()
77 let result!: R
78 withScopeSetup(
79 () =>
80 scope.run(() => {
81 result = fn()
82 }),
83 () => scope.stop(),
84 )
85 return { result, scope }
86}
87
88function makeHandle(
89 result: any,
90 scope: ReturnType<typeof effectScope>,
91): InfiniteQueryHandle {
92 return {
93 current() {
94 return {
95 data: result.data.value,
96 pages: result.pages.value,
97 pageParams: result.pageParams.value,
98 hasNextPage: result.hasNextPage.value,
99 isFetchingNextPage: result.isFetchingNextPage.value,
100 error: result.error.value,
101 status: result.status.value,
102 collection: result.collection.value,
103 }
104 },
105 fetchNextPage: () => result.fetchNextPage(),
106 flush: settle,
107 async apply(fn) {
108 fn()
109 await settle()
110 },
111 unmount() {
112 scope.stop()
113 },
114 }
115}
116
117function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
118 const { result, scope } = runInScope(() =>
119 useLiveInfiniteQuery(build as any, config as any),
120 )
121 return makeHandle(result, scope)
122}
123
124function mountControllable<P>(
125 build: (q: any, param: P) => any,
126 initial: P,
127 config: InfiniteQueryConfig = {},
128) {
129 const param = ref(initial) as { value: P }
130 const { result, scope } = runInScope(() =>
131 useLiveInfiniteQuery((q: any) => build(q, param.value), config as any, [
132 param,
133 ]),
134 )
135 const handle = makeHandle(result, scope)
136 return {
137 ...handle,
138 setParamSync(next: P) {
139 param.value = next
140 },
141 }
142}
143
144function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
145 const { result, scope } = runInScope(() =>
146 useLiveInfiniteQuery(collection, config as any),
147 )
148 return makeHandle(result, scope)
149}
150
151function mountCollectionControllable(
152 initial: any,
153 config: InfiniteQueryConfig = {},
154) {
155 const collection = shallowRef(initial)
156 const { result, scope } = runInScope(() =>
157 useLiveInfiniteQuery(collection, config as any),
158 )
159 const handle = makeHandle(result, scope)
160 return {
161 ...handle,
162 replaceCollectionSync(next: any) {
163 collection.value = next
164 },
165 }
166}
167
168function mountConfigControllable(
169 build: QueryBuild,
170 initial: InfiniteQueryConfig,
171) {
172 const config = reactive({ ...initial })
173 const { result, scope } = runInScope(() =>
174 useLiveInfiniteQuery(build as any, config as any),
175 )
176 const handle = makeHandle(result, scope)
177 return {
178 ...handle,
179 setConfigSync(next: InfiniteQueryConfig) {
180 delete config.pageSize
181 delete config.initialPageParam
182 Object.assign(config, next)
183 },
184 }
185}
186
187function mountInputControllable(
188 collection: any,
189 build: QueryBuild,
190 config: InfiniteQueryConfig = {},
191) {
192 const kind = ref<`collection` | `query`>(`collection`)
193 const { result, scope } = runInScope(() =>
194 useLiveInfiniteQuery(
195 (q: any) => (kind.value === `collection` ? collection : build(q)),
196 config as any,
197 [kind],
198 ),
199 )
200 const handle = makeHandle(result, scope)
201 return {
202 ...handle,
203 setInputKindSync(next: `collection` | `query`) {
204 kind.value = next
205 },
206 }
207}
208
209const vueInfiniteDriver: InfiniteQueryDriver = {
210 name: `vue`,
211 gt,
212 makeSource,
213 makeOnDemandSource: (data, delay) =>
214 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
215 makePrecreated,
216 mount,
217 mountControllable,
218 mountCollection,
219 mountCollectionControllable,
220 mountConfigControllable,
221 mountInputControllable,
222 knownGaps: [],
223}
224
225runInfiniteQuerySuite(vueInfiniteDriver)
226
227describe(`infinite driver scope ownership`, () => {
228 it(`retains successful scope until its owner disposes`, () => {
229 let calls = 0
230 const { scope } = runInScope(() =>
231 onScopeDispose(() => {
232 calls++
233 }),
234 )
235 expect(calls).toBe(0)
236 scope.stop()
237 expect(calls).toBe(1)
238 })
239 it.each([false, true])(
240 `cleans failed setup, cleanupFails=%s`,
241 (cleanupFails) => {
242 const primary = new Error(`setup`)
243 const secondary = new Error(`cleanup`)
244 let calls = 0
245 let caught: unknown
246 try {
247 runInScope(() => {
248 onScopeDispose(() => {
249 calls++
250 if (cleanupFails) throw secondary
251 })
252 throw primary
253 })
254 } catch (error) {
255 caught = error
256 }
257 expect(calls).toBe(1)
258 if (cleanupFails) {
259 expect(caught).toBeInstanceOf(AggregateError)
260 expect((caught as AggregateError).errors).toEqual([primary, secondary])
261 expect((caught as AggregateError).cause).toBe(primary)
262 } else expect(caught).toBe(primary)
263 },
264 )
265})