@jsudc/react 0.4.0 → 0.5.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 (105) hide show
  1. package/README.md +615 -11
  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 +4 -3
  15. package/dist/calendar/CalendarRenderer.js.map +1 -1
  16. package/dist/cards/CardRenderer.d.ts +6 -0
  17. package/dist/cards/CardRenderer.js +45 -9
  18. package/dist/cards/CardRenderer.js.map +1 -1
  19. package/dist/chart/ChartRenderer.js +6 -4
  20. package/dist/chart/ChartRenderer.js.map +1 -1
  21. package/dist/chart/ChartWindowControl.js +1 -1
  22. package/dist/data-view/BulkBar.d.ts +36 -0
  23. package/dist/data-view/BulkBar.js +239 -0
  24. package/dist/data-view/BulkBar.js.map +1 -0
  25. package/dist/data-view/FilePreview.js +1 -1
  26. package/dist/data-view/FilterBuilder.js +1 -1
  27. package/dist/data-view/FilterChips.js +1 -1
  28. package/dist/data-view/LiveIndicator.d.ts +10 -0
  29. package/dist/data-view/LiveIndicator.js +33 -0
  30. package/dist/data-view/LiveIndicator.js.map +1 -0
  31. package/dist/data-view/UdcDataView.d.ts +28 -1
  32. package/dist/data-view/UdcDataView.js +76 -9
  33. package/dist/data-view/UdcDataView.js.map +1 -1
  34. package/dist/headless.d.ts +6 -0
  35. package/dist/headless.js +9 -2
  36. package/dist/i18n/translations.js +144 -0
  37. package/dist/i18n/translations.js.map +1 -1
  38. package/dist/index.d.ts +10 -2
  39. package/dist/index.js +13 -4
  40. package/dist/kanban/KanbanCard.js +1 -1
  41. package/dist/kanban/KanbanRenderer.js +5 -4
  42. package/dist/kanban/KanbanRenderer.js.map +1 -1
  43. package/dist/lookup/batch.js +1 -1
  44. package/dist/lookup/options.js +4 -1
  45. package/dist/lookup/options.js.map +1 -1
  46. package/dist/lookup/useUdcLookup.js +9 -3
  47. package/dist/lookup/useUdcLookup.js.map +1 -1
  48. package/dist/map/MapRenderer.js +3 -2
  49. package/dist/map/MapRenderer.js.map +1 -1
  50. package/dist/renderers/types.d.ts +32 -1
  51. package/dist/renderers/types.js.map +1 -1
  52. package/dist/rows/useRowActivation.d.ts +17 -0
  53. package/dist/rows/useRowActivation.js +37 -5
  54. package/dist/rows/useRowActivation.js.map +1 -1
  55. package/dist/rows/useRowSelection.d.ts +92 -0
  56. package/dist/rows/useRowSelection.js +156 -0
  57. package/dist/rows/useRowSelection.js.map +1 -0
  58. package/dist/schema-editor/DeleteFieldDialog.js +1 -1
  59. package/dist/schema-editor/FieldFormDialog.js +1 -1
  60. package/dist/styles.css +1 -1
  61. package/dist/styles.scoped.css +1 -1
  62. package/dist/table/CellEditor.js +1 -1
  63. package/dist/table/Pager.d.ts +10 -2
  64. package/dist/table/Pager.js +26 -20
  65. package/dist/table/Pager.js.map +1 -1
  66. package/dist/table/SelectCheckbox.d.ts +15 -0
  67. package/dist/table/SelectCheckbox.js +37 -0
  68. package/dist/table/SelectCheckbox.js.map +1 -0
  69. package/dist/table/TableRenderer.d.ts +13 -0
  70. package/dist/table/TableRenderer.js +284 -125
  71. package/dist/table/TableRenderer.js.map +1 -1
  72. package/dist/table/cells.js +1 -1
  73. package/dist/table/index.d.ts +1 -0
  74. package/dist/table/states.js +1 -1
  75. package/dist/table/useRowWindow.d.ts +82 -0
  76. package/dist/table/useRowWindow.js +182 -0
  77. package/dist/table/useRowWindow.js.map +1 -0
  78. package/dist/table.js.map +1 -1
  79. package/dist/tree/TreeRenderer.d.ts +2 -0
  80. package/dist/tree/TreeRenderer.js +15 -9
  81. package/dist/tree/TreeRenderer.js.map +1 -1
  82. package/dist/udc/changeFeed.d.ts +107 -0
  83. package/dist/udc/changeFeed.js +281 -0
  84. package/dist/udc/changeFeed.js.map +1 -0
  85. package/dist/udc/changes.d.ts +40 -0
  86. package/dist/udc/changes.js +85 -0
  87. package/dist/udc/changes.js.map +1 -0
  88. package/dist/udc/client.js +5 -2
  89. package/dist/udc/client.js.map +1 -1
  90. package/dist/udc/hooks.d.ts +93 -20
  91. package/dist/udc/hooks.js +115 -11
  92. package/dist/udc/hooks.js.map +1 -1
  93. package/dist/udc/keys.d.ts +2 -0
  94. package/dist/udc/keys.js.map +1 -1
  95. package/dist/udc/listCache.d.ts +11 -0
  96. package/dist/udc/listCache.js +38 -0
  97. package/dist/udc/listCache.js.map +1 -0
  98. package/dist/udc/provider.d.ts +34 -2
  99. package/dist/udc/provider.js +28 -2
  100. package/dist/udc/provider.js.map +1 -1
  101. package/dist/udc/unauthenticated.d.ts +4 -0
  102. package/dist/udc/unauthenticated.js +17 -0
  103. package/dist/udc/unauthenticated.js.map +1 -0
  104. package/dist/ui-kit/types.d.ts +14 -0
  105. package/package.json +3 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"changeFeed.js","names":[],"sources":["../../src/udc/changeFeed.ts"],"sourcesContent":["import { type ChangeEvent, isUnauthenticated } from \"@jsudc/core\";\nimport type { ChangesOptions, UdcClient } from \"@jsudc/core/client\";\nimport type { Query, QueryClient } from \"@tanstack/react-query\";\nimport { udcKeys } from \"./keys.js\";\nimport { applyToListRows, type ListCache } from \"./listCache.js\";\nimport { notifyUnauthenticated } from \"./unauthenticated.js\";\n\n/**\n * Where the change feed stands for one collection, as `useUdcChanges` reports\n * it:\n * - `off`: no feed (the provider has none, or the collection does not offer\n * `capabilities.changes`); the view polls as it always did.\n * - `connecting`: subscribed, the stream that carries it is not open yet.\n * - `live`: the stream is open; timer polling is suspended.\n * - `reconnecting`: the stream dropped and is being reopened; polling resumes.\n * - `down`: the server refused the stream (signed out, forbidden, unknown\n * collection); no reconnecting, polling only.\n */\nexport type UdcChangeFeedStatus = \"off\" | \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\n/** `UdcProvider changes={…}`: `true` takes every default. */\nexport interface UdcChangeFeedOptions {\n /** A burst of events for one collection within this many ms makes one invalidation. Default 200. */\n debounceMs?: number;\n /**\n * How long to wait after a view mounts or unmounts before the stream is\n * reopened with the new list of collections, so a page that mounts several\n * views opens one stream. Default 50.\n */\n batchMs?: number;\n /**\n * A `delete` event that names its ids removes those rows from the cached\n * lists at once, before the refetch. Default `true`.\n */\n removeDeleted?: boolean;\n /** Passed to `UdcClient.changes`: the first reconnect delay. */\n minDelayMs?: number;\n /** Passed to `UdcClient.changes`: the longest reconnect delay. */\n maxDelayMs?: number;\n /** Passed to `UdcClient.changes`: a silent stream is reopened after this long. */\n idleTimeoutMs?: number;\n}\n\ninterface Subscriber {\n qc: QueryClient;\n onEvent: ((event: ChangeEvent) => void) | undefined;\n}\n\ntype ConnState = \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\ninterface Conn {\n key: string;\n collections: ReadonlySet<string>;\n ctl: AbortController;\n state: ConnState;\n /** When the stream was asked for: data fetched before it may have missed an event. */\n startedAt: number;\n /** Opened by `reconnect()`: no stream carries its collections until it is open (\"reconnecting\"). */\n resumed: boolean;\n}\n\nconst keyOf = (collections: Iterable<string>) => [...collections].sort().join(\"\\n\");\n\n/**\n * The change feed of one `UdcProvider`: one stream for every collection a\n * mounted view (or hook) shows. Collections are reference-counted; when the\n * set changes the new stream is opened first and the old one closed only once\n * the new one is subscribed, so the collections that stay miss nothing. An\n * event marks its collection dirty and, after `debounceMs`, its lists, lookup\n * batches and lookup options are invalidated; \"reconnected\" invalidates every\n * collection of the stream. Framework-free apart from TanStack's QueryClient;\n * `useUdcChanges` is the React side.\n */\nexport class UdcChangeFeed {\n readonly client: UdcClient;\n private readonly opts: Required<\n Omit<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">\n > &\n Pick<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">;\n private readonly subs = new Map<string, Set<Subscriber>>();\n private current: Conn | null = null;\n private pending: Conn | null = null;\n private reconcileTimer: ReturnType<typeof setTimeout> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly dirty = new Map<string, number | undefined>();\n private readonly listeners = new Set<() => void>();\n\n constructor(client: UdcClient, options: UdcChangeFeedOptions = {}) {\n this.client = client;\n this.opts = {\n debounceMs: options.debounceMs ?? 200,\n batchMs: options.batchMs ?? 50,\n removeDeleted: options.removeDeleted ?? true,\n ...(options.minDelayMs === undefined ? {} : { minDelayMs: options.minDelayMs }),\n ...(options.maxDelayMs === undefined ? {} : { maxDelayMs: options.maxDelayMs }),\n ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),\n };\n }\n\n /**\n * Count one more user of `collection` (whose queries live in `qc`); the\n * returned function counts it out. `onEvent` hears every event of the\n * collection as it arrives, before the debounced invalidation.\n */\n subscribe(collection: string, qc: QueryClient, onEvent?: (event: ChangeEvent) => void) {\n const sub: Subscriber = { qc, onEvent };\n let set = this.subs.get(collection);\n if (!set) {\n set = new Set();\n this.subs.set(collection, set);\n }\n set.add(sub);\n this.scheduleReconcile();\n this.emit();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n const s = this.subs.get(collection);\n s?.delete(sub);\n if (s?.size === 0) this.subs.delete(collection);\n this.scheduleReconcile();\n this.emit();\n };\n }\n\n /** The collections the stream is (or is about to be) asked for. */\n collections(): string[] {\n return [...this.subs.keys()].sort();\n }\n\n /** Where the feed stands for `collection`. */\n status(collection: string): UdcChangeFeedStatus {\n if (!this.subs.has(collection)) return \"off\";\n const cur = this.current;\n if (cur?.collections.has(collection) && !(cur.state === \"down\" && this.pending)) {\n return cur.state;\n }\n const pen = this.pending;\n if (pen?.collections.has(collection)) {\n if (pen.state === \"live\" || pen.state === \"down\") return pen.state;\n return pen.resumed ? \"reconnecting\" : \"connecting\";\n }\n return \"connecting\";\n }\n\n /** Called whenever a status may have changed (for `useSyncExternalStore`). */\n onStatus(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Close the stream and open it again for the same collections, now: the\n * server runs the plugin's `context` again, so the stream is scoped to\n * whoever `UdcClient`'s `headers` (or cookies) say is signed in now. For an\n * identity switch with a `headers` function (a demo user, an account\n * switcher, impersonation), or after signing in again, since a stream the\n * server refused is otherwise not asked for until the set of collections\n * changes. Meanwhile the collections report `reconnecting` (polling\n * resumes); once it is open, data fetched before the call is refetched. Does\n * nothing while nobody is subscribed. `UdcProvider changes={{ identity }}`\n * calls it when `identity` changes.\n */\n reconnect(): void {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = null;\n const wanted = this.collections();\n if (wanted.length === 0) {\n this.close();\n return;\n }\n // The open stream carries the previous identity's scope: nothing of it is kept.\n this.pending?.ctl.abort();\n this.current?.ctl.abort();\n this.current = null;\n this.pending = this.open(wanted, keyOf(wanted), true);\n this.emit();\n }\n\n /** Close the stream and drop every timer; the feed opens again when somebody subscribes. */\n close(): void {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.reconcileTimer = this.flushTimer = null;\n this.dirty.clear();\n this.pending?.ctl.abort();\n this.current?.ctl.abort();\n this.pending = this.current = null;\n this.emit();\n }\n\n // The stream ---------------------------------------------------------------\n\n private emit() {\n for (const l of this.listeners) l();\n }\n\n private scheduleReconcile() {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = setTimeout(() => {\n this.reconcileTimer = null;\n this.reconcile();\n }, this.opts.batchMs);\n }\n\n private reconcile() {\n const wanted = this.collections();\n const key = keyOf(wanted);\n if (wanted.length === 0) {\n this.close();\n return;\n }\n const cur = this.current;\n if (cur && cur.key === key) {\n // The set went back to what is open: a reopen in flight is not needed. A stream the\n // server refused for this very set stays refused until the set changes.\n if (this.pending) {\n this.pending.ctl.abort();\n this.pending = null;\n this.emit();\n }\n return;\n }\n if (this.pending?.key === key) return;\n // A set that changes while `reconnect()` is reopening: still no stream carries it.\n const resumed = cur === null && this.pending?.resumed === true;\n this.pending?.ctl.abort();\n this.pending = this.open(wanted, key, resumed);\n this.emit();\n }\n\n private open(collections: string[], key: string, resumed = false): Conn {\n const conn: Conn = {\n key,\n collections: new Set(collections),\n ctl: new AbortController(),\n state: \"connecting\",\n startedAt: Date.now(),\n resumed,\n };\n const { minDelayMs, maxDelayMs, idleTimeoutMs } = this.opts;\n const options: ChangesOptions = {\n collections,\n signal: conn.ctl.signal,\n onChange: (event) => this.deliver(conn, event),\n onOpen: ({ reconnected }) => this.opened(conn, reconnected),\n onError: () => this.dropped(conn),\n ...(minDelayMs === undefined ? {} : { minDelayMs }),\n ...(maxDelayMs === undefined ? {} : { maxDelayMs }),\n ...(idleTimeoutMs === undefined ? {} : { idleTimeoutMs }),\n };\n this.client.changes(options).then(\n () => {},\n (err: unknown) => this.refused(conn, err),\n );\n return conn;\n }\n\n private live(conn: Conn) {\n return conn === this.current || conn === this.pending;\n }\n\n private opened(conn: Conn, reconnected: boolean) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const prev = this.current;\n if (conn === this.pending) {\n // The new stream is subscribed: it takes over, the old one closes.\n this.current = conn;\n this.pending = null;\n if (prev && prev !== conn) prev.ctl.abort();\n }\n conn.state = \"live\";\n if (reconnected) {\n // Changes made while the stream was down were not sent: refetch everything it carries.\n for (const c of conn.collections) this.markDirty(c);\n } else {\n // A collection that was not carried by an open stream until now may have changed between\n // its last fetch and this subscription: refetch what was fetched before the stream was asked for.\n const carried = prev && prev !== conn && prev.state === \"live\" ? prev.collections : new Set();\n for (const c of conn.collections) if (!carried.has(c)) this.markDirty(c, conn.startedAt);\n }\n this.emit();\n }\n\n private dropped(conn: Conn) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"reconnecting\";\n this.emit();\n }\n\n /** `changes()` rejected: the server refused (401, 403, 404, 400). No reconnecting. */\n private refused(conn: Conn, err: unknown) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"down\";\n if (isUnauthenticated(err))\n for (const qc of this.queryClients()) notifyUnauthenticated(qc, err);\n // A refused reopen stays as `pending` in state `down`: the old stream (if open) still carries\n // what it carried, and the same set is not asked for again until it changes.\n this.emit();\n }\n\n private deliver(conn: Conn, event: ChangeEvent) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const subs = this.subs.get(event.collection);\n if (!subs) return; // Not a collection on screen.\n for (const s of [...subs]) {\n try {\n s.onEvent?.(event);\n } catch (err) {\n console.error(\"useUdcChanges: onEvent threw\", err);\n }\n }\n if (event.op === \"delete\" && event.ids?.length && this.opts.removeDeleted) {\n const gone = new Set(event.ids);\n for (const qc of this.queryClients(event.collection)) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(event.collection) }, (data) =>\n applyToListRows(data, (r) => gone.has(r.__meta.id)),\n );\n }\n }\n this.markDirty(event.collection);\n }\n\n // Invalidation -------------------------------------------------------------\n\n /**\n * Refetch `collection` after the debounce; `before` limits it to queries\n * whose data is older than that time (a later plain mark lifts the limit).\n */\n private markDirty(collection: string, before?: number) {\n const had = this.dirty.has(collection);\n const prev = this.dirty.get(collection);\n const next =\n before === undefined || (had && prev === undefined) ? undefined : Math.max(prev ?? 0, before);\n this.dirty.set(collection, next);\n this.scheduleFlush();\n }\n\n private scheduleFlush() {\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.flushTimer = setTimeout(() => this.flush(), this.opts.debounceMs);\n }\n\n private flush() {\n this.flushTimer = null;\n const clients = this.queryClients();\n // A mutation in flight invalidates when it settles; refetching under it would show the\n // row as it was before the optimistic patch. Wait for it.\n if ([...clients].some((qc) => qc.isMutating() > 0)) {\n this.scheduleFlush();\n return;\n }\n const batch = [...this.dirty];\n this.dirty.clear();\n for (const [collection, before] of batch) {\n const predicate =\n before === undefined\n ? undefined\n : (q: Query) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < before;\n for (const qc of this.queryClients(collection)) {\n for (const queryKey of invalidatedKeys(collection)) {\n void qc.invalidateQueries(predicate ? { queryKey, predicate } : { queryKey });\n }\n }\n }\n }\n\n /** The query clients of `collection`'s subscribers, or of everybody's. */\n private queryClients(collection?: string): Set<QueryClient> {\n const out = new Set<QueryClient>();\n const sets = collection === undefined ? [...this.subs.values()] : [this.subs.get(collection)];\n for (const set of sets) for (const s of set ?? []) out.add(s.qc);\n return out;\n }\n}\n\n/** What a change of `collection` makes stale: its lists, the lookups into it, its picker options. */\nexport function invalidatedKeys(collection: string): (readonly unknown[])[] {\n return [\n udcKeys.lists(collection),\n udcKeys.lookups(collection),\n [\"udc\", \"lookup-options\", collection],\n ];\n}\n"],"mappings":";;;;;AA6DA,IAAM,SAAS,gBAAkC,CAAC,GAAG,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;AAYlF,IAAa,gBAAb,MAA2B;CACzB;CACA;CAIA,uBAAwB,IAAI,IAA6B;CACzD,UAA+B;CAC/B,UAA+B;CAC/B,iBAA+D;CAC/D,aAA2D;CAC3D,wBAAyB,IAAI,IAAgC;CAC7D,4BAA6B,IAAI,IAAgB;CAEjD,YAAY,QAAmB,UAAgC,CAAC,GAAG;EACjE,KAAK,SAAS;EACd,KAAK,OAAO;GACV,YAAY,QAAQ,cAAc;GAClC,SAAS,QAAQ,WAAW;GAC5B,eAAe,QAAQ,iBAAiB;GACxC,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;GAC7E,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,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abilities, type ChangeEvent } from "@jsudc/core";
