@macrostrat/data-sheet 4.0.1 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +11 -1
  3. package/dist/actions/column-controls.cjs +102 -1
  4. package/dist/actions/column-controls.cjs.map +1 -1
  5. package/dist/actions/column-controls.js +104 -3
  6. package/dist/actions/column-controls.js.map +1 -1
  7. package/dist/actions/column-filter.cjs +48 -25
  8. package/dist/actions/column-filter.cjs.map +1 -1
  9. package/dist/actions/column-filter.js +50 -27
  10. package/dist/actions/column-filter.js.map +1 -1
  11. package/dist/actions/selection.cjs +2 -1
  12. package/dist/actions/selection.cjs.map +1 -1
  13. package/dist/actions/selection.js +2 -1
  14. package/dist/actions/selection.js.map +1 -1
  15. package/dist/actions/table-controls.cjs +21 -0
  16. package/dist/actions/table-controls.cjs.map +1 -1
  17. package/dist/actions/table-controls.d.ts +4 -0
  18. package/dist/actions/table-controls.js +21 -0
  19. package/dist/actions/table-controls.js.map +1 -1
  20. package/dist/actions/toolbar.cjs +34 -4
  21. package/dist/actions/toolbar.cjs.map +1 -1
  22. package/dist/actions/toolbar.js +35 -5
  23. package/dist/actions/toolbar.js.map +1 -1
  24. package/dist/actions/types.d.ts +9 -0
  25. package/dist/cell-renderer.cjs +9 -7
  26. package/dist/cell-renderer.cjs.map +1 -1
  27. package/dist/cell-renderer.js +9 -7
  28. package/dist/cell-renderer.js.map +1 -1
  29. package/dist/core.cjs +68 -9
  30. package/dist/core.cjs.map +1 -1
  31. package/dist/core.d.ts +32 -1
  32. package/dist/core.js +69 -10
  33. package/dist/core.js.map +1 -1
  34. package/dist/filters/operators.cjs +2 -2
  35. package/dist/filters/operators.cjs.map +1 -1
  36. package/dist/filters/operators.d.ts +1 -1
  37. package/dist/filters/operators.js +2 -2
  38. package/dist/filters/operators.js.map +1 -1
  39. package/dist/index.cjs +4 -2
  40. package/dist/index.cjs.map +1 -1
  41. package/dist/index.js +4 -2
  42. package/dist/postgrest-table/data-loaders.cjs +1 -8
  43. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  44. package/dist/postgrest-table/data-loaders.js +1 -8
  45. package/dist/postgrest-table/data-loaders.js.map +1 -1
  46. package/dist/provider.cjs +9 -3
  47. package/dist/provider.cjs.map +1 -1
  48. package/dist/provider.d.ts +2 -1
  49. package/dist/provider.js +9 -3
  50. package/dist/provider.js.map +1 -1
  51. package/dist/renderers/column-header-cell.cjs +33 -32
  52. package/dist/renderers/column-header-cell.cjs.map +1 -1
  53. package/dist/renderers/column-header-cell.d.ts +1 -2
  54. package/dist/renderers/column-header-cell.js +34 -33
  55. package/dist/renderers/column-header-cell.js.map +1 -1
  56. package/dist/types.cjs +11 -0
  57. package/dist/types.cjs.map +1 -1
  58. package/dist/types.d.ts +55 -2
  59. package/dist/types.js +11 -0
  60. package/dist/types.js.map +1 -1
  61. package/dist/utils/column-spec.cjs.map +1 -1
  62. package/dist/utils/column-spec.d.ts +8 -0
  63. package/dist/utils/column-spec.js.map +1 -1
  64. package/dist/zustand-store.cjs +7 -3
  65. package/dist/zustand-store.cjs.map +1 -1
  66. package/dist/zustand-store.js +8 -4
  67. package/dist/zustand-store.js.map +1 -1
  68. package/package.json +1 -1
  69. package/src/actions/column-controls.ts +133 -2
  70. package/src/actions/column-filter.ts +59 -30
  71. package/src/actions/selection.ts +1 -0
  72. package/src/actions/table-controls.ts +24 -0
  73. package/src/actions/toolbar.ts +61 -5
  74. package/src/actions/types.ts +10 -0
  75. package/src/cell-renderer.ts +23 -10
  76. package/src/core.ts +131 -13
  77. package/src/filters/operators.ts +5 -3
  78. package/src/postgrest-table/data-loaders.ts +6 -10
  79. package/src/provider.ts +22 -5
  80. package/src/renderers/column-header-cell.ts +51 -36
  81. package/src/types.ts +66 -2
  82. package/src/utils/column-spec.ts +8 -0
  83. package/src/zustand-store.ts +12 -5
