@jsudc/react 0.3.1 → 0.5.0

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 (144) hide show
  1. package/README.md +1137 -22
  2. package/dist/actions/RowActionsMenu.d.ts +45 -0
  3. package/dist/actions/RowActionsMenu.js +161 -0
  4. package/dist/actions/RowActionsMenu.js.map +1 -0
  5. package/dist/actions/bulk.d.ts +81 -0
  6. package/dist/actions/bulk.js +54 -0
  7. package/dist/actions/bulk.js.map +1 -0
  8. package/dist/actions/row.d.ts +50 -0
  9. package/dist/actions/row.js +34 -0
  10. package/dist/actions/row.js.map +1 -0
  11. package/dist/actions/useRowActionRunner.d.ts +26 -0
  12. package/dist/actions/useRowActionRunner.js +198 -0
  13. package/dist/actions/useRowActionRunner.js.map +1 -0
  14. package/dist/calendar/CalendarRenderer.js +5 -4
  15. package/dist/calendar/CalendarRenderer.js.map +1 -1
  16. package/dist/calendar/EventDetail.js +1 -1
  17. package/dist/calendar.js +1 -1
  18. package/dist/cards/CardRenderer.d.ts +8 -1
  19. package/dist/cards/CardRenderer.js +179 -110
  20. package/dist/cards/CardRenderer.js.map +1 -1
  21. package/dist/cells/registry.d.ts +60 -0
  22. package/dist/cells/registry.js +47 -0
  23. package/dist/cells/registry.js.map +1 -0
  24. package/dist/chart/ChartRenderer.js +6 -4
  25. package/dist/chart/ChartRenderer.js.map +1 -1
  26. package/dist/chart/ChartWindowControl.js +2 -2
  27. package/dist/components/ui/checkbox.js +1 -1
  28. package/dist/components/ui/dialog.js +4 -3
  29. package/dist/components/ui/dialog.js.map +1 -1
  30. package/dist/components/ui/dropdown-menu.js +2 -1
  31. package/dist/components/ui/dropdown-menu.js.map +1 -1
  32. package/dist/components/ui/popover.js +2 -1
  33. package/dist/components/ui/popover.js.map +1 -1
  34. package/dist/components/ui/select.js +2 -1
  35. package/dist/components/ui/select.js.map +1 -1
  36. package/dist/components/ui/toast.js +3 -2
  37. package/dist/components/ui/toast.js.map +1 -1
  38. package/dist/components/ui/tooltip.js +2 -1
  39. package/dist/components/ui/tooltip.js.map +1 -1
  40. package/dist/data-view/BulkBar.d.ts +36 -0
  41. package/dist/data-view/BulkBar.js +239 -0
  42. package/dist/data-view/BulkBar.js.map +1 -0
  43. package/dist/data-view/FilePreview.js +1 -1
  44. package/dist/data-view/FilterBuilder.js +2 -2
  45. package/dist/data-view/FilterChips.js +2 -2
  46. package/dist/data-view/Freshness.js +1 -1
  47. package/dist/data-view/LiveIndicator.d.ts +10 -0
  48. package/dist/data-view/LiveIndicator.js +33 -0
  49. package/dist/data-view/LiveIndicator.js.map +1 -0
  50. package/dist/data-view/SearchBox.js +1 -1
  51. package/dist/data-view/UdcDataView.d.ts +110 -1
  52. package/dist/data-view/UdcDataView.js +237 -90
  53. package/dist/data-view/UdcDataView.js.map +1 -1
  54. package/dist/data-view/useDataViewState.d.ts +8 -0
  55. package/dist/data-view/useDataViewState.js +2 -1
  56. package/dist/data-view/useDataViewState.js.map +1 -1
  57. package/dist/headless.d.ts +9 -0
  58. package/dist/headless.js +12 -2
  59. package/dist/i18n/translations.js +136 -0
  60. package/dist/i18n/translations.js.map +1 -1
  61. package/dist/index.d.ts +15 -4
  62. package/dist/index.js +17 -4
  63. package/dist/kanban/KanbanCard.js +1 -1
  64. package/dist/kanban/KanbanColumn.js +1 -1
  65. package/dist/kanban/KanbanRenderer.js +6 -5
  66. package/dist/kanban/KanbanRenderer.js.map +1 -1
  67. package/dist/lib/scope.d.ts +8 -0
  68. package/dist/lib/scope.js +12 -0
  69. package/dist/lib/scope.js.map +1 -0
  70. package/dist/lookup/LookupCombobox.js +1 -1
  71. package/dist/lookup/batch.js +1 -1
  72. package/dist/lookup/options.js +4 -1
  73. package/dist/lookup/options.js.map +1 -1
  74. package/dist/lookup/useUdcLookup.js +9 -3
  75. package/dist/lookup/useUdcLookup.js.map +1 -1
  76. package/dist/map/MapRenderer.js +4 -3
  77. package/dist/map/MapRenderer.js.map +1 -1
  78. package/dist/renderers/types.d.ts +44 -1
  79. package/dist/renderers/types.js.map +1 -1
  80. package/dist/rows/useRowActivation.d.ts +91 -0
  81. package/dist/rows/useRowActivation.js +257 -0
  82. package/dist/rows/useRowActivation.js.map +1 -0
  83. package/dist/rows/useRowSelection.d.ts +92 -0
  84. package/dist/rows/useRowSelection.js +156 -0
  85. package/dist/rows/useRowSelection.js.map +1 -0
  86. package/dist/schema-editor/DeleteFieldDialog.js +2 -2
  87. package/dist/schema-editor/FieldFormDialog.js +2 -2
  88. package/dist/schema-editor/TagInput.js +1 -1
  89. package/dist/styles.css +1 -1
  90. package/dist/styles.scoped.css +2 -0
  91. package/dist/table/CellEditor.js +2 -1
  92. package/dist/table/CellEditor.js.map +1 -1
  93. package/dist/table/SelectCheckbox.d.ts +15 -0
  94. package/dist/table/SelectCheckbox.js +37 -0
  95. package/dist/table/SelectCheckbox.js.map +1 -0
  96. package/dist/table/TableRenderer.d.ts +15 -1
  97. package/dist/table/TableRenderer.js +305 -114
  98. package/dist/table/TableRenderer.js.map +1 -1
  99. package/dist/table/cells.d.ts +13 -2
  100. package/dist/table/cells.js +15 -2
  101. package/dist/table/cells.js.map +1 -1
  102. package/dist/table/index.d.ts +1 -0
  103. package/dist/table/states.d.ts +6 -0
  104. package/dist/table/states.js +14 -1
  105. package/dist/table/states.js.map +1 -1
  106. package/dist/table/useRowWindow.d.ts +82 -0
  107. package/dist/table/useRowWindow.js +182 -0
  108. package/dist/table/useRowWindow.js.map +1 -0
  109. package/dist/table.js.map +1 -1
  110. package/dist/tree/TreeNode.js +1 -1
  111. package/dist/tree/TreeRenderer.d.ts +2 -0
  112. package/dist/tree/TreeRenderer.js +16 -10
  113. package/dist/tree/TreeRenderer.js.map +1 -1
  114. package/dist/udc/changeFeed.d.ts +94 -0
  115. package/dist/udc/changeFeed.js +250 -0
  116. package/dist/udc/changeFeed.js.map +1 -0
  117. package/dist/udc/changes.d.ts +34 -0
  118. package/dist/udc/changes.js +79 -0
  119. package/dist/udc/changes.js.map +1 -0
  120. package/dist/udc/client.d.ts +15 -1
  121. package/dist/udc/client.js +34 -10
  122. package/dist/udc/client.js.map +1 -1
  123. package/dist/udc/hooks.d.ts +94 -16
  124. package/dist/udc/hooks.js +113 -10
  125. package/dist/udc/hooks.js.map +1 -1
  126. package/dist/udc/keys.d.ts +2 -0
  127. package/dist/udc/keys.js.map +1 -1
  128. package/dist/udc/listCache.d.ts +11 -0
  129. package/dist/udc/listCache.js +38 -0
  130. package/dist/udc/listCache.js.map +1 -0
  131. package/dist/udc/provider.d.ts +21 -3
  132. package/dist/udc/provider.js +23 -2
  133. package/dist/udc/provider.js.map +1 -1
  134. package/dist/udc/unauthenticated.d.ts +4 -0
  135. package/dist/udc/unauthenticated.js +17 -0
  136. package/dist/udc/unauthenticated.js.map +1 -0
  137. package/dist/ui-kit/types.d.ts +14 -0
  138. package/dist/ui-kit/ui.d.ts +1 -0
  139. package/dist/ui.js +2 -1
  140. package/dist/url-state/adapters.d.ts +23 -0
  141. package/dist/url-state/adapters.js +57 -0
  142. package/dist/url-state/adapters.js.map +1 -0
  143. package/dist/url-state/index.d.ts +1 -0
  144. package/package.json +6 -4
