Open History to see the last commit
1/**
2 * Preact receives the shared inline-option binding law through its real hook.
3 * The finite grammar varies each configured option and query/key identity.
4 * Three ordinary rerenders, a source publication and identity replacement are
5 * observed at Preact commit after its native act flush. A render budget catches
6 * repeated reconstruction. Preact has no DbClient input; cache admission is
7 * therefore not its public receiving boundary.
8 */
9import { createCollection, gt } from '@tanstack/db'
10import { act } from 'preact/test-utils'
11import { afterAll, expect, test } from 'vitest'
12import { useLiveQuery } from '../src/useLiveQuery'
13import {
14 mockSyncCollectionOptions,
15 withOracleCleanup,
16} from '../../db/tests/utils'
17import {
18 boundOptionHistories,
19 captureBoundOptions,
20 checkBoundOptions,
21} from '../../db/tests/live-query-bound-options-oracle'
22import { declareOracle } from '../../db/tests/oracle-declaration'
23import { createOracleReach } from '../../db/tests/oracle-reach'
24import { renderHook, settle } from './render-probe'
25import type { InitialQueryBuilder } from '@tanstack/db'
26
27type Row = { id: string; label: string; rank: number }
28const reach = createOracleReach(`Preact bound options`, [
29 `rerender`,
30 `source-update`,
31 `identity-change`,
32 `getKey`,
33 `schema`,
34 `both`,
35 `query`,
36 `queryKey`,
37])
38afterAll(() => {
39 reach.assertReached()
40 if (process.env.TANSTACK_DB_ORACLE_STATISTICS === `1`)
41 console.info(
42 `Preact bound option reach`,
43 Object.fromEntries(reach.counts()),
44 )
45})
46declareOracle({ check: [checkBoundOptions], grammar: [boundOptionHistories] })
47test.each(boundOptionHistories)(
48 `Preact retains bound options %j`,
49 async ({ option, identity }) => {
50 reach.beginHistory()
51 const source = createCollection(
52 mockSyncCollectionOptions<Row>({
53 id: `preact-bound-options`,
54 getKey: (row) => row.id,
55 initialData: [{ id: `one`, label: `before`, rank: 1 }],
56 }),
57 )
58 const collections = new Set<{ cleanup: () => Promise<void> }>()
59 let renders = 0
60 let unmount: (() => void) | undefined
61 await withOracleCleanup(async () => {
62 const hook = renderHook(
63 ({ revision }: { revision: number }) => {
64 if (++renders > 30)
65 throw new Error(`inline options rebuilt on every render`)
66 const config = {
67 query: (q: InitialQueryBuilder) =>
68 q
69 .from({ row: source })
70 .where(({ row }) =>
71 gt(row.rank, identity === `query` ? -revision : 0),
72 ),
73 ...(identity === `queryKey` ? { queryKey: [revision] } : {}),
74 ...(option !== `schema`
75 ? { getKey: (row: Row) => `bound-${revision}-${row.id}` }
76 : {}),
77 }
78 if (option !== `getKey`)
79 Object.assign(config, {
80 schema: {
81 '~standard': {
82 version: 1,
83 vendor: `bound-options`,
84 validate: (value: unknown) => ({ value }),
85 },
86 },
87 })
88 const result = useLiveQuery(config)
89 collections.add(result.collection)
90 return result
91 },
92 { initialProps: { revision: 0 } },
93 )
94 unmount = hook.unmount
95 await settle()
96 const initial = captureBoundOptions(hook.result.current.collection)
97 for (let turn = 0; turn < 3; turn++) {
98 hook.rerender({ revision: 0 })
99 await settle()
100 checkBoundOptions(
101 initial,
102 hook.result.current.collection,
103 false,
104 option,
105 )
106 reach.reach(`rerender`)
107 }
108 act(() => {
109 source.utils.begin()
110 source.utils.write({
111 type: `update`,
112 value: { id: `one`, label: `after`, rank: 1 },
113 })
114 source.utils.commit()
115 })
116 await settle()
117 checkBoundOptions(initial, hook.result.current.collection, false, option)
118 expect(
119 hook.result.current.data.map((row: Row) => ({
120 id: row.id,
121 label: row.label,
122 })),
123 ).toEqual([{ id: `one`, label: `after` }])
124 reach.reach(`source-update`)
125 hook.rerender({ revision: 1 })
126 await settle()
127 checkBoundOptions(initial, hook.result.current.collection, true, option)
128 expect([...hook.result.current.state.keys()]).toEqual([
129 option === `schema` ? `one` : `bound-1-one`,
130 ])
131 reach.reach(`identity-change`)
132 reach.reach(option)
133 reach.reach(identity)
134 }, [
135 () => unmount?.(),
136 () =>
137 withOracleCleanup(() => {}, [
138 ...[...collections].map((collection) => () => collection.cleanup()),
139 () => source.cleanup({ dependents: true }),
140 ]),
141 ])
142 },
143)
144
145// Same-Collection config mutation must not mutate the expected references too.
146test.each(boundOptionHistories)(
147 `bound-option checker rejects in-place replacement %j`,
148 ({ option }) => {
149 const collection = { config: { getKey: () => `initial`, schema: {} } }
150 const initial = captureBoundOptions(collection)
151 if (option !== `schema`) collection.config.getKey = () => `replacement`
152 if (option !== `getKey`) collection.config.schema = {}
153 expect(() =>
154 checkBoundOptions(initial, collection, false, option),
155 ).toThrow()
156 },
157)