2
+ import type { UdcChangeFeed, UdcChangeFeedStatus } from "./changeFeed.js";
3
+ /**
4
+ * The provider's change feed; `null` when `UdcProvider changes` is off (the
5
+ * default). A host may provide a `UdcChangeFeed` of its own here (one per
6
+ * user, say: `useMemo(() => new UdcChangeFeed(client, opts), [client, user])`,
7
+ * closed with `feed.close()` when replaced); a `UdcProvider` below it with
8
+ * the same client and without `changes` uses it.
9
+ */
10
+ export declare const UdcChangeFeedContext: import("react").Context<UdcChangeFeed | null>;
11
+ /** The provider's change feed, or `null` without one. */
12
+ export declare function useUdcChangeFeed(): UdcChangeFeed | null;
13
+ export interface UseUdcChangesOptions {
14
+ /**
15
+ * The collection's capabilities when the caller has them (`describe`): with
16
+ * `changes` set, no `describe` is asked; without it the hook reads the
17
+ * cached `describe` of the collection (only when the provider has a feed).
18
+ */
19
+ capabilities?: Pick<Capabilities, "changes"> | undefined;
20
+ /** `false`: no subscription (a hidden or disabled view). Default `true`. */
21
+ enabled?: boolean | undefined;
22
+ }
23
+ export interface UdcChangesResult {
24
+ /** Where the feed stands for this collection (see `UdcChangeFeedStatus`). */
25
+ status: UdcChangeFeedStatus;
26
+ /** `status === "live"`: the stream carries the collection, timer polling is suspended. */
27
+ live: boolean;
28
+ }
29
+ /**
30
+ * Follow the change feed of `collection`: while it is mounted the provider's
31
+ * stream carries the collection (`UdcProvider changes`), its lists and lookups
32
+ * are refetched when the server says its rows changed, and `onEvent` (if
33
+ * given) hears each `ChangeEvent` as it arrives (e.g. a badge counter).
34
+ * Answers where the feed stands; `live` is when the views of the collection
35
+ * stop polling. Without a feed in the provider, or for a collection that does
36
+ * not offer `capabilities.changes`, it does nothing and answers `off`.
37
+ */
38
+ export declare function useUdcChanges(collection: string, onEvent?: (event: ChangeEvent) => void, opts?: UseUdcChangesOptions): UdcChangesResult;
39
+ /** `useUdcChanges` for several collections at once, without a status (the lookup hooks). */
40
+ export declare function useUdcChangesMany(collections: readonly string[], opts?: Omit<UseUdcChangesOptions, "capabilities">): void;
@@ -0,0 +1,85 @@
1
+ import { UdcClientContext } from "./client.js";
2
+ import { udcKeys } from "./keys.js";
3
+ import { sourcePushesChanges } from "@jsudc/core";
4
+ import { createContext, useContext, useEffect, useRef, useSyncExternalStore } from "react";
5
+ import { QueryClientContext, useQueries } from "@tanstack/react-query";
6
+ // src/udc/changes.ts
7
+ /**
8
+ * The provider's change feed; `null` when `UdcProvider changes` is off (the
9
+ * default). A host may provide a `UdcChangeFeed` of its own here (one per
10
+ * user, say: `useMemo(() => new UdcChangeFeed(client, opts), [client, user])`,
11
+ * closed with `feed.close()` when replaced); a `UdcProvider` below it with
12
+ * the same client and without `changes` uses it.
13
+ */
14
+ var UdcChangeFeedContext = createContext(null);
15
+ /** The provider's change feed, or `null` without one. */
16
+ function useUdcChangeFeed() {
17
+ return useContext(UdcChangeFeedContext);
18
+ }
19
+ var noSubscribe = () => () => {};
20
+ /**
21
+ * Subscribe `collections` to the provider's feed, each one that offers
22
+ * `capabilities.changes`. Nothing at all (no `describe`, no connection) when
23
+ * the provider has no feed. Answers the collections that are subscribed.
24
+ */
25
+ function useFeedSubscriptions(collections, onEvent, opts) {
26
+ const feed = useContext(UdcChangeFeedContext);
27
+ const client = useContext(UdcClientContext);
28
+ const qc = useContext(QueryClientContext);
29
+ const wanted = feed !== null && client !== null && qc !== void 0 && (opts.enabled ?? true) ? [...new Set(collections.filter((c) => c !== ""))] : [];
30
+ const known = opts.capabilities?.changes;
31
+ const described = useQueries({ queries: known === void 0 && client ? wanted.map((c) => ({
32
+ queryKey: udcKeys.describe(c),
33
+ queryFn: () => client.describe(c),
34
+ staleTime: 3e5
35
+ })) : [] });
36
+ const offered = known === void 0 ? wanted.filter((_, i) => sourcePushesChanges(described[i]?.data?.capabilities)) : known ? wanted : [];
37
+ const onEventRef = useRef(onEvent);
38
+ useEffect(() => {
39
+ onEventRef.current = onEvent;
40
+ });
41
+ const hasOnEvent = onEvent !== void 0;
42
+ const key = offered.join("\n");
43
+ useEffect(() => {
44
+ if (!feed || !qc || key === "") return;
45
+ const listener = hasOnEvent ? (e) => onEventRef.current?.(e) : void 0;
46
+ const offs = key.split("\n").map((c) => feed.subscribe(c, qc, listener));
47
+ return () => {
48
+ for (const off of offs) off();
49
+ };
50
+ }, [
51
+ feed,
52
+ qc,
53
+ key,
54
+ hasOnEvent
55
+ ]);
56
+ return {
57
+ feed,
58
+ offered
59
+ };
60
+ }
61
+ /**
62
+ * Follow the change feed of `collection`: while it is mounted the provider's
63
+ * stream carries the collection (`UdcProvider changes`), its lists and lookups
64
+ * are refetched when the server says its rows changed, and `onEvent` (if
65
+ * given) hears each `ChangeEvent` as it arrives (e.g. a badge counter).
66
+ * Answers where the feed stands; `live` is when the views of the collection
67
+ * stop polling. Without a feed in the provider, or for a collection that does
68
+ * not offer `capabilities.changes`, it does nothing and answers `off`.
69
+ */
70
+ function useUdcChanges(collection, onEvent, opts = {}) {
71
+ const { feed, offered } = useFeedSubscriptions([collection], onEvent, opts);
72
+ const subscribed = offered.length > 0;
73
+ const status = useSyncExternalStore(feed ? (l) => feed.onStatus(l) : noSubscribe, () => feed && subscribed ? feed.status(collection) : "off", () => "off");
74
+ return {
75
+ status,
76
+ live: status === "live"
77
+ };
78
+ }
79
+ /** `useUdcChanges` for several collections at once, without a status (the lookup hooks). */
80
+ function useUdcChangesMany(collections, opts = {}) {
81
+ useFeedSubscriptions(collections, void 0, opts);
82
+ }
83
+ export { UdcChangeFeedContext, useUdcChangeFeed, useUdcChanges, useUdcChangesMany };
84
+
85
+ //# sourceMappingURL=changes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"changes.js","names":[],"sources":["../../src/udc/changes.ts"],"sourcesContent":["import { type Capabilities, type ChangeEvent, sourcePushesChanges } from \"@jsudc/core\";\nimport { QueryClientContext, useQueries } from \"@tanstack/react-query\";\nimport { createContext, useContext, useEffect, useRef, useSyncExternalStore } from \"react\";\nimport type { UdcChangeFeed, UdcChangeFeedStatus } from \"./changeFeed.js\";\nimport { UdcClientContext } from \"./client.js\";\nimport { udcKeys } from \"./keys.js\";\n\n/**\n * The provider's change feed; `null` when `UdcProvider changes` is off (the\n * default). A host may provide a `UdcChangeFeed` of its own here (one per\n * user, say: `useMemo(() => new UdcChangeFeed(client, opts), [client, user])`,\n * closed with `feed.close()` when replaced); a `UdcProvider` below it with\n * the same client and without `changes` uses it.\n */\nexport const UdcChangeFeedContext = createContext<UdcChangeFeed | null>(null);\n\n/** The provider's change feed, or `null` without one. */\nexport function useUdcChangeFeed(): UdcChangeFeed | null {\n return useContext(UdcChangeFeedContext);\n}\n\nexport interface UseUdcChangesOptions {\n /**\n * The collection's capabilities when the caller has them (`describe`): with\n * `changes` set, no `describe` is asked; without it the hook reads the\n * cached `describe` of the collection (only when the provider has a feed).\n */\n capabilities?: Pick<Capabilities, \"changes\"> | undefined;\n /** `false`: no subscription (a hidden or disabled view). Default `true`. */\n enabled?: boolean | undefined;\n}\n\nexport interface UdcChangesResult {\n /** Where the feed stands for this collection (see `UdcChangeFeedStatus`). */\n status: UdcChangeFeedStatus;\n /** `status === \"live\"`: the stream carries the collection, timer polling is suspended. */\n live: boolean;\n}\n\nconst noSubscribe = () => () => {};\n\n/**\n * Subscribe `collections` to the provider's feed, each one that offers\n * `capabilities.changes`. Nothing at all (no `describe`, no connection) when\n * the provider has no feed. Answers the collections that are subscribed.\n */\nfunction useFeedSubscriptions(\n collections: readonly string[],\n onEvent: ((event: ChangeEvent) => void) | undefined,\n opts: UseUdcChangesOptions,\n): { feed: UdcChangeFeed | null; offered: string[] } {\n const feed = useContext(UdcChangeFeedContext);\n const client = useContext(UdcClientContext);\n const qc = useContext(QueryClientContext);\n const on = feed !== null && client !== null && qc !== undefined && (opts.enabled ?? true);\n const wanted = on ? [...new Set(collections.filter((c) => c !== \"\"))] : [];\n const known = opts.capabilities?.changes;\n // The capability, from `describe` (cached for minutes, shared with the view that shows it).\n const described = useQueries({\n queries:\n known === undefined && client\n ? wanted.map((c) => ({\n queryKey: udcKeys.describe(c),\n queryFn: () => client.describe(c),\n staleTime: 5 * 60_000,\n }))\n : [],\n });\n const offered =\n known === undefined\n ? wanted.filter((_, i) => sourcePushesChanges(described[i]?.data?.capabilities))\n : known\n ? wanted\n : [];\n\n const onEventRef = useRef(onEvent);\n useEffect(() => {\n onEventRef.current = onEvent;\n });\n const hasOnEvent = onEvent !== undefined;\n const key = offered.join(\"\\n\");\n useEffect(() => {\n if (!feed || !qc || key === \"\") return;\n const listener = hasOnEvent ? (e: ChangeEvent) => onEventRef.current?.(e) : undefined;\n const offs = key.split(\"\\n\").map((c) => feed.subscribe(c, qc, listener));\n return () => {\n for (const off of offs) off();\n };\n }, [feed, qc, key, hasOnEvent]);\n return { feed, offered };\n}\n\n/**\n * Follow the change feed of `collection`: while it is mounted the provider's\n * stream carries the collection (`UdcProvider changes`), its lists and lookups\n * are refetched when the server says its rows changed, and `onEvent` (if\n * given) hears each `ChangeEvent` as it arrives (e.g. a badge counter).\n * Answers where the feed stands; `live` is when the views of the collection\n * stop polling. Without a feed in the provider, or for a collection that does\n * not offer `capabilities.changes`, it does nothing and answers `off`.\n */\nexport function useUdcChanges(\n collection: string,\n onEvent?: (event: ChangeEvent) => void,\n opts: UseUdcChangesOptions = {},\n): UdcChangesResult {\n const { feed, offered } = useFeedSubscriptions([collection], onEvent, opts);\n const subscribed = offered.length > 0;\n const status = useSyncExternalStore(\n feed ? (l: () => void) => feed.onStatus(l) : noSubscribe,\n () => (feed && subscribed ? feed.status(collection) : \"off\"),\n () => \"off\" as const,\n );\n return { status, live: status === \"live\" };\n}\n\n/** `useUdcChanges` for several collections at once, without a status (the lookup hooks). */\nexport function useUdcChangesMany(\n collections: readonly string[],\n opts: Omit<UseUdcChangesOptions, \"capabilities\"> = {},\n): void {\n useFeedSubscriptions(collections, undefined, opts);\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,IAAa,uBAAuB,cAAoC,IAAI;;AAG5E,SAAgB,mBAAyC;CACvD,OAAO,WAA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AA6B,CAAC,GACZ;CAClB,MAAM,EAAE,MAAM,YAAY,qBAAqB,CAAC,UAAU,GAAG,SAAS,IAAI;CAC1E,MAAM,aAAa,QAAQ,SAAS;CACpC,MAAM,SAAS,qBACb,QAAQ,MAAkB,KAAK,SAAS,CAAC,IAAI,mBACtC,QAAQ,aAAa,KAAK,OAAO,UAAU,IAAI,aAChD,KACR;CACA,OAAO;EAAE;EAAQ,MAAM,WAAW;CAAO;AAC3C;;AAGA,SAAgB,kBACd,aACA,OAAmD,CAAC,GAC9C;CACN,qBAAqB,aAAa,KAAA,GAAW,IAAI;AACnD"}
@@ -1,5 +1,6 @@
1
- import { createContext, useContext } from "react";
1
+ import { registerUnauthenticated } from "./unauthenticated.js";
2
2
  import { isUdcError, isUnauthenticated } from "@jsudc/core";
