@dudousxd/nestjs-catalog-react 0.16.0 → 0.17.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.
@@ -1,10 +1,13 @@
1
- import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { coerceFilterValue, encodeObjectFilter, filterOperatorTakesValue, } from '@dudousxd/nestjs-catalog/client';
2
3
  import { useQuery } from '@tanstack/react-query';
3
- import { ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, Search } from 'lucide-react';
4
- import { useEffect, useMemo, useState } from 'react';
4
+ import { ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, History, Search, X, } from 'lucide-react';
5
+ import { useCallback, useEffect, useMemo, useState } from 'react';
5
6
  import { cn } from './cn';
6
7
  import { catalogQueryKeys, useCatalogClient } from './context';
8
+ import { Button } from './ui/button';
7
9
  import { DataTable } from './ui/data-table';
10
+ import { Select } from './ui/select';
8
11
  /**
9
12
  * One table for every object type in the catalog.
10
13
  *
@@ -12,11 +15,24 @@ import { DataTable } from './ui/data-table';
12
15
  * their alignment and their units all arrive with the data — which is the
13
16
  * point: the screen that replaces N hand-written tables cannot afford to know
14
17
  * about any of them.
18
+ *
19
+ * **The filter controls are derived, not listed.** Which columns can be filtered
20
+ * and what each one may be filtered with come from `filterOperators` on the
21
+ * page's own columns, which the server computes with `filterOperatorsFor` and
22
+ * narrows to what its store can apply. So a type published this morning with a
23
+ * new column is filterable this morning, and a control this screen draws is one
24
+ * the read will accept. A list of filterable columns kept here would be a list
25
+ * that goes quiet the day somebody publishes a column nobody edited it for.
26
+ *
27
+ * **A property's `name` is what a filter names; its `columnName` is how the
28
+ * source spells it.** On a published type those differ whenever the source used
29
+ * something SQL cannot: `Asset Id` becomes the property `Asset_Id`. The source
30
+ * spelling is what a reader recognises, so it is shown; the property name is what
31
+ * the server resolves, so it is what is sent.
15
32
  */
16
33
  const MUTED = 'text-zinc-400 dark:text-zinc-500';
17
34
  const PANEL = 'bg-white dark:bg-zinc-900';
18
35
  const RULE = 'border-zinc-200 dark:border-zinc-800';
