Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useCollection.ts

407 lines12.2 KB

1import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector.js"
2import { Collection, collectionsStore, preloadCollection } from "./collection"
3import type { SortedMap } from "./SortedMap"
4import type { CollectionConfig, Transaction } from "./types"
5​
6export { preloadCollection }
7​
8// Cache for snapshots to prevent infinite loops
9let snapshotCache: Map<
10 string,
11 { state: Map<unknown, unknown>; transactions: SortedMap<string, Transaction> }
12> | null = null
13​
14/**
15 * Hook that provides access to all collections
16 *
17 * @returns A Map of all collections with their states and transactions
18 */
19export function useCollections() {
20 return useSyncExternalStoreWithSelector(
21 (callback) => {
22 // Subscribe to the collections store for new collections
23 const storeUnsubscribe = collectionsStore.subscribe(() => {
24 snapshotCache = null // Invalidate cache when collections change
25 callback()
26 })
27​
28 // Subscribe to all collections' derived states and transactions
29 const collectionUnsubscribes = Array.from(
30 collectionsStore.state.values()
31 ).map((collection) => {
32 const derivedStateUnsub = collection.derivedState.subscribe(() => {
33 snapshotCache = null // Invalidate cache when state changes
34 callback()
35 })
36 const transactionsUnsub =
37 collection.transactionManager.transactions.subscribe(() => {
38 snapshotCache = null // Invalidate cache when transactions change
39 callback()
40 })
41 return () => {
42 derivedStateUnsub()
43 transactionsUnsub()
44 }
45 })
46​
47 return () => {
48 storeUnsubscribe()
49 collectionUnsubscribes.forEach((unsubscribe) => unsubscribe())
50 }
51 },
52 // Get snapshot of all collections and their transactions
53 () => {
54 if (snapshotCache) {
55 return snapshotCache
56 }
57​
58 const snapshot = new Map<
59 string,
60 {
61 state: Map<unknown, unknown>
62 transactions: SortedMap<string, Transaction>
63 }
64 >()
65 for (const [id, collection] of collectionsStore.state) {
66 snapshot.set(id, {
67 state: collection.derivedState.state,
68 transactions: collection.transactionManager.transactions.state,
69 })
70 }
71 snapshotCache = snapshot
72 return snapshot
73 },
74 // Server snapshot (same as client for now)
75 () => {
76 if (snapshotCache) {
77 return snapshotCache
78 }
79​
80 const snapshot = new Map<
81 string,
82 {
83 state: Map<unknown, unknown>
84 transactions: SortedMap<string, Transaction>
85 }
86 >()
87 for (const [id, collection] of collectionsStore.state) {
88 snapshot.set(id, {
89 state: collection.derivedState.state,
90 transactions: collection.transactionManager.transactions.state,
91 })
92 }
93 snapshotCache = snapshot
94 return snapshot
95 },
96 // Identity selector
97 (state) => state,
98 // Custom equality function for Maps
99 (a, b) => {
100 if (a === b) return true
101 if (!(a instanceof Map) || !(b instanceof Map)) return false
102 if (a.size !== b.size) return false
103 for (const [key, value] of a) {
104 const bValue = b.get(key)
105 if (!b.has(key)) return false
106 if (value instanceof Map) {
107 if (!(bValue instanceof Map)) return false
108 if (!shallow(value, bValue)) return false
109 } else if (!Object.is(value, bValue)) {
110 return false
111 }
112 }
113 return true
114 }
115 )
117​
118/**
119 * Hook to use a specific collection with React
120 *
121 * @template T - Type of data in the collection
122 * @template R - Return type of the selector function
123 * @param config - Configuration for the collection
124 * @param selector - TODO Optional selector function to transform the collection data
125 * @returns Object containing collection data and CRUD operations
126 */
127// Overload for when selector is not provided
128​
129export function useCollection<T extends object>(
130 config: CollectionConfig<T>
131): {
132 /**
133 * The collection data as a Map with keys as identifiers
134 */
135 state: Map<string, T>
136 /**
137 * The collection data as an Array of data
138 */
139 data: Array<T>
140 /**
141 * Updates an existing item in the collection
142 *
143 * @param item - The item to update (must exist in collection)
144 * @param configOrCallback - Update configuration or callback function
145 * @param maybeCallback - Callback function if config was provided
146 * @returns {Transaction} A Transaction object representing the update operation
147 * @throws {SchemaValidationError} If the updated data fails schema validation
148 * @example
149 * // Update a single item
150 * update(todo, (draft) => { draft.completed = true })
151 *
152 * // Update multiple items
153 * update([todo1, todo2], (drafts) => {
154 * drafts.forEach(draft => { draft.completed = true })
155 * })
156 *
157 * // Update with metadata
158 * update(todo, { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" })
159 */
160 update: Collection<T>[`update`]
161 /**
162 * Inserts a new item or items into the collection
163 *
164 * @param data - Single item or array of items to insert
165 * @param config - Optional configuration including key(s) and metadata
166 * @returns {Transaction} A Transaction object representing the insert operation
167 * @throws {SchemaValidationError} If the data fails schema validation
168 * @throws {Error} If more keys provided than items to insert
169 * @example
170 * // Insert a single item
171 * insert({ text: "Buy groceries", completed: false })
172 *
173 * // Insert multiple items
174 * insert([
175 * { text: "Buy groceries", completed: false },
176 * { text: "Walk dog", completed: false }
177 * ])
178 *
179 * // Insert with custom key
180 * insert({ text: "Buy groceries" }, { key: "grocery-task" })
181 */
182 insert: Collection<T>[`insert`]
183 /**
184 * Deletes an item or items from the collection
185 *
186 * @param items - Item(s) to delete (must exist in collection) or their key(s)
187 * @param config - Optional configuration including metadata
188 * @returns {Transaction} A Transaction object representing the delete operation
189 * @example
190 * // Delete a single item
191 * delete(todo)
192 *
193 * // Delete multiple items
194 * delete([todo1, todo2])
195 *
196 * // Delete with metadata
197 * delete(todo, { metadata: { reason: "completed" } })
198 */
199 delete: Collection<T>[`delete`]
201​
202// Overload for when selector is provided
203// eslint-disable-next-line
204export function useCollection<T extends object, R>(
205 config: CollectionConfig<T>,
206 selector: (d: Map<string, T>) => R
207): {
208 /**
209 * The collection data as a Map with keys as identifiers
210 */
211 state: Map<string, T>
212 /**
213 * The collection data as an Array of items
214 */
215 data: Array<T>
216 /**
217 * Updates an existing item in the collection
218 *
219 * @param item - The item to update (must exist in collection)
220 * @param configOrCallback - Update configuration or callback function
221 * @param maybeCallback - Callback function if config was provided
222 * @returns {Transaction} A Transaction object representing the update operation
223 * @throws {SchemaValidationError} If the updated data fails schema validation
224 * @example
225 * // Update a single item
226 * update(todo, (draft) => { draft.completed = true })
227 *
228 * // Update multiple items
229 * update([todo1, todo2], (drafts) => {
230 * drafts.forEach(draft => { draft.completed = true })
231 * })
232 *
233 * // Update with metadata
234 * update(todo, { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" })
235 */
236 update: Collection<T>[`update`]
237 /**
238 * Inserts a new item or items into the collection
239 *
240 * @param data - Single item or array of items to insert
241 * @param config - Optional configuration including key(s) and metadata
242 * @returns {Transaction} A Transaction object representing the insert operation
243 * @throws {SchemaValidationError} If the data fails schema validation
244 * @throws {Error} If more keys provided than items to insert
245 * @example
246 * // Insert a single item
247 * insert({ text: "Buy groceries", completed: false })
248 *
249 * // Insert multiple items
250 * insert([
251 * { text: "Buy groceries", completed: false },
252 * { text: "Walk dog", completed: false }
253 * ])
254 *
255 * // Insert with custom key
256 * insert({ text: "Buy groceries" }, { key: "grocery-task" })
257 */
258 insert: Collection<T>[`insert`]
259 /**
260 * Deletes an item or items from the collection
261 *
262 * @param items - Item(s) to delete (must exist in collection) or their key(s)
263 * @param config - Optional configuration including metadata
264 * @returns {Transaction} A Transaction object representing the delete operation
265 * @example
266 * // Delete a single item
267 * delete(todo)
268 *
269 * // Delete multiple items
270 * delete([todo1, todo2])
271 *
272 * // Delete with metadata
273 * delete(todo, { metadata: { reason: "completed" } })
274 */
275 delete: Collection<T>[`delete`]
277​
278// Implementation
279// eslint-disable-next-line
280export function useCollection<T extends object, R = any>(
281 config: CollectionConfig<T>,
282 selector?: (d: Map<string, T>) => R
283) {
284 if (selector) {
285 console.log(`selector support not yet implemented`, selector)
286 }
287 // Get or create collection instance
288 if (!collectionsStore.state.has(config.id)) {
289 // If collection doesn't exist yet, create it
290 // This will reuse any existing collection created by preloadCollection
291 collectionsStore.setState((prev) => {
292 const next = new Map(prev)
293 next.set(
294 config.id,
295 new Collection<T>({
296 id: config.id,
297 sync: config.sync,
298 mutationFn: config.mutationFn,
299 schema: config.schema,
300 })
301 )
302 return next
303 })
304 }
305​
306 const collection = collectionsStore.state.get(config.id)! as Collection<T>
307​
308 // Use a single subscription to get all the data we need
309 const result = useSyncExternalStoreWithSelector<
310 Map<string, T>,
311 { state: Map<string, T>; data: Array<T> }
312 >(
313 collection.derivedState.subscribe,
314 () => collection.derivedState.state,
315 () => collection.derivedState.state,
316 (stateMap) => {
317 return {
318 state: stateMap,
319 // derivedState & derivedArray are recomputed at the same time.
320 data: collection.derivedArray.state,
321 }
322 },
323 (a, b) => {
324 // Custom equality function that checks each property
325 if (a === b) return true
326​
327 // Check if state maps are equal
328 const stateEqual =
329 a.state.size === b.state.size &&
330 Array.from(a.state.keys()).every((key) =>
331 shallow(a.state.get(key), b.state.get(key))
332 )
333​
334 // Check if data arrays are equal
335 const dataEqual =
336 a.data.length === b.data.length &&
337 a.data.every((datum, i) => shallow(datum, b.data[i]))
338​
339 return stateEqual && dataEqual
340 }
341 )
342​
343 const returnValue = {
344 state: result.state,
345 data: result.data,
346 insert: collection.insert.bind(collection),
347 update: collection.update.bind(collection),
348 delete: collection.delete.bind(collection),
349 }
350​
351 return returnValue
353​
354/**
355 * Performs a shallow comparison between two objects
356 * Used for equality checking in React hooks
357 *
358 * @template T - Type of objects to compare
359 * @param objA - First object
360 * @param objB - Second object
361 * @returns True if objects are shallowly equal, false otherwise
362 */
363export function shallow<T>(objA: T, objB: T) {
364 if (Object.is(objA, objB)) {
365 return true
366 }
367​
368 if (
369 typeof objA !== `object` ||
370 objA === null ||
371 typeof objB !== `object` ||
372 objB === null
373 ) {
374 return false
375 }
376​
377 if (objA instanceof Map && objB instanceof Map) {
378 if (objA.size !== objB.size) return false
379 for (const [k, v] of objA) {
380 if (!objB.has(k) || !Object.is(v, objB.get(k))) return false
381 }
382 return true
383 }
384​
385 if (objA instanceof Set && objB instanceof Set) {
386 if (objA.size !== objB.size) return false
387 for (const v of objA) {
388 if (!objB.has(v)) return false
389 }
390 return true
391 }
392​
393 const keysA = Object.keys(objA)
394 if (keysA.length !== Object.keys(objB).length) {
395 return false
396 }
397​
398 for (const i of keysA) {
399 if (
400 !Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
401 !Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])
402 ) {
403 return false
404 }
405 }
406 return true