3
+ import { createContext, useContext } from "react";
3
4
  import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
4
5
  // src/udc/client.ts
5
6
  /** The client every hook talks to; `UdcProvider` sets it. */
@@ -32,7 +33,7 @@ function unauthenticatedNotifier(fn, quietMs) {
32
33
  }
33
34
  function createUdcQueryClient(options = {}) {
34
35
  const notify = options.onUnauthenticated ? unauthenticatedNotifier(options.onUnauthenticated, options.unauthenticatedQuietMs ?? 2e3) : void 0;
35
- return new QueryClient({
36
+ const qc = new QueryClient({
36
37
  ...notify ? {
37
38
  queryCache: new QueryCache({ onError: notify }),
38
39
  mutationCache: new MutationCache({ onError: notify })
@@ -45,6 +46,8 @@ function createUdcQueryClient(options = {}) {
45
46
  mutations: { retry: false }
46
47
  }
47
48
  });
49
+ if (notify) registerUnauthenticated(qc, notify);
50
+ return qc;
48
51
  }
49
52
  export { UdcClientContext, createUdcQueryClient, shouldRetry, useUdcClient };
50
53
 
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../src/udc/client.ts"],"sourcesContent":["import { isUdcError, isUnauthenticated, type UdcError } from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport { MutationCache, QueryCache, QueryClient } from \"@tanstack/react-query\";\nimport { createContext, useContext } from \"react\";\n\n/** The client every hook talks to; `UdcProvider` sets it. */\nexport const UdcClientContext = createContext<UdcClient | null>(null);\n\nexport function useUdcClient(): UdcClient {\n const client = useContext(UdcClientContext);\n if (!client) throw new Error(\"useUdcClient needs a <UdcProvider client={...}> above it\");\n return client;\n}\n\n/**\n * A protocol error is the server's answer, not a hiccup: asking again gives\n * the same answer. Only transport failures are retried, twice.\n */\nexport function shouldRetry(failureCount: number, error: unknown): boolean {\n return !isUdcError(error) && failureCount < 2;\n}\n\nexport interface UdcQueryClientOptions {\n /**\n * Called when a query or a mutation fails because the user is not signed in\n * (`isUnauthenticated`: an HTTP 401 in front of `/udc`, or the server's\n * in-protocol refusal) — the place to send the user to the host's login.\n * Once per burst: the failures that arrive together (every query of a page,\n * say) make one call; it fires again only after `unauthenticatedQuietMs`\n * without such a failure.\n */\n onUnauthenticated?: (error: UdcError) => void;\n /** The quiet time, in ms, that ends a burst of unauthenticated failures. Default 2000. */\n unauthenticatedQuietMs?: number;\n}\n\n/**\n * Calls `fn` on the first unauthenticated error and swallows the rest until\n * `quietMs` pass without one (each further error restarts that wait).\n */\nfunction unauthenticatedNotifier(\n fn: (error: UdcError) => void,\n quietMs: number,\n): (error: unknown) => void {\n let lastAt: number | null = null;\n return (error) => {\n if (!isUnauthenticated(error)) return;\n const now = Date.now();\n const inBurst = lastAt !== null && now - lastAt < quietMs;\n lastAt = now;\n if (!inBurst) fn(error as UdcError);\n };\n}\n\nexport function createUdcQueryClient(options: UdcQueryClientOptions = {}): QueryClient {\n const notify = options.onUnauthenticated\n ? unauthenticatedNotifier(options.onUnauthenticated, options.unauthenticatedQuietMs ?? 2000)\n : undefined;\n return new QueryClient({\n ...(notify\n ? {\n queryCache: new QueryCache({ onError: notify }),\n mutationCache: new MutationCache({ onError: notify }),\n }\n : {}),\n defaultOptions: {\n queries: { retry: shouldRetry, refetchOnWindowFocus: false },\n mutations: { retry: false },\n },\n });\n}\n"],"mappings":";;;;;AAMA,IAAa,mBAAmB,cAAgC,IAAI;AAEpE,SAAgB,eAA0B;CACxC,MAAM,SAAS,WAAW,gBAAgB;CAC1C,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,0DAA0D;CACvF,OAAO;AACT;;;;;AAMA,SAAgB,YAAY,cAAsB,OAAyB;CACzE,OAAO,CAAC,WAAW,KAAK,KAAK,eAAe;AAC9C;;;;;AAoBA,SAAS,wBACP,IACA,SAC0B;CAC1B,IAAI,SAAwB;CAC5B,QAAQ,UAAU;EAChB,IAAI,CAAC,kBAAkB,KAAK,GAAG;EAC/B,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,UAAU,WAAW,QAAQ,MAAM,SAAS;EAClD,SAAS;EACT,IAAI,CAAC,SAAS,GAAG,KAAiB;CACpC;AACF;AAEA,SAAgB,qBAAqB,UAAiC,CAAC,GAAgB;CACrF,MAAM,SAAS,QAAQ,oBACnB,wBAAwB,QAAQ,mBAAmB,QAAQ,0BAA0B,GAAI,IACzF,KAAA;CACJ,OAAO,IAAI,YAAY;EACrB,GAAI,SACA;GACE,YAAY,IAAI,WAAW,EAAE,SAAS,OAAO,CAAC;GAC9C,eAAe,IAAI,cAAc,EAAE,SAAS,OAAO,CAAC;EACtD,IACA,CAAC;EACL,gBAAgB;GACd,SAAS;IAAE,OAAO;IAAa,sBAAsB;GAAM;GAC3D,WAAW,EAAE,OAAO,MAAM;EAC5B;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/udc/client.ts"],"sourcesContent":["import { isUdcError, isUnauthenticated, type UdcError } from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport { MutationCache, QueryCache, QueryClient } from \"@tanstack/react-query\";\nimport { createContext, useContext } from \"react\";\nimport { registerUnauthenticated } from \"./unauthenticated.js\";\n\n/** The client every hook talks to; `UdcProvider` sets it. */\nexport const UdcClientContext = createContext<UdcClient | null>(null);\n\nexport function useUdcClient(): UdcClient {\n const client = useContext(UdcClientContext);\n if (!client) throw new Error(\"useUdcClient needs a <UdcProvider client={...}> above it\");\n return client;\n}\n\n/**\n * A protocol error is the server's answer, not a hiccup: asking again gives\n * the same answer. Only transport failures are retried, twice.\n */\nexport function shouldRetry(failureCount: number, error: unknown): boolean {\n return !isUdcError(error) && failureCount < 2;\n}\n\nexport interface UdcQueryClientOptions {\n /**\n * Called when a query or a mutation fails because the user is not signed in\n * (`isUnauthenticated`: an HTTP 401 in front of `/udc`, or the server's\n * in-protocol refusal) — the place to send the user to the host's login.\n * Once per burst: the failures that arrive together (every query of a page,\n * say) make one call; it fires again only after `unauthenticatedQuietMs`\n * without such a failure.\n */\n onUnauthenticated?: (error: UdcError) => void;\n /** The quiet time, in ms, that ends a burst of unauthenticated failures. Default 2000. */\n unauthenticatedQuietMs?: number;\n}\n\n/**\n * Calls `fn` on the first unauthenticated error and swallows the rest until\n * `quietMs` pass without one (each further error restarts that wait).\n */\nfunction unauthenticatedNotifier(\n fn: (error: UdcError) => void,\n quietMs: number,\n): (error: unknown) => void {\n let lastAt: number | null = null;\n return (error) => {\n if (!isUnauthenticated(error)) return;\n const now = Date.now();\n const inBurst = lastAt !== null && now - lastAt < quietMs;\n lastAt = now;\n if (!inBurst) fn(error as UdcError);\n };\n}\n\nexport function createUdcQueryClient(options: UdcQueryClientOptions = {}): QueryClient {\n const notify = options.onUnauthenticated\n ? unauthenticatedNotifier(options.onUnauthenticated, options.unauthenticatedQuietMs ?? 2000)\n : undefined;\n const qc = new QueryClient({\n ...(notify\n ? {\n queryCache: new QueryCache({ onError: notify }),\n mutationCache: new MutationCache({ onError: notify }),\n }\n : {}),\n defaultOptions: {\n queries: { retry: shouldRetry, refetchOnWindowFocus: false },\n mutations: { retry: false },\n },\n });\n // The change feed's unauthenticated error takes the same path (and the same burst).\n if (notify) registerUnauthenticated(qc, notify);\n return qc;\n}\n"],"mappings":";;;;;;AAOA,IAAa,mBAAmB,cAAgC,IAAI;AAEpE,SAAgB,eAA0B;CACxC,MAAM,SAAS,WAAW,gBAAgB;CAC1C,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,0DAA0D;CACvF,OAAO;AACT;;;;;AAMA,SAAgB,YAAY,cAAsB,OAAyB;CACzE,OAAO,CAAC,WAAW,KAAK,KAAK,eAAe;AAC9C;;;;;AAoBA,SAAS,wBACP,IACA,SAC0B;CAC1B,IAAI,SAAwB;CAC5B,QAAQ,UAAU;EAChB,IAAI,CAAC,kBAAkB,KAAK,GAAG;EAC/B,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,UAAU,WAAW,QAAQ,MAAM,SAAS;EAClD,SAAS;EACT,IAAI,CAAC,SAAS,GAAG,KAAiB;CACpC;AACF;AAEA,SAAgB,qBAAqB,UAAiC,CAAC,GAAgB;CACrF,MAAM,SAAS,QAAQ,oBACnB,wBAAwB,QAAQ,mBAAmB,QAAQ,0BAA0B,GAAI,IACzF,KAAA;CACJ,MAAM,KAAK,IAAI,YAAY;EACzB,GAAI,SACA;GACE,YAAY,IAAI,WAAW,EAAE,SAAS,OAAO,CAAC;GAC9C,eAAe,IAAI,cAAc,EAAE,SAAS,OAAO,CAAC;EACtD,IACA,CAAC;EACL,gBAAgB;GACd,SAAS;IAAE,OAAO;IAAa,sBAAsB;GAAM;GAC3D,WAAW,EAAE,OAAO,MAAM;EAC5B;CACF,CAAC;CAED,IAAI,QAAQ,wBAAwB,IAAI,MAAM;CAC9C,OAAO;AACT"}
@@ -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,6 +21,9 @@ 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
28
  source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu" | "postgres_table";
