@macrostrat/data-sheet 4.4.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/dist/components/indicators/unified-filters.cjs +30 -10
- package/dist/components/indicators/unified-filters.cjs.map +1 -1
- package/dist/components/indicators/unified-filters.js +30 -10
- package/dist/components/indicators/unified-filters.js.map +1 -1
- package/dist/data-panel.cjs +3 -1
- package/dist/data-panel.cjs.map +1 -1
- package/dist/data-panel.d.ts +1 -1
- package/dist/data-panel.js +3 -1
- package/dist/data-panel.js.map +1 -1
- package/dist/data-panel.module.sass.cjs +25 -25
- package/dist/data-panel.module.sass.js +25 -25
- package/dist/data-sheet.cjs +3 -1
- package/dist/data-sheet.cjs.map +1 -1
- package/dist/data-sheet.css +37 -38
- package/dist/data-sheet.d.ts +1 -1
- package/dist/data-sheet.js +3 -1
- package/dist/data-sheet.js.map +1 -1
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/postgrest-table/data-loaders.cjs +67 -2
- package/dist/postgrest-table/data-loaders.cjs.map +1 -1
- package/dist/postgrest-table/data-loaders.d.ts +8 -1
- package/dist/postgrest-table/data-loaders.js +67 -2
- package/dist/postgrest-table/data-loaders.js.map +1 -1
- package/dist/provider/core.cjs +23 -2
- package/dist/provider/core.cjs.map +1 -1
- package/dist/provider/core.d.ts +2 -2
- package/dist/provider/core.js +23 -2
- package/dist/provider/core.js.map +1 -1
- package/dist/provider/distinct-values.cjs +65 -0
- package/dist/provider/distinct-values.cjs.map +1 -0
- package/dist/provider/distinct-values.d.ts +21 -0
- package/dist/provider/distinct-values.js +65 -0
- package/dist/provider/distinct-values.js.map +1 -0
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/table-data.cjs +21 -0
- package/dist/provider/table-data.cjs.map +1 -1
- package/dist/provider/table-data.d.ts +22 -0
- package/dist/provider/table-data.js +21 -0
- package/dist/provider/table-data.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +27 -4
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/components/indicators/unified-filters.ts +40 -10
- package/src/data-panel.module.sass +2 -3
- package/src/data-panel.ts +3 -1
- package/src/data-sheet.ts +3 -1
- package/src/postgrest-table/data-loaders.ts +106 -3
- package/src/provider/core.ts +36 -3
- package/src/provider/distinct-values.ts +127 -0
- package/src/provider/index.ts +1 -0
- package/src/provider/table-data.ts +51 -0
- package/src/types.ts +33 -4
package/dist/types.d.ts
CHANGED
|
@@ -1,11 +1,26 @@
|
|
|
1
|
-
import { EditEvent, FetchData, InteractionOptions, RowHeaderRenderContext, RowStatusStyles, TableDataProvider, TableElementStatus, VisibleCells, ColumnSpec, ColumnSpecOptions } from './provider';
|
|
1
|
+
import { EditEvent, FetchData, InteractionOptions, RowHeaderRenderContext, RowStatusStyles, TableDataProvider, TableElementStatus, VisibleCells, ColumnSort, ColumnSpec, ColumnSpecOptions } from './provider';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { TableAction, TableActionContext, TableFilter } from './actions';
|
|
3
|
+
import { ActiveFilterEntry, TableAction, TableActionContext, TableFilter } from './actions';
|
|
4
4
|
import { Region, TableProps } from '@blueprintjs/table';
|
|
5
5
|
export type FetchMode = "scroll" | "paged";
|
|
6
|
-
export interface
|
|
6
|
+
export interface InitialDataChunk<T = any> {
|
|
7
|
+
rows: T[];
|
|
8
|
+
/** Total rows in the source, when the caller's fetch reported it. */
|
|
9
|
+
totalCount?: number | null;
|
|
10
|
+
}
|
|
11
|
+
export interface FetchDataOptions<T = any> {
|
|
7
12
|
pageSize?: number;
|
|
8
13
|
fetchMode?: FetchMode;
|
|
14
|
+
/** Rows already in hand for the first window — typically fetched outside the
|
|
15
|
+
* view (a server render, a parent that needed the data anyway) — so mounting
|
|
16
|
+
* doesn't re-request a page the caller already has. The loader starts
|
|
17
|
+
* populated and initialized; scrolling past the seed fetches as usual, and any
|
|
18
|
+
* view change discards it and re-fetches (the seed only describes the view it
|
|
19
|
+
* was fetched for, so pass matching `initialFilters` / `initialSorts`).
|
|
20
|
+
*
|
|
21
|
+
* Pass `totalCount` when it's known — the array is pre-sized to it, so the
|
|
22
|
+
* scrollbar and the counter are right from the first paint. */
|
|
23
|
+
initialData?: T[] | InitialDataChunk<T>;
|
|
9
24
|
/** Debounce (ms) applied to view-state → refetch, so rapid changes (typing a
|
|
10
25
|
* text filter) collapse into one fetch once the view settles. The input stays
|
|
11
26
|
* instant; only the fetch waits. `0` (default) keeps immediate refetching. */
|
|
@@ -42,8 +57,16 @@ export interface DataViewCoreProps<T> extends InteractionOptions {
|
|
|
42
57
|
/** Bump to force a re-fetch from scratch (e.g. after an immediate edit that
|
|
43
58
|
* mutated rows through the provider). */
|
|
44
59
|
refreshToken?: number | string;
|
|
60
|
+
/** Filters active from the start, applied when the store is *created* rather
|
|
61
|
+
* than in an effect — so a restored view (from a link, a saved query, a
|
|
62
|
+
* server render) never fires an unfiltered fetch first and immediately
|
|
63
|
+
* supersedes it. Uncontrolled: the user's later changes win, and changing
|
|
64
|
+
* this prop afterwards does nothing. */
|
|
65
|
+
initialFilters?: ActiveFilterEntry[];
|
|
66
|
+
/** Sorts active from the start. Same contract as `initialFilters`. */
|
|
67
|
+
initialSorts?: ColumnSort[];
|
|
45
68
|
}
|
|
46
|
-
export interface DataViewSharedProps<T = any> extends FetchDataOptions
|
|
69
|
+
export interface DataViewSharedProps<T = any> extends FetchDataOptions<T>, DataViewCoreProps<T> {
|
|
47
70
|
/** Configurable table actions shown in a selection-aware toolbar.
|
|
48
71
|
* When provided, the actions toolbar renders alongside the existing
|
|
49
72
|
* edit toolbar. Actions are filtered by the current selection cardinality. */
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport {
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import {\n EditEvent,\n FetchData,\n InteractionOptions,\n RowHeaderRenderContext,\n RowStatusStyles,\n TableDataProvider,\n TableElementStatus,\n VisibleCells,\n} from \"./provider\";\nimport type { ColumnSort, ColumnSpec, ColumnSpecOptions } from \"./provider\";\nimport { ReactNode } from \"react\";\nimport {\n ActiveFilterEntry,\n TableAction,\n TableActionContext,\n TableFilter,\n} from \"./actions\";\nimport { Region, TableProps } from \"@blueprintjs/table\";\n\nexport type FetchMode = \"scroll\" | \"paged\";\n\nexport interface InitialDataChunk<T = any> {\n rows: T[];\n /** Total rows in the source, when the caller's fetch reported it. */\n totalCount?: number | null;\n}\n\nexport interface FetchDataOptions<T = any> {\n pageSize?: number;\n fetchMode?: FetchMode;\n /** Rows already in hand for the first window — typically fetched outside the\n * view (a server render, a parent that needed the data anyway) — so mounting\n * doesn't re-request a page the caller already has. The loader starts\n * populated and initialized; scrolling past the seed fetches as usual, and any\n * view change discards it and re-fetches (the seed only describes the view it\n * was fetched for, so pass matching `initialFilters` / `initialSorts`).\n *\n * Pass `totalCount` when it's known — the array is pre-sized to it, so the\n * scrollbar and the counter are right from the first paint. */\n initialData?: T[] | InitialDataChunk<T>;\n /** Debounce (ms) applied to view-state → refetch, so rapid changes (typing a\n * text filter) collapse into one fetch once the view settles. The input stays\n * instant; only the fetch waits. `0` (default) keeps immediate refetching. */\n filterDebounce?: number;\n}\n\n/** Props shared between the wrapper components and the provider */\nexport interface DataViewCoreProps<T> extends InteractionOptions {\n /** In-memory rows. Internally wrapped in a local `TableDataProvider` and\n * driven through the same loader as any other source. */\n data?: T[];\n /** Column definitions. Either a static array, or a function derived from the\n * loaded rows — invoked once the first rows arrive (and re-invoked when the\n * function's identity changes), so a data-shaped spec needs no separate fetch\n * of sample data. Omit entirely to auto-generate a plain spec via\n * `columnSpecOptions`. */\n columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);\n columnSpecOptions?: ColumnSpecOptions<T>;\n enableColumnReordering?: boolean;\n defaultColumnWidth?: number;\n // function to fetch a chunk of data (the read side of a data provider)\n fetchData?: FetchData<T>;\n /** A data provider instantiated separately and passed in — bundles the read\n * side (`fetchData` + `identity`) and, optionally, the persistence side\n * (`saveRows` / `deleteRows` / `insertRow`) that drives the Save action. An\n * explicit alternative to the loose `data` / `fetchData` / `identity` props;\n * takes precedence when given. */\n provider?: TableDataProvider<T>;\n /** Row identity for the edit overlay — stable across a provider re-sort (a\n * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits\n * survive a re-ordered re-fetch. */\n identity?: (row: T) => string | number | null | undefined;\n /** Shown as the toolbar's leading label when nothing is selected. */\n name?: string;\n // itemLabel (e.g., \"row\", \"item\")\n itemLabel?: string;\n /** Bump to force a re-fetch from scratch (e.g. after an immediate edit that\n * mutated rows through the provider). */\n refreshToken?: number | string;\n /** Filters active from the start, applied when the store is *created* rather\n * than in an effect — so a restored view (from a link, a saved query, a\n * server render) never fires an unfiltered fetch first and immediately\n * supersedes it. Uncontrolled: the user's later changes win, and changing\n * this prop afterwards does nothing. */\n initialFilters?: ActiveFilterEntry[];\n /** Sorts active from the start. Same contract as `initialFilters`. */\n initialSorts?: ColumnSort[];\n}\n\nexport interface DataViewSharedProps<T = any>\n extends FetchDataOptions<T>, DataViewCoreProps<T> {\n /** Configurable table actions shown in a selection-aware toolbar.\n * When provided, the actions toolbar renders alongside the existing\n * edit toolbar. Actions are filtered by the current selection cardinality. */\n actions?: TableAction<T>[];\n /** Available column/table filters shown in a filter bar.\n * Filters can also be defined per-column via `ColumnSpec.filters`. */\n filters?: TableFilter<T>[];\n //enableSelection?: boolean;\n}\n\nexport enum DataSheetDensity {\n HIGH = \"high\",\n MEDIUM = \"medium\",\n LOW = \"low\",\n}\n\n/**\n * How selecting a cell activates its surface (an editor, or a read-only detail\n * panel):\n * - `\"auto\"` (default when `autoFocusEditor` is `true`): open the surface on\n * selection and, for editors, focus it. Editors relinquish focus at their\n * edges — arrow past the start/end of a text cell, or press Escape, and focus\n * returns to the table — so the keyboard stays operable without the mouse.\n * Pressing Escape drops into navigation mode (surfaces stop auto-opening)\n * until the next click.\n * - `\"manual\"` (default when `autoFocusEditor` is `false`): the surface stays\n * closed until the cell is clicked; arrow keys always navigate the table.\n */\nexport type CellInteraction = \"auto\" | \"manual\";\n\nexport interface DataSheetRendererProps<T = any>\n extends TableProps, DataViewSharedProps<T> {\n onVisibleCellsChange?: (visibleCells: VisibleCells) => void;\n onUpdateData?: (updatedData: any[], data: T[]) => void;\n /** Observer called for every user edit as a structured `EditEvent`\n * (Workstream A). Additive: the built-in `updatedData` overlay still\n * applies. */\n onEdit?: (event: EditEvent<T>) => void;\n /** Controlled edited-cell overlay (Workstream A). When provided, it is\n * synced into the store as the source of truth for edited values — pair with\n * `onEdit` to own edit state externally (e.g. an ops model). Optimistic\n * in-table edits are superseded by the next value you pass back. */\n updatedData?: T[];\n /** Controlled row-status overlay (edited / added / deleted), the companion\n * to `updatedData`. */\n rowStatus?: TableElementStatus[];\n\n /** Derive the controlled edit overlay from the loaded rows, *inside* the\n * sheet. For provider-backed tables whose overlay is a function of the loaded\n * data plus external edit state (e.g. an ops stack): the library owns the\n * rows, so it calls this with them and uses the result as the controlled\n * overlay, re-deriving when the rows — or this function's identity (close it\n * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */\n deriveOverlay?: (rows: T[]) => {\n updatedData: T[];\n rowStatus: TableElementStatus[];\n };\n /** Persistence handler for the built-in Save action. When provided, a Save\n * control is added to the toolbar (always visible, disabled when there are\n * no pending changes). */\n onSave?: (ctx: TableActionContext<T>) => void | Promise<void>;\n onDeleteRows?: (selection: Region[]) => void;\n verbose?: boolean;\n enableColumnReordering?: boolean;\n enableClipboard?: boolean;\n enableFocusedCell?: boolean;\n /** @deprecated Prefer `cellInteraction`. `true` maps to `\"auto\"`,\n * `false` to `\"manual\"`. */\n autoFocusEditor?: boolean;\n /** How selecting a cell activates its surface (editor or detail panel).\n * Defaults from `autoFocusEditor` for backward compatibility. */\n cellInteraction?: CellInteraction;\n density?: DataSheetDensity;\n /** Optional custom column header cell renderer, called for each column.\n * Receives the ColumnSpec and column index; should return a React element\n * (typically a Blueprint ColumnHeaderCell). */\n columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;\n /** Arbitrary nodes for the bottom status bar (left group), rendered beside\n * the active sort/filter tags — the home for view-state controls (show/hide\n * omitted rows/columns, a group-by indicator, etc.). */\n statusBar?: ReactNode;\n /** Presentation per row-status value, merged over the built-in defaults\n * (which style `\"deleted\"`). Supply styles for consumer-defined statuses\n * (e.g. `\"omitted\"`) and/or override the defaults. Each entry may set the\n * cells' style/intent and the row header's style. */\n rowStatusStyles?: RowStatusStyles;\n /** Render the content of a row's header cell (the left gutter). Receives the\n * row, its status, and the default 1-based label; return a node to use, or a\n * nullish value to keep the default. For group-key labels, omit indicators,\n * etc. Header-cell *styling* still comes from `rowStatusStyles`. */\n rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;\n minRowHeight: number;\n defaultColumnWidth: number;\n debug: boolean;\n}\n\nexport type DataSheetProps<T> = DataViewCoreProps<T> &\n DataSheetRendererProps<T>;\n"],"names":["DataSheetDensity"],"mappings":"AAsGO,IAAK,qCAAAA,sBAAL;AACLA,oBAAA,MAAA,IAAO;AACPA,oBAAA,QAAA,IAAS;AACTA,oBAAA,KAAA,IAAM;AAHI,SAAAA;AAAA,GAAA,oBAAA,CAAA,CAAA;"}
|
package/package.json
CHANGED
|
@@ -225,8 +225,31 @@ function presentationOf(filter: TableFilter): string {
|
|
|
225
225
|
return filter.presentation ?? "menu";
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
-
|
|
229
|
-
|
|
228
|
+
/** Active-state + clear for a subset of filters, keyed by id. */
|
|
229
|
+
function useFilterSubsetState(entries: FilterEntry[]): [boolean, () => void] {
|
|
230
|
+
const ids = entries.map((e) => e.filter.id);
|
|
231
|
+
const key = ids.join("\u0000");
|
|
232
|
+
const subsetAtom = useMemo(
|
|
233
|
+
() =>
|
|
234
|
+
atom(
|
|
235
|
+
(get) => {
|
|
236
|
+
const active = get(storeAtom)?.activeFilters;
|
|
237
|
+
if (active == null) return false;
|
|
238
|
+
return ids.some((id) => active.has(id));
|
|
239
|
+
},
|
|
240
|
+
(get) => {
|
|
241
|
+
const store = get(storeAtom);
|
|
242
|
+
if (store == null) return;
|
|
243
|
+
for (const id of ids) store.removeFilter(id);
|
|
244
|
+
},
|
|
245
|
+
),
|
|
246
|
+
[key],
|
|
247
|
+
);
|
|
248
|
+
const [hasActive, clear] = ctx.use(subsetAtom);
|
|
249
|
+
return [hasActive, clear as () => void];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function useDisplayIntent([hasActive, clearActive]: [boolean, () => void]) {
|
|
230
253
|
const intent = hasActive ? "primary" : "none";
|
|
231
254
|
|
|
232
255
|
let rightIcon: "caret-down" | undefined = "caret-down";
|
|
@@ -243,7 +266,11 @@ function useDisplayIntent(atom) {
|
|
|
243
266
|
}
|
|
244
267
|
|
|
245
268
|
function useFilterMenuAction(entries: FilterEntry[]): TableAction | null {
|
|
246
|
-
|
|
269
|
+
// Scoped to the filters this menu actually holds. An `"inline"` filter has
|
|
270
|
+
// its own always-visible control, so it must not light up the Filter tag —
|
|
271
|
+
// nor be wiped by its clear button, which reads as "clear the filters in
|
|
272
|
+
// here".
|
|
273
|
+
const rest = useDisplayIntent(useFilterSubsetState(entries));
|
|
247
274
|
|
|
248
275
|
if (entries.length === 0) return null;
|
|
249
276
|
|
|
@@ -291,7 +318,7 @@ function useFilterMenuAction(entries: FilterEntry[]): TableAction | null {
|
|
|
291
318
|
function useSortAction(): TableAction | null {
|
|
292
319
|
const columnSpec = useSelector((s) => s.columnSpec);
|
|
293
320
|
|
|
294
|
-
const rest = useDisplayIntent(hasActiveSortsAtom);
|
|
321
|
+
const rest = useDisplayIntent(ctx.use(hasActiveSortsAtom));
|
|
295
322
|
|
|
296
323
|
const sortableCols = useMemo(
|
|
297
324
|
() => columnSpec.filter((c) => c.sortable),
|
|
@@ -330,15 +357,18 @@ function useSortAction(): TableAction | null {
|
|
|
330
357
|
};
|
|
331
358
|
}
|
|
332
359
|
|
|
360
|
+
// Both of these clear through the store's *actions* rather than writing the
|
|
361
|
+
// state directly: the actions are what also drop a now-meaningless row
|
|
362
|
+
// selection (see `dropRowSelection`).
|
|
333
363
|
const hasActiveFiltersAtom = atom(
|
|
334
|
-
(get) => get(storeAtom)?.activeFilters
|
|
335
|
-
(get
|
|
336
|
-
|
|
364
|
+
(get) => (get(storeAtom)?.activeFilters?.size ?? 0) > 0,
|
|
365
|
+
(get) => {
|
|
366
|
+
get(storeAtom)?.clearFilters?.();
|
|
337
367
|
},
|
|
338
368
|
);
|
|
339
369
|
const hasActiveSortsAtom = atom(
|
|
340
|
-
(get) => get(storeAtom)?.columnSorts
|
|
341
|
-
(get
|
|
342
|
-
|
|
370
|
+
(get) => (get(storeAtom)?.columnSorts?.length ?? 0) > 0,
|
|
371
|
+
(get) => {
|
|
372
|
+
get(storeAtom)?.clearColumnSorts?.();
|
|
343
373
|
},
|
|
344
374
|
);
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
--data-panel-content-padding: 12px
|
|
15
15
|
--data-panel-item-gap: 8px
|
|
16
16
|
// Fallback to percentage
|
|
17
|
-
--data-panel-content-width:
|
|
17
|
+
--data-panel-content-width: 100%
|
|
18
18
|
|
|
19
19
|
--data-panel-selected-color: #2d72d2
|
|
20
20
|
--data-panel-selected-background: rgba(45, 114, 210, 0.1)
|
|
@@ -173,8 +173,7 @@
|
|
|
173
173
|
width: unset
|
|
174
174
|
|
|
175
175
|
.data-panel-toolbar
|
|
176
|
-
left:
|
|
177
|
-
transform: translateX(calc((var(--data-panel-content-width, 100cqw) / -2) + var(--data-panel-content-padding) - 4px))
|
|
176
|
+
left: calc(var(--data-panel-content-padding, 12px) - 4px)
|
|
178
177
|
top: var(--data-panel-content-padding, 12px)
|
|
179
178
|
background-color: var(--panel-secondary-background-color)
|
|
180
179
|
box-shadow: 0 0 0 1px var(--panel-rule-color)
|
package/src/data-panel.ts
CHANGED
|
@@ -189,6 +189,7 @@ export function DataPanelRenderer<T>({
|
|
|
189
189
|
filters = [],
|
|
190
190
|
pageSize = 50,
|
|
191
191
|
filterDebounce,
|
|
192
|
+
initialData,
|
|
192
193
|
name,
|
|
193
194
|
// Bottom bar
|
|
194
195
|
statusBar,
|
|
@@ -352,6 +353,7 @@ export function DataPanelRenderer<T>({
|
|
|
352
353
|
pageSize: loaderPageSize,
|
|
353
354
|
fetchMode: isLocalProvider ? undefined : "scroll",
|
|
354
355
|
filterDebounce,
|
|
356
|
+
initialData,
|
|
355
357
|
});
|
|
356
358
|
}
|
|
357
359
|
|
|
@@ -472,7 +474,7 @@ function DefaultScrollBody({ children }: { children: ReactNode }) {
|
|
|
472
474
|
function PanelLoader<T = any>({
|
|
473
475
|
fetchData,
|
|
474
476
|
...options
|
|
475
|
-
}: { fetchData: FetchData<T> } & FetchDataOptions) {
|
|
477
|
+
}: { fetchData: FetchData<T> } & FetchDataOptions<T>) {
|
|
476
478
|
useDataLoader(fetchData, options);
|
|
477
479
|
return null;
|
|
478
480
|
}
|
package/src/data-sheet.ts
CHANGED
|
@@ -109,6 +109,7 @@ export function DataSheetRenderer<T>({
|
|
|
109
109
|
pageSize,
|
|
110
110
|
fetchMode,
|
|
111
111
|
filterDebounce,
|
|
112
|
+
initialData,
|
|
112
113
|
onVisibleCellsChange,
|
|
113
114
|
onUpdateData,
|
|
114
115
|
onEdit,
|
|
@@ -541,6 +542,7 @@ export function DataSheetRenderer<T>({
|
|
|
541
542
|
pageSize: isLocalProvider ? Math.max(localCount, 1) : pageSize,
|
|
542
543
|
fetchMode: isLocalProvider ? undefined : fetchMode,
|
|
543
544
|
filterDebounce,
|
|
545
|
+
initialData,
|
|
544
546
|
});
|
|
545
547
|
}
|
|
546
548
|
const showFilterBar =
|
|
@@ -670,7 +672,7 @@ function _DataLoaderManager<T = any>({
|
|
|
670
672
|
...rest
|
|
671
673
|
}: {
|
|
672
674
|
fetchData: FetchData<T>;
|
|
673
|
-
} & FetchDataOptions) {
|
|
675
|
+
} & FetchDataOptions<any>) {
|
|
674
676
|
useDataLoader(fetchData, rest);
|
|
675
677
|
return null;
|
|
676
678
|
}
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
useSelector,
|
|
23
23
|
} from "../provider";
|
|
24
24
|
import { atom } from "jotai";
|
|
25
|
-
import { FetchDataOptions, FetchMode } from "../types.ts";
|
|
25
|
+
import { FetchDataOptions, FetchMode, InitialDataChunk } from "../types.ts";
|
|
26
26
|
|
|
27
27
|
interface LazyLoaderStateCore<T> {
|
|
28
28
|
loading: boolean;
|
|
@@ -130,6 +130,7 @@ function splitFilterList(value: any): string[] {
|
|
|
130
130
|
|
|
131
131
|
type LazyLoaderAction<T> =
|
|
132
132
|
| { type: "start-loading" }
|
|
133
|
+
| { type: "seed"; data: T[]; totalCount?: number | null }
|
|
133
134
|
| {
|
|
134
135
|
type: "loaded";
|
|
135
136
|
data: T[];
|
|
@@ -199,6 +200,26 @@ function lazyLoadingReducer<T>(
|
|
|
199
200
|
fetchMode: state.fetchMode,
|
|
200
201
|
pageSize: state.pageSize,
|
|
201
202
|
};
|
|
203
|
+
case "seed": {
|
|
204
|
+
// Rows the caller already had (a server render, say). Same shape as a
|
|
205
|
+
// completed first fetch: pre-size to the reported total so the scrollbar
|
|
206
|
+
// and counter are right immediately, and mark the loader `initialized` so
|
|
207
|
+
// it neither refetches the seeded window nor flashes an empty state.
|
|
208
|
+
const rows = action.data ?? [];
|
|
209
|
+
const size = Math.max(action.totalCount ?? rows.length, rows.length);
|
|
210
|
+
const data: (T | null)[] = new Array(size).fill(null);
|
|
211
|
+
for (let i = 0; i < rows.length; i++) data[i] = rows[i];
|
|
212
|
+
return {
|
|
213
|
+
visibleRegion: defaultVisibleRegion,
|
|
214
|
+
data: data as T[],
|
|
215
|
+
loading: false,
|
|
216
|
+
error: null,
|
|
217
|
+
initialized: true,
|
|
218
|
+
totalCount: action.totalCount ?? null,
|
|
219
|
+
fetchMode: state.fetchMode,
|
|
220
|
+
pageSize: state.pageSize,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
202
223
|
case "error":
|
|
203
224
|
return {
|
|
204
225
|
...state,
|
|
@@ -445,6 +466,13 @@ export interface LoadControls {
|
|
|
445
466
|
/** Advance one page *without* resuming a paused auto-load (the sentinel
|
|
446
467
|
* uses this; `loadMore` is the manual, un-pausing variant). */
|
|
447
468
|
advance: () => void;
|
|
469
|
+
/** Rows per page. */
|
|
470
|
+
pageSize: number;
|
|
471
|
+
/** Current page index (0-based). Only meaningful in `"paged"` fetch mode —
|
|
472
|
+
* scroll mode accumulates windows rather than sitting on a page. */
|
|
473
|
+
page: number;
|
|
474
|
+
/** Total pages when the source reported a total, else `null`. */
|
|
475
|
+
totalPages: number | null;
|
|
448
476
|
}
|
|
449
477
|
|
|
450
478
|
/** Store-managed load controls (see `LoadControls`). Reads the loader's footer
|
|
@@ -492,6 +520,14 @@ export function useLoadControls(): LoadControls {
|
|
|
492
520
|
paused,
|
|
493
521
|
canLoadMore,
|
|
494
522
|
advance,
|
|
523
|
+
pageSize,
|
|
524
|
+
page: footer.page,
|
|
525
|
+
totalPages: footer.totalPages,
|
|
526
|
+
// Page addressing is exposed so a footer can render a real link to the next
|
|
527
|
+
// page, not just a button that calls `loadMore`. That's the difference
|
|
528
|
+
// between a list a crawler (or a JS-less client) can follow and one it
|
|
529
|
+
// can't — see the note on crawlable pagination in the Data list editors
|
|
530
|
+
// feature doc.
|
|
495
531
|
};
|
|
496
532
|
}
|
|
497
533
|
|
|
@@ -639,9 +675,14 @@ export function useScrollHandler() {
|
|
|
639
675
|
*/
|
|
640
676
|
export function useDataLoader<T = any>(
|
|
641
677
|
fetchChunk: FetchData<T>,
|
|
642
|
-
options: FetchDataOptions = {},
|
|
678
|
+
options: FetchDataOptions<T> = {},
|
|
643
679
|
) {
|
|
644
|
-
const {
|
|
680
|
+
const {
|
|
681
|
+
pageSize = 100,
|
|
682
|
+
fetchMode = "scroll",
|
|
683
|
+
filterDebounce = 0,
|
|
684
|
+
initialData,
|
|
685
|
+
} = options;
|
|
645
686
|
const [state, dispatch] = useLazyLoaderReducer();
|
|
646
687
|
|
|
647
688
|
const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);
|
|
@@ -692,7 +733,24 @@ export function useDataLoader<T = any>(
|
|
|
692
733
|
// `visibleRegion`/`data`, not this key. `filterDebounce: 0` (default) keeps
|
|
693
734
|
// the immediate behavior.
|
|
694
735
|
const debouncedViewKey = useDebouncedValue(viewKey, filterDebounce);
|
|
736
|
+
// A caller-supplied first window (`initialData`) stands in for the mount-time
|
|
737
|
+
// reset+fetch. It's consumed once: any later view change resets normally,
|
|
738
|
+
// since the seed only describes the view it was fetched for.
|
|
739
|
+
const seedRef = useRef(resolveInitialData(initialData));
|
|
740
|
+
// Gate on the seed until it's actually in state (see the fetch effect).
|
|
741
|
+
const awaitingSeedRef = useRef(seedRef.current != null);
|
|
695
742
|
useEffect(() => {
|
|
743
|
+
const seed = seedRef.current;
|
|
744
|
+
seedRef.current = null;
|
|
745
|
+
if (seed != null) {
|
|
746
|
+
dispatch({ type: "seed", data: seed.rows, totalCount: seed.totalCount });
|
|
747
|
+
setPage(0);
|
|
748
|
+
// Paged mode tracks which (page, view) it has in hand separately from the
|
|
749
|
+
// array; record the seed there too, or it would immediately re-fetch the
|
|
750
|
+
// page it was just handed.
|
|
751
|
+
loadedRef.current = { page: 0, viewKey };
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
696
754
|
dispatch({ type: "reset" });
|
|
697
755
|
setPage(0);
|
|
698
756
|
}, [debouncedViewKey, fetchMode, refreshToken]);
|
|
@@ -700,6 +758,15 @@ export function useDataLoader<T = any>(
|
|
|
700
758
|
useAsyncEffect(async () => {
|
|
701
759
|
if (state.loading) return;
|
|
702
760
|
|
|
761
|
+
// A seed hasn't landed in state yet. Every effect in a commit sees the
|
|
762
|
+
// render's snapshot, so this one runs *before* the seed it was mounted
|
|
763
|
+
// alongside is visible — and would issue exactly the request the seed
|
|
764
|
+
// exists to avoid. Skip until the seeded state arrives.
|
|
765
|
+
if (awaitingSeedRef.current) {
|
|
766
|
+
if (state.initialized) awaitingSeedRef.current = false;
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
|
|
703
770
|
// Determine the chunk offset to fetch, and (scroll mode) a keyset cursor:
|
|
704
771
|
// the already-loaded row just before the chunk, so keyset sources can page
|
|
705
772
|
// from it instead of a slow OFFSET.
|
|
@@ -787,6 +854,21 @@ export function useDataLoader<T = any>(
|
|
|
787
854
|
|
|
788
855
|
/** A value that trails `value` by `delay` ms of stability — the first value is
|
|
789
856
|
* returned immediately, and `delay <= 0` disables debouncing entirely. */
|
|
857
|
+
/** Normalize the two accepted `initialData` shapes (bare rows, or rows with a
|
|
858
|
+
* total) to one. An empty seed is treated as no seed — there'd be nothing to
|
|
859
|
+
* show and nothing saved. */
|
|
860
|
+
function resolveInitialData<T>(
|
|
861
|
+
initialData: FetchDataOptions<T>["initialData"],
|
|
862
|
+
): InitialDataChunk<T> | null {
|
|
863
|
+
if (initialData == null) return null;
|
|
864
|
+
if (Array.isArray(initialData)) {
|
|
865
|
+
if (initialData.length === 0) return null;
|
|
866
|
+
return { rows: initialData };
|
|
867
|
+
}
|
|
868
|
+
if ((initialData.rows ?? []).length === 0) return null;
|
|
869
|
+
return initialData;
|
|
870
|
+
}
|
|
871
|
+
|
|
790
872
|
function useDebouncedValue<T>(value: T, delay: number): T {
|
|
791
873
|
const [debounced, setDebounced] = useState(value);
|
|
792
874
|
useEffect(() => {
|
|
@@ -898,6 +980,27 @@ export function createPostgRESTProvider<T = any>(config: {
|
|
|
898
980
|
return {
|
|
899
981
|
fetchData: createPostgRESTFetchChunk<T>(config),
|
|
900
982
|
identity: (row: any) => row?.[config.identityKey],
|
|
983
|
+
async distinctValues(columnKey, options = {}) {
|
|
984
|
+
// PostgREST derives a GROUP BY from a `select` that mixes a plain column
|
|
985
|
+
// with an aggregate, so one small request returns the whole vocabulary
|
|
986
|
+
// *with* frequencies — rather than paging the table and deduplicating
|
|
987
|
+
// client-side. Ordered by the value so the picker's list is stable.
|
|
988
|
+
//
|
|
989
|
+
// `baseFilter` applies (it defines the rows this view is *about*), but the
|
|
990
|
+
// *active* filters deliberately don't: a picker whose options disappear as
|
|
991
|
+
// you narrow the view can't be used to widen it again.
|
|
992
|
+
let req: any = from().select(`${columnKey},count()`);
|
|
993
|
+
if (config.baseFilter != null) req = config.baseFilter(req);
|
|
994
|
+
req = req.order(columnKey, { ascending: true, nullsFirst: false });
|
|
995
|
+
if (options.limit != null) req = req.limit(options.limit);
|
|
996
|
+
if (options.signal != null) req = req.abortSignal(options.signal);
|
|
997
|
+
const { data, error } = await req;
|
|
998
|
+
if (error != null) throw error;
|
|
999
|
+
return (data ?? []).map((row: any) => ({
|
|
1000
|
+
value: row[columnKey],
|
|
1001
|
+
count: row.count,
|
|
1002
|
+
}));
|
|
1003
|
+
},
|
|
901
1004
|
async saveRows(rows) {
|
|
902
1005
|
const res: any = await from().upsert(rows as any[], {
|
|
903
1006
|
defaultToNull: false,
|
package/src/provider/core.ts
CHANGED
|
@@ -41,7 +41,7 @@ import {
|
|
|
41
41
|
resolveInteractionOptions,
|
|
42
42
|
} from "./interactions.ts";
|
|
43
43
|
import { DataViewProps } from "../data-view.ts";
|
|
44
|
-
import { DataSheetProps } from "../types.ts";
|
|
44
|
+
import { DataSheetProps, DataViewCoreProps } from "../types.ts";
|
|
45
45
|
import { DataPanelProps } from "../data-panel.ts";
|
|
46
46
|
|
|
47
47
|
/** Create a Jotai scoped store */
|
|
@@ -153,12 +153,23 @@ export function useResolvedProvider<T>(props: {
|
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
function DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {
|
|
156
|
-
const { toaster, ...rest } = props;
|
|
156
|
+
const { toaster, initialFilters, initialSorts, ...rest } = props;
|
|
157
|
+
|
|
158
|
+
// Initial view state is folded into the store's *creation*, not applied in an
|
|
159
|
+
// effect: the loader mounts below this and its effects run first, so an
|
|
160
|
+
// effect-applied filter would arrive after the first (unfiltered) fetch had
|
|
161
|
+
// already gone out — and be immediately superseded. Creating the store with
|
|
162
|
+
// the view already set means the first fetch is the right one.
|
|
163
|
+
const initializeStore = (set: any, get: any) => ({
|
|
164
|
+
...createZustandStore<T>(set, get),
|
|
165
|
+
...initialViewState({ initialFilters, initialSorts }),
|
|
166
|
+
});
|
|
167
|
+
|
|
157
168
|
return h(
|
|
158
169
|
ZustandStoreProvider,
|
|
159
170
|
{
|
|
160
171
|
ctx,
|
|
161
|
-
initializeStore
|
|
172
|
+
initializeStore,
|
|
162
173
|
atoms: [[toasterAtom, toaster]],
|
|
163
174
|
debugName: "DataSheetProvider",
|
|
164
175
|
},
|
|
@@ -166,6 +177,26 @@ function DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {
|
|
|
166
177
|
);
|
|
167
178
|
}
|
|
168
179
|
|
|
180
|
+
/** The store fields that carry a caller-supplied starting view. Absent props
|
|
181
|
+
* contribute nothing, so the store's own defaults stand. */
|
|
182
|
+
function initialViewState<T>({
|
|
183
|
+
initialFilters,
|
|
184
|
+
initialSorts,
|
|
185
|
+
}: Pick<DataViewCoreProps<T>, "initialFilters" | "initialSorts">): Partial<
|
|
186
|
+
DataSheetState<T>
|
|
187
|
+
> {
|
|
188
|
+
const state: Partial<DataSheetState<T>> = {};
|
|
189
|
+
if (initialFilters != null && initialFilters.length > 0) {
|
|
190
|
+
state.activeFilters = new Map(
|
|
191
|
+
initialFilters.map((entry) => [entry.filter.id, entry]),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
if (initialSorts != null && initialSorts.length > 0) {
|
|
195
|
+
state.columnSorts = [...initialSorts];
|
|
196
|
+
}
|
|
197
|
+
return state;
|
|
198
|
+
}
|
|
199
|
+
|
|
169
200
|
const tableDataProviderKeys = new Set([
|
|
170
201
|
"provider",
|
|
171
202
|
"fetchData",
|
|
@@ -174,6 +205,8 @@ const tableDataProviderKeys = new Set([
|
|
|
174
205
|
]);
|
|
175
206
|
|
|
176
207
|
const dataProviderKeys = new Set([
|
|
208
|
+
"initialFilters",
|
|
209
|
+
"initialSorts",
|
|
177
210
|
"columnSpec",
|
|
178
211
|
"columnSpecOptions",
|
|
179
212
|
"name",
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a column's vocabulary — the distinct values it holds — so a filter
|
|
3
|
+
* control can offer choices that actually match something.
|
|
4
|
+
*
|
|
5
|
+
* The provider answers the question (`TableDataProvider.distinctValues`); this
|
|
6
|
+
* is the ergonomic half: one hook, one fetch per column per view, shared by
|
|
7
|
+
* every control that asks. Without it every consumer hand-rolls a fetch and a
|
|
8
|
+
* cache per facet, which is exactly what the ingestion list was doing three
|
|
9
|
+
* times over.
|
|
10
|
+
*/
|
|
11
|
+
import { useEffect, useState } from "react";
|
|
12
|
+
import { ctx, dataProviderAtom } from "./core.ts";
|
|
13
|
+
import {
|
|
14
|
+
dataRefreshTokenAtom,
|
|
15
|
+
DistinctValue,
|
|
16
|
+
DistinctValuesOptions,
|
|
17
|
+
TableDataProvider,
|
|
18
|
+
} from "./table-data.ts";
|
|
19
|
+
|
|
20
|
+
export interface DistinctValuesState<V = any> {
|
|
21
|
+
/** The column's values, most useful first (frequency, then value). */
|
|
22
|
+
values: DistinctValue<V>[];
|
|
23
|
+
loading: boolean;
|
|
24
|
+
error: Error | null;
|
|
25
|
+
/** `false` when the source can't answer — a control should fall back to free
|
|
26
|
+
* entry rather than showing an empty list. */
|
|
27
|
+
supported: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const EMPTY: DistinctValue[] = [];
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The distinct values of `columnKey` in the enclosing view's source.
|
|
34
|
+
*
|
|
35
|
+
* Cached per (provider, column, refresh token): controls mount and unmount as
|
|
36
|
+
* menus open, and shouldn't each pay for a request. A provider mutation bumps
|
|
37
|
+
* the refresh token, so a newly-created value shows up without a manual
|
|
38
|
+
* invalidation step.
|
|
39
|
+
*/
|
|
40
|
+
export function useDistinctValues<V = any>(
|
|
41
|
+
columnKey: string | null | undefined,
|
|
42
|
+
options: DistinctValuesOptions = {},
|
|
43
|
+
): DistinctValuesState<V> {
|
|
44
|
+
const { provider } = ctx.useValue(dataProviderAtom);
|
|
45
|
+
const refreshToken = ctx.useValue(dataRefreshTokenAtom);
|
|
46
|
+
const { limit } = options;
|
|
47
|
+
|
|
48
|
+
const supported = provider?.distinctValues != null && columnKey != null;
|
|
49
|
+
const [state, setState] = useState<DistinctValuesState<V>>({
|
|
50
|
+
values: EMPTY,
|
|
51
|
+
loading: supported,
|
|
52
|
+
error: null,
|
|
53
|
+
supported,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (!supported) {
|
|
58
|
+
setState({ values: EMPTY, loading: false, error: null, supported });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
let active = true;
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
setState((prev) => ({ ...prev, loading: true, supported }));
|
|
64
|
+
|
|
65
|
+
read(provider!, columnKey!, refreshToken, limit)
|
|
66
|
+
.then((values) => {
|
|
67
|
+
if (!active) return;
|
|
68
|
+
setState({ values, loading: false, error: null, supported: true });
|
|
69
|
+
})
|
|
70
|
+
.catch((error) => {
|
|
71
|
+
if (!active || controller.signal.aborted) return;
|
|
72
|
+
setState({ values: EMPTY, loading: false, error, supported: true });
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
return () => {
|
|
76
|
+
active = false;
|
|
77
|
+
controller.abort();
|
|
78
|
+
};
|
|
79
|
+
}, [provider, columnKey, refreshToken, limit, supported]);
|
|
80
|
+
|
|
81
|
+
return state;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Just the values, for a control that doesn't care about counts or status. */
|
|
85
|
+
export function useDistinctValueList<V = any>(
|
|
86
|
+
columnKey: string | null | undefined,
|
|
87
|
+
options: DistinctValuesOptions = {},
|
|
88
|
+
): V[] {
|
|
89
|
+
const { values } = useDistinctValues<V>(columnKey, options);
|
|
90
|
+
return values.map((v) => v.value);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// One in-flight-or-settled promise per (provider, column, token, limit). Keyed
|
|
94
|
+
// weakly on the provider so a discarded view's cache goes with it.
|
|
95
|
+
const cache = new WeakMap<
|
|
96
|
+
TableDataProvider<any>,
|
|
97
|
+
Map<string, Promise<DistinctValue[]>>
|
|
98
|
+
>();
|
|
99
|
+
|
|
100
|
+
function read(
|
|
101
|
+
provider: TableDataProvider<any>,
|
|
102
|
+
columnKey: string,
|
|
103
|
+
refreshToken: number,
|
|
104
|
+
limit: number | undefined,
|
|
105
|
+
): Promise<DistinctValue[]> {
|
|
106
|
+
let byKey = cache.get(provider);
|
|
107
|
+
if (byKey == null) {
|
|
108
|
+
byKey = new Map();
|
|
109
|
+
cache.set(provider, byKey);
|
|
110
|
+
}
|
|
111
|
+
const key = `${columnKey} ${refreshToken} ${limit ?? ""}`;
|
|
112
|
+
const cached = byKey.get(key);
|
|
113
|
+
if (cached != null) return cached;
|
|
114
|
+
|
|
115
|
+
// The shared promise deliberately carries no abort signal: one unmounting
|
|
116
|
+
// control must not cancel the fetch for the others. Each caller's own signal
|
|
117
|
+
// only decides whether it still cares about the result.
|
|
118
|
+
const pending = provider.distinctValues!(columnKey, { limit }).catch(
|
|
119
|
+
(error) => {
|
|
120
|
+
// Don't cache a failure — the next control to mount should retry.
|
|
121
|
+
byKey!.delete(key);
|
|
122
|
+
throw error;
|
|
123
|
+
},
|
|
124
|
+
);
|
|
125
|
+
byKey.set(key, pending);
|
|
126
|
+
return pending;
|
|
127
|
+
}
|
package/src/provider/index.ts
CHANGED