@convex-dev/agent 0.1.8-alpha.0 → 0.1.8-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +2 -0
  2. package/dist/commonjs/client/index.d.ts +65 -51
  3. package/dist/commonjs/client/index.d.ts.map +1 -1
  4. package/dist/commonjs/client/index.js +70 -4
  5. package/dist/commonjs/client/index.js.map +1 -1
  6. package/dist/commonjs/component/_generated/api.d.ts +235 -0
  7. package/dist/commonjs/component/messages.d.ts +361 -155
  8. package/dist/commonjs/component/messages.d.ts.map +1 -1
  9. package/dist/commonjs/component/messages.js +25 -0
  10. package/dist/commonjs/component/messages.js.map +1 -1
  11. package/dist/commonjs/component/schema.d.ts +670 -670
  12. package/dist/commonjs/component/streams.d.ts +18 -18
  13. package/dist/commonjs/component/threads.d.ts +6 -6
  14. package/dist/commonjs/component/vector/index.d.ts +12 -12
  15. package/dist/commonjs/component/vector/index.d.ts.map +1 -1
  16. package/dist/commonjs/component/vector/index.js +4 -0
  17. package/dist/commonjs/component/vector/index.js.map +1 -1
  18. package/dist/commonjs/component/vector/tables.d.ts +6 -6
  19. package/dist/commonjs/react/index.d.ts.map +1 -1
  20. package/dist/commonjs/react/index.js +1 -1
  21. package/dist/commonjs/react/index.js.map +1 -1
  22. package/dist/commonjs/validators.d.ts +161 -161
  23. package/dist/commonjs.tsbuildinfo +1 -1
  24. package/dist/esm/client/index.d.ts +31 -17
  25. package/dist/esm/client/index.d.ts.map +1 -1
  26. package/dist/esm/client/index.js +70 -4
  27. package/dist/esm/client/index.js.map +1 -1
  28. package/dist/esm/component/_generated/api.d.ts +235 -0
  29. package/dist/esm/component/messages.d.ts +233 -27
  30. package/dist/esm/component/messages.d.ts.map +1 -1
  31. package/dist/esm/component/messages.js +25 -0
  32. package/dist/esm/component/messages.js.map +1 -1
  33. package/dist/esm/component/schema.d.ts +48 -48
  34. package/dist/esm/component/threads.d.ts +8 -8
  35. package/dist/esm/component/vector/index.d.ts.map +1 -1
  36. package/dist/esm/component/vector/index.js +4 -0
  37. package/dist/esm/component/vector/index.js.map +1 -1
  38. package/dist/esm/react/index.d.ts.map +1 -1
  39. package/dist/esm/react/index.js +1 -1
  40. package/dist/esm/react/index.js.map +1 -1
  41. package/dist/esm/validators.d.ts +19 -19
  42. package/dist/esm.tsbuildinfo +1 -1
  43. package/package.json +4 -5
  44. package/src/client/index.ts +94 -4
  45. package/src/client/setup.test.ts +2 -2
  46. package/src/component/_generated/api.d.ts +235 -0
  47. package/src/component/messages.test.ts +140 -0
  48. package/src/component/messages.ts +30 -0
  49. package/src/component/vector/index.ts +4 -0
  50. package/src/react/index.ts +1 -2
  51. package/dist/commonjs/react/usePaginatedQuery.d.ts +0 -241
  52. package/dist/commonjs/react/usePaginatedQuery.d.ts.map +0 -1
  53. package/dist/commonjs/react/usePaginatedQuery.js +0 -627
  54. package/dist/commonjs/react/usePaginatedQuery.js.map +0 -1
  55. package/dist/esm/react/usePaginatedQuery.d.ts +0 -241
  56. package/dist/esm/react/usePaginatedQuery.d.ts.map +0 -1
  57. package/dist/esm/react/usePaginatedQuery.js +0 -627
  58. package/dist/esm/react/usePaginatedQuery.js.map +0 -1
  59. package/react/package.json +0 -5
  60. package/src/react/usePaginatedQuery.ts +0 -901