@@ -1,7 +1,9 @@
1
- import { type ActionRequest, type Capabilities, type FilterNode, type ListResponse, type Row, type SortKey } from "@jsudc/core";
1
+ import { type ActionRequest, type Capabilities, type FilterNode, type HostAction, type HostActionPayload, type HostActionResponse, type ListResponse, type Row, type SortKey } from "@jsudc/core";
2
2
  import type { UdcClient } from "@jsudc/core/client";
3
- import { type InfiniteData } from "@tanstack/react-query";
3
+ import { type UseMutationOptions, type UseMutationResult } from "@tanstack/react-query";
4
4
  import { type PagingMode } from "./keys.js";
5
+ import { applyToListRows, type ListCache } from "./listCache.js";
6
+ export { applyToListRows };
5
7
  export declare function useUdcCollections(): import("@tanstack/react-query").UseQueryResult<{
6
8
  collections: {
7
9
  [x: string]: unknown;
@@ -19,8 +21,11 @@ export declare function useUdcCollections(): import("@tanstack/react-query").Use
19
21
  source_yaml: boolean;
20
22
  supported_filter_ops: ("eq" | "neq" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | "gt" | "gte" | "lt" | "lte" | "between" | "is_null" | "is_not_null")[];
21
23
  paging?: ("cursor" | "offset")[] | undefined;
24
+ mutate_many?: boolean | undefined;
25
+ search?: "source" | undefined;
26
+ changes?: boolean | undefined;
22
27
  };
23
- source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu";
28
+ source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu" | "postgres_table";
24
29
  label?: string | undefined;
25
30
  group?: "database" | "files" | "internet" | undefined;
26
31
  }[];