19
- const HAIRLINE = 'border-zinc-100 dark:border-zinc-900';
20
36
  function formatCell(value, type) {
21
37
  if (value === null || value === undefined || value === '')
22
38
  return '—';
@@ -37,6 +53,24 @@ function formatCell(value, type) {
37
53
  return String(value);
38
54
  }
39
55
  const isNumeric = (type) => type === 'number';
56
+ /**
57
+ * How each operator reads in a control.
58
+ *
59
+ * A total map rather than a lookup with a fallback: an operator added to the
60
+ * contract and not to this table fails to compile here, instead of appearing in
61
+ * a dropdown as its own wire name.
62
+ */
63
+ const OPERATOR_LABELS = {
64
+ eq: 'is',
65
+ ne: 'is not',
66
+ contains: 'contains',
67
+ gte: 'is at least',
68
+ lte: 'is at most',
69
+ gt: 'is more than',
70
+ lt: 'is less than',
71
+ empty: 'has no value',
72
+ notEmpty: 'has a value',
73
+ };
40
74
  /**
41
75
  * A parameter asked for in the URL, wherever the host keeps it.
42
76
  *
@@ -78,32 +112,19 @@ export function ObjectExplorer({ type: typeProp, pageSize = 25, backHref, backLa
78
112
  queryFn: () => client.snapshot(),
79
113
  staleTime: 30_000,
80
114
  });
81
- const [typeName, setTypeName] = useState(typeProp ?? '');
115
+ const [typeName, setTypeName] = useSelectedType(snapshot?.types, typeProp);
82
116
  const [page, setPage] = useState(1);
117
+ const { sort, dir, toggleSort, clearSort } = useSort(() => setPage(1));
83
118
  const [search, setSearch] = useState('');
84
119
  const [debouncedSearch, setDebouncedSearch] = useState('');
85
- const [sort, setSort] = useState();
86
- const [dir, setDir] = useState('asc');
87
120
  const [switcherOpen, setSwitcherOpen] = useState(false);
88
- // The prop wins whenever it changes, not only on the first render.
89
- //
90
- // Guarding this on "no type chosen yet" meant a host that linked from one
91
- // type to another — the ordinary way to arrive here — set the prop, watched
92
- // it be ignored, and showed the previous type under a URL naming the new one.
93
- useEffect(() => {
94
- if (!typeProp || !snapshot?.types.length)
95
- return;
96
- const match = snapshot.types.find((type) => type.name === typeProp);
97
- if (match)
98
- setTypeName(match.name);
99
- }, [snapshot, typeProp]);
100
- useEffect(() => {
101
- if (typeName || !snapshot?.types.length)
102
- return;
103
- const requested = typeProp ?? paramFromLocation('type');
104
- const match = snapshot.types.find((t) => t.name === requested);
105
- setTypeName(match?.name ?? snapshot.types[0].name);
106
- }, [snapshot, typeName, typeProp]);
121
+ const [filters, setFilters] = useState([]);
122
+ // Empty string, not undefined: the picker is a `Select`, whose value is a
123
+ // string, and "" is the option that means the load readers get by default.
124
+ // That default is not negotiable — nobody opening this screen may silently be
125
+ // reading an old load — so it is the initial state and the state a type change
126
+ // returns to.
127
+ const [snapshotId, setSnapshotId] = useState('');
107
128
  useEffect(() => {
108
129
  const timer = setTimeout(() => {
109
130
  setDebouncedSearch(search);
@@ -111,60 +132,415 @@ export function ObjectExplorer({ type: typeProp, pageSize = 25, backHref, backLa
111
132
  }, 250);
112
133
  return () => clearTimeout(timer);
113
134
  }, [search]);
135
+ /**
136
+ * The filters actually in force, as the server parses them.
137
+ *
138
+ * Filled by a debounce rather than derived on the spot: what is being typed and
139
+ * what has been asked for are two different facts, and a table that refetched
140
+ * on every keystroke of a filter value would ask a warehouse a question per
141
+ * character. The columns it needs to check a value against come from the read
142
+ * below, which is why the hook is fed twice — see {@link useAppliedFilters}.
143
+ */
144
+ const [applied, setApplied] = useState([]);
145
+ // Stable, so the debounce inside the hook can depend on it honestly rather
146
+ // than restarting its timer on every render. Back to page one whenever the
147
+ // filters change: page 7 of an unfiltered table is very often past the end of
148
+ // a filtered one, and a page past the end reads as "nothing matches".
149
+ const apply = useCallback((encoded) => {
150
+ setApplied(encoded);
151
+ setPage(1);
152
+ }, []);
114
153
  const params = useMemo(() => ({
115
154
  page,
116
155
  size: pageSize,
117
156
  search: debouncedSearch || undefined,
118
157
  sort,
119
158
  dir,
120
- }), [page, pageSize, debouncedSearch, sort, dir]);
121
- const { data, isFetching } = useQuery({
159
+ // Omitted rather than sent empty, so a screen with no filters asks the
160
+ // same question it always did.
161
+ filter: applied.length > 0 ? applied : undefined,
162
+ snapshot: snapshotId || undefined,
163
+ }), [page, pageSize, debouncedSearch, sort, dir, applied, snapshotId]);
164
+ const { data, isFetching, error } = useQuery({
122
165
  queryKey: catalogQueryKeys.objects(typeName, params),
123
166
  queryFn: () => client.objects(typeName, params),
124
167
  enabled: Boolean(typeName),
125
168
  placeholderData: (previous) => previous,
126
169
  });
170
+ /**
171
+ * Every load of this type, for the picker.
172
+ *
173
+ * One request per type rather than per page: it is keyed on the type and held
174
+ * for half a minute, so paging, sorting and filtering never re-ask. A store
175
+ * that keeps no history answers with an empty list and the picker does not
176
+ * appear at all.
177
+ */
178
+ const { data: snapshots } = useQuery({
179
+ queryKey: catalogQueryKeys.objectSnapshots(typeName),
180
+ queryFn: () => client.snapshots(typeName),
181
+ enabled: Boolean(typeName),
182
+ staleTime: 30_000,
183
+ });
184
+ useAppliedFilters(filters, data?.columns, apply);
127
185
  const selectedType = snapshot?.types.find((t) => t.name === typeName);
128
186
  // Derived from what the SERVER said the columns are, not from a type this
129
187
  // file knows: the explorer renders whatever was published. The second header
130
188
  // line is the physical column name, which is what somebody writing SQL
131
- // against the same table needs and the display name will not give them.
189
+ // against the same table needs and the display name will not give them —
190
+ // followed by the source's own spelling when the two differ, which is what the
191
+ // person who sent the file recognises.
132
192
  const columns = useMemo(() => (data?.columns ?? []).map((column) => ({
133
193
  id: column.name,
134
194
  accessorFn: (row) => row[column.name],
135
- header: () => (_jsxs(_Fragment, { children: [_jsxs("span", { children: [column.displayName, column.unit && (_jsxs("span", { className: cn('ml-1 font-mono text-[10px]', MUTED), children: ["(", column.unit, ")"] }))] }), _jsx("div", { className: cn('font-mono text-[10px] font-normal', MUTED), children: column.name })] })),
195
+ header: () => _jsx(ColumnHeading, { column: column }),
136
196
  cell: (context) => formatCell(context.getValue(), column.type),
137
197
  })), [data?.columns]);
138
198
  const numericColumns = useMemo(() => new Set((data?.columns ?? []).filter((c) => isNumeric(c.type)).map((c) => c.name)), [data?.columns]);
