@eskais/app-sdk 0.1.0 → 0.2.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 (90) hide show
  1. package/README.md +17 -11
  2. package/dist/action/action.d.ts +69 -10
  3. package/dist/action/action.js +147 -29
  4. package/dist/action/bulk.d.ts +24 -0
  5. package/dist/action/bulk.js +24 -0
  6. package/dist/core/constants.d.ts +57 -0
  7. package/dist/core/constants.js +31 -0
  8. package/dist/core/contracts.d.ts +7 -0
  9. package/dist/core/data-labels.d.ts +14 -0
  10. package/dist/core/data-labels.js +40 -0
  11. package/dist/core/errors.d.ts +11 -5
  12. package/dist/core/errors.js +52 -9
  13. package/dist/dialogs/dialogs.d.ts +75 -0
  14. package/dist/dialogs/dialogs.js +66 -0
  15. package/dist/errors/adapters.d.ts +21 -0
  16. package/dist/errors/adapters.js +81 -0
  17. package/dist/errors/define-errors.d.ts +88 -0
  18. package/dist/errors/define-errors.js +168 -0
  19. package/dist/errors/idempotency.d.ts +2 -0
  20. package/dist/errors/idempotency.js +13 -0
  21. package/dist/i18n/adapters.d.ts +53 -0
  22. package/dist/i18n/adapters.js +56 -0
  23. package/dist/i18n/format.d.ts +10 -0
  24. package/dist/i18n/format.js +273 -0
  25. package/dist/i18n/labels.d.ts +10 -0
  26. package/dist/i18n/labels.js +227 -0
  27. package/dist/i18n/locale.d.ts +73 -0
  28. package/dist/i18n/locale.js +74 -0
  29. package/dist/i18n/messages.d.ts +93 -0
  30. package/dist/i18n/messages.js +16 -0
  31. package/dist/import/import.d.ts +4 -2
  32. package/dist/import/import.js +7 -4
  33. package/dist/index.d.ts +18 -3
  34. package/dist/index.js +17 -2
  35. package/dist/navigation/nav.d.ts +14 -5
  36. package/dist/navigation/nav.js +37 -14
  37. package/dist/next/server/index.d.ts +2 -1
  38. package/dist/next/server/index.js +2 -1
  39. package/dist/next/server/page.d.ts +8 -2
  40. package/dist/next/server/page.js +14 -7
  41. package/dist/next/server/session.d.ts +13 -0
  42. package/dist/next/server/session.js +13 -0
  43. package/dist/permissions/permissions.d.ts +134 -0
  44. package/dist/permissions/permissions.js +121 -0
  45. package/dist/react/data-layer.d.ts +42 -5
  46. package/dist/react/data-layer.js +49 -4
  47. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  48. package/dist/react/hooks/use-action-dialog.js +31 -0
  49. package/dist/react/hooks/use-action.d.ts +30 -5
  50. package/dist/react/hooks/use-action.js +85 -27
  51. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  52. package/dist/react/hooks/use-bulk-action.js +24 -0
  53. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  54. package/dist/react/hooks/use-dialogs.js +20 -0
  55. package/dist/react/hooks/use-nav.js +3 -2
  56. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  57. package/dist/react/hooks/use-new-rows.js +24 -0
  58. package/dist/react/hooks/use-permissions.d.ts +13 -0
  59. package/dist/react/hooks/use-permissions.js +19 -0
  60. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  61. package/dist/react/hooks/use-reauthenticate.js +11 -0
  62. package/dist/react/hooks/use-resource.d.ts +28 -5
  63. package/dist/react/hooks/use-resource.js +63 -26
  64. package/dist/react/index.d.ts +11 -4
  65. package/dist/react/index.js +11 -4
  66. package/dist/react/keys.d.ts +9 -0
  67. package/dist/react/keys.js +4 -0
  68. package/dist/react/new-rows.d.ts +22 -0
  69. package/dist/react/new-rows.js +72 -0
  70. package/dist/refresh/new-rows.d.ts +13 -0
  71. package/dist/refresh/new-rows.js +18 -0
  72. package/dist/resource/resource-relations.d.ts +6 -3
  73. package/dist/resource/resource-relations.js +26 -13
  74. package/dist/resource/resource-schema.d.ts +1 -1
  75. package/dist/resource/resource-schema.js +1 -1
  76. package/dist/resource/resource-texts.d.ts +18 -0
  77. package/dist/resource/resource-texts.js +13 -0
  78. package/dist/resource/resource-types.d.ts +169 -30
  79. package/dist/resource/resource-words.d.ts +25 -0
  80. package/dist/resource/resource-words.js +221 -0
  81. package/dist/resource/resource.d.ts +6 -2
  82. package/dist/resource/resource.js +99 -173
  83. package/dist/services/read-only-service.d.ts +18 -0
  84. package/dist/services/read-only-service.js +25 -0
  85. package/dist/services/rest-service.d.ts +4 -1
  86. package/dist/services/rest-service.js +2 -0
  87. package/dist/view/view-types.d.ts +4 -2
  88. package/locales/en.json +193 -0
  89. package/locales/es.json +193 -0
  90. package/package.json +5 -2