@@ -37,7 +37,11 @@ export function basicCellRenderer<T>(
37
37
  const data = state.data;
38
38
  const updatedData = state.updatedData;
39
39
 
40
- const isDeleted = state.rowStatus[dataRowIndex] == TableElementStatus.DELETED;
40
+ const statusVal = state.rowStatus[dataRowIndex];
41
+ const isDeleted = statusVal == TableElementStatus.DELETED;
42
+ // Presentation for this row's status (deleted, or a consumer-defined status
43
+ // like "omitted"), from the merged `rowStatusStyles`.
44
+ const statusStyle = statusVal != null ? state.rowStatusStyles?.[statusVal] : undefined;
41
45
 
42
46
  const row = data[dataRowIndex] ?? updatedData[dataRowIndex];
43
47
  const loading = row == null;
@@ -68,6 +72,7 @@ export function basicCellRenderer<T>(
68
72
  row,
69
73
  isEdited: edited,
70
74
  isDeleted,
75
+ status: statusVal,
71
76
  validation,
72
77
  };
73
78
 
@@ -75,12 +80,13 @@ export function basicCellRenderer<T>(
75
80
  ? null
76
81
  : (col.valueRenderer?.(value, cellContext) ?? value);
77
82
 
78
- // Clone so we never mutate the caller's column-spec style object
83
+ // Clone so we never mutate the caller's column-spec style object, then layer
84
+ // the row-status presentation (deleted → dimmed/struck-through by default;
85
+ // consumer statuses supply their own `cellStyle`).
79
86
  let style = { ...(col.style ?? {}) };
80
87
 
81
- if (isDeleted) {
82
- style.opacity = 0.5;
83
- style.textDecoration = "line-through";
88
+ if (statusStyle?.cellStyle != null) {
89
+ style = { ...style, ...statusStyle.cellStyle };
84
90
  }
85
91
 
86
92
  const editable = (col.editable ?? state.editable) && !isDeleted;
@@ -91,15 +97,17 @@ export function basicCellRenderer<T>(
91
97
 
92
98
  const tableIsEditable = state.editable;
93
99
 
94
- // Intent precedence: error > warning > deleted > edited. Validation state
95
- // overrides the edited-green so an edited-but-invalid cell reads as invalid.
100
+ // Intent precedence: error > warning > row-status intent > edited. Validation
101
+ // state overrides the edited-green so an edited-but-invalid cell reads as
102
+ // invalid. A row's status intent (e.g. deleted → danger) outranks the
103
+ // edited-green so status reads through even on an edited row.
96
104
  let intent: string | undefined;
97
105
  if (validation?.severity === "error") {
98
106
  intent = "danger";
99
107
  } else if (validation?.severity === "warning") {
100
108
  intent = "warning";
101
- } else if (isDeleted) {
102
- intent = "danger";
109
+ } else if (statusStyle?.intent != null) {
110
+ intent = statusStyle.intent;
103
111
  } else if (edited) {
104
112
  intent = "success";
105
113
  }
@@ -279,7 +287,12 @@ export function basicCellRenderer<T>(
279
287
  isEdited: edited,
280
288
  onChange(value) {
281
289
  if (!editable) return;
282
- state.onSelectionEdited(value);
290
+ // Commit to THIS cell — not the live selection. The editor can
291
+ // commit (e.g. on blur) after the selection has moved to another
292
+ // cell or a whole column; `onSelectionEdited` would then write the
293
+ // value to the wrong target (emptying it). `onCellEdited` addresses
294
+ // the editor's own data cell.
295
+ state.onCellEdited(dataRowIndex, col.key, value);
283
296
  },
284
297
  resetValue() {
285
298
  state.resetChanges();
package/src/core.ts CHANGED
@@ -24,12 +24,19 @@ import {
24
24
  import { atom } from "jotai";
25
25
  import {
26
26
  DataSheetProviderProps,
27
+ DEFAULT_ROW_STATUS_STYLES,
27
28
  EditEvent,
29
+ RowHeaderRenderContext,
30
+ RowStatusStyles,
28
31
  TableElementStatus,
29
32
  VisibleCells,
30
33
  } from "./types.ts";
31
34
  import { basicCellRenderer } from "./cell-renderer.ts";
32
- import { CellRendererDebugOverlay, tableHotkeysAtom } from "./utils";
35
+ import {
36
+ CellRendererDebugOverlay,
37
+ tableHotkeysAtom,
38
+ type ColumnSpec,
39
+ } from "./utils";
33
40
  import {
34
41
  ActionsToolbar,
35
42
  clipboardActions,
@@ -85,6 +92,9 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
85
92
  /** In-memory rows. Internally wrapped in a local `TableDataProvider` and
86
93
  * driven through the same loader as any other source. */
87
94
  data?: T[];
95
+ /** Passed through from the public props so a function form can be derived
96
+ * from the loaded rows here (a static array is handled by the provider). */
97
+ columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);
88
98
  // function to fetch a chunk of data (the read side of a data provider)
89
99
  fetchData?: FetchData<T>;
90
100
  /** A data provider instantiated separately and passed in — bundles the read
@@ -113,6 +123,19 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
113
123
  * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits
114
124
  * survive a re-ordered re-fetch. */
115
125
  identity?: (row: T) => string | number | null | undefined;
126
+ /** Derive the controlled edit overlay from the loaded rows, *inside* the
127
+ * sheet. For provider-backed tables whose overlay is a function of the loaded
128
+ * data plus external edit state (e.g. an ops stack): the library owns the
129
+ * rows, so it calls this with them and uses the result as the controlled
130
+ * overlay, re-deriving when the rows — or this function's identity (close it
131
+ * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */
132
+ deriveOverlay?: (rows: T[]) => {
133
+ updatedData: T[];
134
+ rowStatus: TableElementStatus[];
135
+ };
136
+ /** Bump to force the data provider to re-fetch from scratch (e.g. after a
137
+ * save/delete that invalidated the loaded rows). */
138
+ refreshToken?: number | string;
116
139
  /** Persistence handler for the built-in Save action. When provided, a Save
117
140
  * control is added to the toolbar (always visible, disabled when there are
118
141
  * no pending changes). */
@@ -141,6 +164,20 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
141
164
  * Receives the ColumnSpec and column index; should return a React element
142
165
  * (typically a Blueprint ColumnHeaderCell). */
143
166
  columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;
167
+ /** Arbitrary nodes for the bottom status bar (left group), rendered beside
168
+ * the active sort/filter tags — the home for view-state controls (show/hide
169
+ * omitted rows/columns, a group-by indicator, etc.). */
170
+ statusBar?: ReactNode;
171
+ /** Presentation per row-status value, merged over the built-in defaults
172
+ * (which style `"deleted"`). Supply styles for consumer-defined statuses
173
+ * (e.g. `"omitted"`) and/or override the defaults. Each entry may set the
174
+ * cells' style/intent and the row header's style. */
175
+ rowStatusStyles?: RowStatusStyles;
176
+ /** Render the content of a row's header cell (the left gutter). Receives the
177
+ * row, its status, and the default 1-based label; return a node to use, or a
178
+ * nullish value to keep the default. For group-key labels, omit indicators,
179
+ * etc. Header-cell *styling* still comes from `rowStatusStyles`. */
180
+ rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;
144
181
  }
145
182
 
146
183
  type DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;
@@ -174,6 +211,7 @@ export function DataSheet<T>(props: DataSheetProps<T>) {
174
211
  h(_DataSheet<any>, {
175
212
  ...rest,
176
213
  data: data ?? emptyData,
214
+ columnSpec,
177
215
  children,
178
216
  editable,
179
217
  enableColumnReordering,
@@ -182,11 +220,6 @@ export function DataSheet<T>(props: DataSheetProps<T>) {
182
220
  );
183
221
  }
184
222
 
185
- const deletedRowHeaderStyle = {
186
- opacity: 0.5,
187
- textDecoration: "line-through",
188
- };
189
-
190
223
  /** Persist all pending changes through a data provider: added rows via
191
224
  * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`
192
225
  * (addressed by `provider.identity`). Used by the built-in Save action when an
@@ -241,6 +274,8 @@ function _DataSheet<T>({
241
274
  updatedData: updatedDataProp,
242
275
  rowStatus: rowStatusProp,
243
276
  identity,
277
+ deriveOverlay,
278
+ refreshToken,
244
279
  onDeleteRows,
245
280
  name,
246
281
  verbose = false,
@@ -253,6 +288,10 @@ function _DataSheet<T>({
253
288
  actions,
254
289
  filters,
255
290
  columnHeaderCellRenderer,
291
+ columnSpec: columnSpecProp,
292
+ statusBar,
293
+ rowStatusStyles,
294
+ rowHeaderRenderer,
256
295
  children,
257
296
  ...rest
258
297
  }: DataSheetInternalProps<T>) {
@@ -455,12 +494,57 @@ function _DataSheet<T>({
455
494
  // next render when the caller passes an updated value back. When the caller
456
495
  // controls it, the loader-boundary identity remap steps aside.
457
496
  const controlled =
458
- updatedDataProp !== undefined || rowStatusProp !== undefined;
497
+ updatedDataProp !== undefined ||
498
+ rowStatusProp !== undefined ||
499
+ deriveOverlay != null;
459
500
  const patch: Record<string, unknown> = { controlledOverlay: controlled };
460
501
  if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;
461
502
  if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;
462
503
  storeState.setState(patch);
463
- }, [storeState, updatedDataProp, rowStatusProp]);
504
+ }, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);
505
+
506
+ // Derived controlled overlay: the library owns the loaded rows, so it runs
507
+ // the consumer's `deriveOverlay(rows)` here and pushes the result. Re-derives
508
+ // when the rows load/change or the function's identity changes (close it over
509
+ // your external edit state). The `controlledOverlay` flag above suppresses the
510
+ // loader-boundary identity remap so this derivation is authoritative.
511
+ const loadedData = useSelector((state) => state.data);
512
+ useEffect(() => {
513
+ if (deriveOverlay == null) return;
514
+ const overlay = deriveOverlay(loadedData);
515
+ storeState.setState({
516
+ updatedData: overlay.updatedData,
517
+ rowStatus: overlay.rowStatus,
518
+ });
519
+ }, [deriveOverlay, loadedData, storeState]);
520
+
521
+ // Function `columnSpec`: derive the spec from the loaded rows (no separate
522
+ // fetch of sample data). Derive once the first rows arrive, and re-derive
523
+ // when the function's identity changes (a consumer memoizes it over its
524
+ // own view state — hidden columns, order, overrides). Not re-run as more
525
+ // rows page in (guarded by the function identity), so it never clobbers
526
+ // in-store column state on scroll.
527
+ const derivedSpecFor = useRef<unknown>(null);
528
+ useEffect(() => {
529
+ if (typeof columnSpecProp !== "function") return;
530
+ if (derivedSpecFor.current === columnSpecProp) return;
531
+ const rows = loadedData.filter((r) => r != null);
532
+ if (rows.length === 0) return;
533
+ derivedSpecFor.current = columnSpecProp;
534
+ storeState.setState({ columnSpec: columnSpecProp(rows) });
535
+ }, [columnSpecProp, loadedData, storeState]);
536
+
537
+ // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g. after
538
+ // a save). Skips the initial mount (the loader does its own first fetch).
539
+ const bumpRefreshFromToken = ctx.useSet(dataRefreshTokenAtom);
540
+ const firstRefreshToken = useRef(true);
541
+ useEffect(() => {
542
+ if (firstRefreshToken.current) {
543
+ firstRefreshToken.current = false;
544
+ return;
545
+ }
546
+ bumpRefreshFromToken((v) => v + 1);
547
+ }, [refreshToken, bumpRefreshFromToken]);
464
548
 
465
549
  // The active provider supplies the row identity for the edit overlay.
466
550
  useEffect(() => {
@@ -476,6 +560,17 @@ function _DataSheet<T>({
476
560
  storeState.setState({ canDeleteRows });
477
561
  }, [storeState, provider]);
478
562
 
563
+ // Merge consumer `rowStatusStyles` over the built-in defaults and hand the
564
+ // result to the store, where the cell renderer and row-header renderer read
565
+ // it. Merged (not replaced) so overriding one status doesn't drop the rest.
566
+ const mergedRowStatusStyles = useMemo<RowStatusStyles>(
567
+ () => ({ ...DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),
568
+ [rowStatusStyles],
569
+ );
570
+ useEffect(() => {
571
+ storeState.setState({ rowStatusStyles: mergedRowStatusStyles });
572
+ }, [storeState, mergedRowStatusStyles]);
573
+
479
574
  const realizedColumns = useMemo(() => {
480
575
  return columnSpec.map((col, colIndex) => {
481
576
  let fn =
@@ -541,19 +636,41 @@ function _DataSheet<T>({
541
636
  filteredRowIndices != null
542
637
  ? (filteredRowIndices[rowIndex] ?? rowIndex)
543
638
  : rowIndex;
639
+ const statusVal = rowStatus[dataRowIndex];
544
640
  const style =
545
- rowStatus[dataRowIndex] == TableElementStatus.DELETED
546
- ? deletedRowHeaderStyle
547
- : null;
641
+ (statusVal != null
642
+ ? mergedRowStatusStyles[statusVal]?.headerStyle
643
+ : null) ?? null;
644
+
645
+ const defaultLabel = `${dataRowIndex + 1}`;
646
+ let name: ReactNode = defaultLabel;
647
+ if (rowHeaderRenderer != null) {
648
+ const custom = rowHeaderRenderer({
649
+ rowIndex: dataRowIndex,
650
+ visibleIndex: rowIndex,
651
+ row: data[dataRowIndex] ?? updatedData[dataRowIndex],
652
+ status: statusVal,
653
+ isDeleted: statusVal === TableElementStatus.DELETED,
654
+ defaultLabel,
655
+ });
656
+ if (custom != null) name = custom;
657
+ }
548
658
 
549
659
  return h(RowHeaderCell, {
550
660
  enableRowReordering: false,
551
661
  index: rowIndex,
552
- name: `${dataRowIndex + 1}`,
662
+ name,
553
663
  style,
554
664
  });
555
665
  },
556
- [rowStatus, filteredRowIndices],
666
+ [
667
+ rowStatus,
668
+ filteredRowIndices,
669
+ mergedRowStatusStyles,
670
+ rowHeaderRenderer,
671
+ data,
672
+ updatedData,
673
+ ],
557
674
  );
558
675
 
559
676
  let _selectionModes = selectionModes;
@@ -644,6 +761,7 @@ function _DataSheet<T>({
644
761
  ),
645
762
  h("div.status-bar", [
646
763
  filterStatus,
764
+ statusBar,
647
765
  h("div.spacer"),
648
766
  h.if(_showLoadProgress)(LoadProgressIndicator),
649
767
  ]),
@@ -32,7 +32,9 @@ export const OPERATOR_LABELS: Record<FilterOperator, string> = {
32
32
  is: "is",
33
33
  };
34
34
 
35
- const STRING_OPERATORS: FilterOperator[] = ["eq", "neq", "ilike"];
35
+ // "contains" (`ilike`) leads for text, so it's the default operator — the most
36
+ // common intent when filtering a string column.
37
+ const STRING_OPERATORS: FilterOperator[] = ["ilike", "eq", "neq"];
36
38
  const NUMERIC_OPERATORS: FilterOperator[] = [
37
39
  "eq",
38
40
  "neq",
@@ -43,11 +45,11 @@ const NUMERIC_OPERATORS: FilterOperator[] = [
43
45
  ];
44
46
  const BOOLEAN_OPERATORS: FilterOperator[] = ["eq", "neq"];
45
47
 
46
- /** Fallback when the column has no type information. */
48
+ /** Fallback when the column has no type information. Leads with "contains". */
47
49
  export const DEFAULT_FILTER_OPERATORS: FilterOperator[] = [
50
+ "ilike",
48
51
  "eq",
49
52
  "neq",
50
- "ilike",
51
53
  "gt",
52
54
  "lt",
53
55
  "gte",
@@ -109,7 +109,6 @@ type LazyLoaderAction<T> =
109
109
  | { type: "error"; error: Error }
110
110
  | { type: "update-data"; changes: Spec<T[]> }
111
111
  | { type: "reset" }
112
- | { type: "start-reload" }
113
112
  | { type: "configure"; fetchMode: FetchMode; pageSize: number };
114
113
 
115
114
  function lazyLoadingReducer<T>(
@@ -153,18 +152,15 @@ function lazyLoadingReducer<T>(
153
152
  fetchMode: action.fetchMode,
154
153
  pageSize: action.pageSize,
155
154
  };
156
- case "start-reload":
157
- // Preserve the table dimensions but show ghost/skeleton cells
158
- return {
159
- ...state,
160
- data: new Array(state.data.length).fill(null),
161
- loading: true,
162
- initialized: false,
163
- };
164
155
  case "reset":
156
+ // A view change (or initial load) re-fetches from scratch. Rather than
157
+ // blanking the table (which reads as a jarring empty flash while the
158
+ // request is in flight — very visible on sort/filter), pre-size to a page
159
+ // of `null` ghost/skeleton rows so the body stays populated and the load
160
+ // is legible. `loaded` then adjusts the array to the real size.
165
161
  return {
166
162
  visibleRegion: defaultVisibleRegion,
167
- data: [],
163
+ data: new Array(Math.max(state.pageSize, 0)).fill(null),
168
164
  loading: false,
169
165
  error: null,
170
166
  initialized: false,
package/src/provider.ts CHANGED
@@ -2,7 +2,7 @@ import { SetStateAction, useEffect, useRef, useState } from "react";
2
2
  import h from "@macrostrat/hyper";
3
3
  import { createStore, StoreApi, useStore } from "zustand";
4
4
  import type { Table } from "@blueprintjs/table";
5
- import { generateColumnSpec } from "./utils";
5
+ import { generateColumnSpec, type ColumnSpec } from "./utils";
6
6
  import { createScopedStore } from "@macrostrat/data-components";
7
7
  import {
8
8
  DataSheetProviderProps,
@@ -48,6 +48,10 @@ export const storeAtom = atom(
48
48
  },
49
49
  );
50
50
 
51
+ /** Stable empty spec so a function `columnSpec` yields a constant init value
52
+ * (see `DataSheetProviderInner`). */
53
+ const EMPTY_SPEC: ColumnSpec[] = [];
54
+
51
55
  const initializeStoreAtom = atom(
52
56
  null,
53
57
  (get, set, payload: Partial<DataSheetStore<T>>) => {
@@ -92,17 +96,28 @@ export function DataSheetProviderInner<T>({
92
96
 
93
97
  const initializeStore = ctx.useSet(initializeStoreAtom);
94
98
 
99
+ // A function `columnSpec` is derived from the loaded rows later (in
100
+ // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the
101
+ // init effect's deps: re-running init also resets `data`, so re-initializing
102
+ // when the function's identity changes (e.g. a consumer hiding a column)
103
+ // would wipe the loaded rows. `staticSpec` is a stable value in that case.
104
+ const isFnSpec = typeof columnSpec === "function";
105
+ const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;
106
+
95
107
  // Not sure how required this initialization is
96
108
  useEffect(() => {
97
109
  initializeStore({
98
- columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),
110
+ columnSpec: staticSpec ?? generateColumnSpec(data, columnSpecOptions),
111
+ // A function spec is derived from the loaded rows in `_DataSheet`; tell
112
+ // the loader not to auto-generate a plain spec from the first chunk.
113
+ deferColumnSpec: isFnSpec,
99
114
  editable,
100
115
  enableColumnReordering,
101
116
  data,
102
117
  defaultColumnWidth,
103
118
  tableRef,
104
119
  });
105
- }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);
120
+ }, [data, editable, staticSpec, isFnSpec, columnSpecOptions, enableColumnReordering]);
106
121
 
107
122
  return children;
108
123
  }
@@ -135,9 +150,11 @@ export const tableDataAtom = atom(
135
150
  if (
136
151
  state.data.length == 0 &&
137
152
  newData.length > 0 &&
138
- state.columnSpec.length == 0
153
+ state.columnSpec.length == 0 &&
154
+ !state.deferColumnSpec
139
155
  ) {
140
- // We haven't yet generated the column spec, and we need to do so.
156
+ // No spec yet and none deferred to a function — auto-generate a plain
157
+ // spec from the first chunk. (A function spec is derived separately.)
141
158
  next.columnSpec = generateColumnSpec(newData, state.columnSpecOptions);
142
159
  }
143
160
 
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import h from "@macrostrat/hyper";
10
10
  import { ColumnHeaderCell, RegionCardinality } from "@blueprintjs/table";
11
- import { Button, Icon, Menu, MenuItem } from "@blueprintjs/core";
11
+ import { Icon, Menu, MenuItem } from "@blueprintjs/core";
12
12
  import { ctx, tableActionsAtom, useStoreAPI } from "../provider";
13
13
  import { buildActionContext } from "../actions/selection";
14
14
  import type { ColumnSpec } from "../utils/column-spec";
@@ -47,8 +47,21 @@ export function renderColumnHeaderCell({
47
47
  const hasCustomActions =
48
48
  Array.isArray((col as any).actions) && (col as any).actions.length > 0;
49
49
 
50
+ // A column may be pinned against drag-reordering via `reorderable: false`.
51
+ const enableColumnReordering = col.reorderable !== false;
52
+
50
53
  if (!isSortable && !isFilterable && !hasCustomActions) {
51
- return h(ColumnHeaderCell, { name: col.name });
54
+ return h(ColumnHeaderCell, {
55
+ name: col.name,
56
+ enableColumnReordering,
57
+ nameRenderer: () =>
58
+ h(ColumnHeaderName, {
59
+ col,
60
+ hasSortActive: false,
61
+ hasFilterActive: false,
62
+ activeSort: null,
63
+ }),
64
+ });
52
65
  }
53
66
 
54
67
  // `activeFilter` is the active store entry targeting this column (any filter
@@ -58,6 +71,7 @@ export function renderColumnHeaderCell({
58
71
 
59
72
  return h(ColumnHeaderCell, {
60
73
  name: col.name,
74
+ enableColumnReordering,
61
75
  // Persistent interaction bar so the menu caret is always clickable — the
62
76
  // hover-triggered caret was blocked by the selection overlay when the
63
77
  // column was selected.
@@ -68,11 +82,16 @@ export function renderColumnHeaderCell({
68
82
  });
69
83
  }
70
84
 
71
- /** Column name with active sort/filter indicator icons. */
85
+ /** Column name with active sort/filter indicator icons. The column key is
86
+ * exposed as `data-column-key` so consumers can target a specific header from
87
+ * CSS (e.g. to tint a column) without a bespoke styling prop. */
72
88
  function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
73
89
  return h(
74
90
  "div",
75
- { style: { display: "flex", alignItems: "center", width: "100%" } },
91
+ {
92
+ "data-column-key": col.key,
93
+ style: { display: "flex", alignItems: "center", width: "100%" },
94
+ },
76
95
  [
77
96
  h(
78
97
  "span",
@@ -106,7 +125,7 @@ function ColumnHeaderName({ col, hasSortActive, hasFilterActive, activeSort }) {
106
125
  h.if(hasFilterActive)(Icon, {
107
126
  icon: "filter",
108
127
  size: 12,
109
- style: { color: "var(--intent-warning, #d99e0b)" },
128
+ style: { color: "var(--intent-primary, #2965cc)" },
110
129
  }),
111
130
  ],
112
131
  ),
@@ -131,46 +150,42 @@ function ColumnHeaderControls({ colIndex }: { colIndex: number }) {
131
150
  storeAPI.setState,
132
151
  );
133
152
 
153
+ // Only actions *limited* to column scope belong in a column's dropdown —
154
+ // sort/filter and column-specific actions. Global actions (Save / Reset /
155
+ // Clear-selection, marked by a FULL_TABLE or "none" target) are confusing
156
+ // here, so they're excluded even though they nominally apply to columns too.
157
+ const isGlobal = (a: (typeof actions)[number]) =>
158
+ a.targets.includes(RegionCardinality.FULL_TABLE) ||
159
+ a.targets.includes("none" as any);
134
160
  const controls = actions.filter(
135
161
  (a) =>
136
162
  a.targets.includes(RegionCardinality.FULL_COLUMNS) &&
163
+ !isGlobal(a) &&
137
164
  (a.appliesTo?.(actionCtx) ?? true),
138
165
  );
139
166
 
140
- const rendered = controls
141
- .map((a) =>
142
- a.render != null
143
- ? a.render(actionCtx)
144
- : h(
145
- Button,
146
- {
147
- key: a.id,
148
- small: true,
149
- minimal: true,
150
- icon: a.icon,
151
- intent: a.intent,
152
- onClick: () => a.run?.(actionCtx),
153
- },
154
- a.name,
155
- ),
156
- )
167
+ // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as
168
+ // items with submenus, so the whole dropdown is one Blueprint `Menu`. A
169
+ // control that only has `render` (a live toolbar control) is embedded as-is;
170
+ // a plain `run` action becomes a clickable item.
171
+ const items = controls
172
+ .map((a, i) => {
173
+ if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
174
+ if (a.render != null)
175
+ return h("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
176
+ return h(MenuItem, {
177
+ key: a.id ?? i,
178
+ icon: a.icon,
179
+ intent: a.intent,
180
+ text: a.name,
181
+ onClick: () => a.run?.(actionCtx),
182
+ });
183
+ })
157
184
  .filter(Boolean);
158
185
 
159
- if (rendered.length === 0) {
186
+ if (items.length === 0) {
160
187
  return h(Menu, [h(MenuItem, { text: "No options", disabled: true })]);
161
188
  }
162
189
 
163
- return h(
164
- "div.column-header-controls",
165
- {
166
- style: {
167
- padding: "8px",
168
- display: "flex",
169
- flexDirection: "column",
170
- gap: "6px",
171
- alignItems: "flex-start",
172
- },
173
- },
174
- rendered,
175
- );
190
+ return h(Menu, { className: "column-header-controls" }, items);
176
191
  }
package/src/types.ts CHANGED
@@ -34,7 +34,12 @@ export type EditEvent<T = any> =
34
34
 
35
35
  export interface DataSheetCoreProps<T> {
36
36
  data: T[];
37
- columnSpec?: ColumnSpec[];
37
+ /** Column definitions. Either a static array, or a function derived from the
38
+ * loaded rows — invoked once the first rows arrive (and re-invoked when the
39
+ * function's identity changes), so a data-shaped spec needs no separate fetch
40
+ * of sample data. Omit entirely to auto-generate a plain spec via
41
+ * `columnSpecOptions`. */
42
+ columnSpec?: ColumnSpec[] | ((rows: T[]) => ColumnSpec[]);
38
43
  editable?: boolean;
39
44
  enableColumnReordering?: boolean;
40
45
  defaultColumnWidth?: number;
@@ -45,6 +50,57 @@ export enum TableElementStatus {
45
50
  ADDED = "added",
46
51
  }
47
52
 
53
+ /** A row's status value. The built-in `TableElementStatus` members
54
+ * (`"deleted"` / `"added"`) plus any consumer-defined status string (e.g.
55
+ * `"omitted"`). The `(string & {})` keeps autocomplete for the enum members
56
+ * while still accepting arbitrary strings. */
57
+ export type RowStatusValue = TableElementStatus | (string & {});
58
+
59
+ /** Presentation for a row status: applied to the row's cells and its header
60
+ * cell. Keyed by status value in `rowStatusStyles`. The library ships a
61
+ * default for `"deleted"` (dimmed + struck through, danger intent); consumers
62
+ * merge in styles for their own statuses (and may override the defaults). */
63
+ export interface RowStatusStyle {
64
+ /** Style merged onto each cell in a row with this status. */
65
+ cellStyle?: import("react").CSSProperties;
66
+ /** Style applied to the row's header cell. */
67
+ headerStyle?: import("react").CSSProperties;
68
+ /** Blueprint intent applied to the row's cells (precedence: validation >
69
+ * this > edited-green). */
70
+ intent?: import("@blueprintjs/core").Intent;
71
+ }
72
+
73
+ export type RowStatusStyles = Record<string, RowStatusStyle>;
74
+
75
+ /** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged
76
+ * over this, so `"deleted"` keeps its look unless explicitly overridden. */
77
+ export const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {
78
+ [TableElementStatus.DELETED]: {
79
+ cellStyle: { opacity: 0.5, textDecoration: "line-through" },
80
+ headerStyle: { opacity: 0.5, textDecoration: "line-through" },
81
+ intent: "danger",
82
+ },
83
+ };
84
+
85
+ /** Context passed to a custom `rowHeaderRenderer`, so it can label and style
86
+ * the row header from the row's data and status (group-key labels, an
87
+ * omit indicator, etc.). Return a node to use as the header's name, or a
88
+ * nullish value to fall back to the default (1-based row number). */
89
+ export interface RowHeaderRenderContext<T = any> {
90
+ /** Data-row index (stable under sort/filter). */
91
+ rowIndex: number;
92
+ /** Visible (display) row index. */
93
+ visibleIndex: number;
94
+ /** The row's data (base, overlaid with edits if present). */
95
+ row: T | undefined;
96
+ /** The row's status, if any. */
97
+ status: RowStatusValue | undefined;
98
+ /** Convenience: `status === TableElementStatus.DELETED`. */
99
+ isDeleted: boolean;
100
+ /** The default label (`"${rowIndex + 1}"`). */
101
+ defaultLabel: string;
102
+ }
103
+
48
104
  /** Property key holding a stable synthetic id on rows added in-table. Added
49
105
  * rows aren't in the data provider, so they need their own identity to survive
50
106
  * a provider re-fetch; it's carried on the row and preserved through edits. */
@@ -66,6 +122,10 @@ export interface ClipboardProxy {
66
122
  export interface DataSheetState<T> {
67
123
  selection: Region[];
68
124
  columnSpec: ColumnSpec[];
125
+ /** When `true`, the loader's first-chunk auto-generation of `columnSpec` is
126
+ * suppressed — a function `columnSpec` derives it from the loaded rows
127
+ * instead (in `_DataSheet`). Set at init from the prop's shape. */
128
+ deferColumnSpec: boolean;
69
129
  fillValueBaseCell: FocusedCellCoordinates | null;
70
130
  focusedCell: FocusedCellCoordinates | null;
71
131
  topLeftCell: FocusedCellCoordinates | null;
@@ -76,7 +136,11 @@ export interface DataSheetState<T> {
76
136
  * This is used to track which rows should be reverted when
77
137
  * a "reset" action is performed.
78
138
  */
79
- rowStatus: TableElementStatus[];
139
+ rowStatus: RowStatusValue[];
140
+ /** Presentation per row-status value (merged: defaults + the
141
+ * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer
142
+ * to style rows by status. */
143
+ rowStatusStyles: RowStatusStyles;
80
144
  // Sparse data structure for updated data
81
145
  updatedData: T[];
82
146
  initialized: boolean;