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