@@ -2,14 +2,16 @@
2
2
  import { keepPreviousData, useQuery, useQueryClient } from "@tanstack/react-query";
3
3
  import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
4
4
  import { assumeType } from "../../core/assume.js";
5
- import { ResourceAction, ServiceErrorKind, TotalKind } from "../../core/constants.js";
5
+ import { Idempotency, Operation, ResourceAction, ServiceErrorKind, TotalKind } from "../../core/constants.js";
6
6
  import { ServiceFailure, serviceError, toServiceError } from "../../core/errors.js";
7
7
  import { isRecord } from "../../core/guards.js";
8
- import { dependentsOf } from "../../resource/resource.js";
8
+ import { dependentsOf, refreshPolicy } from "../../resource/resource.js";
9
9
  import { includeOf, resolveRelations } from "../../resource/relations.js";
10
10
  import { warnInDevelopment } from "../../navigation/shortcuts.js";
11
11
  import { useDataLayer } from "../data-layer.js";
12
12
  import { resourceCountKey, resourceDetailKey, resourceDetailWithKey, resourcePageKey } from "../keys.js";
13
+ import { heldRead, markOwnChange } from "../new-rows.js";
14
+ import { useNewRows } from "./use-new-rows.js";
13
15
  const pageMeta = { serverData: "page" };
14
16
  const resourceMeta = { serverData: "resource" };