24
29
  label?: string | undefined;
@@ -41,6 +46,9 @@ 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
53
  source_kind: "postgres_jsonb" | "memory" | "filesystem" | "http_api" | "yaml_menu" | "postgres_table";
46
54
  schema: {
@@ -278,12 +286,7 @@ export declare function useUdcDescribe(collection: string, opts?: {
278
286
  icon_size: number;
279
287
  radius_field?: string | undefined;
280
288
  popup_fields?: string[] | undefined;
281
- center
282
- /**
283
- * The three schema edits. Each answers the new schema; `describe` (which
284
- * derives the columns) and the lists are refetched afterwards.
285
- */
286
- ?: [number, number] | undefined;
289
+ center?: [number, number] | undefined;
287
290
  regions?: {
288
291
  [x: string]: unknown;
289
292
  id: string;
@@ -373,6 +376,9 @@ export declare function useUdcDescribe(collection: string, opts?: {
373
376
  when?: boolean | FilterNode | undefined;
374
377
  icon?: string | undefined;
375
378
  variant?: "default" | "outline" | "destructive" | undefined;
379
+ set?: Record<string, unknown> | undefined;
380
+ action?: string | undefined;
381
+ confirm?: string | boolean | undefined;
376
382
  }[] | undefined;
377
383
  bulk_actions?: {
378
384
  [x: string]: unknown;
@@ -381,6 +387,9 @@ export declare function useUdcDescribe(collection: string, opts?: {
381
387
  when?: boolean | FilterNode | undefined;
382
388
  icon?: string | undefined;
383
389
  variant?: "default" | "outline" | "destructive" | undefined;
390
+ set?: Record<string, unknown> | undefined;
391
+ action?: string | undefined;
392
+ confirm?: string | boolean | undefined;
384
393
  }[] | undefined;
385
394
  multiselect?: boolean | undefined;
386
395
  row_actions_display?: "inline" | "menu" | undefined;
@@ -436,10 +445,22 @@ export interface UseUdcCollectionArgs {
436
445
  /** 1-based; pages mode only. */
437
446
  page?: number;
438
447
  enabled?: boolean;
439
- /** From `describe`: a source without `cursor` paging is walked by offset in infinite mode too. */
440
- capabilities?: Pick<Capabilities, "paging"> | undefined;
441
- /** 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
+ */
442
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;
443
464
  }
444
465
  export interface UdcCollectionResult {
445
466
  rows: Row[];
@@ -463,6 +484,10 @@ export declare function freshnessOf(res: Pick<ListResponse, "fetched_at" | "stal
463
484
  fetchedAt: string | null;
464
485
  stale: boolean;
465
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
+ };
466
491
  /** The `offset` a 1-based page asks for. */
467
492
  export declare function pageOffset(page: number, limit: number): number;
468
493
  /**
@@ -485,6 +510,8 @@ export interface FetchAllRowsArgs {
485
510
  pageLimit?: number;
486
511
  /** Keyset paging unless the source pages by offset only. */
487
512
  cursor: boolean;
513
+ /** Sent as `ListRequest.search` when not blank (a source that answers search). */
514
+ search?: string | undefined;
488
515
  signal?: AbortSignal;
489
516
  onProgress?: (loaded: number, total: number | null) => void;
490
517
  }
@@ -502,11 +529,16 @@ export interface UseUdcAllRowsArgs {
502
529
  sort?: SortKey[];
503
530
  /** Default 2,000. */
504
531
  max?: number;
505
- /** From `describe`: whether the source pages by cursor. */
506
- 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;
507
534
  enabled?: boolean;
508
- /** 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
+ */
509
539
  refetchInterval?: number | undefined;
540
+ /** Sent as `ListRequest.search` when not blank (`capabilities.search === "source"`). */
541
+ search?: string | undefined;
510
542
  }
511
543
  export interface UdcAllRowsResult {
512
544
  rows: Row[];
@@ -532,7 +564,6 @@ export interface UdcAllRowsResult {
532
564
  * patches and invalidations reach it like every other list.
533
565
  */
534
566
  export declare function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult;
535
- type ListCache = ListResponse | InfiniteData<ListResponse, unknown>;
536
567
  /** `data` with every row whose id is `id` passed through `patch`. */
537
568
  export declare function patchRowInList(data: ListCache | undefined, id: string, patch: (row: Row) => Row): ListCache | undefined;
538
569
  export type UdcMutateVars = Omit<ActionRequest<"mutate">, "collection">;
@@ -543,7 +574,7 @@ export type UdcMutateVars = Omit<ActionRequest<"mutate">, "collection">;
543
574
  * value that won; the error still reaches the caller. Lists are invalidated
544
575
  * once the call settles.
545
576
  */
546
- export declare function useUdcMutate(collection: string): import("@tanstack/react-query").UseMutationResult<{
577
+ export declare function useUdcMutate(collection: string): UseMutationResult<{
547
578
  row: {
548
579
  [x: string]: unknown;
549
580
  __meta: {
@@ -560,7 +591,7 @@ export declare function useUdcMutate(collection: string): import("@tanstack/reac
560
591
  * derives the columns) and the lists are refetched afterwards.
561
592
  */
562
593
  export declare function useUdcSchema(collection: string): {
563
- addField: import("@tanstack/react-query").UseMutationResult<{
594
+ addField: UseMutationResult<{
564
595
  schema: {
565
596
  field_order: string[];
566
597
  version: string;
@@ -616,7 +647,7 @@ export declare function useUdcSchema(collection: string): {
616
647
  anchor?: string | undefined;
617
648
  };
618
649
  }, "collection">, unknown>;
619
- updateField: import("@tanstack/react-query").UseMutationResult<{
650
+ updateField: UseMutationResult<{
620
651
  schema: {
621
652
  field_order: string[];
622
653
  version: string;
@@ -668,7 +699,7 @@ export declare function useUdcSchema(collection: string): {
668
699
  } | undefined;
669
700
  };
670
701
  }, "collection">, unknown>;
671
- softDeleteField: import("@tanstack/react-query").UseMutationResult<{
702
+ softDeleteField: UseMutationResult<{
672
703
  schema: {
673
704
  field_order: string[];
674
705
  version: string;
@@ -697,4 +728,46 @@ export declare function useUdcSchema(collection: string): {
697
728
  };
698
729
  }, Error, string, unknown>;
699
730
  };
700
- 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>;