@oaiz/app-kit 0.0.0-stage → 0.1.4128

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/THIRD_PARTY_NOTICES.md +76 -0
  4. package/package.json +139 -4
  5. package/registry.json +1847 -0
  6. package/src/components/activity-timeline.tsx +227 -0
  7. package/src/components/app-shell.tsx +622 -0
  8. package/src/components/bar-list.tsx +47 -0
  9. package/src/components/board.tsx +700 -0
  10. package/src/components/calendar-view.tsx +1388 -0
  11. package/src/components/card-grid.tsx +462 -0
  12. package/src/components/charts.tsx +701 -0
  13. package/src/components/chat-markdown.tsx +230 -0
  14. package/src/components/chat-panel.tsx +760 -0
  15. package/src/components/code-editor.tsx +276 -0
  16. package/src/components/collection-controls.tsx +226 -0
  17. package/src/components/command-palette.tsx +403 -0
  18. package/src/components/confirm-action.tsx +123 -0
  19. package/src/components/data-table.tsx +821 -0
  20. package/src/components/date-input.tsx +429 -0
  21. package/src/components/empty-state.tsx +31 -0
  22. package/src/components/error-state.tsx +37 -0
  23. package/src/components/file-upload.tsx +595 -0
  24. package/src/components/filter-bar.tsx +415 -0
  25. package/src/components/grouped-picker.tsx +250 -0
  26. package/src/components/line-items.tsx +601 -0
  27. package/src/components/list-view.tsx +491 -0
  28. package/src/components/metrics.tsx +53 -0
  29. package/src/components/page-header.tsx +33 -0
  30. package/src/components/property-picker.tsx +546 -0
  31. package/src/components/record-detail.tsx +416 -0
  32. package/src/components/record-form.tsx +295 -0
  33. package/src/components/record-name.tsx +85 -0
  34. package/src/components/save-bar.tsx +142 -0
  35. package/src/components/sign-in.tsx +179 -0
  36. package/src/components/split-view.tsx +128 -0
  37. package/src/components/status-dot.tsx +56 -0
  38. package/src/components/stepper.tsx +153 -0
  39. package/src/components/text-diff-model.ts +111 -0
  40. package/src/components/text-diff.tsx +98 -0
  41. package/src/components/time-zone-picker.tsx +69 -0
  42. package/src/components/ui/accordion.tsx +138 -0
  43. package/src/components/ui/alert-dialog.tsx +67 -0
  44. package/src/components/ui/alert.tsx +65 -0
  45. package/src/components/ui/avatar-group.tsx +119 -0
  46. package/src/components/ui/avatar.tsx +55 -0
  47. package/src/components/ui/badge.tsx +59 -0
  48. package/src/components/ui/bottom-navigation.tsx +102 -0
  49. package/src/components/ui/breadcrumb.tsx +117 -0
  50. package/src/components/ui/button.tsx +71 -0
  51. package/src/components/ui/card.tsx +95 -0
  52. package/src/components/ui/checkbox.tsx +31 -0
  53. package/src/components/ui/collapsible.tsx +27 -0
  54. package/src/components/ui/context-menu.tsx +270 -0
  55. package/src/components/ui/count-up.tsx +136 -0
  56. package/src/components/ui/detail-disclosure-section.tsx +109 -0
  57. package/src/components/ui/dialog.tsx +157 -0
  58. package/src/components/ui/dropdown-menu.tsx +273 -0
  59. package/src/components/ui/form-field.tsx +155 -0
  60. package/src/components/ui/heading.tsx +126 -0
  61. package/src/components/ui/hover-card.tsx +45 -0
  62. package/src/components/ui/input.tsx +50 -0
  63. package/src/components/ui/label.tsx +30 -0
  64. package/src/components/ui/orb-spinner.tsx +238 -0
  65. package/src/components/ui/popover.tsx +59 -0
  66. package/src/components/ui/progress-ring.tsx +125 -0
  67. package/src/components/ui/progress.tsx +38 -0
  68. package/src/components/ui/radio-group.tsx +124 -0
  69. package/src/components/ui/resizable.tsx +48 -0
  70. package/src/components/ui/scroll-fade.tsx +98 -0
  71. package/src/components/ui/segmented-control.tsx +70 -0
  72. package/src/components/ui/select.tsx +230 -0
  73. package/src/components/ui/separator.tsx +29 -0
  74. package/src/components/ui/sheet.tsx +170 -0
  75. package/src/components/ui/shimmer-text.tsx +87 -0
  76. package/src/components/ui/shortcut.tsx +39 -0
  77. package/src/components/ui/skeleton.tsx +15 -0
  78. package/src/components/ui/slider.tsx +48 -0
  79. package/src/components/ui/switch.tsx +44 -0
  80. package/src/components/ui/table.tsx +119 -0
  81. package/src/components/ui/tabs.tsx +80 -0
  82. package/src/components/ui/text.tsx +93 -0
  83. package/src/components/ui/textarea.tsx +51 -0
  84. package/src/components/ui/toast.tsx +141 -0
  85. package/src/components/ui/toaster.tsx +40 -0
  86. package/src/components/ui/tooltip.tsx +38 -0
  87. package/src/components/ui/top-banner.tsx +108 -0
  88. package/src/components/ui/tree-view.tsx +215 -0
  89. package/src/components/ui/use-toast.tsx +184 -0
  90. package/src/components/ui/voice-orb.tsx +252 -0
  91. package/src/hooks/oaiz-chat.tsx +530 -0
  92. package/src/hooks/oaiz-data.tsx +617 -0
  93. package/src/hooks/oaiz-session.tsx +63 -0
  94. package/src/hooks/use-arrivals.ts +19 -0
  95. package/src/hooks/use-breakpoint.ts +100 -0
  96. package/src/hooks/use-media-query.ts +36 -0
  97. package/src/hooks/use-theme.ts +67 -0
  98. package/src/hooks/use-url-state.ts +77 -0
  99. package/src/lib/breakpoints.ts +81 -0
  100. package/src/lib/csp-nonce.ts +15 -0
  101. package/src/lib/format.ts +291 -0
  102. package/src/lib/speech-level.ts +118 -0
  103. package/src/lib/utils.ts +109 -0
  104. package/src/styles/oaiz/app.css +21 -0
  105. package/src/styles/oaiz/scrollbars.css +20 -0
  106. package/src/styles/oaiz/tokens.css +952 -0
  107. package/src/styles/oaiz/voice-orb.css +39 -0