199
+ /**
200
+ * The columns this deployment will accept a filter on.
201
+ *
202
+ * `filterOperators` absent is read as "not filterable" rather than as "all of
203
+ * them": a server older than the field has not been asked, and offering a
204
+ * control it would refuse is worse than offering none.
205
+ */
206
+ const filterable = useMemo(() => (data?.columns ?? []).filter((column) => (column.filterOperators ?? []).length > 0), [data?.columns]);
207
+ function readSnapshot(next) {
208
+ setSnapshotId(next);
209
+ setPage(1);
210
+ }
211
+ function backToCurrent() {
212
+ readSnapshot('');
213
+ }
214
+ function chooseType(name) {
215
+ setTypeName(name);
216
+ setSwitcherOpen(false);
217
+ setPage(1);
218
+ clearSort();
219
+ setSearch('');
220
+ // Filters name properties of the type that is leaving, and a snapshot id
221
+ // belongs to it too — carried across, they would be refused by the read, and
222
+ // the refusal would be about a type the reader is no longer looking at.
223
+ //
224
+ // Both halves, and the second is the one that bites: the controls are
225
+ // emptied by `setFilters`, but what the read sends is the debounced copy, so
226
+ // clearing only the controls left the very next request — the one for the new
227
+ // type — carrying the old type's filters and coming back a 400.
228
+ setFilters([]);
229
+ apply([]);
230
+ setSnapshotId('');
231
+ }
232
+ if (loadingCatalog) {
233
+ return (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx("p", { className: cn('font-mono text-sm', MUTED), children: "Reading the catalog\u2026" }) }));
234
+ }
235
+ // What the SERVER says it read, never what this screen believes it asked for.
236
+ // A request in flight, a stale cache or a snapshot that has since been dropped
237
+ // all make those two disagree, and only one of them is evidence.
238
+ const stale = data?.snapshot?.current === false;
239
+ return (_jsxs("div", { className: "flex h-full flex-col bg-zinc-50 dark:bg-zinc-950", children: [_jsxs("header", { className: cn('shrink-0 border-b px-8 py-5', RULE, PANEL), children: [backHref && (_jsxs("a", { href: backHref, className: cn('mb-3 inline-flex items-center gap-1.5 font-mono text-[11px] uppercase tracking-[0.14em]', MUTED, 'hover:text-zinc-950 dark:hover:text-zinc-50'), children: [_jsx(ArrowLeft, { size: 12 }), backLabel] })), _jsxs("div", { className: "flex flex-wrap items-end justify-between gap-4", children: [_jsx(TypeSwitcher, { types: snapshot?.types ?? [], selected: selectedType, open: switcherOpen, onToggle: () => setSwitcherOpen((o) => !o), onChoose: chooseType, caption: tableCaption(selectedType, data) }), _jsx(SearchBox, { value: search, onChange: setSearch, what: selectedType?.pluralDisplayName })] }), _jsx(FilterBar, { columns: filterable, filters: filters, onChange: setFilters, snapshots: snapshots ?? [], snapshotId: snapshotId, onSnapshot: readSnapshot }), stale && (_jsx(StaleSnapshotBanner, { snapshots: snapshots ?? [], id: data?.snapshot?.id, onCurrent: backToCurrent }))] }), _jsxs("div", { className: "min-h-0 flex-1 overflow-auto px-8 py-6", children: [error ? (_jsx(RefusedRead, { error: error })) : (_jsxs("div", { className: cn('overflow-hidden rounded-lg border transition-opacity',
240
+ // The stale border is not decoration: the banner is at the top of a
241
+ // scrolling page, and somebody who came back to this tab after
242
+ // lunch may only ever see the grid.
243
+ stale ? 'border-amber-400 dark:border-amber-500/60' : RULE, PANEL, isFetching && 'opacity-60'), children: [_jsx(DataTable, { data: data?.rows ?? [], columns: columns, getRowId: (row, index) => String(row[selectedType?.primaryKey[0] ?? 'id'] ?? index), sort: { by: sort ?? null, dir, onSort: toggleSort }, numeric: (id) => numericColumns.has(id) }), data && data.rows.length === 0 && (_jsx(EmptyState, { type: selectedType, search: debouncedSearch, filtered: applied.length > 0, onClear: () => {
244
+ setSearch('');
245
+ setFilters([]);
246
+ } }))] })), data && _jsx(Pager, { page: data.page, pages: data.pages, onPage: setPage })] })] }));
247
+ }
248
+ /**
249
+ * The line under the title: the physical table, the row count, the columns.
250
+ *
251
+ * The row count is the page's `total`, so it moves with the filters — which is
252
+ * the point of putting it here rather than on the pager. An ellipsis rather than
253
+ * a zero while the read is in flight: "0 rows" and "not yet answered" are
254
+ * different facts and only one of them is worth reacting to.
255
+ */
256
+ function tableCaption(type, data) {
257
+ const rows = data ? `${data.total.toLocaleString()} rows` : '…';
258
+ return `${type?.tableName} · ${rows} · ${data?.columns.length ?? 0} columns from the catalog`;
259
+ }
260
+ /** The one control that searches every text column at once. */
261
+ function SearchBox({ value, onChange, what, }) {
262
+ return (_jsxs("div", { className: "relative", children: [_jsx(Search, { size: 14, className: cn('pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2', MUTED) }), _jsx("input", { type: "text", value: value, onChange: (event) => onChange(event.target.value), placeholder: `Search ${what?.toLowerCase() ?? 'objects'}`, "aria-label": "Search objects", className: cn('w-72 rounded-md border bg-zinc-50 py-2 pl-8 pr-3 text-sm outline-none dark:bg-zinc-950', RULE, 'placeholder:text-zinc-400 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/15') })] }));
263
+ }
264
+ /**
265
+ * The sort, which this screen reports rather than performs.
266
+ *
267
+ * A hook so the three-state toggle — a new column sorts ascending, the same
268
+ * column reverses, a type change clears — is in one place. Every one of those
269
+ * sends the reader back to the first page, which is what `onSorted` is for: the
270
+ * rows on screen are a window onto a warehouse table, and page 7 of one order is
271
+ * not page 7 of another.
272
+ */
273
+ function useSort(onSorted) {
274
+ const [sort, setSort] = useState();
275
+ const [dir, setDir] = useState('asc');
139
276
  function toggleSort(column) {
140
- if (sort === column) {
277
+ if (sort === column)
141
278
  setDir((d) => (d === 'asc' ? 'desc' : 'asc'));
142
- }
143
279
  else {
144
280
  setSort(column);
145
281
  setDir('asc');
146
282
  }
147
- setPage(1);
283
+ onSorted();
148
284
  }
149
- if (loadingCatalog) {
150
- return (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx("p", { className: cn('font-mono text-sm', MUTED), children: "Reading the catalog\u2026" }) }));
285
+ return { sort, dir, toggleSort, clearSort: () => setSort(undefined) };
286
+ }
287
+ /**
288
+ * Which type this screen is showing, and how it gets chosen.
289
+ *
290
+ * A hook rather than two effects in the component because the rules are fiddly
291
+ * and none of them are about rows:
292
+ *
293
+ * - **The prop wins whenever it changes**, not only on the first render. Guarding
294
+ * it on "no type chosen yet" meant a host that linked from one type to another
295
+ * — the ordinary way to arrive here — set the prop, watched it be ignored, and
296
+ * showed the previous type under a URL naming the new one.
297
+ * - Failing a prop, the URL, and failing that the first type in the catalog.
298
+ */
299
+ function useSelectedType(types, typeProp) {
300
+ const [typeName, setTypeName] = useState(typeProp ?? '');
301
+ useEffect(() => {
302
+ if (!typeProp || !types?.length)
303
+ return;
304
+ const match = types.find((type) => type.name === typeProp);
305
+ if (match)
306
+ setTypeName(match.name);
307
+ }, [types, typeProp]);
308
+ useEffect(() => {
309
+ if (typeName || !types?.length)
310
+ return;
311
+ const requested = typeProp ?? paramFromLocation('type');
312
+ const match = types.find((type) => type.name === requested);
313
+ setTypeName(match?.name ?? types[0].name);
314
+ }, [types, typeName, typeProp]);
315
+ return [typeName, setTypeName];
316
+ }
317
+ /**
318
+ * Debounce what has been built into what will be asked for.
319
+ *
320
+ * Only the filters that are ready go through. A half-typed filter is not a
321
+ * filter: a row whose value box is still empty, or whose text is not yet a
322
+ * number, would either narrow nothing or be refused — and a refusal for something
323
+ * somebody is in the middle of typing reads as the screen being broken.
324
+ * `coerceFilterValue` is the server's own check, imported rather than
325
+ * reimplemented, so what is held back here is exactly what would have been
326
+ * rejected there.
327
+ *
328
+ * `columns` comes from the read the applied filters feed, which sounds circular
329
+ * and is not: the applied list is state, so this runs after the render that used
330
+ * it. A filter can only have been built out of a column that had already arrived.
331
+ */
332
+ function useAppliedFilters(filters, columns, onApplied) {
333
+ const encoded = useMemo(() => {
334
+ const byName = new Map((columns ?? []).map((column) => [column.name, column]));
335
+ return filters
336
+ .filter((filter) => filterIsReady(filter, byName.get(filter.property)))
337
+ .map((filter) => encodeObjectFilter(filter));
338
+ }, [filters, columns]);
339
+ // One string, so the debounce below depends on a value rather than on an array
340
+ // identity that is new on every render.
341
+ const key = encoded.join('\n');
342
+ useEffect(() => {
343
+ const timer = setTimeout(() => onApplied(key ? key.split('\n') : []), 250);
344
+ return () => clearTimeout(timer);
345
+ // `onApplied` has to be stable — a callback with a new identity every render
346
+ // would restart this timer on every render and never fire. The caller wraps it
347
+ // in `useCallback` for exactly that reason, which is what makes listing it
348
+ // here honest rather than decorative.
349
+ }, [key, onApplied]);
350
+ }
351
+ /**
352
+ * Whether a filter is complete enough to send.
353
+ *
354
+ * The value is checked with the server's own coercion, so nothing leaves here
355
+ * that would come back a 400 — the alternative is a refusal fired at every
356
+ * keystroke of a number somebody is halfway through typing.
357
+ */
358
+ function filterIsReady(filter, column) {
359
+ if (!filterOperatorTakesValue(filter.op))
360
+ return true;
361
+ const value = filter.value ?? '';
362
+ if (value.trim() === '')
363
+ return false;
364
+ if (!column)
365
+ return true;
366
+ return coerceFilterValue(column.type, value).ok;
367
+ }
368
+ /** The reason a filter is not being applied, when there is one worth saying. */
369
+ function filterProblem(filter, column) {
370
+ if (!filterOperatorTakesValue(filter.op))
371
+ return undefined;
372
+ const value = filter.value ?? '';
373
+ if (value.trim() === '')
374
+ return undefined;
375
+ const coerced = coerceFilterValue(column.type, value);
376
+ return coerced.ok ? undefined : coerced.problem;
377
+ }
378
+ /**
379
+ * The filter and snapshot controls, both derived from what the server said.
380
+ *
381
+ * Together in one bar because they answer the same question in two directions —
382
+ * which rows, and which load — and because a reader who has narrowed to eleven
383
+ * rows should be able to see, without scrolling, whether those eleven are
384
+ * current.
385
+ */
386
+ function FilterBar({ columns, filters, onChange, snapshots, snapshotId, onSnapshot, }) {
387
+ const addable = columns.filter((column) => !filters.some((filter) => filter.property === column.name));
388
+ function add(name) {
389
+ const column = columns.find((each) => each.name === name);
390
+ const [first] = column?.filterOperators ?? [];
391
+ if (!column || !first)
392
+ return;
393
+ onChange([...filters, { property: column.name, op: first, value: '' }]);
151
394
  }
152
- return (_jsxs("div", { className: "flex h-full flex-col bg-zinc-50 dark:bg-zinc-950", children: [_jsxs("header", { className: cn('shrink-0 border-b px-8 py-5', RULE, PANEL), children: [backHref && (_jsxs("a", { href: backHref, className: cn('mb-3 inline-flex items-center gap-1.5 font-mono text-[11px] uppercase tracking-[0.14em]', MUTED, 'hover:text-zinc-950 dark:hover:text-zinc-50'), children: [_jsx(ArrowLeft, { size: 12 }), backLabel] })), _jsxs("div", { className: "flex flex-wrap items-end justify-between gap-4", children: [_jsxs("div", { className: "relative", children: [_jsxs("button", { type: "button", onClick: () => setSwitcherOpen((o) => !o), "aria-expanded": switcherOpen, className: "flex items-baseline gap-2 text-left", children: [_jsx("span", { className: "text-2xl leading-none", children: selectedType?.icon ?? '◈' }), _jsx("span", { className: "text-2xl font-semibold tracking-tight", children: selectedType?.pluralDisplayName ?? 'Objects' }), _jsx(ChevronDown, { size: 16, className: MUTED })] }), _jsxs("p", { className: cn('mt-1 pl-1 font-mono text-[11px]', MUTED), children: [selectedType?.tableName, " \u00B7 ", data ? `${data.total.toLocaleString()} rows` : '…', " \u00B7", ' ', data?.columns.length ?? 0, " columns from the catalog"] }), switcherOpen && (_jsx("div", { className: cn('absolute left-0 top-full z-20 mt-2 max-h-96 w-80 overflow-y-auto', 'rounded-lg border p-1 shadow-lg', RULE, PANEL), children: snapshot?.types.map((t) => (_jsxs("button", { type: "button", onClick: () => {
153
- setTypeName(t.name);
154
- setSwitcherOpen(false);
155
- setPage(1);
156
- setSort(undefined);
157
- setSearch('');
158
- }, className: cn('flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm', t.name === typeName
159
- ? 'bg-sky-100 dark:bg-sky-950'
160
- : 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx("span", { children: t.icon ?? '◈' }), _jsx("span", { className: "flex-1 truncate", children: t.pluralDisplayName }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: t.tableName })] }, t.name))) }))] }), _jsxs("div", { className: "relative", children: [_jsx(Search, { size: 14, className: cn('pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2', MUTED) }), _jsx("input", { type: "text", value: search, onChange: (e) => setSearch(e.target.value), placeholder: `Search ${selectedType?.pluralDisplayName?.toLowerCase() ?? 'objects'}`, "aria-label": "Search objects", className: cn('w-72 rounded-md border bg-zinc-50 py-2 pl-8 pr-3 text-sm outline-none dark:bg-zinc-950', RULE, 'placeholder:text-zinc-400 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/15') })] })] })] }), _jsxs("div", { className: "min-h-0 flex-1 overflow-auto px-8 py-6", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border transition-opacity', RULE, PANEL, isFetching && 'opacity-60'), children: [_jsx(DataTable, { data: data?.rows ?? [], columns: columns, getRowId: (row, index) => String(row[selectedType?.primaryKey[0] ?? 'id'] ?? index), sort: { by: sort ?? null, dir, onSort: toggleSort }, numeric: (id) => numericColumns.has(id) }), data && data.rows.length === 0 && (_jsx(EmptyState, { type: selectedType, search: debouncedSearch, onClear: () => setSearch('') }))] }), data && data.pages > 1 && (_jsxs("div", { className: "mt-4 flex items-center justify-between", children: [_jsxs("p", { className: cn('font-mono text-[11px]', MUTED), children: ["Page ", data.page, " of ", data.pages] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(PageButton, { onClick: () => setPage((p) => Math.max(1, p - 1)), disabled: data.page <= 1, label: "Previous page", children: _jsx(ChevronLeft, { size: 14 }) }), _jsx(PageButton, { onClick: () => setPage((p) => Math.min(data.pages, p + 1)), disabled: data.page >= data.pages, label: "Next page", children: _jsx(ChevronRight, { size: 14 }) })] })] }))] })] }));
161
- }
162
- function EmptyState({ type, search, onClear, }) {
163
- if (search) {
164
- return (_jsxs("div", { className: "px-6 py-16 text-center", children: [_jsxs("p", { className: "text-sm text-zinc-500 dark:text-zinc-400", children: ["Nothing matches \u201C", search, "\u201D."] }), _jsx("button", { type: "button", onClick: onClear, className: "mt-2 text-sm text-sky-600 underline underline-offset-2 dark:text-sky-400", children: "Clear the search" })] }));
395
+ // Nothing to offer and no history to pick from: draw nothing rather than an
396
+ // empty toolbar. That is the honest state on a store that neither filters nor
397
+ // keeps snapshots.
398
+ if (columns.length === 0 && snapshots.length === 0)
399
+ return null;
400
+ return (_jsxs("div", { className: "mt-4 flex flex-wrap items-start gap-2", children: [columns.length > 0 && (_jsx(Select, { value: "", onValueChange: add, ariaLabel: "Add a filter", placeholder: "Add a filter\u2026", className: "w-56", options: addable.map((column) => ({
401
+ value: column.name,
402
+ label: column.displayName,
403
+ // The property name is what the filter will carry; the source
404
+ // spelling is what the reader recognises. Both, when they differ.
405
+ hint: column.columnName && column.columnName !== column.name
406
+ ? `${column.name} ← ${column.columnName}`
407
+ : column.name,
408
+ })) })), snapshots.length > 0 && (_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(History, { size: 13, className: MUTED }), _jsx(Select, { value: snapshotId, onValueChange: onSnapshot, ariaLabel: "Load to read", className: "w-72", options: [
409
+ { value: '', label: 'Current load' },
410
+ ...snapshots.map((each) => ({
411
+ value: each.id,
412
+ label: describeSnapshot(each),
413
+ hint: `${each.rowCount.toLocaleString()} rows · ${each.principalId}`,
414
+ })),
415
+ ] })] })), filters.map((filter, index) => {
416
+ const column = columns.find((each) => each.name === filter.property);
417
+ if (!column)
418
+ return null;
419
+ return (_jsx(FilterRow, { column: column, filter: filter, onChange: (next) => onChange(filters.map((each, at) => (at === index ? next : each))), onRemove: () => onChange(filters.filter((_, at) => at !== index)) }, filter.property));
420
+ })] }));
421
+ }
422
+ /** One filter: the column, an operator it actually offers, and a value. */
423
+ function FilterRow({ column, filter, onChange, onRemove, }) {
424
+ const problem = filterProblem(filter, column);
425
+ const label = column.displayName;
426
+ return (_jsxs("div", { className: cn('flex flex-col gap-1 rounded-md border px-2 py-1.5', problem ? 'border-amber-400 dark:border-amber-500/60' : RULE, PANEL), children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: "text-xs font-medium", children: label }), _jsx(Select, { value: filter.op, onValueChange: (op) => {
427
+ if (isOfferedOperator(column, op))
428
+ onChange({ ...filter, op });
429
+ }, ariaLabel: `Operator for ${label}`, className: "w-36", options: (column.filterOperators ?? []).map((operator) => ({
430
+ value: operator,
431
+ label: OPERATOR_LABELS[operator],
432
+ })) }), filterOperatorTakesValue(filter.op) && (_jsx(FilterValue, { column: column, value: filter.value ?? '', onChange: (value) => onChange({ ...filter, value }) })), _jsx(Button, { variant: "ghost", size: "icon", onClick: onRemove, "aria-label": `Remove the filter on ${label}`, children: _jsx(X, { size: 12 }) })] }), problem && (_jsxs("p", { className: "text-[11px] text-amber-600 dark:text-amber-400", children: [problem, " Not applied \u2014 these rows are not filtered by ", label, "."] }))] }));
433
+ }
434
+ /**
435
+ * The value box, typed by the column.
436
+ *
437
+ * A `date` column gets a date field, which is what makes a range on a date usable
438
+ * at all: the control cannot produce something that is not a date.
439
+ *
440
+ * A `number` column deliberately does NOT get `type="number"`. That control drops
441
+ * characters it dislikes as they are typed, so `1,200` — which is how people
442
+ * write a mileage — becomes `1200` or nothing with no explanation, and a pasted
443
+ * `12 000` vanishes. A text box with a numeric keypad accepts it, and the
444
+ * coercion the SERVER would apply runs here instead and says why the filter is
445
+ * not being applied. That check is the same function, imported, so the two can
446
+ * never disagree about what a number is.
447
+ */
448
+ function FilterValue({ column, value, onChange, }) {
449
+ const label = `Value for ${column.displayName}`;
450
+ const className = cn('w-40 rounded-md border bg-white px-2 py-1 text-xs outline-none dark:bg-zinc-900', RULE, 'focus:border-sky-500 focus:ring-2 focus:ring-sky-500/15');
451
+ if (column.type === 'boolean') {
452
+ return (_jsx(Select, { value: value, onValueChange: onChange, ariaLabel: label, className: "w-28", options: [
453
+ { value: 'true', label: 'Yes' },
454
+ { value: 'false', label: 'No' },
455
+ ] }));
456
+ }
457
+ return (_jsx("input", { type: column.type === 'date' ? 'date' : 'text', inputMode: column.type === 'number' ? 'numeric' : undefined, value: value, "aria-label": label, onChange: (event) => onChange(event.target.value), className: className }));
458
+ }
459
+ /** Narrowed rather than asserted: a select hands back a string. */
460
+ function isOfferedOperator(column, value) {
461
+ return (column.filterOperators ?? []).some((operator) => operator === value);
462
+ }
463
+ function describeSnapshot(snapshot) {
464
+ const at = new Date(snapshot.createdAt);
465
+ if (Number.isNaN(at.getTime()))
466
+ return snapshot.id;
467
+ return at.toLocaleString(undefined, {
468
+ year: 'numeric',
469
+ month: 'short',
470
+ day: '2-digit',
471
+ hour: '2-digit',
472
+ minute: '2-digit',
473
+ });
474
+ }
475
+ /**
476
+ * That these rows are not the current data.
477
+ *
478
+ * Loud, and phrased as a fact about the data rather than about the control:
479
+ * somebody who selected a load an hour ago and came back to the tab has no
480
+ * memory of the selection, and "as of 4 March" beside a table is exactly as
481
+ * misleading as no label at all if it reads like a caption. The way back is here
482
+ * rather than only in the picker, because the picker is what they did not notice.
483
+ */
484
+ function StaleSnapshotBanner({ snapshots, id, onCurrent, }) {
485
+ const snapshot = snapshots.find((each) => each.id === id);
486
+ return (
487
+ // `<output>` rather than a div with `role="status"`: it carries that role
488
+ // already, so an assistive reader announces the change of load when the
489
+ // banner appears, and it is the element the linter asks for.
490
+ _jsxs("output", { className: cn('mt-3 flex flex-wrap items-center gap-3 rounded-md border px-3 py-2', 'border-amber-400 bg-amber-50 text-amber-900', 'dark:border-amber-500/60 dark:bg-amber-950/40 dark:text-amber-200'), children: [_jsx(History, { size: 14, className: "shrink-0" }), _jsxs("p", { className: "text-xs", children: [_jsx("span", { className: "font-semibold", children: "You are reading an earlier load." }), ' ', snapshot
491
+ ? `These rows are ${describeSnapshot(snapshot)}, loaded by ${snapshot.principalId}, and are not what this type currently serves.`
492
+ : `These rows are an earlier snapshot${id ? ` (${id})` : ''} and are not what this type currently serves.`] }), _jsx(Button, { variant: "outline", size: "sm", onClick: onCurrent, children: "Back to the current load" })] }));
493
+ }
494
+ /**
495
+ * What the server refused, verbatim.
496
+ *
497
+ * A read can now be refused for a reason the reader can act on — a filter this
498
+ * store cannot apply, a value that is not a number, a snapshot on a store with no
499
+ * history — and the previous behaviour was to render an empty grid, which says
500
+ * "no rows match" for every one of them.
501
+ */
502
+ function RefusedRead({ error }) {
503
+ const message = error instanceof Error ? error.message : String(error);
504
+ return (_jsxs("div", { className: cn('rounded-lg border px-6 py-10 text-center', RULE, PANEL), children: [_jsx("p", { className: "text-sm text-zinc-900 dark:text-zinc-100", children: "This read was refused." }), _jsx("p", { className: cn('mt-2 font-mono text-xs', MUTED), children: message })] }));
505
+ }
506
+ function EmptyState({ type, search, filtered, onClear, }) {
507
+ if (search || filtered) {
508
+ return (_jsxs("div", { className: "px-6 py-16 text-center", children: [_jsx("p", { className: "text-sm text-zinc-500 dark:text-zinc-400", children: search ? `Nothing matches “${search}”.` : 'Nothing matches these filters.' }), _jsx("button", { type: "button", onClick: onClear, className: "mt-2 text-sm text-sky-600 underline underline-offset-2 dark:text-sky-400", children: search && filtered
509
+ ? 'Clear the search and the filters'
510
+ : search
511
+ ? 'Clear the search'
512
+ : 'Clear the filters' })] }));
165
513
  }
166
514
  return (_jsxs("div", { className: "px-6 py-16 text-center", children: [_jsxs("p", { className: "text-sm text-zinc-500 dark:text-zinc-400", children: [type?.tableName, " has no rows yet."] }), _jsx("p", { className: cn('mt-1 text-xs', MUTED), children: "The type is in the catalog, so this table will fill in as soon as something writes to it." })] }));
167
515
  }