15
17
  function totalOf(page) {
@@ -20,9 +22,23 @@ function totalOf(page) {
20
22
  return { kind: TotalKind.none };
21
23
  }
22
24
  const toError = (error) => error === null || error === undefined ? undefined : toServiceError(error);
25
+ function read(layer, signal, call) {
26
+ return layer.errors.run(call, { operation: Operation.query, signal, session: layer.session });
27
+ }
28
+ /** A refresh policy as TanStack Query's options. */
29
+ export function refreshOptions(policy) {
30
+ return {
31
+ staleTime: policy.staleTime,
32
+ refetchOnWindowFocus: policy.onFocus,
33
+ refetchOnReconnect: policy.onReconnect,
34
+ refetchInterval: policy.interval,
35
+ };
36
+ }
23
37
  const emptyFilter = {};
24
38
  export function useResourceList(resource, options = {}) {
25
- const { session } = useDataLayer();
39
+ const layer = useDataLayer();
40
+ const client = useQueryClient();
41
+ const policy = refreshPolicy(resource, options.refresh);
26
42
  const [own, setOwn] = useState(() => ({
27
43
  filter: {},
28
44
  search: "",
@@ -46,20 +62,23 @@ export function useResourceList(resource, options = {}) {
46
62
  position: { page: state.page },
47
63
  };
48
64
  }, [resource, view, state, fixed]);
65
+ const queryKey = resourcePageKey(resource, query);
49
66
  const result = useQuery({
50
- queryKey: resourcePageKey(resource, query),
51
- queryFn: ({ signal }) => resource.service.list(query, { signal, session }),
67
+ queryKey,
68
+ queryFn: ({ signal }) => heldRead(client, resource, queryKey, policy.newRows, () => read(layer, signal, (context) => resource.service.list(query, context))),
69
+ retry: false,
52
70
  enabled: options.enabled !== false,
53
- staleTime: resource.staleTime,
71
+ ...refreshOptions(policy),
54
72
  placeholderData: keepPreviousData,
55
73
  meta: pageMeta,
56
74
  });
75
+ const held = useNewRows(queryKey);
57
76
  const setState = useCallback((patch) => {
58
77
  if (view)
59
78
  view.setState(patch);
60
79
  else
61
80
  setOwn((previous) => ({ ...previous, ...patch }));
62
- }, [view]);
81
+ }, [view, setOwn]);
63
82
  const { refetch } = result;
64
83
  return {
65
84
  rows: result.data?.items ?? [],
@@ -70,6 +89,8 @@ export function useResourceList(resource, options = {}) {
70
89
  isFetching: result.isFetching,
71
90
  error: toError(result.error),
72
91
  refetch: () => void refetch(),
92
+ newRows: held.count,
93
+ showNewRows: held.apply,
73
94
  };
74
95
  }
75
96
  /**
@@ -77,8 +98,10 @@ export function useResourceList(resource, options = {}) {
77
98
  * read in one request per relation, through the cache, and the plain record stays cached on its own.
78
99
  */
79
100
  export function useResource(resource, id, options = {}) {
80
- const { session } = useDataLayer();
101
+ const layer = useDataLayer();
102
+ const { session } = layer;
81
103
  const client = useQueryClient();
104
+ const { onFocus, onReconnect } = resource.refresh;
82
105
  const key = id === undefined ? "" : resource.idKey(id);
83
106
  const include = includeOf(resource.relations, options.paths ?? []);
84
107
  const readPlain = (signal) => client.fetchQuery({
@@ -86,8 +109,9 @@ export function useResource(resource, id, options = {}) {
86
109
  queryFn: () => {
87
110
  if (id === undefined)
88
111
  return Promise.reject(new TypeError("No id."));
89
- return resource.service.get(id, { signal, session });
112
+ return read(layer, signal, (context) => resource.service.get(id, context));
90
113
  },
114
+ retry: false,
91
115
  staleTime: resource.staleTime,
92
116
  });
93
117
  const result = useQuery({
@@ -96,7 +120,7 @@ export function useResource(resource, id, options = {}) {
96
120
  if (id === undefined)
97
121
  return Promise.reject(new TypeError("No id."));
98
122
  if (include.length === 0)
99
- return resource.service.get(id, { signal, session });
123
+ return read(layer, signal, (context) => resource.service.get(id, context));
100
124
  const [row] = await resolveRelations(resource, [await readPlain(signal)], options.paths ?? [], {
101
125
  signal,
102
126
  session,
@@ -111,7 +135,9 @@ export function useResource(resource, id, options = {}) {
111
135
  },
112
136
  enabled: id !== undefined,
113
137
  staleTime: resource.staleTime,
114
- retry: (failures, error) => toServiceError(error).retryable && failures < 2,
138
+ refetchOnWindowFocus: onFocus,
139
+ refetchOnReconnect: onReconnect,
140
+ retry: false,
115
141
  meta: resourceMeta,
116
142
  });
117
143
  const row = result.data;
@@ -130,6 +156,9 @@ export function useResource(resource, id, options = {}) {
130
156
  */
131
157
  export function invalidateResource(client, resource) {
132
158
  const dependents = resource.key === undefined ? [] : dependentsOf({ key: resource.key });
159
+ for (const changed of [resource.key, ...dependents.map((entry) => entry.resource.key)])
160
+ if (changed !== undefined)
161
+ markOwnChange(client, changed);
133
162
  return Promise.all([
134
163
  client.invalidateQueries({ queryKey: resource.queryKey }),
135
164
  ...dependents.map((entry) => client.invalidateQueries({ queryKey: entry.resource.queryKey })),
@@ -137,6 +166,7 @@ export function invalidateResource(client, resource) {
137
166
  }
138
167
  export function writeRow(client, resource, row) {
139
168
  const id = resource.idKey(resource.idOf(row));
169
+ markOwnChange(client, resource.key);
140
170
  const merged = (old) => (isRecord(old) && isRecord(row) ? { ...old, ...row } : row);
141
171
  client.setQueryData(resourceDetailKey(resource, id), row);
142
172
  client.setQueriesData({ queryKey: [...resourceDetailKey(resource, id), "with"] }, merged);
@@ -170,47 +200,54 @@ function withRelated(item, relation, id, row) {
170
200
  return sameId(shown) ? { ...item, [relation]: row } : item;
171
201
  }
172
202
  export function useResourceMutations(resource) {
173
- const { session } = useDataLayer();
203
+ const { session, errors } = useDataLayer();
174
204
  const client = useQueryClient();
175
205
  return useMemo(() => {
176
- const context = () => ({ signal: new AbortController().signal, session });
206
+ const write = (action, options, call) => errors.run(call, {
207
+ operation: Operation.mutation,
208
+ session,
209
+ signal: options.signal,
210
+ idempotency: resource.options.idempotency?.[action] ?? Idempotency.none,
211
+ idempotencyKey: options.idempotencyKey,
212
+ });
177
213
  return {
178
- async create(input) {
179
- const row = await resource.service.create(input, context());
214
+ async create(input, options = {}) {
215
+ const row = await write(ResourceAction.create, options, (context) => resource.service.create(input, context));
180
216
  void invalidateResource(client, resource);
181
217
  return row;
182
218
  },
183
219
  async update(id, patch, options = {}) {
184
- const row = await resource.service.update(id, patch, { ...context(), version: options.version });
220
+ const row = await write(ResourceAction.update, options, (context) => resource.service.update(id, patch, { ...context, version: options.version }));
185
221
  writeRow(client, resource, row);
186
222
  void invalidateResource(client, resource);
187
223
  return row;
188
224
  },
189
- async remove(target) {
190
- await resource.service.remove(target, context());
225
+ async remove(target, options = {}) {
226
+ await write(ResourceAction.remove, options, (context) => resource.service.remove(target, context));
191
227
  void invalidateResource(client, resource);
192
228
  },
193
- async restore(target) {
229
+ async restore(target, options = {}) {
194
230
  const restore = resource.service.restore;
195
231
  if (!restore)
196
232
  throw new ServiceFailure(serviceError(ServiceErrorKind.forbidden, "This resource has no restore."));
197
- await restore.call(resource.service, target, context());
233
+ await write(ResourceAction.restore, options, (context) => restore.call(resource.service, target, context));
198
234
  void invalidateResource(client, resource);
199
235
  },
200
236
  };
201
- }, [client, resource, session]);
237
+ }, [client, resource, session, errors]);
202
238
  }
203
239
  export function useResourceCount(resource, filter, options = {}) {
204
- const { session } = useDataLayer();
240
+ const layer = useDataLayer();
205
241
  const result = useQuery({
206
242
  queryKey: resourceCountKey(resource, filter),
207
- queryFn: async ({ signal }) => {
243
+ queryFn: ({ signal }) => read(layer, signal, async (context) => {
208
244
  const full = resource.filterOf(filter);
209
245
  if (resource.service.count)
210
- return resource.service.count(full, { signal, session });
211
- const page = await resource.service.list({ filter: full, sort: [], size: 1, position: { page: 1 } }, { signal, session });
246
+ return resource.service.count(full, context);
247
+ const page = await resource.service.list({ filter: full, sort: [], size: 1, position: { page: 1 } }, context);
212
248
  return page.total ?? page.items.length;
213
- },
249
+ }),
250
+ retry: false,
214
251
  staleTime: resource.staleTime,
215
252
  ...(options.refetchInterval === undefined ? {} : { refetchInterval: options.refetchInterval }),
216
253
  });
@@ -1,8 +1,15 @@
1
- export { DataLayer, useDataLayer, useLabels, useSession, type DataLayerProps, type DataLayerValue, } from "./data-layer.js";
2
- export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, type ResourceTableQuery, } from "./keys.js";
3
- export { invalidateResource, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, type ResourceListOptions, type ResourceListState, type ResourceMutations, type ResourceState, type TotalInfo, } from "./hooks/use-resource.js";
4
- export { useAction, type ActionState } from "./hooks/use-action.js";
1
+ export { DataLayer, useDataLayer, useLabels, useLocalized, useResourceLayer, useSession, type DataLayerProps, type DataLayerValue, } from "./data-layer.js";
2
+ export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, sourcePageKey, type ResourceTableQuery, } from "./keys.js";
3
+ export { invalidateResource, refreshOptions, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, type ResourceListOptions, type ResourceListState, type ResourceMutations, type ResourceState, type TotalInfo, type WriteOptions, } from "./hooks/use-resource.js";
4
+ export { invalidateAfter, useAction, useErrorText, type ActionState, type ActionSubmitOptions, } from "./hooks/use-action.js";
5
+ export { useReauthenticate } from "./hooks/use-reauthenticate.js";
6
+ export { useActionDialog, type ActionDialogOptions, type ActionDialogState } from "./hooks/use-action-dialog.js";
7
+ export { useBulkAction, type UseBulkActionOptions, type BulkActionState, type BulkSelection, } from "./hooks/use-bulk-action.js";
5
8
  export { useView } from "./hooks/use-view.js";
6
9
  export { useDocumentTitle, useNav, useRoutedNav, type NavState } from "./hooks/use-nav.js";
7
10
  export { useDraft } from "./hooks/use-draft.js";
8
11
  export { useBetterAuthSession, type BetterAuthSessionState } from "./hooks/use-better-auth.js";
12
+ export { usePermission, usePermissionSession } from "./hooks/use-permissions.js";
13
+ export { useDialogHost, useDialogs, type DialogHost } from "./hooks/use-dialogs.js";
14
+ export { useHeldSource, useNewRows, type NewRowsState } from "./hooks/use-new-rows.js";
15
+ export { applyNewRows, heldRead, markOwnChange, newRowsOf } from "./new-rows.js";
@@ -1,8 +1,15 @@
1
- export { DataLayer, useDataLayer, useLabels, useSession, } from "./data-layer.js";
2
- export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, } from "./keys.js";
3
- export { invalidateResource, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, } from "./hooks/use-resource.js";
4
- export { useAction } from "./hooks/use-action.js";
1
+ export { DataLayer, useDataLayer, useLabels, useLocalized, useResourceLayer, useSession, } from "./data-layer.js";
2
+ export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, sourcePageKey, } from "./keys.js";
3
+ export { invalidateResource, refreshOptions, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, } from "./hooks/use-resource.js";
4
+ export { invalidateAfter, useAction, useErrorText, } from "./hooks/use-action.js";
5
+ export { useReauthenticate } from "./hooks/use-reauthenticate.js";
6
+ export { useActionDialog } from "./hooks/use-action-dialog.js";
7
+ export { useBulkAction, } from "./hooks/use-bulk-action.js";
5
8
  export { useView } from "./hooks/use-view.js";
6
9
  export { useDocumentTitle, useNav, useRoutedNav } from "./hooks/use-nav.js";
7
10
  export { useDraft } from "./hooks/use-draft.js";
8
11
  export { useBetterAuthSession } from "./hooks/use-better-auth.js";
12
+ export { usePermission, usePermissionSession } from "./hooks/use-permissions.js";
13
+ export { useDialogHost, useDialogs } from "./hooks/use-dialogs.js";
14
+ export { useHeldSource, useNewRows } from "./hooks/use-new-rows.js";
15
+ export { applyNewRows, heldRead, markOwnChange, newRowsOf } from "./new-rows.js";
@@ -6,6 +6,15 @@ import type { View } from "../view/view.js";
6
6
  export declare function resourcePageKey<F>(resource: {
7
7
  queryKey: readonly unknown[];
8
8
  }, query: Query<F>): QueryKey;
9
+ /** The key a `PageSource` page is cached under, as `server-data`'s `pageKey` writes it. */
10
+ export declare function sourcePageKey(source: {
11
+ key: readonly unknown[];
12
+ }, request: {
13
+ filter: unknown;
14
+ sort: unknown;
15
+ position: unknown;
16
+ size: number;
17
+ }): QueryKey;
9
18
  export declare function resourceDetailKey(resource: {
10
19
  queryKey: readonly unknown[];
11
20
  }, id: string): QueryKey;
@@ -6,6 +6,10 @@ export function resourcePageKey(resource, query) {
6
6
  const filter = { ...query.filter, ...(query.search === undefined ? {} : { [searchKey]: query.search }) };
7
7
  return [...resource.queryKey, "page", filter, query.sort, query.position, query.size];
8
8
  }
9
+ /** The key a `PageSource` page is cached under, as `server-data`'s `pageKey` writes it. */
10
+ export function sourcePageKey(source, request) {
11
+ return [...source.key, "page", request.filter, request.sort, request.position, request.size];
12
+ }
9
13
  export function resourceDetailKey(resource, id) {
10
14
  return [...resource.queryKey, "detail", id];
11
15
  }
@@ -0,0 +1,22 @@
1
+ import { type QueryClient, type QueryKey } from "@tanstack/react-query";
2
+ import { NewRows } from "../core/constants.js";
3
+ import type { Page } from "../core/contracts.js";
4
+ /** This browser changed the resource: its next reloads are its own doing and show every row at once. */
5
+ export declare function markOwnChange(client: QueryClient, resource: string): void;
6
+ type HeldResource<T, Id> = {
7
+ readonly key: string;
8
+ idOf(row: T): Id;
9
+ idKey(id: Id): string;
10
+ };
11
+ /**
12
+ * Reads a page for a query that may already be on screen. A reload of a shown page (focus, reconnect, a poll, a
13
+ * remount) keeps its rows in place with their new values and holds rows it didn't show for `applyNewRows`; a first
14
+ * read, a reload after this browser's own change and `NewRows.show` take the page as read.
15
+ */
16
+ export declare function heldRead<T, Id>(client: QueryClient, resource: HeldResource<T, Id>, queryKey: QueryKey, newRows: NewRows, read: () => Promise<Page<T>>): Promise<Page<T>>;
17
+ /** How many new rows a reload held back for the query. */
18
+ export declare function newRowsOf(client: QueryClient, queryKey: QueryKey): number;
19
+ /** Shows the rows held back for the query: the page as the reload read it. */
20
+ export declare function applyNewRows(client: QueryClient, queryKey: QueryKey): boolean;
21
+ export declare function subscribeNewRows(client: QueryClient, listener: () => void): () => void;
22
+ export {};
@@ -0,0 +1,72 @@
1
+ import { hashKey } from "@tanstack/react-query";
2
+ import { NewRows } from "../core/constants.js";
3
+ import { holdNewRows } from "../refresh/new-rows.js";
4
+ const states = new WeakMap();
5
+ function stateOf(client) {
6
+ const known = states.get(client);
7
+ if (known)
8
+ return known;
9
+ const state = { held: new Map(), listeners: new Set(), changed: new Map() };
10
+ states.set(client, state);
11
+ return state;
12
+ }
13
+ function notify(state) {
14
+ for (const listener of state.listeners)
15
+ listener();
16
+ }
17
+ function forget(state, hash) {
18
+ if (state.held.delete(hash))
19
+ notify(state);
20
+ }
21
+ /** This browser changed the resource: its next reloads are its own doing and show every row at once. */
22
+ export function markOwnChange(client, resource) {
23
+ stateOf(client).changed.set(resource, Date.now());
24
+ }
25
+ /**
26
+ * Reads a page for a query that may already be on screen. A reload of a shown page (focus, reconnect, a poll, a
27
+ * remount) keeps its rows in place with their new values and holds rows it didn't show for `applyNewRows`; a first
28
+ * read, a reload after this browser's own change and `NewRows.show` take the page as read.
29
+ */
30
+ export async function heldRead(client, resource, queryKey, newRows, read) {
31
+ const fresh = await read();
32
+ const state = stateOf(client);
33
+ const hash = hashKey(queryKey);
34
+ const shown = client.getQueryData(queryKey);
35
+ const updatedAt = client.getQueryState(queryKey)?.dataUpdatedAt ?? 0;
36
+ const ownChange = state.changed.get(resource.key) ?? Number.NEGATIVE_INFINITY;
37
+ if (newRows === NewRows.show || shown === undefined || !Array.isArray(shown.items) || ownChange >= updatedAt) {
38
+ forget(state, hash);
39
+ return fresh;
40
+ }
41
+ const idOf = (row) => resource.idKey(resource.idOf(row));
42
+ const held = holdNewRows(shown, fresh, idOf);
43
+ if (held.added.length === 0) {
44
+ forget(state, hash);
45
+ return held.page;
46
+ }
47
+ state.held.set(hash, { key: queryKey, fresh, count: held.added.length });
48
+ notify(state);
49
+ return held.page;
50
+ }
51
+ /** How many new rows a reload held back for the query. */
52
+ export function newRowsOf(client, queryKey) {
53
+ return stateOf(client).held.get(hashKey(queryKey))?.count ?? 0;
54
+ }
55
+ /** Shows the rows held back for the query: the page as the reload read it. */
56
+ export function applyNewRows(client, queryKey) {
57
+ const state = stateOf(client);
58
+ const hash = hashKey(queryKey);
59
+ const held = state.held.get(hash);
60
+ if (!held)
61
+ return false;
62
+ client.setQueryData(held.key, held.fresh);
63
+ forget(state, hash);
64
+ return true;
65
+ }
66
+ export function subscribeNewRows(client, listener) {
67
+ const { listeners } = stateOf(client);
68
+ listeners.add(listener);
69
+ return () => {
70
+ listeners.delete(listener);
71
+ };
72
+ }
@@ -0,0 +1,13 @@
1
+ import type { Page } from "../core/contracts.js";
2
+ export type HeldPage<T> = {
3
+ /** What the list keeps showing: its rows in their order, each as the reload read it. */
4
+ page: Page<T>;
5
+ /** The rows the reload found that weren't shown, held back. */
6
+ added: readonly T[];
7
+ };
8
+ /**
9
+ * Merges a background reload into the page on screen without moving it: shown rows keep their place and take the
10
+ * reload's values, rows that are gone leave, and rows that are new wait in `added`. A row the reload no longer has
11
+ * stays while new rows are held, since they pushed it to the next page rather than deleting it.
12
+ */
13
+ export declare function holdNewRows<T>(shown: Page<T>, fresh: Page<T>, idOf: (row: T) => string): HeldPage<T>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Merges a background reload into the page on screen without moving it: shown rows keep their place and take the
3
+ * reload's values, rows that are gone leave, and rows that are new wait in `added`. A row the reload no longer has
4
+ * stays while new rows are held, since they pushed it to the next page rather than deleting it.
5
+ */
6
+ export function holdNewRows(shown, fresh, idOf) {
7
+ const freshById = new Map(fresh.items.map((row) => [idOf(row), row]));
8
+ const shownIds = new Set(shown.items.map(idOf));
9
+ const added = fresh.items.filter((row) => !shownIds.has(idOf(row)));
10
+ const items = shown.items.flatMap((row) => {
11
+ const latest = freshById.get(idOf(row));
12
+ if (latest !== undefined)
13
+ return [latest];
14
+ return added.length > 0 ? [row] : [];
15
+ });
16
+ const total = fresh.total === undefined ? shown.total : fresh.total - added.length;
17
+ return { page: { ...fresh, items, ...(total === undefined ? {} : { total }) }, added };
18
+ }
@@ -2,6 +2,8 @@ import { type Relation, type Relations } from "./relations.js";
2
2
  import type { FieldDef, FieldGroup, ResolvedField } from "./resource-types.js";
3
3
  import { type Introspect, type SchemaProperty } from "./schema.js";
4
4
  import type { AnyResource, ResolvedRelation } from "./resource-types.js";
5
+ import { type ResourceTexts } from "./resource-texts.js";
6
+ import type { Text } from "../i18n/locale.js";
5
7
  export declare const defined: Set<AnyResource>;
6
8
  /**
7
9
  * The resources whose rows show `resource`'s records through a `belongsTo` or `manyToMany`, with the relation's
@@ -18,8 +20,9 @@ type RelationToolsContext = {
18
20
  relations: Relations;
19
21
  properties: () => readonly SchemaProperty[];
20
22
  introspect: Introspect | undefined;
23
+ texts: ResourceTexts;
21
24
  };
22
- export declare function relationTools<T>({ relations, properties, introspect }: RelationToolsContext): {
25
+ export declare function relationTools<T>({ relations, properties, introspect, texts }: RelationToolsContext): {
23
26
  relationAt: (key: string) => {
24
27
  relation: ResolvedRelation;
25
28
  rest?: string;
@@ -38,7 +41,7 @@ export declare function valueLabelsIn(options: {
38
41
  fields?: readonly (FieldDef<never> | FieldGroup<never>)[];
39
42
  columns?: readonly {
40
43
  key: string;
41
- valueLabels?: Readonly<Record<string, string>>;
44
+ valueLabels?: Readonly<Record<string, Text>>;
42
45
  }[];
43
- }, key: string): Readonly<Record<string, string>> | undefined;
46
+ }, key: string): Readonly<Record<string, Text>> | undefined;
44
47
  export {};
@@ -4,6 +4,7 @@ import { isFunction } from "../core/guards.js";
4
4
  import { keyRelation } from "./relations.js";
5
5
  import { columnKindOf, optionsOfEnum, propertyAt, schemaFields } from "./resource-schema.js";
6
6
  import { isListSchema } from "./schema.js";
7
+ import { resourceTexts } from "./resource-texts.js";
7
8
  export const defined = new Set();
8
9
  /**
9
10
  * The resources whose rows show `resource`'s records through a `belongsTo` or `manyToMany`, with the relation's
@@ -43,8 +44,9 @@ export function relationOf(name, relation) {
43
44
  }
44
45
  const always = () => true;
45
46
  const never = () => false;
46
- export function relationTools({ relations, properties, introspect }) {
47
+ export function relationTools({ relations, properties, introspect, texts }) {
47
48
  const options = { introspect };
49
+ const ownLabel = (field) => texts.text(field.label) ?? texts.field(field.key);
48
50
  function relationAt(key) {
49
51
  const [head = "", ...rest] = key.split(".");
50
52
  const named = relations[head];
@@ -58,9 +60,15 @@ export function relationTools({ relations, properties, introspect }) {
58
60
  const property = propertyAt(properties(), field.key);
59
61
  const readOnly = field.readOnly;
60
62
  const hidden = field.hidden;
63
+ const description = texts.text(field.description) ?? texts.own(`descriptions.${field.key}`);
64
+ const placeholder = texts.text(field.placeholder);
65
+ const groupLabel = group
66
+ ? (texts.text(group.label) ?? texts.own(`groups.${group.group}`) ?? group.group)
67
+ : undefined;
68
+ const groupDescription = texts.text(group?.description);
61
69
  return {
62
70
  key: field.key,
63
- label: field.label ?? property?.title ?? field.key,
71
+ label: ownLabel(field) ?? property?.title ?? field.key,
64
72
  kind: FieldKind.text,
65
73
  required: property?.required ?? false,
66
74
  multiple: false,
@@ -68,21 +76,23 @@ export function relationTools({ relations, properties, introspect }) {
68
76
  hidden: isFunction(hidden) ? hidden : hidden === true ? always : never,
69
77
  colSpan: field.colSpan ?? 1,
70
78
  ...(property?.type === undefined ? {} : { valueType: property.type }),
71
- ...(field.description === undefined ? {} : { description: field.description }),
72
- ...(field.placeholder === undefined ? {} : { placeholder: field.placeholder }),
73
- ...(group
74
- ? { group: group.group, ...(group.description === undefined ? {} : { groupDescription: group.description }) }
75
- : {}),
79
+ ...(description === undefined ? {} : { description }),
80
+ ...(placeholder === undefined ? {} : { placeholder }),
81
+ ...(groupLabel === undefined
82
+ ? {}
83
+ : { group: groupLabel, ...(groupDescription === undefined ? {} : { groupDescription }) }),
76
84
  };
77
85
  }
78
86
  function relationField(field, group) {
79
87
  const named = relations[field.key];
80
88
  if (named?.kind === RelationKind.embeds) {
81
- const children = schemaFields(named.schema, options.introspect);
89
+ const children = schemaFields(named.schema, options.introspect).map((child) => ({
90
+ ...child,
91
+ label: texts.field(`${field.key}.${child.key}`) ?? child.label,
92
+ }));
82
93
  const list = isListSchema(named.schema);
83
94
  return {
84
95
  ...baseField(field, group),
85
- label: field.label ?? propertyAt(properties(), field.key)?.title ?? field.key,
86
96
  kind: list ? FieldKind.rows : FieldKind.object,
87
97
  multiple: list,
88
98
  fields: children,
@@ -92,7 +102,7 @@ export function relationTools({ relations, properties, introspect }) {
92
102
  if (!reached || reached.rest !== undefined)
93
103
  return undefined;
94
104
  const { relation } = reached;
95
- const target = relation.target();
105
+ const target = texts.related(relation.target());
96
106
  if (relation.kind === RelationKind.hasMany) {
97
107
  const childKeys = new Set(field.fields?.map((child) => child.key));
98
108
  const children = target
@@ -100,7 +110,7 @@ export function relationTools({ relations, properties, introspect }) {
100
110
  .filter((child) => child.key !== relation.key && (childKeys.size === 0 || childKeys.has(child.key)));
101
111
  return {
102
112
  ...baseField(field, group),
103
- label: field.label ?? target.label(2),
113
+ label: ownLabel(field) ?? target.label(2),
104
114
  kind: FieldKind.rows,
105
115
  multiple: true,
106
116
  relation,
@@ -110,7 +120,8 @@ export function relationTools({ relations, properties, introspect }) {
110
120
  const declared = named?.kind === RelationKind.belongsTo ? named.create : undefined;
111
121
  return {
112
122
  ...baseField({ ...field, key: relation.key }, group),
113
- label: field.label ??
123
+ label: ownLabel(field) ??
124
+ texts.field(relation.key) ??
114
125
  propertyAt(properties(), relation.key)?.title ??
115
126
  target.label(relation.kind === RelationKind.manyToMany ? 2 : 1),
116
127
  kind: FieldKind.resource,
@@ -126,10 +137,12 @@ export function relationTools({ relations, properties, introspect }) {
126
137
  export function inheritedColumn(related, rest) {
127
138
  const declared = rest === undefined ? undefined : related?.options.columns?.find((entry) => entry.key === rest);
128
139
  const property = rest === undefined ? undefined : propertyAt(related?.properties() ?? [], rest);
140
+ const labels = related && rest !== undefined ? valueLabelsIn(related.options, rest) : undefined;
141
+ const labelOf = related && rest !== undefined ? resourceTexts(related.key, related.locale).valueLabel(rest, labels) : undefined;
129
142
  return {
130
143
  tones: declared?.tones,
131
144
  align: declared?.align,
132
- options: optionsOfEnum(property, declared?.valueLabels),
145
+ options: optionsOfEnum(property, labelOf),
133
146
  kind: (toned) => declared?.as ?? (property ? columnKindOf(property, toned) : undefined),
134
147
  };
135
148
  }
@@ -1,7 +1,7 @@
1
1
  import { ColumnKind, FieldKind } from "../core/constants.js";
2
2
  import type { FieldDef, FieldGroup, Option, ResolvedField } from "./resource-types.js";
3
3
  import { type Introspect, type SchemaProperty } from "./schema.js";
4
- export declare const optionsOfEnum: (property: SchemaProperty | undefined, labels?: Readonly<Record<string, string>>) => Option[] | undefined;
4
+ export declare const optionsOfEnum: (property: SchemaProperty | undefined, labelOf?: (value: string) => string | undefined) => Option[] | undefined;
5
5
  export declare function columnKindOf(property: SchemaProperty, tones: boolean): ColumnKind;
6
6
  export declare function fieldKindOf(property: SchemaProperty | undefined): FieldKind;
7
7
  export declare function propertyAt(properties: readonly SchemaProperty[], path: string): SchemaProperty | undefined;
@@ -1,6 +1,6 @@
1
1
  import { ColumnKind, FieldKind, JsonFormat, JsonType } from "../core/constants.js";
2
2
  import { zodIntrospect } from "./schema.js";
3
- export const optionsOfEnum = (property, labels) => property?.enum?.map((value) => ({ value, label: labels?.[value] ?? value }));
3
+ export const optionsOfEnum = (property, labelOf) => property?.enum?.map((value) => ({ value, label: labelOf?.(value) ?? value }));
4
4
  export function columnKindOf(property, tones) {
5
5
  if (property.enum)
6
6
  return tones ? ColumnKind.status : ColumnKind.badge;
@@ -0,0 +1,18 @@
1
+ import { type Locale, type Text } from "../i18n/locale.js";
2
+ import type { AnyResource } from "./resource-types.js";
3
+ /** How a resource's definition turns into text in one locale: its own strings first, then `resources.<key>.…`. */
4
+ export type ResourceTexts = {
5
+ readonly locale: Locale | undefined;
6
+ text(value: Text | undefined): string | undefined;
7
+ /** `resources.<key>.<path>` in the locale, when it has it. */
8
+ own(path: string): string | undefined;
9
+ /**
10
+ * A field's label: `resources.<key>.fields.<path>`, or its `label` when the path holds more (a subdocument's
11
+ * fields, a relation's): `"shipping": { "label": "Envío", "city": "Ciudad" }`.
12
+ */
13
+ field(path: string): string | undefined;
14
+ related(resource: AnyResource): AnyResource;
15
+ /** A value's label: the definition's, then `resources.<key>.values.<field>.<value>`. */
16
+ valueLabel(field: string, labels: Readonly<Record<string, Text>> | undefined): (value: string) => string | undefined;
17
+ };
18
+ export declare function resourceTexts(key: string, locale: Locale | undefined): ResourceTexts;
@@ -0,0 +1,13 @@
1
+ import { lookup, resolveText } from "../i18n/locale.js";
2
+ export function resourceTexts(key, locale) {
3
+ const own = (path) => lookup(locale, `resources.${key}.${path}`);
4
+ const text = (value) => resolveText(value, locale);
5
+ return {
6
+ locale,
7
+ text,
8
+ own,
9
+ field: (path) => own(`fields.${path}`) ?? own(`fields.${path}.label`),
10
+ related: (resource) => resource.in(locale),
11
+ valueLabel: (field, labels) => (value) => text(labels?.[value]) ?? own(`values.${field}.${value}`),
12
+ };
13
+ }