@@ -0,0 +1,617 @@
1
+ import { createContext, useCallback, useContext, useEffect, useRef, type ReactNode } from 'react';
2
+ import {
3
+ QueryClient,
4
+ hashKey,
5
+ useMutation,
6
+ useQuery,
7
+ useQueryClient,
8
+ type QueryKey,
9
+ } from '@tanstack/react-query';
10
+ import type { OaizClient, OaizError, OaizFilters } from '@oaiz/sdk';
11
+
12
+
13
+ type OaizData = {
14
+ client: OaizClient;
15
+ /** The id of the database `client` reads; query keys carry it, so two databases never share a cache entry. */
16
+ database: string;
17
+ /** The signed-in member's id; query keys carry it, because row policies give each member their own rows. */
18
+ member: string;
19
+ };
20
+
21
+ const OaizDataContext = createContext<OaizData | null>(null);
22
+
23
+ /** Gives the row hooks the client and database they use. Place it inside `QueryClientProvider`. */
24
+ export function OaizDataProvider({
25
+ client,
26
+ database,
27
+ member,
28
+ children,
29
+ }: OaizData & { children: ReactNode }) {
30
+ return (
31
+ <OaizDataContext.Provider value={{ client, database, member }}>
32
+ {children}
33
+ </OaizDataContext.Provider>
34
+ );
35
+ }
36
+
37
+ function useOaizData(): OaizData {
38
+ const data = useContext(OaizDataContext);
39
+ if (data === null) {
40
+ throw new Error('The OAIZ row hooks need an OaizDataProvider above them.');
41
+ }
42
+ return data;
43
+ }
44
+
45
+ /** A request OAIZ refused or that got no answer; `status` is 0 when no answer arrived. */
46
+ export class OaizRequestError extends Error {
47
+ readonly code: string;
48
+ readonly hints: string[];
49
+ readonly status: number;
50
+
51
+ constructor(error: OaizError, status: number) {
52
+ super(error.message);
53
+ this.name = 'OaizRequestError';
54
+ this.code = error.code;
55
+ this.hints = error.hints;
56
+ this.status = status;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * The query client of an app: rows stay fresh for 30 seconds, so moving between screens reads no
62
+ * row twice, and a failed read is tried once more unless OAIZ refused it.
63
+ */
64
+ export function newOaizQueryClient(): QueryClient {
65
+ return new QueryClient({
66
+ defaultOptions: {
67
+ queries: {
68
+ staleTime: 30_000,
69
+ retry: (failures, error) => {
70
+ const refused =
71
+ error instanceof OaizRequestError && error.status >= 400 && error.status < 500;
72
+ return failures < 1 && !refused;
73
+ },
74
+ },
75
+ },
76
+ });
77
+ }
78
+
79
+ /** The key prefix of every query of one table: its row lists, pages and single rows. */
80
+ export const tableKey = (member: string, database: string, table: string) =>
81
+ ['oaiz', member, database, table] as const;
82
+
83
+ /** The key prefix of every row list of one table. */
84
+ export const rowsKey = (member: string, database: string, table: string) =>
85
+ [...tableKey(member, database, table), 'rows'] as const;
86
+
87
+ /** The key prefix of every page of one table. */
88
+ export const pageKey = (member: string, database: string, table: string) =>
89
+ [...tableKey(member, database, table), 'page'] as const;
90
+
91
+ /** The key of one row of one table. */
92
+ export const rowKey = (member: string, database: string, table: string, id: RowId) =>
93
+ [...tableKey(member, database, table), 'row', id] as const;
94
+
95
+ export type RowId = string | number;
96
+
97
+ /** One condition on one column; the query sends it, so OAIZ filters before it pages. */
98
+ export type RowFilter =
99
+ | {
100
+ column: string;
101
+ op: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte';
102
+ value: string | number | boolean;
103
+ }
104
+ | { column: string; op: 'ilike'; value: string }
105
+ | { column: string; op: 'in'; value: readonly (string | number)[] }
106
+ | { column: string; op: 'is'; value: null | boolean }
107
+ /** Matches when any member does, from a string such as `a.eq.1,b.ilike."%x%"`. */
108
+ | { op: 'or'; value: string };
109
+
110
+ export type RowsOptions = {
111
+ /** The columns to read, as in `select`; all columns when omitted. */
112
+ columns?: string;
113
+ filters?: RowFilter[];
114
+ orderBy?: string;
115
+ ascending?: boolean;
116
+ limit?: number;
117
+ /**
118
+ * Keeps the rows on screen while a changed filter loads. Set it on a search or filter the member
119
+ * types in. Without it, rows show only for their own filters, so one record's screen never shows
120
+ * another record's rows.
121
+ */
122
+ keepRows?: boolean;
123
+ };
124
+
125
+ export type PageOptions = Omit<RowsOptions, 'limit'> & {
126
+ /** The page to read, from 0. */
127
+ page: number;
128
+ pageSize: number;
129
+ };
130
+
131
+ /** One page of rows and the number of rows that match the filters. */
132
+ export type RowPage<Row> = { rows: Row[]; count: number };
133
+
134
+ type Filterable = OaizFilters<Record<string, unknown>>;
135
+
136
+ function applyFilters<Builder extends Filterable>(
137
+ request: Builder,
138
+ filters: RowFilter[] = [],
139
+ ): Builder {
140
+ let filtered = request;
141
+ for (const filter of filters) {
142
+ switch (filter.op) {
143
+ case 'or':
144
+ filtered = filtered.or(filter.value);
145
+ break;
146
+ case 'ilike':
147
+ filtered = filtered.ilike(filter.column, filter.value);
148
+ break;
149
+ case 'in':
150
+ filtered = filtered.in(filter.column, filter.value);
151
+ break;
152
+ case 'is':
153
+ filtered = filtered.is(filter.column, filter.value);
154
+ break;
155
+ default:
156
+ filtered = filtered[filter.op](filter.column, filter.value);
157
+ }
158
+ }
159
+ return filtered;
160
+ }
161
+
162
+ /**
163
+ * Keeps the previous rows through a new page or order of the same table and columns; a new filter
164
+ * keeps them only on `keepRows`.
165
+ */
166
+ function keepRowsFor<Data>(queryKey: QueryKey, keepRows = false) {
167
+ const read = (key: QueryKey) => {
168
+ const { columns, filters } = key[key.length - 1] as Pick<RowsOptions, 'columns' | 'filters'>;
169
+ return hashKey([...key.slice(0, -1), columns, keepRows ? [] : (filters ?? [])]);
170
+ };
171
+ return (previous: Data | undefined, query?: { queryKey: QueryKey }) =>
172
+ query && read(query.queryKey) === read(queryKey) ? previous : undefined;
173
+ }
174
+
175
+ /**
176
+ * The rows of one table, or its totals when `columns` names aggregates, as in
177
+ * `stage, total:amount.sum(), count()`. The previous rows stay on screen through a new order, and
178
+ * through a new filter on `keepRows`. A refused read rejects with `OaizRequestError`.
179
+ */
180
+ export function useRows<Row>(table: string, { keepRows, ...options }: RowsOptions = {}) {
181
+ const { client, database, member } = useOaizData();
182
+ const queryKey = [...rowsKey(member, database, table), options];
183
+ return useQuery({
184
+ queryKey,
185
+ placeholderData: keepRowsFor<Row[]>(queryKey, keepRows),
186
+ queryFn: async () => {
187
+ let request = applyFilters(
188
+ client.from(table).select(options.columns ?? '*'),
189
+ options.filters,
190
+ );
191
+ if (options.orderBy !== undefined) {
192
+ request = request.order(options.orderBy, {
193
+ ascending: options.ascending ?? true,
194
+ });
195
+ }
196
+ if (options.limit !== undefined) {
197
+ request = request.limit(options.limit);
198
+ }
199
+ const { data, error, status } = await request;
200
+ if (error !== null) {
201
+ throw new OaizRequestError(error, status);
202
+ }
203
+ return data as Row[];
204
+ },
205
+ });
206
+ }
207
+
208
+ /**
209
+ * One page of the rows of one table and the count of every matching row. The previous page stays
210
+ * on screen while the next one loads, and through a new filter on `keepRows`. A refused read rejects
211
+ * with `OaizRequestError`.
212
+ */
213
+ export function usePagedRows<Row>(table: string, { keepRows, ...options }: PageOptions) {
214
+ const { client, database, member } = useOaizData();
215
+ const queryKey = [...pageKey(member, database, table), options];
216
+ return useQuery({
217
+ queryKey,
218
+ placeholderData: keepRowsFor<RowPage<Row>>(queryKey, keepRows),
219
+ queryFn: async (): Promise<RowPage<Row>> => {
220
+ let request = applyFilters(
221
+ client
222
+ .from(table)
223
+ .select(options.columns ?? '*', { count: 'exact' }),
224
+ options.filters,
225
+ );
226
+ if (options.orderBy !== undefined) {
227
+ request = request.order(options.orderBy, {
228
+ ascending: options.ascending ?? true,
229
+ });
230
+ }
231
+ const from = options.page * options.pageSize;
232
+ const { data, error, count, status } = await request.range(
233
+ from,
234
+ from + options.pageSize - 1,
235
+ );
236
+ if (error !== null) {
237
+ throw new OaizRequestError(error, status);
238
+ }
239
+ return { rows: data as Row[], count: count ?? 0 };
240
+ },
241
+ });
242
+ }
243
+
244
+ export type RowOptions = {
245
+ /** The key column; `id` when omitted. */
246
+ idColumn?: string;
247
+ columns?: string;
248
+ };
249
+
250
+ /**
251
+ * One row by its key. It is `undefined` while no id is given. A missing row and a refused read
252
+ * reject with `OaizRequestError`.
253
+ */
254
+ export function useRow<Row>(
255
+ table: string,
256
+ id: RowId | undefined,
257
+ options: RowOptions = {},
258
+ ) {
259
+ const { client, database, member } = useOaizData();
260
+ return useQuery({
261
+ queryKey: [...rowKey(member, database, table, id ?? ''), options],
262
+ enabled: id !== undefined,
263
+ queryFn: () => readRow<Row>(client, table, id!, options),
264
+ });
265
+ }
266
+
267
+ async function readRow<Row>(client: OaizClient, table: string, id: RowId, options: RowOptions) {
268
+ const { data, error, status } = await client
269
+ .from(table)
270
+ .select(options.columns ?? '*')
271
+ .eq(options.idColumn ?? 'id', id)
272
+ .single();
273
+ if (error !== null) {
274
+ throw new OaizRequestError(error, status);
275
+ }
276
+ return data as Row;
277
+ }
278
+
279
+ /**
280
+ * Answers a function that reads one row ahead of time, for a row's hover and focus, so that opening
281
+ * it shows at once. Pass `useRow`'s options, which key the cache.
282
+ */
283
+ export function usePrefetchRow<Row>(table: string, options: RowOptions = {}) {
284
+ const { client, database, member } = useOaizData();
285
+ const queryClient = useQueryClient();
286
+ return (id: RowId) => {
287
+ void queryClient.prefetchQuery({
288
+ queryKey: [...rowKey(member, database, table, id), options],
289
+ queryFn: () => readRow<Row>(client, table, id, options),
290
+ });
291
+ };
292
+ }
293
+
294
+ /** The writes of each table that have started and not settled, per query client. */
295
+ const savingWrites = new WeakMap<QueryClient, Map<string, number>>();
296
+
297
+ function startWrite(queryClient: QueryClient, prefix: readonly unknown[]) {
298
+ const saving = savingWrites.get(queryClient) ?? new Map<string, number>();
299
+ savingWrites.set(queryClient, saving);
300
+ const table = hashKey(prefix);
301
+ saving.set(table, (saving.get(table) ?? 0) + 1);
302
+ }
303
+
304
+ /**
305
+ * Refetches the table's queries when its last write settles. A refetch while another write to the
306
+ * table is still saving would answer rows without that write and undo it on screen. The count
307
+ * drops as each write settles, so of two writes that settle together exactly one refetches.
308
+ */
309
+ function refetchAfterLastWrite(queryClient: QueryClient, prefix: readonly unknown[]) {
310
+ const saving = savingWrites.get(queryClient);
311
+ const table = hashKey(prefix);
312
+ const left = (saving?.get(table) ?? 1) - 1;
313
+ if (left > 0) {
314
+ saving?.set(table, left);
315
+ return;
316
+ }
317
+ saving?.delete(table);
318
+ return queryClient.invalidateQueries({ queryKey: prefix });
319
+ }
320
+
321
+ /**
322
+ * Inserts rows into one table and answers the inserted rows. The new rows show when OAIZ has saved
323
+ * them, because OAIZ fills their key and defaults. A refused insert rejects with `OaizRequestError`.
324
+ * The table's queries refetch when the last write to the table settles.
325
+ */
326
+ export function useInsertRow<
327
+ Insert extends Record<string, unknown>,
328
+ Row = Insert,
329
+ >(table: string) {
330
+ const { client, database, member } = useOaizData();
331
+ const queryClient = useQueryClient();
332
+ const prefix = tableKey(member, database, table);
333
+ return useMutation({
334
+ mutationFn: async (values: Insert | Insert[]) => {
335
+ const { data, error, status } = await client
336
+ .from(table)
337
+ .insert(values)
338
+ .select();
339
+ if (error !== null) {
340
+ throw new OaizRequestError(error, status);
341
+ }
342
+ return data as Row[];
343
+ },
344
+ onMutate: () => startWrite(queryClient, prefix),
345
+ onSettled: () => refetchAfterLastWrite(queryClient, prefix),
346
+ });
347
+ }
348
+
349
+ type Snapshot = [QueryKey, unknown][];
350
+ type CachedRow = Record<string, unknown>;
351
+
352
+ /**
353
+ * Changes every cached row of one table whose key is `id`: in lists, in pages and as a single row.
354
+ * `change` answers the new row, or `null` to remove it. Answers the cache before the change.
355
+ */
356
+ function patchCachedRows(
357
+ queryClient: QueryClient,
358
+ prefix: readonly unknown[],
359
+ idColumn: string,
360
+ id: RowId,
361
+ change: (row: CachedRow) => CachedRow | null,
362
+ ): Snapshot {
363
+ const snapshot = queryClient.getQueriesData({ queryKey: prefix });
364
+ const patch = (rows: CachedRow[]) =>
365
+ rows.flatMap((row) => {
366
+ if (row[idColumn] !== id) return [row];
367
+ const next = change(row);
368
+ return next === null ? [] : [next];
369
+ });
370
+ for (const [key, data] of snapshot) {
371
+ if (data === undefined) continue;
372
+ const kind = key[prefix.length];
373
+ if (kind === 'rows' && Array.isArray(data)) {
374
+ queryClient.setQueryData(key, patch(data));
375
+ } else if (kind === 'page') {
376
+ const page = data as RowPage<CachedRow>;
377
+ const rows = patch(page.rows);
378
+ queryClient.setQueryData(key, {
379
+ rows,
380
+ count: page.count - (page.rows.length - rows.length),
381
+ });
382
+ } else if (kind === 'row' && key[prefix.length + 1] === id) {
383
+ const next = change(data as CachedRow);
384
+ if (next !== null) queryClient.setQueryData(key, next);
385
+ }
386
+ }
387
+ return snapshot;
388
+ }
389
+
390
+ /**
391
+ * Undoes one refused write to the row whose key is `id`, from the cache before that write. Only
392
+ * that row goes back, and after an update only the columns that still hold what it wrote, so
393
+ * another write that is still saving stays on screen, also in the same column. `written` is
394
+ * `null` after a delete: the row returns where it was.
395
+ */
396
+ function undoRowWrite(
397
+ queryClient: QueryClient,
398
+ prefix: readonly unknown[],
399
+ snapshot: Snapshot | undefined,
400
+ idColumn: string,
401
+ id: RowId,
402
+ written: CachedRow | null,
403
+ ) {
404
+ const undo = (before: CachedRow, now: CachedRow) => {
405
+ if (written === null) return before;
406
+ const back = Object.keys(written).filter((column) => Object.is(now[column], written[column]));
407
+ return { ...now, ...Object.fromEntries(back.map((column) => [column, before[column]])) };
408
+ };
409
+ const undoIn = (before: CachedRow[], now: CachedRow[]) => {
410
+ const was = before.findIndex((row) => row[idColumn] === id);
411
+ if (was < 0) return now;
412
+ const is = now.findIndex((row) => row[idColumn] === id);
413
+ if (is >= 0) return now.map((row, index) => (index === is ? undo(before[was], row) : row));
414
+ // An update leaves a row that another write removed where it is.
415
+ if (written !== null) return now;
416
+ return [...now.slice(0, was), before[was], ...now.slice(was)];
417
+ };
418
+ for (const [key, before] of snapshot ?? []) {
419
+ const now = queryClient.getQueryData(key);
420
+ if (before === undefined || now === undefined) continue;
421
+ const kind = key[prefix.length];
422
+ if (kind === 'rows' && Array.isArray(before) && Array.isArray(now)) {
423
+ queryClient.setQueryData(key, undoIn(before, now));
424
+ } else if (kind === 'page') {
425
+ const page = now as RowPage<CachedRow>;
426
+ const rows = undoIn((before as RowPage<CachedRow>).rows, page.rows);
427
+ queryClient.setQueryData(key, { rows, count: page.count + rows.length - page.rows.length });
428
+ } else if (kind === 'row' && key[prefix.length + 1] === id) {
429
+ queryClient.setQueryData(key, undo(before as CachedRow, now as CachedRow));
430
+ }
431
+ }
432
+ }
433
+
434
+ export type UpdateRow<Values> = { id: RowId; values: Values };
435
+
436
+ export type RowWriteOptions<Variables> = {
437
+ idColumn?: string;
438
+ /**
439
+ * Runs for every refused write, after its change left the cache. Callbacks passed to `mutate`
440
+ * run only for the latest call, so a refusal that must always show belongs here.
441
+ */
442
+ onError?: (error: Error, variables: Variables) => void;
443
+ };
444
+
445
+ /**
446
+ * Updates one row by its key. The cached rows change at once; when OAIZ refuses, the columns this
447
+ * update wrote change back, unless a later write changed them again. A row that a row policy hides or blocks rejects with
448
+ * `OaizRequestError`, as a refused update does. The table's queries refetch when the last write to
449
+ * the table settles.
450
+ */
451
+ export function useUpdateRow<
452
+ Values extends Record<string, unknown>,
453
+ Row = Values,
454
+ >(table: string, options: RowWriteOptions<UpdateRow<Values>> = {}) {
455
+ const { client, database, member } = useOaizData();
456
+ const queryClient = useQueryClient();
457
+ const idColumn = options.idColumn ?? 'id';
458
+ const prefix = tableKey(member, database, table);
459
+ return useMutation({
460
+ mutationFn: async ({ id, values }: UpdateRow<Values>) => {
461
+ // `.single()` turns "no row changed" into an error: a row policy blocks without one.
462
+ const { data, error, status } = await client
463
+ .from(table)
464
+ .update(values)
465
+ .eq(idColumn, id)
466
+ .select()
467
+ .single();
468
+ if (error !== null) {
469
+ throw new OaizRequestError(error, status);
470
+ }
471
+ return data as Row;
472
+ },
473
+ onMutate: async ({ id, values }) => {
474
+ startWrite(queryClient, prefix);
475
+ await queryClient.cancelQueries({ queryKey: prefix });
476
+ return patchCachedRows(queryClient, prefix, idColumn, id, (row) => ({ ...row, ...values }));
477
+ },
478
+ onError: (error, variables, snapshot) => {
479
+ undoRowWrite(queryClient, prefix, snapshot, idColumn, variables.id, variables.values);
480
+ options.onError?.(error, variables);
481
+ },
482
+ onSettled: () => refetchAfterLastWrite(queryClient, prefix),
483
+ });
484
+ }
485
+
486
+ /**
487
+ * Deletes one row by its key. The row leaves the cache at once and comes back where it was when
488
+ * OAIZ refuses. A row that a row policy hides or blocks rejects with `OaizRequestError`. The
489
+ * table's queries refetch when the last write to the table settles.
490
+ */
491
+ export function useDeleteRow(table: string, options: RowWriteOptions<RowId> = {}) {
492
+ const { client, database, member } = useOaizData();
493
+ const queryClient = useQueryClient();
494
+ const idColumn = options.idColumn ?? 'id';
495
+ const prefix = tableKey(member, database, table);
496
+ return useMutation({
497
+ mutationFn: async (id: RowId) => {
498
+ const { error, status } = await client
499
+ .from(table)
500
+ .delete()
501
+ .eq(idColumn, id)
502
+ .select(idColumn)
503
+ .single();
504
+ if (error !== null) {
505
+ throw new OaizRequestError(error, status);
506
+ }
507
+ },
508
+ onMutate: async (id) => {
509
+ startWrite(queryClient, prefix);
510
+ await queryClient.cancelQueries({ queryKey: prefix });
511
+ return patchCachedRows(queryClient, prefix, idColumn, id, () => null);
512
+ },
513
+ onError: (error, id, snapshot) => {
514
+ undoRowWrite(queryClient, prefix, snapshot, idColumn, id, null);
515
+ options.onError?.(error, id);
516
+ },
517
+ onSettled: () => refetchAfterLastWrite(queryClient, prefix),
518
+ });
519
+ }
520
+
521
+ /** How long a delete waits for an undo before it is sent. */
522
+ const UNDO_WINDOW_MS = 5000;
523
+
524
+ /**
525
+ * Deletes rows with an undo window, as a mail app does: `remove(id)` hides the row at once and
526
+ * sends the delete when the window ends, and the `undo` it answers brings the row back while the
527
+ * window is open. Show the undo in a toast. A delete still in its window is sent when the screen
528
+ * unmounts or the page is hidden. A refused delete brings the row back and calls `onError`.
529
+ */
530
+ export function useUndoableDeleteRow(
531
+ table: string,
532
+ options: RowWriteOptions<RowId> & { undoWindowMs?: number } = {},
533
+ ) {
534
+ const { client, database, member } = useOaizData();
535
+ const queryClient = useQueryClient();
536
+ const idColumn = options.idColumn ?? 'id';
537
+ const prefix = tableKey(member, database, table);
538
+ const latest = useRef({ client, queryClient, idColumn, prefix, table, options });
539
+ latest.current = { client, queryClient, idColumn, prefix, table, options };
540
+ type PendingDelete = {
541
+ id: RowId;
542
+ key: string;
543
+ context: typeof latest.current;
544
+ timer?: ReturnType<typeof setTimeout>;
545
+ snapshot: Snapshot;
546
+ };
547
+ const waiting = useRef(new Set<PendingDelete>());
548
+
549
+ const send = useCallback(async (entry: PendingDelete) => {
550
+ if (!waiting.current.delete(entry)) return;
551
+ clearTimeout(entry.timer);
552
+ const { id, context } = entry;
553
+ try {
554
+ const { error, status } = await context.client
555
+ .from(context.table)
556
+ .delete()
557
+ .eq(context.idColumn, id)
558
+ .select(context.idColumn)
559
+ .single();
560
+ if (error !== null) {
561
+ throw new OaizRequestError(error, status);
562
+ }
563
+ } catch (error) {
564
+ undoRowWrite(context.queryClient, context.prefix, entry.snapshot, context.idColumn, id, null);
565
+ context.options.onError?.(error as Error, id);
566
+ } finally {
567
+ void refetchAfterLastWrite(context.queryClient, context.prefix);
568
+ }
569
+ }, []);
570
+
571
+ useEffect(() => {
572
+ const sendAll = () => {
573
+ for (const entry of [...waiting.current]) void send(entry);
574
+ };
575
+ window.addEventListener('pagehide', sendAll);
576
+ return () => {
577
+ window.removeEventListener('pagehide', sendAll);
578
+ sendAll();
579
+ };
580
+ }, [send]);
581
+
582
+ const remove = useCallback(
583
+ (id: RowId) => {
584
+ const context = latest.current;
585
+ const key = hashKey([...context.prefix, context.idColumn, id]);
586
+ let entry = [...waiting.current].find((pending) =>
587
+ pending.key === key && pending.context.client === context.client &&
588
+ pending.context.queryClient === context.queryClient,
589
+ );
590
+ if (!entry) {
591
+ // The open write keeps another write's refetch from showing the row again.
592
+ startWrite(context.queryClient, context.prefix);
593
+ void context.queryClient.cancelQueries({ queryKey: context.prefix });
594
+ const snapshot = patchCachedRows(context.queryClient, context.prefix, context.idColumn, id, () => null);
595
+ entry = { id, key, context, snapshot };
596
+ waiting.current.add(entry);
597
+ const pending = entry;
598
+ pending.timer = setTimeout(() => void send(pending), context.options.undoWindowMs ?? UNDO_WINDOW_MS);
599
+ }
600
+ const pending = entry;
601
+ return {
602
+ /** Brings this operation's row back; false when its delete was already sent or undone. */
603
+ undo: () => {
604
+ if (!waiting.current.delete(pending)) return false;
605
+ clearTimeout(pending.timer);
606
+ const at = pending.context;
607
+ undoRowWrite(at.queryClient, at.prefix, pending.snapshot, at.idColumn, pending.id, null);
608
+ void refetchAfterLastWrite(at.queryClient, at.prefix);
609
+ return true;
610
+ },
611
+ };
612
+ },
613
+ [send],
614
+ );
615
+
616
+ return { remove };
617
+ }
@@ -0,0 +1,63 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import type { OaizAuth, OaizError, OaizUser } from '@oaiz/sdk';
3
+
4
+ export type OaizSessionStatus = 'loading' | 'signed-out' | 'signed-in';
5
+
6
+ export type OaizSessionState = {
7
+ status: OaizSessionStatus;
8
+ /** The signed-in member; `null` unless `status` is `signed-in`. */
9
+ user: OaizUser | null;
10
+ /** The last sign-in, session or sign-out failure. */
11
+ error: OaizError | null;
12
+ /** Sends the browser to OAIZ; the page loads again, signed in. */
13
+ signIn: () => Promise<void>;
14
+ /** Ends the session. It signs out in this browser even when OAIZ answers with an error. */
15
+ signOut: () => Promise<void>;
16
+ };
17
+
18
+ /** The member signed in to this app through `auth` (`client.auth` of the app's `@oaiz/sdk` client). */
19
+ export function useOaizSession(auth: OaizAuth): OaizSessionState {
20
+ const [status, setStatus] = useState<OaizSessionStatus>('loading');
21
+ const [user, setUser] = useState<OaizUser | null>(null);
22
+ const [error, setError] = useState<OaizError | null>(null);
23
+
24
+ useEffect(() => {
25
+ let current = true;
26
+ void (async () => {
27
+ const session = await auth.getSession();
28
+ if (!current) return;
29
+ if (session.error) setError(session.error);
30
+ if (!session.data) {
31
+ setStatus('signed-out');
32
+ return;
33
+ }
34
+ const member = await auth.getUser();
35
+ if (!current) return;
36
+ if (member.error) {
37
+ setError(member.error);
38
+ setStatus('signed-out');
39
+ return;
40
+ }
41
+ setUser(member.data);
42
+ setStatus('signed-in');
43
+ })();
44
+ return () => {
45
+ current = false;
46
+ };
47
+ }, [auth]);
48
+
49
+ const signIn = useCallback(async () => {
50
+ setError(null);
51
+ const answer = await auth.signIn();
52
+ if (answer.error) setError(answer.error);
53
+ }, [auth]);
54
+
55
+ const signOut = useCallback(async () => {
56
+ const answer = await auth.signOut();
57
+ setError(answer.error);
58
+ setUser(null);
59
+ setStatus('signed-out');
60
+ }, [auth]);
61
+
62
+ return { status, user, error, signIn, signOut };
63
+ }
@@ -0,0 +1,19 @@
1
+ import { useEffect, useRef } from 'react';
2
+
3
+ /** The class that eases an arriving item in; reduced motion stops it with every other animation. */
4
+ export const ARRIVAL_CLASS = 'animate-in fade-in-0 slide-in-from-bottom-1 duration-normal ease-enter';
5
+
6
+ /**
7
+ * Tells which keys arrived after the first render, so a live list eases new items in without
8
+ * animating everything that was there when the screen opened.
9
+ */
10
+ export function useArrivals(keys: readonly (string | number)[]): (key: string | number) => boolean {
11
+ const known = useRef<Set<string | number> | null>(null);
12
+ if (known.current === null) known.current = new Set(keys);
13
+ const seen = known.current;
14
+ const arrived = new Set(keys.filter((key) => !seen.has(key)));
15
+ useEffect(() => {
16
+ for (const key of keys) seen.add(key);
17
+ });
18
+ return (key) => arrived.has(key);
19
+ }