516
+ /**
517
+ * The type being read, and every other type, in one control.
518
+ *
519
+ * Its own component because the dropdown is the branchiest thing on the screen
520
+ * and none of its branches are about reading rows.
521
+ */
522
+ function TypeSwitcher({ types, selected, open, onToggle, onChoose, caption, }) {
523
+ return (_jsxs("div", { className: "relative", children: [_jsxs("button", { type: "button", onClick: onToggle, "aria-expanded": open, className: "flex items-baseline gap-2 text-left", children: [_jsx("span", { className: "text-2xl leading-none", children: selected?.icon ?? '◈' }), _jsx("span", { className: "text-2xl font-semibold tracking-tight", children: selected?.pluralDisplayName ?? 'Objects' }), _jsx(ChevronDown, { size: 16, className: MUTED })] }), _jsx("p", { className: cn('mt-1 pl-1 font-mono text-[11px]', MUTED), children: caption }), open && (_jsx("div", { className: cn('absolute left-0 top-full z-20 mt-2 max-h-96 w-80 overflow-y-auto', 'rounded-lg border p-1 shadow-lg', RULE, PANEL), children: types.map((t) => (_jsxs("button", { type: "button", onClick: () => onChoose(t.name), className: cn('flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm', t.name === selected?.name
524
+ ? 'bg-sky-100 dark:bg-sky-950'
525
+ : 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx("span", { children: t.icon ?? '◈' }), _jsx("span", { className: "flex-1 truncate", children: t.pluralDisplayName }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: t.tableName })] }, t.name))) }))] }));
526
+ }
527
+ /**
528
+ * A column's label, its unit, and the two names it goes by.
529
+ *
530
+ * The mono line is the property name — what somebody writing SQL against the
531
+ * same table needs, and what a filter carries — followed by the source's own
532
+ * spelling when the two differ, which is what the person who sent the file
533
+ * recognises. Neither is the display name, which is the curated label above.
534
+ */
535
+ function ColumnHeading({ column }) {
536
+ return (_jsxs(_Fragment, { children: [_jsxs("span", { children: [column.displayName, column.unit && (_jsxs("span", { className: cn('ml-1 font-mono text-[10px]', MUTED), children: ["(", column.unit, ")"] }))] }), _jsxs("div", { className: cn('font-mono text-[10px] font-normal', MUTED), children: [column.name, column.columnName && column.columnName !== column.name && ` ← ${column.columnName}`] })] }));
537
+ }
538
+ /** Nothing to page when there is one page: a lone disabled pair is noise. */
539
+ function Pager({ page, pages, onPage, }) {
540
+ if (pages <= 1)
541
+ return null;
542
+ return (_jsxs("div", { className: "mt-4 flex items-center justify-between", children: [_jsxs("p", { className: cn('font-mono text-[11px]', MUTED), children: ["Page ", page, " of ", pages] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(PageButton, { onClick: () => onPage((p) => Math.max(1, p - 1)), disabled: page <= 1, label: "Previous page", children: _jsx(ChevronLeft, { size: 14 }) }), _jsx(PageButton, { onClick: () => onPage((p) => Math.min(pages, p + 1)), disabled: page >= pages, label: "Next page", children: _jsx(ChevronRight, { size: 14 }) })] })] }));
543
+ }
168
544
  function PageButton({ children, onClick, disabled, label, }) {
169
545
  return (_jsx("button", { type: "button", onClick: onClick, disabled: disabled, "aria-label": label, className: cn('rounded-md border p-1.5 transition-colors disabled:opacity-40', RULE, PANEL, 'hover:bg-zinc-50 disabled:hover:bg-white dark:hover:bg-zinc-800'), children: children }));
170
546
  }