@@ -1,901 +0,0 @@
1
- import { useMemo, useState } from "react";
2
-
3
- import type { OptimisticLocalStore } from "convex/browser";
4
- import type {
5
- FunctionReturnType,
6
- PaginationOptions,
7
- paginationOptsValidator,
8
- PaginationResult,
9
- } from "convex/server";
10
- import {
11
- ConvexError,
12
- convexToJson,
13
- type Infer,
14
- type Value,
15
- } from "convex/values";
16
- import { useQueries } from "convex/react";
17
- import {
18
- type FunctionArgs,
19
- type FunctionReference,
20
- getFunctionName,
21
- } from "convex/server";
22
- import type { BetterOmit, Expand } from "convex/server";
23
- import { useConvex } from "convex/react";
24
- import { compareValues } from "convex/values";
25
-
26
- /* eslint-disable @typescript-eslint/no-explicit-any */
27
-
28
- /**
29
- * A {@link server.FunctionReference} that is usable with {@link usePaginatedQuery}.
30
- *
31
- * This function reference must:
32
- * - Refer to a public query
33
- * - Have an argument named "paginationOpts" of type {@link server.PaginationOptions}
34
- * - Have a return type of {@link server.PaginationResult}.
35
- *
36
- * @public
37
- */
38
- export type PaginatedQueryReference = FunctionReference<
39
- "query",
40
- "public",
41
- { paginationOpts: PaginationOptions },
42
- PaginationResult<any>
43
- >;
44
-
45
- // Incrementing integer for each page queried in the usePaginatedQuery hook.
46
- type QueryPageKey = number;
47
-
48
- type UsePaginatedQueryState = {
49
- query: FunctionReference<"query">;
50
- args: Record<string, Value>;
51
- id: number;
52
- nextPageKey: QueryPageKey;
53
- pageKeys: QueryPageKey[];
54
- queries: Record<
55
- QueryPageKey,
56
- {
57
- query: FunctionReference<"query">;
58
- // Use the validator type as a test that it matches the args
59
- // we generate.
60
- args: { paginationOpts: Infer<typeof paginationOptsValidator> };
61
- }
62
- >;
63
- ongoingSplits: Record<QueryPageKey, [QueryPageKey, QueryPageKey]>;
64
- skip: boolean;
65
- };
66
-
67
- const splitQuery =
68
- (key: QueryPageKey, splitCursor: string, continueCursor: string) =>
69
- (prevState: UsePaginatedQueryState) => {
70
- const queries = { ...prevState.queries };
71
- const splitKey1 = prevState.nextPageKey;
72
- const splitKey2 = prevState.nextPageKey + 1;
73
- const nextPageKey = prevState.nextPageKey + 2;
74
- queries[splitKey1] = {
75
- query: prevState.query,
76
- args: {
77
- ...prevState.args,
78
- paginationOpts: {
79
- ...prevState.queries[key].args.paginationOpts,
80
- endCursor: splitCursor,
81
- },
82
- },
83
- };
84
- queries[splitKey2] = {
85
- query: prevState.query,
86
- args: {
87
- ...prevState.args,
88
- paginationOpts: {
89
- ...prevState.queries[key].args.paginationOpts,
90
- cursor: splitCursor,
91
- endCursor: continueCursor,
92
- },
93
- },
94
- };
95
- const ongoingSplits = { ...prevState.ongoingSplits };
96
- ongoingSplits[key] = [splitKey1, splitKey2];
97
- return {
98
- ...prevState,
99
- nextPageKey,
100
- queries,
101
- ongoingSplits,
102
- };
103
- };
104
-
105
- const completeSplitQuery =
106
- (key: QueryPageKey) => (prevState: UsePaginatedQueryState) => {
107
- const completedSplit = prevState.ongoingSplits[key];
108
- if (completedSplit === undefined) {
109
- return prevState;
110
- }
111
- const queries = { ...prevState.queries };
112
- delete queries[key];
113
- const ongoingSplits = { ...prevState.ongoingSplits };
114
- delete ongoingSplits[key];
115
- let pageKeys = prevState.pageKeys.slice();
116
- const pageIndex = prevState.pageKeys.findIndex((v) => v === key);
117
- if (pageIndex >= 0) {
118
- pageKeys = [
119
- ...prevState.pageKeys.slice(0, pageIndex),
120
- ...completedSplit,
121
- ...prevState.pageKeys.slice(pageIndex + 1),
122
- ];
123
- }
124
- return {
125
- ...prevState,
126
- queries,
127
- pageKeys,
128
- ongoingSplits,
129
- };
130
- };
131
-
132
- /**
133
- * This is a clone of the `usePaginatedQuery` hook from `convex-helpers`.
134
- * The difference is that we lazily pin the end cursor on loading a new page.
135
- * This will be standard behavior in a future version of `convex/react`, but
136
- * for now it allows the agent to have correct behavior when loading a new page
137
- * where new items are still coming in.
138
- */
139
- export function usePaginatedQuery<Query extends PaginatedQueryReference>(
140
- query: Query,
141
- args: PaginatedQueryArgs<Query> | "skip",
142
- options: { initialNumItems: number }
143
- ): UsePaginatedQueryReturnType<Query> {
144
- if (
145
- typeof options?.initialNumItems !== "number" ||
146
- options.initialNumItems < 0
147
- ) {
148
- throw new Error(
149
- `\`options.initialNumItems\` must be a positive number. Received \`${options?.initialNumItems}\`.`
150
- );
151
- }
152
- const skip = args === "skip";
153
- const argsObject = skip ? {} : args;
154
- const queryName = getFunctionName(query);
155
- const createInitialState = useMemo(() => {
156
- return () => {
157
- const id = nextPaginationId();
158
- return {
159
- query,
160
- args: argsObject as Record<string, Value>,
161
- id,
162
- nextPageKey: 1,
163
- pageKeys: skip ? [] : [0],
164
- queries: skip
165
- ? ({} as UsePaginatedQueryState["queries"])
166
- : {
167
- 0: {
168
- query,
169
- args: {
170
- ...argsObject,
171
- paginationOpts: {
172
- numItems: options.initialNumItems,
173
- cursor: null,
174
- id,
175
- },
176
- },
177
- },
178
- },
179
- ongoingSplits: {},
180
- skip,
181
- };
182
- };
183
- // ESLint doesn't like that we're stringifying the args. We do this because
184
- // we want to avoid rerendering if the args are a different
185
- // object that serializes to the same result.
186
- // eslint-disable-next-line react-hooks/exhaustive-deps
187
- }, [
188
- // eslint-disable-next-line react-hooks/exhaustive-deps
189
- JSON.stringify(convexToJson(argsObject as Value)),
190
- queryName,
191
- options.initialNumItems,
192
- skip,
193
- ]);
194
-
195
- const [state, setState] =
196
- useState<UsePaginatedQueryState>(createInitialState);
197
-
198
- // `currState` is the state that we'll render based on.
199
- let currState = state;
200
- if (
201
- getFunctionName(query) !== getFunctionName(state.query) ||
202
- JSON.stringify(convexToJson(argsObject as Value)) !==
203
- JSON.stringify(convexToJson(state.args)) ||
204
- skip !== state.skip
205
- ) {
206
- currState = createInitialState();
207
- setState(currState);
208
- }
209
- const convexClient = useConvex();
210
- const logger = convexClient.logger;
211
-
212
- const resultsObject = useQueries(currState.queries);
213
-
214
- const [results, maybeLastResult]: [
215
- Value[],
216
- undefined | PaginationResult<Value>,
217
- ] = useMemo(() => {
218
- let currResult = undefined;
219
-
220
- const allItems = [];
221
- for (const pageKey of currState.pageKeys) {
222
- currResult = resultsObject[pageKey];
223
- if (currResult === undefined) {
224
- break;
225
- }
226
-
227
- if (currResult instanceof Error) {
228
- if (
229
- currResult.message.includes("InvalidCursor") ||
230
- (currResult instanceof ConvexError &&
231
- typeof currResult.data === "object" &&
232
- currResult.data?.isConvexSystemError === true &&
233
- currResult.data?.paginationError === "InvalidCursor")
234
- ) {
235
- // - InvalidCursor: If the cursor is invalid, probably the paginated
236
- // database query was data-dependent and changed underneath us. The
237
- // cursor in the params or journal no longer matches the current
238
- // database query.
239
-
240
- // In all cases, we want to restart pagination to throw away all our
241
- // existing cursors.
242
- logger.warn(
243
- "usePaginatedQuery hit error, resetting pagination state: " +
244
- currResult.message
245
- );
246
- setState(createInitialState);
247
- return [[], undefined];
248
- } else {
249
- throw currResult;
250
- }
251
- }
252
- const ongoingSplit = currState.ongoingSplits[pageKey];
253
- if (ongoingSplit !== undefined) {
254
- if (
255
- resultsObject[ongoingSplit[0]] !== undefined &&
256
- resultsObject[ongoingSplit[1]] !== undefined
257
- ) {
258
- // Both pages of the split have results now. Swap them in.
259
- setState(completeSplitQuery(pageKey));
260
- }
261
- } else if (
262
- currResult.splitCursor &&
263
- (currResult.pageStatus === "SplitRecommended" ||
264
- currResult.pageStatus === "SplitRequired" ||
265
- currResult.page.length > options.initialNumItems * 2)
266
- ) {
267
- // If a single page has more than double the expected number of items,
268
- // or if the server requests a split, split the page into two.
269
- setState(
270
- splitQuery(pageKey, currResult.splitCursor, currResult.continueCursor)
271
- );
272
- }
273
- if (currResult.pageStatus === "SplitRequired") {
274
- // If pageStatus is 'SplitRequired', it means the server was not able to
275
- // fetch the full page. So we stop results before the incomplete
276
- // page and return 'LoadingMore' while the page is splitting.
277
- return [allItems, undefined];
278
- }
279
- allItems.push(...currResult.page);
280
- }
281
- return [allItems, currResult];
282
- }, [
283
- resultsObject,
284
- currState.pageKeys,
285
- currState.ongoingSplits,
286
- options.initialNumItems,
287
- createInitialState,
288
- logger,
289
- ]);
290
-
291
- const statusObject = useMemo(() => {
292
- if (maybeLastResult === undefined) {
293
- if (currState.nextPageKey === 1) {
294
- return {
295
- status: "LoadingFirstPage",
296
- isLoading: true,
297
- loadMore: (_numItems: number) => {
298
- // Intentional noop.
299
- },
300
- } as const;
301
- } else {
302
- return {
303
- status: "LoadingMore",
304
- isLoading: true,
305
- loadMore: (_numItems: number) => {
306
- // Intentional noop.
307
- },
308
- } as const;
309
- }
310
- }
311
- if (maybeLastResult.isDone) {
312
- return {
313
- status: "Exhausted",
314
- isLoading: false,
315
- loadMore: (_numItems: number) => {
316
- // Intentional noop.
317
- },
318
- } as const;
319
- }
320
- const continueCursor = maybeLastResult.continueCursor;
321
- let alreadyLoadingMore = false;
322
- return {
323
- status: "CanLoadMore",
324
- isLoading: false,
325
- loadMore: (numItems: number) => {
326
- if (!alreadyLoadingMore) {
327
- alreadyLoadingMore = true;
328
- setState((prevState) => {
329
- const lastPageKey = prevState.pageKeys.at(-1)!;
330
- const replaceKey = prevState.nextPageKey;
331
- const newKey = prevState.nextPageKey + 1;
332
- const nextPageKey = prevState.nextPageKey + 2;
333
- const pageKeys = prevState.pageKeys; //[...prevState.pageKeys, prevState.nextPageKey];
334
- const queries = { ...prevState.queries };
335
-
336
- queries[replaceKey] = {
337
- query: prevState.query,
338
- args: {
339
- ...prevState.args,
340
- paginationOpts: {
341
- ...(queries[prevState.pageKeys.at(-1)!]!.args
342
- .paginationOpts as unknown as PaginationOptions),
343
- endCursor: continueCursor,
344
- },
345
- },
346
- };
347
- queries[newKey] = {
348
- query: prevState.query,
349
- args: {
350
- ...prevState.args,
351
- paginationOpts: {
352
- numItems,
353
- cursor: continueCursor,
354
- id: prevState.id,
355
- },
356
- },
357
- };
358
- return {
359
- ...prevState,
360
- nextPageKey,
361
- pageKeys,
362
- queries,
363
- ongoingSplits: {
364
- ...prevState.ongoingSplits,
365
- [lastPageKey]: [replaceKey, newKey],
366
- },
367
- };
368
- });
369
- }
370
- },
371
- } as const;
372
- }, [maybeLastResult, currState.nextPageKey]);
373
-
374
- return {
375
- results,
376
- ...statusObject,
377
- };
378
- }
379
-
380
- let paginationId = 0;
381
- /**
382
- * Generate a new, unique ID for a pagination session.
383
- *
384
- * Every usage of {@link usePaginatedQuery} puts a unique ID into the
385
- * query function arguments as a "cache-buster". This serves two purposes:
386
- *
387
- * 1. All calls to {@link usePaginatedQuery} have independent query
388
- * journals.
389
- *
390
- * Every time we start a new pagination session, we'll load the first page of
391
- * results and receive a fresh journal. Without the ID, we might instead reuse
392
- * a query subscription already present in our client. This isn't desirable
393
- * because the existing query function result may have grown or shrunk from the
394
- * requested `initialNumItems`.
395
- *
396
- * 2. We can restart the pagination session on some types of errors.
397
- *
398
- * Sometimes we want to restart pagination from the beginning if we hit an error.
399
- * Similar to (1), we'd like to ensure that this new session actually requests
400
- * its first page from the server and doesn't reuse a query result already
401
- * present in the client that may have hit the error.
402
- *
403
- * @returns The pagination ID.
404
- */
405
- function nextPaginationId(): number {
406
- paginationId++;
407
- return paginationId;
408
- }
409
-
410
- /**
411
- * Reset pagination id for tests only, so tests know what it is.
412
- */
413
- export function resetPaginationId() {
414
- paginationId = 0;
415
- }
416
-
417
- /**
418
- * The result of calling the {@link usePaginatedQuery} hook.
419
- *
420
- * This includes:
421
- * - `results` - An array of the currently loaded results.
422
- * - `isLoading` - Whether the hook is currently loading results.
423
- * - `status` - The status of the pagination. The possible statuses are:
424
- * - "LoadingFirstPage": The hook is loading the first page of results.
425
- * - "CanLoadMore": This query may have more items to fetch. Call `loadMore` to
426
- * fetch another page.
427
- * - "LoadingMore": We're currently loading another page of results.
428
- * - "Exhausted": We've paginated to the end of the list.
429
- * - `loadMore(n)` A callback to fetch more results. This will only fetch more
430
- * results if the status is "CanLoadMore".
431
- *
432
- * @public
433
- */
434
- export type UsePaginatedQueryResult<Item> = {
435
- results: Item[];
436
- loadMore: (numItems: number) => void;
437
- } & (
438
- | {
439
- status: "LoadingFirstPage";
440
- isLoading: true;
441
- }
442
- | {
443
- status: "CanLoadMore";
444
- isLoading: false;
445
- }
446
- | {
447
- status: "LoadingMore";
448
- isLoading: true;
449
- }
450
- | {
451
- status: "Exhausted";
452
- isLoading: false;
453
- }
454
- );
455
-
456
- /**
457
- * The possible pagination statuses in {@link UsePaginatedQueryResult}.
458
- *
459
- * This is a union of string literal types.
460
- * @public
461
- */
462
- export type PaginationStatus = UsePaginatedQueryResult<any>["status"];
463
-
464
- /**
465
- * Given a {@link PaginatedQueryReference}, get the type of the arguments
466
- * object for the query, excluding the `paginationOpts` argument.
467
- *
468
- * @public
469
- */
470
- export type PaginatedQueryArgs<Query extends PaginatedQueryReference> = Expand<
471
- BetterOmit<FunctionArgs<Query>, "paginationOpts">
472
- >;
473
-
474
- /**
475
- * Given a {@link PaginatedQueryReference}, get the type of the item being
476
- * paginated over.
477
- * @public
478
- */
479
- export type PaginatedQueryItem<Query extends PaginatedQueryReference> =
480
- FunctionReturnType<Query>["page"][number];
481
-
482
- /**
483
- * The return type of {@link usePaginatedQuery}.
484
- *
485
- * @public
486
- */
487
- export type UsePaginatedQueryReturnType<Query extends PaginatedQueryReference> =
488
- UsePaginatedQueryResult<PaginatedQueryItem<Query>>;
489
-
490
- /**
491
- * Optimistically update the values in a paginated list.
492
- *
493
- * This optimistic update is designed to be used to update data loaded with
494
- * {@link usePaginatedQuery}. It updates the list by applying
495
- * `updateValue` to each element of the list across all of the loaded pages.
496
- *
497
- * This will only apply to queries with a matching names and arguments.
498
- *
499
- * Example usage:
500
- * ```ts
501
- * const myMutation = useMutation(api.myModule.myMutation)
502
- * .withOptimisticUpdate((localStore, mutationArg) => {
503
- *
504
- * // Optimistically update the document with ID `mutationArg`
505
- * // to have an additional property.
506
- *
507
- * optimisticallyUpdateValueInPaginatedQuery(
508
- * localStore,
509
- * api.myModule.paginatedQuery
510
- * {},
511
- * currentValue => {
512
- * if (mutationArg === currentValue._id) {
513
- * return {
514
- * ...currentValue,
515
- * "newProperty": "newValue",
516
- * };
517
- * }
518
- * return currentValue;
519
- * }
520
- * );
521
- *
522
- * });
523
- * ```
524
- *
525
- * @param localStore - An {@link OptimisticLocalStore} to update.
526
- * @param query - A {@link FunctionReference} for the paginated query to update.
527
- * @param args - The arguments object to the query function, excluding the
528
- * `paginationOpts` property.
529
- * @param updateValue - A function to produce the new values.
530
- *
531
- * @public
532
- */
533
- export function optimisticallyUpdateValueInPaginatedQuery<
534
- Query extends PaginatedQueryReference,
535
- >(
536
- localStore: OptimisticLocalStore,
537
- query: Query,
538
- args: PaginatedQueryArgs<Query>,
539
- updateValue: (
540
- currentValue: PaginatedQueryItem<Query>
541
- ) => PaginatedQueryItem<Query>
542
- ): void {
543
- const expectedArgs = JSON.stringify(convexToJson(args as Value));
544
-
545
- for (const queryResult of localStore.getAllQueries(query)) {
546
- if (queryResult.value !== undefined) {
547
- const { paginationOpts: _, ...innerArgs } = queryResult.args as {
548
- paginationOpts: PaginationOptions;
549
- };
550
- if (JSON.stringify(convexToJson(innerArgs as Value)) === expectedArgs) {
551
- const value = queryResult.value;
552
- if (
553
- typeof value === "object" &&
554
- value !== null &&
555
- Array.isArray(value.page)
556
- ) {
557
- localStore.setQuery(query, queryResult.args, {
558
- ...value,
559
- page: value.page.map(updateValue),
560
- });
561
- }
562
- }
563
- }
564
- }
565
- }
566
-
567
- /**
568
- * Updates a paginated query to insert an element at the top of the list.
569
- *
570
- * This is regardless of the sort order, so if the list is in descending order,
571
- * the inserted element will be treated as the "biggest" element, but if it's
572
- * ascending, it'll be treated as the "smallest".
573
- *
574
- * Example:
575
- * ```ts
576
- * const createTask = useMutation(api.tasks.create)
577
- * .withOptimisticUpdate((localStore, mutationArgs) => {
578
- * insertAtTop({
579
- * paginatedQuery: api.tasks.list,
580
- * argsToMatch: { listId: mutationArgs.listId },
581
- * localQueryStore: localStore,
582
- * item: { _id: crypto.randomUUID() as Id<"tasks">, title: mutationArgs.title, completed: false },
583
- * });
584
- * });
585
- * ```
586
- *
587
- * @param options.paginatedQuery - A function reference to the paginated query.
588
- * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
589
- * This is useful if you use the same query function with different arguments to load
590
- * different lists.
591
- * @param options.localQueryStore
592
- * @param options.item The item to insert.
593
- * @returns
594
- */
595
- export function insertAtTop<Query extends PaginatedQueryReference>(options: {
596
- paginatedQuery: Query;
597
- argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
598
- localQueryStore: OptimisticLocalStore;
599
- item: PaginatedQueryItem<Query>;
600
- }) {
601
- const { paginatedQuery, argsToMatch, localQueryStore, item } = options;
602
- const queries = localQueryStore.getAllQueries(paginatedQuery);
603
- const queriesThatMatch = queries.filter((q) => {
604
- if (argsToMatch === undefined) {
605
- return true;
606
- }
607
- return Object.keys(argsToMatch).every(
608
- // @ts-expect-error -- This should be safe since both should be plain objects
609
- (k) => compareValues(argsToMatch[k], q.args[k]) === 0
610
- );
611
- });
612
- const firstPage = queriesThatMatch.find(
613
- (q) => q.args.paginationOpts.cursor === null
614
- );
615
- if (firstPage === undefined || firstPage.value === undefined) {
616
- // first page is not loaded, so don't update it until it loads
617
- return;
618
- }
619
- localQueryStore.setQuery(paginatedQuery, firstPage.args, {
620
- ...firstPage.value,
621
- page: [item, ...firstPage.value.page],
622
- });
623
- }
624
-
625
- /**
626
- * Updates a paginated query to insert an element at the bottom of the list.
627
- *
628
- * This is regardless of the sort order, so if the list is in descending order,
629
- * the inserted element will be treated as the "smallest" element, but if it's
630
- * ascending, it'll be treated as the "biggest".
631
- *
632
- * This only has an effect if the last page is loaded, since otherwise it would result
633
- * in the element being inserted at the end of whatever is loaded (which is the middle of the list)
634
- * and then popping out once the optimistic update is over.
635
- *
636
- * @param options.paginatedQuery - A function reference to the paginated query.
637
- * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
638
- * This is useful if you use the same query function with different arguments to load
639
- * different lists.
640
- * @param options.localQueryStore
641
- * @param options.element The element to insert.
642
- * @returns
643
- */
644
- export function insertAtBottomIfLoaded<
645
- Query extends PaginatedQueryReference,
646
- >(options: {
647
- paginatedQuery: Query;
648
- argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
649
- localQueryStore: OptimisticLocalStore;
650
- item: PaginatedQueryItem<Query>;
651
- }) {
652
- const { paginatedQuery, localQueryStore, item, argsToMatch } = options;
653
- const queries = localQueryStore.getAllQueries(paginatedQuery);
654
- const queriesThatMatch = queries.filter((q) => {
655
- if (argsToMatch === undefined) {
656
- return true;
657
- }
658
- return Object.keys(argsToMatch).every(
659
- // @ts-expect-error -- This should be safe since both should be plain objects
660
- (k) => compareValues(argsToMatch[k], q.args[k]) === 0
661
- );
662
- });
663
- const lastPage = queriesThatMatch.find(
664
- (q) => q.value !== undefined && q.value.isDone
665
- );
666
- if (lastPage === undefined) {
667
- // last page is not loaded, so don't update it since the item would immediately pop out
668
- // when the server updates
669
- return;
670
- }
671
- localQueryStore.setQuery(paginatedQuery, lastPage.args, {
672
- ...lastPage.value!,
673
- page: [...lastPage.value!.page, item],
674
- });
675
- }
676
-
677
- type LocalQueryResult<Query extends FunctionReference<"query">> = {
678
- args: FunctionArgs<Query>;
679
- value: undefined | FunctionReturnType<Query>;
680
- };
681
-
682
- type LoadedResult<Query extends FunctionReference<"query">> = {
683
- args: FunctionArgs<Query>;
684
- value: FunctionReturnType<Query>;
685
- };
686
-
687
- /**
688
- * This is a helper function for inserting an item at a specific position in a paginated query.
689
- *
690
- * You must provide the sortOrder and a function for deriving the sort key (an array of values) from an item in the list.
691
- *
692
- * This will only work if the server query uses the same sort order and sort key as the optimistic update.
693
- *
694
- * Example:
695
- * ```ts
696
- * const createTask = useMutation(api.tasks.create)
697
- * .withOptimisticUpdate((localStore, mutationArgs) => {
698
- * insertAtPosition({
699
- * paginatedQuery: api.tasks.listByPriority,
700
- * argsToMatch: { listId: mutationArgs.listId },
701
- * sortOrder: "asc",
702
- * sortKeyFromItem: (item) => [item.priority, item._creationTime],
703
- * localQueryStore: localStore,
704
- * item: {
705
- * _id: crypto.randomUUID() as Id<"tasks">,
706
- * _creationTime: Date.now(),
707
- * title: mutationArgs.title,
708
- * completed: false,
709
- * priority: mutationArgs.priority,
710
- * },
711
- * });
712
- * });
713
- * ```
714
- * @param options.paginatedQuery - A function reference to the paginated query.
715
- * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
716
- * This is useful if you use the same query function with different arguments to load
717
- * different lists.
718
- * @param options.sortOrder - The sort order of the paginated query ("asc" or "desc").
719
- * @param options.sortKeyFromItem - A function for deriving the sort key (an array of values) from an element in the list.
720
- * Including a tie-breaker field like `_creationTime` is recommended.
721
- * @param options.localQueryStore
722
- * @param options.item - The item to insert.
723
- * @returns
724
- */
725
- export function insertAtPosition<
726
- Query extends PaginatedQueryReference,
727
- >(options: {
728
- paginatedQuery: Query;
729
- argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
730
- sortOrder: "asc" | "desc";
731
- sortKeyFromItem: (element: PaginatedQueryItem<Query>) => Value | Value[];
732
- localQueryStore: OptimisticLocalStore;
733
- item: PaginatedQueryItem<Query>;
734
- }) {
735
- const {
736
- paginatedQuery,
737
- sortOrder,
738
- sortKeyFromItem,
739
- localQueryStore,
740
- item,
741
- argsToMatch,
742
- } = options;
743
-
744
- const queries: LocalQueryResult<Query>[] =
745
- localQueryStore.getAllQueries(paginatedQuery);
746
- // Group into sets of pages for the same usePaginatedQuery. Grouping is by all
747
- // args except paginationOpts, but including paginationOpts.id.
748
- const queryGroups: Record<string, LocalQueryResult<Query>[]> = {};
749
- for (const query of queries) {
750
- if (
751
- argsToMatch !== undefined &&
752
- !Object.keys(argsToMatch).every(
753
- (k) =>
754
- // @ts-expect-error why is this not working?
755
- argsToMatch[k] === query.args[k]
756
- )
757
- ) {
758
- continue;
759
- }
760
- const key = JSON.stringify(
761
- Object.fromEntries(
762
- Object.entries(query.args).map(([k, v]) => [
763
- k,
764
- k === "paginationOpts" ? (v as any).id : v,
765
- ])
766
- )
767
- );
768
- queryGroups[key] ??= [];
769
- queryGroups[key].push(query);
770
- }
771
- for (const pageQueries of Object.values(queryGroups)) {
772
- insertAtPositionInPages({
773
- pageQueries,
774
- paginatedQuery,
775
- sortOrder,
776
- sortKeyFromItem,
777
- localQueryStore,
778
- item,
779
- });
780
- }
781
- }
782
-
783
- function insertAtPositionInPages<
784
- Query extends PaginatedQueryReference,
785
- >(options: {
786
- pageQueries: LocalQueryResult<Query>[];
787
- paginatedQuery: Query;
788
- sortOrder: "asc" | "desc";
789
- sortKeyFromItem: (element: PaginatedQueryItem<Query>) => Value | Value[];
790
- localQueryStore: OptimisticLocalStore;
791
- item: PaginatedQueryItem<Query>;
792
- }) {
793
- const {
794
- pageQueries,
795
- sortOrder,
796
- sortKeyFromItem,
797
- localQueryStore,
798
- item,
799
- paginatedQuery,
800
- } = options;
801
- const insertedKey = sortKeyFromItem(item);
802
- const loadedPages: LoadedResult<Query>[] = pageQueries.filter(
803
- (q): q is LoadedResult<Query> =>
804
- q.value !== undefined && q.value.page.length > 0
805
- );
806
- const sortedPages = loadedPages.sort((a, b) => {
807
- const aKey = sortKeyFromItem(a.value.page[0]);
808
- const bKey = sortKeyFromItem(b.value.page[0]);
809
- if (sortOrder === "asc") {
810
- return compareValues(aKey, bKey);
811
- } else {
812
- return compareValues(bKey, aKey);
813
- }
814
- });
815
-
816
- // check if the inserted element is before the first page
817
- const firstLoadedPage = sortedPages[0];
818
- if (firstLoadedPage === undefined) {
819
- // no pages, so don't update until they load
820
- return;
821
- }
822
- const firstPageKey = sortKeyFromItem(firstLoadedPage.value.page[0]);
823
- const isBeforeFirstPage =
824
- sortOrder === "asc"
825
- ? compareValues(insertedKey, firstPageKey) <= 0
826
- : compareValues(insertedKey, firstPageKey) >= 0;
827
- if (isBeforeFirstPage) {
828
- if (firstLoadedPage.args.paginationOpts.cursor === null) {
829
- localQueryStore.setQuery(paginatedQuery, firstLoadedPage.args, {
830
- ...firstLoadedPage.value,
831
- page: [item, ...firstLoadedPage.value.page],
832
- });
833
- } else {
834
- // if the very first page is not loaded
835
- return;
836
- }
837
- return;
838
- }
839
-
840
- const lastLoadedPage = sortedPages[sortedPages.length - 1];
841
- if (lastLoadedPage === undefined) {
842
- // no pages, so don't update until they load
843
- return;
844
- }
845
- const lastPageKey = sortKeyFromItem(
846
- lastLoadedPage.value.page[lastLoadedPage.value.page.length - 1]
847
- );
848
- const isAfterLastPage =
849
- sortOrder === "asc"
850
- ? compareValues(insertedKey, lastPageKey) >= 0
851
- : compareValues(insertedKey, lastPageKey) <= 0;
852
- if (isAfterLastPage) {
853
- // Only update if the last page is done loading, otherwise it will pop out
854
- // when the server updates the query
855
- if (lastLoadedPage.value.isDone) {
856
- localQueryStore.setQuery(paginatedQuery, lastLoadedPage.args, {
857
- ...lastLoadedPage.value,
858
- page: [...lastLoadedPage.value.page, item],
859
- });
860
- }
861
- return;
862
- }
863
-
864
- // if sorted in ascending order, find the first page that starts with a key greater than the inserted element,
865
- // and update the page before it
866
- // if sorted in descending order, find the first page that starts with a key less than the inserted element,
867
- // and update the page before it
868
-
869
- const successorPageIndex = sortedPages.findIndex((p) =>
870
- sortOrder === "asc"
871
- ? compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) > 0
872
- : compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) < 0
873
- );
874
- const pageToUpdate =
875
- successorPageIndex === -1
876
- ? sortedPages[sortedPages.length - 1]
877
- : sortedPages[successorPageIndex - 1];
878
- if (pageToUpdate === undefined) {
879
- // no pages, so don't update until they load
880
- return;
881
- }
882
- // If ascending, find the first element that is greater than or equal to the inserted element
883
- // If descending, find the first element that is less than or equal to the inserted element
884
- const indexWithinPage = pageToUpdate.value.page.findIndex((e) =>
885
- sortOrder === "asc"
886
- ? compareValues(sortKeyFromItem(e), insertedKey) >= 0
887
- : compareValues(sortKeyFromItem(e), insertedKey) <= 0
888
- );
889
- const newPage =
890
- indexWithinPage === -1
891
- ? [...pageToUpdate.value.page, item]
892
- : [
893
- ...pageToUpdate.value.page.slice(0, indexWithinPage),
894
- item,
895
- ...pageToUpdate.value.page.slice(indexWithinPage),
896
- ];
897
- localQueryStore.setQuery(paginatedQuery, pageToUpdate.args, {
898
- ...pageToUpdate.value,
899
- page: newPage,
900
- });
901
- }