@@ -41,8 +46,11 @@ export declare function useUdcDescribe(collection: string, opts?: {
41
46
  source_yaml: boolean;
42
47
  supported_filter_ops: ("eq" | "neq" | "in" | "not_in" | "contains" | "starts_with" | "ends_with" | "gt" | "gte" | "lt" | "lte" | "between" | "is_null" | "is_not_null")[];
43
48
  paging?: ("cursor" | "offset")[] | undefined;
49
+ mutate_many?: boolean | undefined;
50
+ search?: "source" | undefined;
51
+ changes?: boolean | undefined;
44
52
  };
45
- source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu";
53
+ source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu" | "postgres_table";
46
54
  schema: {
47
55
  field_order: string[];
48
56
  version: string;
@@ -368,6 +376,9 @@ export declare function useUdcDescribe(collection: string, opts?: {
368
376
  when?: boolean | FilterNode | undefined;
369
377
  icon?: string | undefined;
370
378
  variant?: "default" | "outline" | "destructive" | undefined;
379
+ set?: Record<string, unknown> | undefined;
380
+ action?: string | undefined;
381
+ confirm?: string | boolean | undefined;
371
382
  }[] | undefined;
372
383
  bulk_actions?: {
373
384
  [x: string]: unknown;
@@ -376,6 +387,9 @@ export declare function useUdcDescribe(collection: string, opts?: {
376
387
  when?: boolean | FilterNode | undefined;
377
388
  icon?: string | undefined;
378
389
  variant?: "default" | "outline" | "destructive" | undefined;
390
+ set?: Record<string, unknown> | undefined;
391
+ action?: string | undefined;
392
+ confirm?: string | boolean | undefined;
379
393
  }[] | undefined;
380
394
  multiselect?: boolean | undefined;
381
395
  row_actions_display?: "inline" | "menu" | undefined;
@@ -431,10 +445,22 @@ export interface UseUdcCollectionArgs {
431
445
  /** 1-based; pages mode only. */
432
446
  page?: number;
433
447
  enabled?: boolean;
434
- /** From `describe`: a source without `cursor` paging is walked by offset in infinite mode too. */
435
- capabilities?: Pick<Capabilities, "paging"> | undefined;
436
- /** Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`). */
448
+ /**
449
+ * From `describe`: a source without `cursor` paging is walked by offset in
450
+ * infinite mode too; `changes` says whether it offers the change feed.
451
+ */
452
+ capabilities?: Pick<Capabilities, "paging" | "changes"> | undefined;
453
+ /**
454
+ * Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`).
455
+ * Suspended while the provider's change feed carries the collection.
456
+ */
437
457
  refetchInterval?: number | undefined;
458
+ /**
459
+ * The search box's text, sent as `ListRequest.search` for a source that
460
+ * answers search itself (`capabilities.search === "source"`); blank or
461
+ * absent: no `search` in the request, nor in the query key.
462
+ */
463
+ search?: string | undefined;
438
464
  }
439
465
  export interface UdcCollectionResult {
440
466
  rows: Row[];
@@ -458,6 +484,10 @@ export declare function freshnessOf(res: Pick<ListResponse, "fetched_at" | "stal
458
484
  fetchedAt: string | null;
459
485
  stale: boolean;
460
486
  };
487
+ /** `{ search }` for a non-blank text, else nothing: spread into a list request and its query key. */
488
+ export declare function searchPart(search: string | undefined): {
489
+ search?: string;
490
+ };
461
491
  /** The `offset` a 1-based page asks for. */
462
492
  export declare function pageOffset(page: number, limit: number): number;
463
493
  /**
@@ -480,6 +510,8 @@ export interface FetchAllRowsArgs {
480
510
  pageLimit?: number;
481
511
  /** Keyset paging unless the source pages by offset only. */
482
512
  cursor: boolean;
513
+ /** Sent as `ListRequest.search` when not blank (a source that answers search). */
514
+ search?: string | undefined;
483
515
  signal?: AbortSignal;
484
516
  onProgress?: (loaded: number, total: number | null) => void;
485
517
  }
@@ -497,11 +529,16 @@ export interface UseUdcAllRowsArgs {
497
529
  sort?: SortKey[];
498
530
  /** Default 2,000. */
499
531
  max?: number;
500
- /** From `describe`: whether the source pages by cursor. */
501
- capabilities?: Pick<Capabilities, "paging"> | undefined;
532
+ /** From `describe`: whether the source pages by cursor, and offers the change feed. */
533
+ capabilities?: Pick<Capabilities, "paging" | "changes"> | undefined;
502
534
  enabled?: boolean;
503
- /** Poll: refetch every row this often (the view's `refresh_interval_ms`). */
535
+ /**
536
+ * Poll: refetch every row this often (the view's `refresh_interval_ms`).
537
+ * Suspended while the provider's change feed carries the collection.
538
+ */
504
539
  refetchInterval?: number | undefined;
540
+ /** Sent as `ListRequest.search` when not blank (`capabilities.search === "source"`). */
541
+ search?: string | undefined;
505
542
  }
506
543
  export interface UdcAllRowsResult {
507
544
  rows: Row[];
@@ -527,7 +564,6 @@ export interface UdcAllRowsResult {
527
564
  * patches and invalidations reach it like every other list.
528
565
  */
529
566
  export declare function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult;
530
- type ListCache = ListResponse | InfiniteData<ListResponse, unknown>;
531
567
  /** `data` with every row whose id is `id` passed through `patch`. */
532
568
  export declare function patchRowInList(data: ListCache | undefined, id: string, patch: (row: Row) => Row): ListCache | undefined;
533
569
  export type UdcMutateVars = Omit<ActionRequest<"mutate">, "collection">;
@@ -538,7 +574,7 @@ export type UdcMutateVars = Omit<ActionRequest<"mutate">, "collection">;
538
574
  * value that won; the error still reaches the caller. Lists are invalidated
539
575
  * once the call settles.
540
576
  */
541
- export declare function useUdcMutate(collection: string): import("@tanstack/react-query").UseMutationResult<{
577
+ export declare function useUdcMutate(collection: string): UseMutationResult<{
542
578
  row: {
543
579
  [x: string]: unknown;
544
580
  __meta: {
@@ -555,7 +591,7 @@ export declare function useUdcMutate(collection: string): import("@tanstack/reac
555
591
  * derives the columns) and the lists are refetched afterwards.
556
592
  */
557
593
  export declare function useUdcSchema(collection: string): {
558
- addField: import("@tanstack/react-query").UseMutationResult<{
594
+ addField: UseMutationResult<{
559
595
  schema: {
560
596
  field_order: string[];
561
597
  version: string;
@@ -611,7 +647,7 @@ export declare function useUdcSchema(collection: string): {
611
647
  anchor?: string | undefined;
612
648
  };
613
649
  }, "collection">, unknown>;
614
- updateField: import("@tanstack/react-query").UseMutationResult<{
650
+ updateField: UseMutationResult<{
615
651
  schema: {
616
652
  field_order: string[];
617
653
  version: string;
@@ -663,7 +699,7 @@ export declare function useUdcSchema(collection: string): {
663
699
  } | undefined;
664
700
  };
665
701
  }, "collection">, unknown>;
666
- softDeleteField: import("@tanstack/react-query").UseMutationResult<{
702
+ softDeleteField: UseMutationResult<{
667
703
  schema: {
668
704
  field_order: string[];
669
705
  version: string;
@@ -692,4 +728,46 @@ export declare function useUdcSchema(collection: string): {
692
728
  };
693
729
  }, Error, string, unknown>;
694
730
  };
695
- export {};
731
+ export type UdcMutateManyVars = Omit<ActionRequest<"mutate_many">, "collection">;
732
+ /**
733
+ * Which cached row a `mutate_many` request touches: one of its `ids`, or a row
734
+ * its `filter` matches (evaluated in the browser, `evaluateFilter`) that is
735
+ * not among `except_ids`. A filter the browser cannot evaluate touches no
736
+ * cached row: the invalidation after the call brings the server's answer.
737
+ */
738
+ export declare function mutateManyTouches(vars: UdcMutateManyVars): (row: Row) => boolean;
739
+ /**
740
+ * Change (`update`, the patch in `row`) or delete many rows of a collection in
741
+ * one `mutate_many` request: by `ids`, or by `filter` with `except_ids` ("all
742
+ * that match, except these"). Like `useUdcMutate` for one row, the loaded
743
+ * rows are patched (or removed) in every cached list at once, put back if the
744
+ * call fails, and the collection's lists and lookups are invalidated once it
745
+ * settles. Resolves to the server's `{ updated, failed }`: `failed` names the
746
+ * ids that were not changed, and why.
747
+ */
748
+ export declare function useUdcMutateMany(collection: string): UseMutationResult<{
749
+ updated: number;
750
+ failed: {
751
+ id: string;
752
+ code: "not_found" | "validation_error" | "version_conflict" | "forbidden" | "unsupported_op" | "internal";
753
+ message?: string | undefined;
754
+ }[];
755
+ }, Error, UdcMutateManyVars, {
756
+ snapshot: [readonly unknown[], ListCache | undefined][];
757
+ }>;
758
+ /** What `useUdcAction` takes besides TanStack's mutation options. */
759
+ export interface UseUdcActionOptions<Res, Req> extends Omit<UseMutationOptions<Res, Error, Req>, "mutationFn"> {
760
+ /** Collections whose lists and lookups to invalidate once the call settles (the rows it changed). */
761
+ invalidates?: readonly string[] | undefined;
762
+ }
763
+ /**
764
+ * A mutation over the client's typed `call`, for any host action: pass the
765
+ * action's definition (`defineHostAction`, shared with the server) and the
766
+ * payload and the result are typed from its schemas; or pass a name and type
767
+ * it yourself (`useUdcAction<Res, Req>("mail.snooze")`). `invalidates` names
768
+ * the collections whose lists to refetch afterwards.
769
+ */
770
+ export declare function useUdcAction<H extends HostAction>(action: H, options?: UseUdcActionOptions<HostActionResponse<H>, HostActionPayload<H>>): UseMutationResult<HostActionResponse<H>, Error, HostActionPayload<H>>;
771
+ export declare function useUdcAction<Res = unknown, Req = Record<string, unknown>>(action: string, options?: UseUdcActionOptions<Res, Req>): UseMutationResult<Res, Error, Req>;
772
+ /** `client.call` for a host action given by definition or by name (the answer unchecked by name). */
773
+ export declare function callAction(client: UdcClient, action: string | HostAction, payload: unknown): Promise<unknown>;
package/dist/udc/hooks.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { useUdcChanges } from "./changes.js";
1
2
  import { useUdcClient } from "./client.js";
2
3
  import { udcKeys } from "./keys.js";
4
+ import { applyToListRows, isInfinite } from "./listCache.js";
5
+ import { evaluateFilter, isVersionConflict } from "@jsudc/core";
3
6
  import { useState } from "react";
4
- import { isVersionConflict } from "@jsudc/core";
5
7
  import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
6
8
  // src/udc/hooks.ts
7
9
  function useUdcCollections() {
@@ -41,6 +43,11 @@ function freshnessOf(res) {
41
43
  stale: res?.stale === true
42
44
  };
43
45
  }
46
+ /** `{ search }` for a non-blank text, else nothing: spread into a list request and its query key. */
47
+ function searchPart(search) {
48
+ const text = search?.trim();
49
+ return text ? { search: text } : {};
50
+ }
44
51
  /** The `offset` a 1-based page asks for. */
45
52
  function pageOffset(page, limit) {
46
53
  return Math.max(0, Math.floor(page) - 1) * limit;
@@ -60,12 +67,17 @@ function useUdcCollection(args) {
60
67
  const page = Math.max(1, args.page ?? 1);
61
68
  const enabled = args.enabled ?? true;
62
69
  const byCursor = args.capabilities?.paging?.includes("cursor") ?? true;
63
- const refetchInterval = pollInterval(args.refetchInterval);
70
+ const refetchInterval = useUdcChanges(collection, void 0, {
71
+ capabilities: args.capabilities,
72
+ enabled
73
+ }).live ? false : pollInterval(args.refetchInterval);
74
+ const searched = searchPart(args.search);
64
75
  const infiniteParams = {
65
76
  filter,
66
77
  sort,
67
78
  limit,
68
- mode: "infinite"
79
+ mode: "infinite",
80
+ ...searched
69
81
  };
70
82
  const infinite = useInfiniteQuery({
71
83
  queryKey: udcKeys.list(collection, infiniteParams),
@@ -73,6 +85,7 @@ function useUdcCollection(args) {
73
85
  collection,
74
86
  ...filter ? { filter } : {},
75
87
  sort,
88
+ ...searched,
76
89
  page: typeof pageParam === "number" ? {
77
90
  limit,
78
91
  offset: pageParam
@@ -96,7 +109,8 @@ function useUdcCollection(args) {
96
109
  sort,
97
110
  limit,
98
111
  mode: "pages",
99
- page
112
+ page,
113
+ ...searched
100
114
  };
101
115
  const paged = useQuery({
102
116
  queryKey: udcKeys.list(collection, pagesParams),
@@ -104,6 +118,7 @@ function useUdcCollection(args) {
104
118
  collection,
105
119
  ...filter ? { filter } : {},
106
120
  sort,
121
+ ...searched,
107
122
  page: {
108
123
  limit,
109
124
  offset: pageOffset(page, limit)
@@ -172,6 +187,7 @@ async function fetchAllRows(client, args) {
172
187
  collection,
173
188
  ...filter ? { filter } : {},
174
189
  sort,
190
+ ...searchPart(args.search),
175
191
  page
176
192
  }, args.signal ? { signal: args.signal } : void 0);
177
193
  if (rows.length === 0) freshness = {
@@ -208,11 +224,17 @@ function useUdcAllRows(args) {
208
224
  const max = args.max ?? 2e3;
209
225
  const cursor = args.capabilities?.paging?.includes("cursor") ?? true;
210
226
  const [progress, setProgress] = useState(null);
227
+ const feed = useUdcChanges(collection, void 0, {
228
+ capabilities: args.capabilities,
229
+ enabled: args.enabled ?? true
230
+ });
231
+ const searched = searchPart(args.search);
211
232
  const key = {
212
233
  filter,
213
234
  sort,
214
235
  limit: max,
215
- mode: "all"
236
+ mode: "all",
237
+ ...searched
216
238
  };
217
239
  const query = useQuery({
218
240
  queryKey: udcKeys.list(collection, key),
@@ -228,6 +250,7 @@ function useUdcAllRows(args) {
228
250
  sort,
229
251
  max,
230
252
  cursor,
253
+ ...searched,
231
254
  signal,
232
255
  onProgress: (loaded, total) => setProgress({
233
256
  loaded,
@@ -240,7 +263,7 @@ function useUdcAllRows(args) {
240
263
  },
241
264
  placeholderData: keepPreviousData,
242
265
  enabled: args.enabled ?? true,
243
- refetchInterval: pollInterval(args.refetchInterval)
266
+ refetchInterval: feed.live ? false : pollInterval(args.refetchInterval)
244
267
  });
245
268
  const rows = query.data?.rows ?? [];
246
269
  const total = query.data?.total ?? null;
@@ -256,9 +279,6 @@ function useUdcAllRows(args) {
256
279
  ...freshnessOf(query.data)
257
280
  };
258
281
  }
259
- function isInfinite(data) {
260
- return "pages" in data;
261
- }
262
282
  /** `data` with every row whose id is `id` passed through `patch`. */
263
283
  function patchRowInList(data, id, patch) {
264
284
  if (!data) return data;
@@ -356,6 +376,89 @@ function useUdcSchema(collection) {
356
376
  })
357
377
  };
358
378
  }
359
- export { ALL_ROWS_MAX, fetchAllRows, freshnessOf, pageOffset, patchRowInList, pollInterval, useUdcAllRows, useUdcCollection, useUdcCollections, useUdcDescribe, useUdcMutate, useUdcSchema, useUdcSource };
379
+ /**
380
+ * Which cached row a `mutate_many` request touches: one of its `ids`, or a row
381
+ * its `filter` matches (evaluated in the browser, `evaluateFilter`) that is
382
+ * not among `except_ids`. A filter the browser cannot evaluate touches no
383
+ * cached row: the invalidation after the call brings the server's answer.
384
+ */
385
+ function mutateManyTouches(vars) {
386
+ if (vars.ids) {
387
+ const ids = new Set(vars.ids);
388
+ return (row) => ids.has(row.__meta.id);
389
+ }
390
+ const except = new Set(vars.except_ids ?? []);
391
+ const filter = vars.filter;
392
+ return (row) => {
393
+ if (except.has(row.__meta.id)) return false;
394
+ try {
395
+ return evaluateFilter(filter, row);
396
+ } catch {
397
+ return false;
398
+ }
399
+ };
400
+ }
401
+ /**
402
+ * Change (`update`, the patch in `row`) or delete many rows of a collection in
403
+ * one `mutate_many` request: by `ids`, or by `filter` with `except_ids` ("all
404
+ * that match, except these"). Like `useUdcMutate` for one row, the loaded
405
+ * rows are patched (or removed) in every cached list at once, put back if the
406
+ * call fails, and the collection's lists and lookups are invalidated once it
407
+ * settles. Resolves to the server's `{ updated, failed }`: `failed` names the
408
+ * ids that were not changed, and why.
409
+ */
410
+ function useUdcMutateMany(collection) {
411
+ const client = useUdcClient();
412
+ const qc = useQueryClient();
413
+ return useMutation({
414
+ mutationFn: (vars) => client.mutateMany({
415
+ collection,
416
+ ...vars
417
+ }),
418
+ onMutate: async (vars) => {
419
+ await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });
420
+ const snapshot = qc.getQueriesData({ queryKey: udcKeys.lists(collection) });
421
+ const touches = mutateManyTouches(vars);
422
+ const set = vars.row;
423
+ const patch = vars.op === "update" && set ? (r) => ({
424
+ ...r,
425
+ ...set,
426
+ __meta: r.__meta
427
+ }) : void 0;
428
+ if (vars.op === "delete" || patch) qc.setQueriesData({ queryKey: udcKeys.lists(collection) }, (data) => applyToListRows(data, touches, patch));
429
+ return { snapshot };
430
+ },
431
+ onError: (_err, _vars, ctx) => {
432
+ for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);
433
+ },
434
+ onSettled: () => Promise.all([
435
+ qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),
436
+ qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),
437
+ qc.invalidateQueries({ queryKey: [
438
+ "udc",
439
+ "lookup-options",
440
+ collection
441
+ ] })
442
+ ])
443
+ });
444
+ }
445
+ function useUdcAction(action, options = {}) {
446
+ const client = useUdcClient();
447
+ const qc = useQueryClient();
448
+ const { invalidates, onSettled, ...rest } = options;
449
+ return useMutation({
450
+ ...rest,
451
+ mutationFn: (payload) => callAction(client, action, payload),
452
+ onSettled: async (...args) => {
453
+ await Promise.all((invalidates ?? []).flatMap((c) => [qc.invalidateQueries({ queryKey: udcKeys.lists(c) }), qc.invalidateQueries({ queryKey: udcKeys.lookups(c) })]));
454
+ return onSettled?.(...args);
455
+ }
456
+ });
457
+ }
458
+ /** `client.call` for a host action given by definition or by name (the answer unchecked by name). */
459
+ function callAction(client, action, payload) {
460
+ return client.call.bind(client)(action, payload);
461
+ }
462
+ export { ALL_ROWS_MAX, applyToListRows, callAction, fetchAllRows, freshnessOf, mutateManyTouches, pageOffset, patchRowInList, pollInterval, searchPart, useUdcAction, useUdcAllRows, useUdcCollection, useUdcCollections, useUdcDescribe, useUdcMutate, useUdcMutateMany, useUdcSchema, useUdcSource };
360
463
 
361
464
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":[],"sources":["../../src/udc/hooks.ts"],"sourcesContent":["import {\n type ActionRequest,\n type Capabilities,\n type FilterNode,\n isVersionConflict,\n type ListResponse,\n type Row,\n type SortKey,\n} from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport {\n type InfiniteData,\n keepPreviousData,\n type QueryClient,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport { useState } from \"react\";\nimport { useUdcClient } from \"./client.js\";\nimport { type ListKeyParams, type PagingMode, udcKeys } from \"./keys.js\";\n\nexport function useUdcCollections() {\n const client = useUdcClient();\n return useQuery({ queryKey: udcKeys.collections(), queryFn: () => client.collections() });\n}\n\nexport function useUdcDescribe(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.describe(collection),\n queryFn: () => client.describe(collection),\n staleTime: 5 * 60_000,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\n/** The file a `source_yaml` collection is read from (`source.read`); fetched again on every mount. */\nexport function useUdcSource(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.source(collection),\n queryFn: () => client.sourceRead(collection),\n staleTime: 0,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\nexport interface UseUdcCollectionArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n mode: PagingMode;\n pageLimit: number;\n /** 1-based; pages mode only. */\n page?: number;\n enabled?: boolean;\n /** From `describe`: a source without `cursor` paging is walked by offset in infinite mode too. */\n capabilities?: Pick<Capabilities, \"paging\"> | undefined;\n /** Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`). */\n refetchInterval?: number | undefined;\n}\n\nexport interface UdcCollectionResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => void;\n /** Infinite mode only; always false in pages mode. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n fetchNextPage: () => void;\n /** A source serving a fetched copy: when it was fetched, and whether the last refresh failed. */\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/** `refetchInterval` for TanStack: a positive number of ms, else off. */\nexport function pollInterval(ms: number | undefined): number | false {\n return typeof ms === \"number\" && ms > 0 ? ms : false;\n}\n\n/** The freshness of a list answer: `fetched_at` and `stale` when the source sent them. */\nexport function freshnessOf(res: Pick<ListResponse, \"fetched_at\" | \"stale\"> | undefined): {\n fetchedAt: string | null;\n stale: boolean;\n} {\n return { fetchedAt: res?.fetched_at ?? null, stale: res?.stale === true };\n}\n\n/** The `offset` a 1-based page asks for. */\nexport function pageOffset(page: number, limit: number): number {\n return Math.max(0, Math.floor(page) - 1) * limit;\n}\n\n/**\n * Rows of one collection. Infinite mode follows `next_cursor` page by page\n * (`useInfiniteQuery`), or the next `offset` while rows remain when the\n * source pages by offset only; pages mode asks for one `offset` page\n * (`useQuery`). Both hooks are always mounted and the inactive one is\n * disabled, so switching modes keeps each cache warm. `refetchInterval`\n * polls the active one.\n */\nexport function useUdcCollection(args: UseUdcCollectionArgs): UdcCollectionResult {\n const client = useUdcClient();\n const { collection, filter, mode, pageLimit: limit } = args;\n const sort = args.sort ?? [];\n const page = Math.max(1, args.page ?? 1);\n const enabled = args.enabled ?? true;\n const byCursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n const refetchInterval = pollInterval(args.refetchInterval);\n\n const infiniteParams: ListKeyParams = { filter, sort, limit, mode: \"infinite\" };\n const infinite = useInfiniteQuery({\n queryKey: udcKeys.list(collection, infiniteParams),\n queryFn: ({ pageParam, signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n page:\n typeof pageParam === \"number\"\n ? { limit, offset: pageParam }\n : pageParam\n ? { limit, cursor: pageParam }\n : { limit },\n },\n { signal },\n ),\n initialPageParam: null as string | number | null,\n getNextPageParam: (last, all) => {\n if (byCursor) return last.next_cursor ?? undefined;\n const loaded = all.reduce((n, p) => n + p.rows.length, 0);\n return last.rows.length > 0 && last.total !== null && loaded < last.total\n ? loaded\n : undefined;\n },\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"infinite\",\n refetchInterval,\n });\n\n const pagesParams: ListKeyParams = { filter, sort, limit, mode: \"pages\", page };\n const paged = useQuery({\n queryKey: udcKeys.list(collection, pagesParams),\n queryFn: ({ signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n page: { limit, offset: pageOffset(page, limit) },\n },\n { signal },\n ),\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"pages\",\n refetchInterval,\n });\n\n if (mode === \"infinite\") {\n const pages = infinite.data?.pages ?? [];\n return {\n rows: pages.flatMap((p) => p.rows),\n total: pages[0]?.total ?? null,\n isLoading: infinite.isLoading,\n isFetching: infinite.isFetching,\n error: infinite.error,\n refetch: () => void infinite.refetch(),\n hasNextPage: infinite.hasNextPage,\n isFetchingNextPage: infinite.isFetchingNextPage,\n fetchNextPage: () => void infinite.fetchNextPage(),\n ...freshnessOf(pages[0]),\n };\n }\n return {\n rows: paged.data?.rows ?? [],\n total: paged.data?.total ?? null,\n isLoading: paged.isLoading,\n isFetching: paged.isFetching,\n error: paged.error,\n refetch: () => void paged.refetch(),\n hasNextPage: false,\n isFetchingNextPage: false,\n fetchNextPage: () => {},\n ...freshnessOf(paged.data),\n };\n}\n\nexport const ALL_ROWS_MAX = 2000;\nconst ALL_ROWS_PAGE = 500;\n\nexport interface FetchAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Stop after this many rows. */\n max: number;\n /** Rows per `list` call. */\n pageLimit?: number;\n /** Keyset paging unless the source pages by offset only. */\n cursor: boolean;\n signal?: AbortSignal;\n onProgress?: (loaded: number, total: number | null) => void;\n}\n\n/**\n * Every row of a filter, `list` page after page, until `total` or `max`.\n * Follows `next_cursor` when keyset paging is on; a source that answers no\n * cursor while rows remain is walked on by offset. Answers one list whose\n * `total` is the server's (so `rows.length < total` means capped), with the\n * first page's `fetched_at` and `stale`.\n */\nexport async function fetchAllRows(\n client: UdcClient,\n args: FetchAllRowsArgs,\n): Promise<ListResponse> {\n const { collection, filter, max } = args;\n const sort = args.sort ?? [];\n const pageLimit = args.pageLimit ?? ALL_ROWS_PAGE;\n const rows: Row[] = [];\n let total: number | null = null;\n let freshness: Pick<ListResponse, \"fetched_at\" | \"stale\"> = {};\n let cursor: string | null = null;\n let byCursor = args.cursor;\n while (rows.length < max) {\n const limit = Math.min(pageLimit, max - rows.length);\n const page = byCursor\n ? cursor\n ? { limit, cursor }\n : { limit }\n : { limit, offset: rows.length };\n const res = await client.list(\n { collection, ...(filter ? { filter } : {}), sort, page },\n args.signal ? { signal: args.signal } : undefined,\n );\n if (rows.length === 0) {\n freshness = {\n ...(res.fetched_at === undefined ? {} : { fetched_at: res.fetched_at }),\n ...(res.stale === undefined ? {} : { stale: res.stale }),\n };\n }\n rows.push(...res.rows);\n total = res.total;\n args.onProgress?.(rows.length, total);\n if (res.rows.length === 0 || (total !== null && rows.length >= total)) break;\n if (byCursor) {\n if (res.next_cursor) cursor = res.next_cursor;\n else if (total === null) break;\n else byCursor = false;\n } else if (total === null && res.rows.length < limit) {\n break;\n }\n }\n return { ...freshness, rows, next_cursor: null, total: total ?? rows.length };\n}\n\nexport interface UseUdcAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Default 2,000. */\n max?: number;\n /** From `describe`: whether the source pages by cursor. */\n capabilities?: Pick<Capabilities, \"paging\"> | undefined;\n enabled?: boolean;\n /** Poll: refetch every row this often (the view's `refresh_interval_ms`). */\n refetchInterval?: number | undefined;\n}\n\nexport interface UdcAllRowsResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => Promise<unknown>;\n /** More rows match than `max`: only the first `max` are here. */\n capped: boolean;\n /** Rows loaded so far by the fetch in flight, for a progress bar. */\n progress: { loaded: number; total: number | null } | null;\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/**\n * All rows of the current filter in one cached list: what the kanban (and\n * the calendar, tree, map and charts after it) draw from. The cache entry\n * sits under `udcKeys.lists(collection)`, so `useUdcMutate`'s optimistic\n * patches and invalidations reach it like every other list.\n */\nexport function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult {\n const client = useUdcClient();\n const { collection, filter } = args;\n const sort = args.sort ?? [];\n const max = args.max ?? ALL_ROWS_MAX;\n const cursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n const [progress, setProgress] = useState<UdcAllRowsResult[\"progress\"]>(null);\n\n const key: ListKeyParams = { filter, sort, limit: max, mode: \"all\" };\n const query = useQuery({\n queryKey: udcKeys.list(collection, key),\n queryFn: async ({ signal }) => {\n setProgress({ loaded: 0, total: null });\n try {\n return await fetchAllRows(client, {\n collection,\n filter,\n sort,\n max,\n cursor,\n signal,\n onProgress: (loaded, total) => setProgress({ loaded, total }),\n });\n } finally {\n setProgress(null);\n }\n },\n placeholderData: keepPreviousData,\n enabled: args.enabled ?? true,\n refetchInterval: pollInterval(args.refetchInterval),\n });\n\n const rows = query.data?.rows ?? [];\n const total = query.data?.total ?? null;\n return {\n rows,\n total,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: query.error,\n refetch: () => query.refetch(),\n capped: total !== null && rows.length < total,\n progress,\n ...freshnessOf(query.data),\n };\n}\n\ntype ListCache = ListResponse | InfiniteData<ListResponse, unknown>;\n\nfunction isInfinite(data: ListCache): data is InfiniteData<ListResponse, unknown> {\n return \"pages\" in data;\n}\n\n/** `data` with every row whose id is `id` passed through `patch`. */\nexport function patchRowInList(\n data: ListCache | undefined,\n id: string,\n patch: (row: Row) => Row,\n): ListCache | undefined {\n if (!data) return data;\n const patchPage = (page: ListResponse): ListResponse =>\n page.rows.some((r) => r.__meta.id === id)\n ? { ...page, rows: page.rows.map((r) => (r.__meta.id === id ? patch(r) : r)) }\n : page;\n return isInfinite(data) ? { ...data, pages: data.pages.map(patchPage) } : patchPage(data);\n}\n\nfunction patchRowEverywhere(\n qc: QueryClient,\n collection: string,\n id: string,\n patch: (row: Row) => Row,\n) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n patchRowInList(data, id, patch),\n );\n}\n\nexport type UdcMutateVars = Omit<ActionRequest<\"mutate\">, \"collection\">;\n\n/**\n * Insert / update / delete one row. An update is applied optimistically to\n * the row in every cached list page and rolled back if the server says no.\n * A `version_conflict` additionally re-reads the row, so the cache holds the\n * value that won; the error still reaches the caller. Lists are invalidated\n * once the call settles.\n */\nexport function useUdcMutate(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateVars) => client.mutate({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const { id, row } = vars;\n if (vars.op === \"update\" && id && row) {\n patchRowEverywhere(qc, collection, id, (r) => ({ ...r, ...row, __meta: r.__meta }));\n }\n return { snapshot };\n },\n onSuccess: (res) => {\n patchRowEverywhere(qc, collection, res.row.__meta.id, () => res.row);\n },\n onError: async (err, vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n if (isVersionConflict(err) && vars.id) {\n try {\n const fresh = await client.read(collection, vars.id);\n patchRowEverywhere(qc, collection, vars.id, () => fresh.row);\n } catch {\n // The invalidation below refetches the lists anyway.\n }\n }\n },\n // A row of this collection may be another collection's lookup label: those batches go stale too.\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/**\n * The three schema edits. Each answers the new schema; `describe` (which\n * derives the columns) and the lists are refetched afterwards.\n */\nexport function useUdcSchema(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n const onSuccess = async () => {\n await qc.invalidateQueries({ queryKey: udcKeys.describe(collection) });\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n };\n\n const addField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.add_field\">, \"collection\">) =>\n client.schemaAddField({ collection, ...req }),\n onSuccess,\n });\n const updateField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.update_field\">, \"collection\">) =>\n client.schemaUpdateField({ collection, ...req }),\n onSuccess,\n });\n const softDeleteField = useMutation({\n mutationFn: (field: string) => client.schemaSoftDeleteField({ collection, field }),\n onSuccess,\n });\n return {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src/udc/hooks.ts"],"sourcesContent":["import {\n type ActionRequest,\n type Capabilities,\n evaluateFilter,\n type FilterNode,\n type HostAction,\n type HostActionPayload,\n type HostActionResponse,\n isVersionConflict,\n type ListResponse,\n type Row,\n type SortKey,\n} from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport {\n keepPreviousData,\n type QueryClient,\n type UseMutationOptions,\n type UseMutationResult,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport { useState } from \"react\";\nimport { useUdcChanges } from \"./changes.js\";\nimport { useUdcClient } from \"./client.js\";\nimport { type ListKeyParams, type PagingMode, udcKeys } from \"./keys.js\";\nimport { applyToListRows, isInfinite, type ListCache } from \"./listCache.js\";\n\nexport { applyToListRows };\n\nexport function useUdcCollections() {\n const client = useUdcClient();\n return useQuery({ queryKey: udcKeys.collections(), queryFn: () => client.collections() });\n}\n\nexport function useUdcDescribe(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.describe(collection),\n queryFn: () => client.describe(collection),\n staleTime: 5 * 60_000,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\n/** The file a `source_yaml` collection is read from (`source.read`); fetched again on every mount. */\nexport function useUdcSource(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.source(collection),\n queryFn: () => client.sourceRead(collection),\n staleTime: 0,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\nexport interface UseUdcCollectionArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n mode: PagingMode;\n pageLimit: number;\n /** 1-based; pages mode only. */\n page?: number;\n enabled?: boolean;\n /**\n * From `describe`: a source without `cursor` paging is walked by offset in\n * infinite mode too; `changes` says whether it offers the change feed.\n */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n /**\n * Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /**\n * The search box's text, sent as `ListRequest.search` for a source that\n * answers search itself (`capabilities.search === \"source\"`); blank or\n * absent: no `search` in the request, nor in the query key.\n */\n search?: string | undefined;\n}\n\nexport interface UdcCollectionResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => void;\n /** Infinite mode only; always false in pages mode. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n fetchNextPage: () => void;\n /** A source serving a fetched copy: when it was fetched, and whether the last refresh failed. */\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/** `refetchInterval` for TanStack: a positive number of ms, else off. */\nexport function pollInterval(ms: number | undefined): number | false {\n return typeof ms === \"number\" && ms > 0 ? ms : false;\n}\n\n/** The freshness of a list answer: `fetched_at` and `stale` when the source sent them. */\nexport function freshnessOf(res: Pick<ListResponse, \"fetched_at\" | \"stale\"> | undefined): {\n fetchedAt: string | null;\n stale: boolean;\n} {\n return { fetchedAt: res?.fetched_at ?? null, stale: res?.stale === true };\n}\n\n/** `{ search }` for a non-blank text, else nothing: spread into a list request and its query key. */\nexport function searchPart(search: string | undefined): { search?: string } {\n const text = search?.trim();\n return text ? { search: text } : {};\n}\n\n/** The `offset` a 1-based page asks for. */\nexport function pageOffset(page: number, limit: number): number {\n return Math.max(0, Math.floor(page) - 1) * limit;\n}\n\n/**\n * Rows of one collection. Infinite mode follows `next_cursor` page by page\n * (`useInfiniteQuery`), or the next `offset` while rows remain when the\n * source pages by offset only; pages mode asks for one `offset` page\n * (`useQuery`). Both hooks are always mounted and the inactive one is\n * disabled, so switching modes keeps each cache warm. `refetchInterval`\n * polls the active one.\n */\nexport function useUdcCollection(args: UseUdcCollectionArgs): UdcCollectionResult {\n const client = useUdcClient();\n const { collection, filter, mode, pageLimit: limit } = args;\n const sort = args.sort ?? [];\n const page = Math.max(1, args.page ?? 1);\n const enabled = args.enabled ?? true;\n const byCursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n // The change feed (when the provider has one) refetches on events; the timer covers the rest.\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled,\n });\n const refetchInterval = feed.live ? false : pollInterval(args.refetchInterval);\n const searched = searchPart(args.search);\n\n const infiniteParams: ListKeyParams = { filter, sort, limit, mode: \"infinite\", ...searched };\n const infinite = useInfiniteQuery({\n queryKey: udcKeys.list(collection, infiniteParams),\n queryFn: ({ pageParam, signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page:\n typeof pageParam === \"number\"\n ? { limit, offset: pageParam }\n : pageParam\n ? { limit, cursor: pageParam }\n : { limit },\n },\n { signal },\n ),\n initialPageParam: null as string | number | null,\n getNextPageParam: (last, all) => {\n if (byCursor) return last.next_cursor ?? undefined;\n const loaded = all.reduce((n, p) => n + p.rows.length, 0);\n return last.rows.length > 0 && last.total !== null && loaded < last.total\n ? loaded\n : undefined;\n },\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"infinite\",\n refetchInterval,\n });\n\n const pagesParams: ListKeyParams = { filter, sort, limit, mode: \"pages\", page, ...searched };\n const paged = useQuery({\n queryKey: udcKeys.list(collection, pagesParams),\n queryFn: ({ signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page: { limit, offset: pageOffset(page, limit) },\n },\n { signal },\n ),\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"pages\",\n refetchInterval,\n });\n\n if (mode === \"infinite\") {\n const pages = infinite.data?.pages ?? [];\n return {\n rows: pages.flatMap((p) => p.rows),\n total: pages[0]?.total ?? null,\n isLoading: infinite.isLoading,\n isFetching: infinite.isFetching,\n error: infinite.error,\n refetch: () => void infinite.refetch(),\n hasNextPage: infinite.hasNextPage,\n isFetchingNextPage: infinite.isFetchingNextPage,\n fetchNextPage: () => void infinite.fetchNextPage(),\n ...freshnessOf(pages[0]),\n };\n }\n return {\n rows: paged.data?.rows ?? [],\n total: paged.data?.total ?? null,\n isLoading: paged.isLoading,\n isFetching: paged.isFetching,\n error: paged.error,\n refetch: () => void paged.refetch(),\n hasNextPage: false,\n isFetchingNextPage: false,\n fetchNextPage: () => {},\n ...freshnessOf(paged.data),\n };\n}\n\nexport const ALL_ROWS_MAX = 2000;\nconst ALL_ROWS_PAGE = 500;\n\nexport interface FetchAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Stop after this many rows. */\n max: number;\n /** Rows per `list` call. */\n pageLimit?: number;\n /** Keyset paging unless the source pages by offset only. */\n cursor: boolean;\n /** Sent as `ListRequest.search` when not blank (a source that answers search). */\n search?: string | undefined;\n signal?: AbortSignal;\n onProgress?: (loaded: number, total: number | null) => void;\n}\n\n/**\n * Every row of a filter, `list` page after page, until `total` or `max`.\n * Follows `next_cursor` when keyset paging is on; a source that answers no\n * cursor while rows remain is walked on by offset. Answers one list whose\n * `total` is the server's (so `rows.length < total` means capped), with the\n * first page's `fetched_at` and `stale`.\n */\nexport async function fetchAllRows(\n client: UdcClient,\n args: FetchAllRowsArgs,\n): Promise<ListResponse> {\n const { collection, filter, max } = args;\n const sort = args.sort ?? [];\n const pageLimit = args.pageLimit ?? ALL_ROWS_PAGE;\n const rows: Row[] = [];\n let total: number | null = null;\n let freshness: Pick<ListResponse, \"fetched_at\" | \"stale\"> = {};\n let cursor: string | null = null;\n let byCursor = args.cursor;\n while (rows.length < max) {\n const limit = Math.min(pageLimit, max - rows.length);\n const page = byCursor\n ? cursor\n ? { limit, cursor }\n : { limit }\n : { limit, offset: rows.length };\n const res = await client.list(\n { collection, ...(filter ? { filter } : {}), sort, ...searchPart(args.search), page },\n args.signal ? { signal: args.signal } : undefined,\n );\n if (rows.length === 0) {\n freshness = {\n ...(res.fetched_at === undefined ? {} : { fetched_at: res.fetched_at }),\n ...(res.stale === undefined ? {} : { stale: res.stale }),\n };\n }\n rows.push(...res.rows);\n total = res.total;\n args.onProgress?.(rows.length, total);\n if (res.rows.length === 0 || (total !== null && rows.length >= total)) break;\n if (byCursor) {\n if (res.next_cursor) cursor = res.next_cursor;\n else if (total === null) break;\n else byCursor = false;\n } else if (total === null && res.rows.length < limit) {\n break;\n }\n }\n return { ...freshness, rows, next_cursor: null, total: total ?? rows.length };\n}\n\nexport interface UseUdcAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Default 2,000. */\n max?: number;\n /** From `describe`: whether the source pages by cursor, and offers the change feed. */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n enabled?: boolean;\n /**\n * Poll: refetch every row this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /** Sent as `ListRequest.search` when not blank (`capabilities.search === \"source\"`). */\n search?: string | undefined;\n}\n\nexport interface UdcAllRowsResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => Promise<unknown>;\n /** More rows match than `max`: only the first `max` are here. */\n capped: boolean;\n /** Rows loaded so far by the fetch in flight, for a progress bar. */\n progress: { loaded: number; total: number | null } | null;\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/**\n * All rows of the current filter in one cached list: what the kanban (and\n * the calendar, tree, map and charts after it) draw from. The cache entry\n * sits under `udcKeys.lists(collection)`, so `useUdcMutate`'s optimistic\n * patches and invalidations reach it like every other list.\n */\nexport function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult {\n const client = useUdcClient();\n const { collection, filter } = args;\n const sort = args.sort ?? [];\n const max = args.max ?? ALL_ROWS_MAX;\n const cursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n const [progress, setProgress] = useState<UdcAllRowsResult[\"progress\"]>(null);\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled: args.enabled ?? true,\n });\n\n const searched = searchPart(args.search);\n const key: ListKeyParams = { filter, sort, limit: max, mode: \"all\", ...searched };\n const query = useQuery({\n queryKey: udcKeys.list(collection, key),\n queryFn: async ({ signal }) => {\n setProgress({ loaded: 0, total: null });\n try {\n return await fetchAllRows(client, {\n collection,\n filter,\n sort,\n max,\n cursor,\n ...searched,\n signal,\n onProgress: (loaded, total) => setProgress({ loaded, total }),\n });\n } finally {\n setProgress(null);\n }\n },\n placeholderData: keepPreviousData,\n enabled: args.enabled ?? true,\n refetchInterval: feed.live ? false : pollInterval(args.refetchInterval),\n });\n\n const rows = query.data?.rows ?? [];\n const total = query.data?.total ?? null;\n return {\n rows,\n total,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: query.error,\n refetch: () => query.refetch(),\n capped: total !== null && rows.length < total,\n progress,\n ...freshnessOf(query.data),\n };\n}\n\n/** `data` with every row whose id is `id` passed through `patch`. */\nexport function patchRowInList(\n data: ListCache | undefined,\n id: string,\n patch: (row: Row) => Row,\n): ListCache | undefined {\n if (!data) return data;\n const patchPage = (page: ListResponse): ListResponse =>\n page.rows.some((r) => r.__meta.id === id)\n ? { ...page, rows: page.rows.map((r) => (r.__meta.id === id ? patch(r) : r)) }\n : page;\n return isInfinite(data) ? { ...data, pages: data.pages.map(patchPage) } : patchPage(data);\n}\n\nfunction patchRowEverywhere(\n qc: QueryClient,\n collection: string,\n id: string,\n patch: (row: Row) => Row,\n) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n patchRowInList(data, id, patch),\n );\n}\n\nexport type UdcMutateVars = Omit<ActionRequest<\"mutate\">, \"collection\">;\n\n/**\n * Insert / update / delete one row. An update is applied optimistically to\n * the row in every cached list page and rolled back if the server says no.\n * A `version_conflict` additionally re-reads the row, so the cache holds the\n * value that won; the error still reaches the caller. Lists are invalidated\n * once the call settles.\n */\nexport function useUdcMutate(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateVars) => client.mutate({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const { id, row } = vars;\n if (vars.op === \"update\" && id && row) {\n patchRowEverywhere(qc, collection, id, (r) => ({ ...r, ...row, __meta: r.__meta }));\n }\n return { snapshot };\n },\n onSuccess: (res) => {\n patchRowEverywhere(qc, collection, res.row.__meta.id, () => res.row);\n },\n onError: async (err, vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n if (isVersionConflict(err) && vars.id) {\n try {\n const fresh = await client.read(collection, vars.id);\n patchRowEverywhere(qc, collection, vars.id, () => fresh.row);\n } catch {\n // The invalidation below refetches the lists anyway.\n }\n }\n },\n // A row of this collection may be another collection's lookup label: those batches go stale too.\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/**\n * The three schema edits. Each answers the new schema; `describe` (which\n * derives the columns) and the lists are refetched afterwards.\n */\nexport function useUdcSchema(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n const onSuccess = async () => {\n await qc.invalidateQueries({ queryKey: udcKeys.describe(collection) });\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n };\n\n const addField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.add_field\">, \"collection\">) =>\n client.schemaAddField({ collection, ...req }),\n onSuccess,\n });\n const updateField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.update_field\">, \"collection\">) =>\n client.schemaUpdateField({ collection, ...req }),\n onSuccess,\n });\n const softDeleteField = useMutation({\n mutationFn: (field: string) => client.schemaSoftDeleteField({ collection, field }),\n onSuccess,\n });\n return { addField, updateField, softDeleteField };\n}\n\n// mutate_many and host actions (0.5.0) --------------------------------------\n\nexport type UdcMutateManyVars = Omit<ActionRequest<\"mutate_many\">, \"collection\">;\n\n/**\n * Which cached row a `mutate_many` request touches: one of its `ids`, or a row\n * its `filter` matches (evaluated in the browser, `evaluateFilter`) that is\n * not among `except_ids`. A filter the browser cannot evaluate touches no\n * cached row: the invalidation after the call brings the server's answer.\n */\nexport function mutateManyTouches(vars: UdcMutateManyVars): (row: Row) => boolean {\n if (vars.ids) {\n const ids = new Set(vars.ids);\n return (row) => ids.has(row.__meta.id);\n }\n const except = new Set(vars.except_ids ?? []);\n const filter = vars.filter;\n return (row) => {\n if (except.has(row.__meta.id)) return false;\n try {\n return evaluateFilter(filter, row);\n } catch {\n return false;\n }\n };\n}\n\n/**\n * Change (`update`, the patch in `row`) or delete many rows of a collection in\n * one `mutate_many` request: by `ids`, or by `filter` with `except_ids` (\"all\n * that match, except these\"). Like `useUdcMutate` for one row, the loaded\n * rows are patched (or removed) in every cached list at once, put back if the\n * call fails, and the collection's lists and lookups are invalidated once it\n * settles. Resolves to the server's `{ updated, failed }`: `failed` names the\n * ids that were not changed, and why.\n */\nexport function useUdcMutateMany(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateManyVars) => client.mutateMany({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const touches = mutateManyTouches(vars);\n const set = vars.row;\n const patch =\n vars.op === \"update\" && set\n ? (r: Row): Row => ({ ...r, ...set, __meta: r.__meta })\n : undefined;\n if (vars.op === \"delete\" || patch) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n applyToListRows(data, touches, patch),\n );\n }\n return { snapshot };\n },\n onError: (_err, _vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n },\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/** What `useUdcAction` takes besides TanStack's mutation options. */\nexport interface UseUdcActionOptions<Res, Req>\n extends Omit<UseMutationOptions<Res, Error, Req>, \"mutationFn\"> {\n /** Collections whose lists and lookups to invalidate once the call settles (the rows it changed). */\n invalidates?: readonly string[] | undefined;\n}\n\n/**\n * A mutation over the client's typed `call`, for any host action: pass the\n * action's definition (`defineHostAction`, shared with the server) and the\n * payload and the result are typed from its schemas; or pass a name and type\n * it yourself (`useUdcAction<Res, Req>(\"mail.snooze\")`). `invalidates` names\n * the collections whose lists to refetch afterwards.\n */\nexport function useUdcAction<H extends HostAction>(\n action: H,\n options?: UseUdcActionOptions<HostActionResponse<H>, HostActionPayload<H>>,\n): UseMutationResult<HostActionResponse<H>, Error, HostActionPayload<H>>;\nexport function useUdcAction<Res = unknown, Req = Record<string, unknown>>(\n action: string,\n options?: UseUdcActionOptions<Res, Req>,\n): UseMutationResult<Res, Error, Req>;\nexport function useUdcAction(\n action: string | HostAction,\n options: UseUdcActionOptions<unknown, unknown> = {},\n): UseMutationResult<unknown, Error, unknown> {\n const client = useUdcClient();\n const qc = useQueryClient();\n const { invalidates, onSettled, ...rest } = options;\n return useMutation<unknown, Error, unknown>({\n ...rest,\n mutationFn: (payload) => callAction(client, action, payload),\n onSettled: async (...args) => {\n await Promise.all(\n (invalidates ?? []).flatMap((c) => [\n qc.invalidateQueries({ queryKey: udcKeys.lists(c) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(c) }),\n ]),\n );\n return onSettled?.(...args);\n },\n });\n}\n\n/** `client.call` for a host action given by definition or by name (the answer unchecked by name). */\nexport function callAction(\n client: UdcClient,\n action: string | HostAction,\n payload: unknown,\n): Promise<unknown> {\n const call = client.call.bind(client) as (a: string | HostAction, p: unknown) => Promise<unknown>;\n return call(action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7
7
  /** `all`: every row up to `limit`, fetched page by page into one list (`useUdcAllRows`). */
8
8
  mode: PagingMode | "all";
9
9
  page?: number;
10
+ /** The text sent as `ListRequest.search` (a source that answers search); absent otherwise. */
11
+ search?: string;
10
12
  }
11
13
  /** Every query this app makes sits under `["udc", ...]`. */
12
14
  export declare const udcKeys: {
@@ -1 +1 @@
1
- {"version":3,"file":"keys.js","names":[],"sources":["../../src/udc/keys.ts"],"sourcesContent":["import type { FilterNode, SortKey } from \"@jsudc/core\";\n\nexport type PagingMode = \"infinite\" | \"pages\";\n\nexport interface ListKeyParams {\n filter: FilterNode | undefined;\n sort: SortKey[];\n limit: number;\n /** `all`: every row up to `limit`, fetched page by page into one list (`useUdcAllRows`). */\n mode: PagingMode | \"all\";\n page?: number;\n}\n\n/** Every query this app makes sits under `[\"udc\", ...]`. */\nexport const udcKeys = {\n all: [\"udc\"] as const,\n collections: () => [\"udc\", \"collections\"] as const,\n describe: (collection: string) => [\"udc\", \"describe\", collection] as const,\n source: (collection: string) => [\"udc\", \"source\", collection] as const,\n lists: (collection: string) => [\"udc\", \"list\", collection] as const,\n list: (collection: string, params: ListKeyParams) => [\"udc\", \"list\", collection, params] as const,\n lookups: (collection: string) => [\"udc\", \"lookup\", collection] as const,\n /** One lookup batch: the target collection, its sorted keys, and the key field when not `id`. */\n lookup: (collection: string, sortedKeys: readonly string[], keyField = \"id\") =>\n keyField === \"id\"\n ? ([\"udc\", \"lookup\", collection, sortedKeys] as const)\n : ([\"udc\", \"lookup\", collection, sortedKeys, keyField] as const),\n /** The options of a lookup picker (a chip, the inline editor): target, label field, search. */\n lookupOptions: (collection: string, labelField: string, search: string) =>\n [\"udc\", \"lookup-options\", collection, labelField, search] as const,\n};\n"],"mappings":";;AAcA,IAAa,UAAU;CACrB,KAAK,CAAC,KAAK;CACX,mBAAmB,CAAC,OAAO,aAAa;CACxC,WAAW,eAAuB;EAAC;EAAO;EAAY;CAAU;CAChE,SAAS,eAAuB;EAAC;EAAO;EAAU;CAAU;CAC5D,QAAQ,eAAuB;EAAC;EAAO;EAAQ;CAAU;CACzD,OAAO,YAAoB,WAA0B;EAAC;EAAO;EAAQ;EAAY;CAAM;CACvF,UAAU,eAAuB;EAAC;EAAO;EAAU;CAAU;;CAE7D,SAAS,YAAoB,YAA+B,WAAW,SACrE,aAAa,OACR;EAAC;EAAO;EAAU;EAAY;CAAU,IACxC;EAAC;EAAO;EAAU;EAAY;EAAY;CAAQ;;CAEzD,gBAAgB,YAAoB,YAAoB,WACtD;EAAC;EAAO;EAAkB;EAAY;EAAY;CAAM;AAC5D"}
1
+ {"version":3,"file":"keys.js","names":[],"sources":["../../src/udc/keys.ts"],"sourcesContent":["import type { FilterNode, SortKey } from \"@jsudc/core\";\n\nexport type PagingMode = \"infinite\" | \"pages\";\n\nexport interface ListKeyParams {\n filter: FilterNode | undefined;\n sort: SortKey[];\n limit: number;\n /** `all`: every row up to `limit`, fetched page by page into one list (`useUdcAllRows`). */\n mode: PagingMode | \"all\";\n page?: number;\n /** The text sent as `ListRequest.search` (a source that answers search); absent otherwise. */\n search?: string;\n}\n\n/** Every query this app makes sits under `[\"udc\", ...]`. */\nexport const udcKeys = {\n all: [\"udc\"] as const,\n collections: () => [\"udc\", \"collections\"] as const,\n describe: (collection: string) => [\"udc\", \"describe\", collection] as const,\n source: (collection: string) => [\"udc\", \"source\", collection] as const,\n lists: (collection: string) => [\"udc\", \"list\", collection] as const,\n list: (collection: string, params: ListKeyParams) => [\"udc\", \"list\", collection, params] as const,\n lookups: (collection: string) => [\"udc\", \"lookup\", collection] as const,\n /** One lookup batch: the target collection, its sorted keys, and the key field when not `id`. */\n lookup: (collection: string, sortedKeys: readonly string[], keyField = \"id\") =>\n keyField === \"id\"\n ? ([\"udc\", \"lookup\", collection, sortedKeys] as const)\n : ([\"udc\", \"lookup\", collection, sortedKeys, keyField] as const),\n /** The options of a lookup picker (a chip, the inline editor): target, label field, search. */\n lookupOptions: (collection: string, labelField: string, search: string) =>\n [\"udc\", \"lookup-options\", collection, labelField, search] as const,\n};\n"],"mappings":";;AAgBA,IAAa,UAAU;CACrB,KAAK,CAAC,KAAK;CACX,mBAAmB,CAAC,OAAO,aAAa;CACxC,WAAW,eAAuB;EAAC;EAAO;EAAY;CAAU;CAChE,SAAS,eAAuB;EAAC;EAAO;EAAU;CAAU;CAC5D,QAAQ,eAAuB;EAAC;EAAO;EAAQ;CAAU;CACzD,OAAO,YAAoB,WAA0B;EAAC;EAAO;EAAQ;EAAY;CAAM;CACvF,UAAU,eAAuB;EAAC;EAAO;EAAU;CAAU;;CAE7D,SAAS,YAAoB,YAA+B,WAAW,SACrE,aAAa,OACR;EAAC;EAAO;EAAU;EAAY;CAAU,IACxC;EAAC;EAAO;EAAU;EAAY;EAAY;CAAQ;;CAEzD,gBAAgB,YAAoB,YAAoB,WACtD;EAAC;EAAO;EAAkB;EAAY;EAAY;CAAM;AAC5D"}
@@ -0,0 +1,11 @@
1
+ import type { ListResponse, Row } from "@jsudc/core";
2
+ import type { InfiniteData } from "@tanstack/react-query";
3
+ /** What a list query caches: one page (`useQuery`) or the pages of an infinite list. */
4
+ export type ListCache = ListResponse | InfiniteData<ListResponse, unknown>;
5
+ export declare function isInfinite(data: ListCache): data is InfiniteData<ListResponse, unknown>;
6
+ /**
7
+ * `data` with every row `touches` picks patched (`patch` given) or removed
8
+ * (`patch` absent; each page's `total` goes down by the rows removed from the
9
+ * whole list).
10
+ */
11
+ export declare function applyToListRows(data: ListCache | undefined, touches: (row: Row) => boolean, patch?: (row: Row) => Row): ListCache | undefined;
@@ -0,0 +1,38 @@
1
+ // src/udc/listCache.ts
2
+ function isInfinite(data) {
3
+ return "pages" in data;
4
+ }
5
+ /**
6
+ * `data` with every row `touches` picks patched (`patch` given) or removed
7
+ * (`patch` absent; each page's `total` goes down by the rows removed from the
8
+ * whole list).
9
+ */
10
+ function applyToListRows(data, touches, patch) {
11
+ if (!data) return data;
12
+ const pages = isInfinite(data) ? data.pages : [data];
13
+ let removed = 0;
14
+ const next = pages.map((page) => {
15
+ if (!page.rows.some(touches)) return page;
16
+ if (patch) return {
17
+ ...page,
18
+ rows: page.rows.map((r) => touches(r) ? patch(r) : r)
19
+ };
20
+ const rows = page.rows.filter((r) => !touches(r));
21
+ removed += page.rows.length - rows.length;
22
+ return {
23
+ ...page,
24
+ rows
25
+ };
26
+ });
27
+ const counted = removed === 0 ? next : next.map((p) => p.total === null ? p : {
28
+ ...p,
29
+ total: Math.max(0, p.total - removed)
30
+ });
31
+ return isInfinite(data) ? {
32
+ ...data,
33
+ pages: counted
34
+ } : counted[0];
35
+ }
36
+ export { applyToListRows, isInfinite };
37
+
38
+ //# sourceMappingURL=listCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listCache.js","names":[],"sources":["../../src/udc/listCache.ts"],"sourcesContent":["import type { ListResponse, Row } from \"@jsudc/core\";\nimport type { InfiniteData } from \"@tanstack/react-query\";\n\n/** What a list query caches: one page (`useQuery`) or the pages of an infinite list. */\nexport type ListCache = ListResponse | InfiniteData<ListResponse, unknown>;\n\nexport function isInfinite(data: ListCache): data is InfiniteData<ListResponse, unknown> {\n return \"pages\" in data;\n}\n\n/**\n * `data` with every row `touches` picks patched (`patch` given) or removed\n * (`patch` absent; each page's `total` goes down by the rows removed from the\n * whole list).\n */\nexport function applyToListRows(\n data: ListCache | undefined,\n touches: (row: Row) => boolean,\n patch?: (row: Row) => Row,\n): ListCache | undefined {\n if (!data) return data;\n const pages = isInfinite(data) ? data.pages : [data];\n let removed = 0;\n const next = pages.map((page) => {\n if (!page.rows.some(touches)) return page;\n if (patch) return { ...page, rows: page.rows.map((r) => (touches(r) ? patch(r) : r)) };\n const rows = page.rows.filter((r) => !touches(r));\n removed += page.rows.length - rows.length;\n return { ...page, rows };\n });\n const counted =\n removed === 0\n ? next\n : next.map((p) => (p.total === null ? p : { ...p, total: Math.max(0, p.total - removed) }));\n return isInfinite(data) ? { ...data, pages: counted } : (counted[0] as ListResponse);\n}\n"],"mappings":";AAMA,SAAgB,WAAW,MAA8D;CACvF,OAAO,WAAW;AACpB;;;;;;AAOA,SAAgB,gBACd,MACA,SACA,OACuB;CACvB,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,QAAQ,WAAW,IAAI,IAAI,KAAK,QAAQ,CAAC,IAAI;CACnD,IAAI,UAAU;CACd,MAAM,OAAO,MAAM,KAAK,SAAS;EAC/B,IAAI,CAAC,KAAK,KAAK,KAAK,OAAO,GAAG,OAAO;EACrC,IAAI,OAAO,OAAO;GAAE,GAAG;GAAM,MAAM,KAAK,KAAK,KAAK,MAAO,QAAQ,CAAC,IAAI,MAAM,CAAC,IAAI,CAAE;EAAE;EACrF,MAAM,OAAO,KAAK,KAAK,QAAQ,MAAM,CAAC,QAAQ,CAAC,CAAC;EAChD,WAAW,KAAK,KAAK,SAAS,KAAK;EACnC,OAAO;GAAE,GAAG;GAAM;EAAK;CACzB,CAAC;CACD,MAAM,UACJ,YAAY,IACR,OACA,KAAK,KAAK,MAAO,EAAE,UAAU,OAAO,IAAI;EAAE,GAAG;EAAG,OAAO,KAAK,IAAI,GAAG,EAAE,QAAQ,OAAO;CAAE,CAAE;CAC9F,OAAO,WAAW,IAAI,IAAI;EAAE,GAAG;EAAM,OAAO;CAAQ,IAAK,QAAQ;AACnE"}