@macrostrat/data-sheet 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +11 -1
  3. package/dist/actions/column-controls.cjs +89 -0
  4. package/dist/actions/column-controls.cjs.map +1 -1
  5. package/dist/actions/column-controls.js +90 -1
  6. package/dist/actions/column-controls.js.map +1 -1
  7. package/dist/actions/selection.cjs +2 -1
  8. package/dist/actions/selection.cjs.map +1 -1
  9. package/dist/actions/selection.js +2 -1
  10. package/dist/actions/selection.js.map +1 -1
  11. package/dist/actions/table-controls.cjs +17 -0
  12. package/dist/actions/table-controls.cjs.map +1 -1
  13. package/dist/actions/table-controls.d.ts +4 -0
  14. package/dist/actions/table-controls.js +17 -0
  15. package/dist/actions/table-controls.js.map +1 -1
  16. package/dist/actions/toolbar.cjs +18 -2
  17. package/dist/actions/toolbar.cjs.map +1 -1
  18. package/dist/actions/toolbar.js +18 -2
  19. package/dist/actions/toolbar.js.map +1 -1
  20. package/dist/actions/types.d.ts +9 -0
  21. package/dist/cell-renderer.cjs +8 -6
  22. package/dist/cell-renderer.cjs.map +1 -1
  23. package/dist/cell-renderer.js +8 -6
  24. package/dist/cell-renderer.js.map +1 -1
  25. package/dist/core.cjs +59 -9
  26. package/dist/core.cjs.map +1 -1
  27. package/dist/core.d.ts +28 -1
  28. package/dist/core.js +60 -10
  29. package/dist/core.js.map +1 -1
  30. package/dist/index.cjs +4 -2
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.js +4 -2
  33. package/dist/renderers/column-header-cell.cjs +14 -28
  34. package/dist/renderers/column-header-cell.cjs.map +1 -1
  35. package/dist/renderers/column-header-cell.js +15 -29
  36. package/dist/renderers/column-header-cell.js.map +1 -1
  37. package/dist/types.cjs +11 -0
  38. package/dist/types.cjs.map +1 -1
  39. package/dist/types.d.ts +45 -1
  40. package/dist/types.js +11 -0
  41. package/dist/types.js.map +1 -1
  42. package/dist/utils/column-spec.cjs.map +1 -1
  43. package/dist/utils/column-spec.d.ts +4 -0
  44. package/dist/utils/column-spec.js.map +1 -1
  45. package/dist/zustand-store.cjs +6 -3
  46. package/dist/zustand-store.cjs.map +1 -1
  47. package/dist/zustand-store.js +7 -4
  48. package/dist/zustand-store.js.map +1 -1
  49. package/package.json +1 -1
  50. package/src/actions/column-controls.ts +114 -0
  51. package/src/actions/selection.ts +1 -0
  52. package/src/actions/table-controls.ts +20 -0
  53. package/src/actions/toolbar.ts +30 -2
  54. package/src/actions/types.ts +10 -0
  55. package/src/cell-renderer.ts +17 -9
  56. package/src/core.ts +107 -12
  57. package/src/renderers/column-header-cell.ts +20 -32
  58. package/src/types.ts +56 -1
  59. package/src/utils/column-spec.ts +4 -0
  60. package/src/zustand-store.ts +11 -5
package/src/core.ts CHANGED
@@ -24,7 +24,10 @@ 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";
@@ -32,6 +35,7 @@ import { basicCellRenderer } from "./cell-renderer.ts";
32
35
  import { CellRendererDebugOverlay, tableHotkeysAtom } from "./utils";
33
36
  import {
34
37
  ActionsToolbar,
38
+ clearSelectionAction,
35
39
  clipboardActions,
36
40
  columnControlActions,
37
41
  createSaveAction,
@@ -113,6 +117,19 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
113
117
  * data provider supplies its own; defaults to `(row) => row?.id`). Lets edits
114
118
  * survive a re-ordered re-fetch. */
115
119
  identity?: (row: T) => string | number | null | undefined;
120
+ /** Derive the controlled edit overlay from the loaded rows, *inside* the
121
+ * sheet. For provider-backed tables whose overlay is a function of the loaded
122
+ * data plus external edit state (e.g. an ops stack): the library owns the
123
+ * rows, so it calls this with them and uses the result as the controlled
124
+ * overlay, re-deriving when the rows — or this function's identity (close it
125
+ * over your edit state) — change. Supersedes `updatedData`/`rowStatus`. */
126
+ deriveOverlay?: (rows: T[]) => {
127
+ updatedData: T[];
128
+ rowStatus: TableElementStatus[];
129
+ };
130
+ /** Bump to force the data provider to re-fetch from scratch (e.g. after a
131
+ * save/delete that invalidated the loaded rows). */
132
+ refreshToken?: number | string;
116
133
  /** Persistence handler for the built-in Save action. When provided, a Save
117
134
  * control is added to the toolbar (always visible, disabled when there are
118
135
  * no pending changes). */
@@ -141,6 +158,20 @@ interface DataSheetInternalProps<T> extends TableProps, FetchDataOptions {
141
158
  * Receives the ColumnSpec and column index; should return a React element
142
159
  * (typically a Blueprint ColumnHeaderCell). */
143
160
  columnHeaderCellRenderer?: (col: any, colIndex: number) => ReactNode;
161
+ /** Arbitrary nodes for the bottom status bar (left group), rendered beside
162
+ * the active sort/filter tags — the home for view-state controls (show/hide
163
+ * omitted rows/columns, a group-by indicator, etc.). */
164
+ statusBar?: ReactNode;
165
+ /** Presentation per row-status value, merged over the built-in defaults
166
+ * (which style `"deleted"`). Supply styles for consumer-defined statuses
167
+ * (e.g. `"omitted"`) and/or override the defaults. Each entry may set the
168
+ * cells' style/intent and the row header's style. */
169
+ rowStatusStyles?: RowStatusStyles;
170
+ /** Render the content of a row's header cell (the left gutter). Receives the
171
+ * row, its status, and the default 1-based label; return a node to use, or a
172
+ * nullish value to keep the default. For group-key labels, omit indicators,
173
+ * etc. Header-cell *styling* still comes from `rowStatusStyles`. */
174
+ rowHeaderRenderer?: (ctx: RowHeaderRenderContext<T>) => ReactNode;
144
175
  }
145
176
 
146
177
  type DataSheetProps<T> = DataSheetProviderProps<T> & DataSheetInternalProps<T>;
@@ -182,11 +213,6 @@ export function DataSheet<T>(props: DataSheetProps<T>) {
182
213
  );
183
214
  }
184
215
 
185
- const deletedRowHeaderStyle = {
186
- opacity: 0.5,
187
- textDecoration: "line-through",
188
- };
189
-
190
216
  /** Persist all pending changes through a data provider: added rows via
191
217
  * `insertRow`, edited rows via `saveRows`, deleted rows via `deleteRows`
192
218
  * (addressed by `provider.identity`). Used by the built-in Save action when an
@@ -241,6 +267,8 @@ function _DataSheet<T>({
241
267
  updatedData: updatedDataProp,
242
268
  rowStatus: rowStatusProp,
243
269
  identity,
270
+ deriveOverlay,
271
+ refreshToken,
244
272
  onDeleteRows,
245
273
  name,
246
274
  verbose = false,
@@ -253,6 +281,9 @@ function _DataSheet<T>({
253
281
  actions,
254
282
  filters,
255
283
  columnHeaderCellRenderer,
284
+ statusBar,
285
+ rowStatusStyles,
286
+ rowHeaderRenderer,
256
287
  children,
257
288
  ...rest
258
289
  }: DataSheetInternalProps<T>) {
@@ -319,6 +350,7 @@ function _DataSheet<T>({
319
350
  };
320
351
  if (actions != null) add(actions);
321
352
  add(columnControlActions);
353
+ add([clearSelectionAction]);
322
354
  if (enableClipboard) add(clipboardActions);
323
355
  // Save/reset last — they're the most significant actions — and present for
324
356
  // every cardinality (editable), so the toolbar stays mounted regardless of
@@ -455,12 +487,41 @@ function _DataSheet<T>({
455
487
  // next render when the caller passes an updated value back. When the caller
456
488
  // controls it, the loader-boundary identity remap steps aside.
457
489
  const controlled =
458
- updatedDataProp !== undefined || rowStatusProp !== undefined;
490
+ updatedDataProp !== undefined ||
491
+ rowStatusProp !== undefined ||
492
+ deriveOverlay != null;
459
493
  const patch: Record<string, unknown> = { controlledOverlay: controlled };
460
494
  if (updatedDataProp !== undefined) patch.updatedData = updatedDataProp;
461
495
  if (rowStatusProp !== undefined) patch.rowStatus = rowStatusProp;
462
496
  storeState.setState(patch);
463
- }, [storeState, updatedDataProp, rowStatusProp]);
497
+ }, [storeState, updatedDataProp, rowStatusProp, deriveOverlay]);
498
+
499
+ // Derived controlled overlay: the library owns the loaded rows, so it runs
500
+ // the consumer's `deriveOverlay(rows)` here and pushes the result. Re-derives
501
+ // when the rows load/change or the function's identity changes (close it over
502
+ // your external edit state). The `controlledOverlay` flag above suppresses the
503
+ // loader-boundary identity remap so this derivation is authoritative.
504
+ const loadedData = useSelector((state) => state.data);
505
+ useEffect(() => {
506
+ if (deriveOverlay == null) return;
507
+ const overlay = deriveOverlay(loadedData);
508
+ storeState.setState({
509
+ updatedData: overlay.updatedData,
510
+ rowStatus: overlay.rowStatus,
511
+ });
512
+ }, [deriveOverlay, loadedData, storeState]);
513
+
514
+ // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g. after
515
+ // a save). Skips the initial mount (the loader does its own first fetch).
516
+ const bumpRefreshFromToken = ctx.useSet(dataRefreshTokenAtom);
517
+ const firstRefreshToken = useRef(true);
518
+ useEffect(() => {
519
+ if (firstRefreshToken.current) {
520
+ firstRefreshToken.current = false;
521
+ return;
522
+ }
523
+ bumpRefreshFromToken((v) => v + 1);
524
+ }, [refreshToken, bumpRefreshFromToken]);
464
525
 
465
526
  // The active provider supplies the row identity for the edit overlay.
466
527
  useEffect(() => {
@@ -476,6 +537,17 @@ function _DataSheet<T>({
476
537
  storeState.setState({ canDeleteRows });
477
538
  }, [storeState, provider]);
478
539
 
540
+ // Merge consumer `rowStatusStyles` over the built-in defaults and hand the
541
+ // result to the store, where the cell renderer and row-header renderer read
542
+ // it. Merged (not replaced) so overriding one status doesn't drop the rest.
543
+ const mergedRowStatusStyles = useMemo<RowStatusStyles>(
544
+ () => ({ ...DEFAULT_ROW_STATUS_STYLES, ...rowStatusStyles }),
545
+ [rowStatusStyles],
546
+ );
547
+ useEffect(() => {
548
+ storeState.setState({ rowStatusStyles: mergedRowStatusStyles });
549
+ }, [storeState, mergedRowStatusStyles]);
550
+
479
551
  const realizedColumns = useMemo(() => {
480
552
  return columnSpec.map((col, colIndex) => {
481
553
  let fn =
@@ -541,19 +613,41 @@ function _DataSheet<T>({
541
613
  filteredRowIndices != null
542
614
  ? (filteredRowIndices[rowIndex] ?? rowIndex)
543
615
  : rowIndex;
616
+ const statusVal = rowStatus[dataRowIndex];
544
617
  const style =
545
- rowStatus[dataRowIndex] == TableElementStatus.DELETED
546
- ? deletedRowHeaderStyle
547
- : null;
618
+ (statusVal != null
619
+ ? mergedRowStatusStyles[statusVal]?.headerStyle
620
+ : null) ?? null;
621
+
622
+ const defaultLabel = `${dataRowIndex + 1}`;
623
+ let name: ReactNode = defaultLabel;
624
+ if (rowHeaderRenderer != null) {
625
+ const custom = rowHeaderRenderer({
626
+ rowIndex: dataRowIndex,
627
+ visibleIndex: rowIndex,
628
+ row: data[dataRowIndex] ?? updatedData[dataRowIndex],
629
+ status: statusVal,
630
+ isDeleted: statusVal === TableElementStatus.DELETED,
631
+ defaultLabel,
632
+ });
633
+ if (custom != null) name = custom;
634
+ }
548
635
 
549
636
  return h(RowHeaderCell, {
550
637
  enableRowReordering: false,
551
638
  index: rowIndex,
552
- name: `${dataRowIndex + 1}`,
639
+ name,
553
640
  style,
554
641
  });
555
642
  },
556
- [rowStatus, filteredRowIndices],
643
+ [
644
+ rowStatus,
645
+ filteredRowIndices,
646
+ mergedRowStatusStyles,
647
+ rowHeaderRenderer,
648
+ data,
649
+ updatedData,
650
+ ],
557
651
  );
558
652
 
559
653
  let _selectionModes = selectionModes;
@@ -644,6 +738,7 @@ function _DataSheet<T>({
644
738
  ),
645
739
  h("div.status-bar", [
646
740
  filterStatus,
741
+ statusBar,
647
742
  h("div.spacer"),
648
743
  h.if(_showLoadProgress)(LoadProgressIndicator),
649
744
  ]),
@@ -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";
@@ -137,40 +137,28 @@ function ColumnHeaderControls({ colIndex }: { colIndex: number }) {
137
137
  (a.appliesTo?.(actionCtx) ?? true),
138
138
  );
139
139
 
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
- )
140
+ // Prefer menu-native rendering (`renderMenuItem`) — sort/filter render as
141
+ // items with submenus, so the whole dropdown is one Blueprint `Menu`. A
142
+ // control that only has `render` (a live toolbar control) is embedded as-is;
143
+ // a plain `run` action becomes a clickable item.
144
+ const items = controls
145
+ .map((a, i) => {
146
+ if (a.renderMenuItem != null) return a.renderMenuItem(actionCtx);
147
+ if (a.render != null)
148
+ return h("li.column-header-control", { key: a.id ?? i }, a.render(actionCtx));
149
+ return h(MenuItem, {
150
+ key: a.id ?? i,
151
+ icon: a.icon,
152
+ intent: a.intent,
153
+ text: a.name,
154
+ onClick: () => a.run?.(actionCtx),
155
+ });
156
+ })
157
157
  .filter(Boolean);
158
158
 
159
- if (rendered.length === 0) {
159
+ if (items.length === 0) {
160
160
  return h(Menu, [h(MenuItem, { text: "No options", disabled: true })]);
161
161
  }
162
162
 
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
- );
163
+ return h(Menu, { className: "column-header-controls" }, items);
176
164
  }
package/src/types.ts CHANGED
@@ -45,6 +45,57 @@ export enum TableElementStatus {
45
45
  ADDED = "added",
46
46
  }
47
47
 
48
+ /** A row's status value. The built-in `TableElementStatus` members
49
+ * (`"deleted"` / `"added"`) plus any consumer-defined status string (e.g.
50
+ * `"omitted"`). The `(string & {})` keeps autocomplete for the enum members
51
+ * while still accepting arbitrary strings. */
52
+ export type RowStatusValue = TableElementStatus | (string & {});
53
+
54
+ /** Presentation for a row status: applied to the row's cells and its header
55
+ * cell. Keyed by status value in `rowStatusStyles`. The library ships a
56
+ * default for `"deleted"` (dimmed + struck through, danger intent); consumers
57
+ * merge in styles for their own statuses (and may override the defaults). */
58
+ export interface RowStatusStyle {
59
+ /** Style merged onto each cell in a row with this status. */
60
+ cellStyle?: import("react").CSSProperties;
61
+ /** Style applied to the row's header cell. */
62
+ headerStyle?: import("react").CSSProperties;
63
+ /** Blueprint intent applied to the row's cells (precedence: validation >
64
+ * this > edited-green). */
65
+ intent?: import("@blueprintjs/core").Intent;
66
+ }
67
+
68
+ export type RowStatusStyles = Record<string, RowStatusStyle>;
69
+
70
+ /** Built-in row-status presentation. Consumers' `rowStatusStyles` are merged
71
+ * over this, so `"deleted"` keeps its look unless explicitly overridden. */
72
+ export const DEFAULT_ROW_STATUS_STYLES: RowStatusStyles = {
73
+ [TableElementStatus.DELETED]: {
74
+ cellStyle: { opacity: 0.5, textDecoration: "line-through" },
75
+ headerStyle: { opacity: 0.5, textDecoration: "line-through" },
76
+ intent: "danger",
77
+ },
78
+ };
79
+
80
+ /** Context passed to a custom `rowHeaderRenderer`, so it can label and style
81
+ * the row header from the row's data and status (group-key labels, an
82
+ * omit indicator, etc.). Return a node to use as the header's name, or a
83
+ * nullish value to fall back to the default (1-based row number). */
84
+ export interface RowHeaderRenderContext<T = any> {
85
+ /** Data-row index (stable under sort/filter). */
86
+ rowIndex: number;
87
+ /** Visible (display) row index. */
88
+ visibleIndex: number;
89
+ /** The row's data (base, overlaid with edits if present). */
90
+ row: T | undefined;
91
+ /** The row's status, if any. */
92
+ status: RowStatusValue | undefined;
93
+ /** Convenience: `status === TableElementStatus.DELETED`. */
94
+ isDeleted: boolean;
95
+ /** The default label (`"${rowIndex + 1}"`). */
96
+ defaultLabel: string;
97
+ }
98
+
48
99
  /** Property key holding a stable synthetic id on rows added in-table. Added
49
100
  * rows aren't in the data provider, so they need their own identity to survive
50
101
  * a provider re-fetch; it's carried on the row and preserved through edits. */
@@ -76,7 +127,11 @@ export interface DataSheetState<T> {
76
127
  * This is used to track which rows should be reverted when
77
128
  * a "reset" action is performed.
78
129
  */
79
- rowStatus: TableElementStatus[];
130
+ rowStatus: RowStatusValue[];
131
+ /** Presentation per row-status value (merged: defaults + the
132
+ * `rowStatusStyles` prop). Read by the cell renderer and row-header renderer
133
+ * to style rows by status. */
134
+ rowStatusStyles: RowStatusStyles;
80
135
  // Sparse data structure for updated data
81
136
  updatedData: T[];
82
137
  initialized: boolean;
@@ -62,6 +62,10 @@ export interface CellRenderContext<T = any> {
62
62
  isEdited: boolean;
63
63
  /** Whether this cell's row is marked for deletion. */
64
64
  isDeleted: boolean;
65
+ /** The row's status value (`RowStatusValue`) — `"deleted"` / `"added"` or a
66
+ * consumer-defined status (e.g. `"omitted"`), or `undefined` for a normal
67
+ * row. Lets a renderer style by arbitrary status, not just deletion. */
68
+ status: string | undefined;
65
69
  /** Validation result for this cell, or `null` when valid. Orthogonal to the
66
70
  * edit status — a cell can be both edited and invalid. */
67
71
  validation: CellValidation | null;
@@ -2,6 +2,7 @@ import {
2
2
  DataSheetState,
3
3
  DataSheetStore,
4
4
  DataSheetStoreMain,
5
+ DEFAULT_ROW_STATUS_STYLES,
5
6
  DS_ROW_ID,
6
7
  StateUpdater,
7
8
  TableElementStatus,
@@ -29,6 +30,7 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
29
30
  data: [],
30
31
  updatedData: [],
31
32
  rowStatus: [],
33
+ rowStatusStyles: DEFAULT_ROW_STATUS_STYLES,
32
34
  columnSpec: [],
33
35
  defaultColumnWidth: 150,
34
36
  editable: false,
@@ -264,12 +266,15 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
264
266
  if (get().editable) {
265
267
  get().onEdit?.({
266
268
  type: "setCells",
267
- cells: [{ rowIndex, column: columnName, value }],
269
+ cells: [
270
+ { rowIndex, column: columnName, value, row: get().data[rowIndex] },
271
+ ],
268
272
  });
269
273
  }
270
274
  },
271
275
  clearSelection() {
272
- const edits: { rowIndex: number; column: string; value: any }[] = [];
276
+ const edits: { rowIndex: number; column: string; value: any; row?: any }[] =
277
+ [];
273
278
  set((state) => {
274
279
  // Delete all selected cells
275
280
  const { selection, updatedData, columnSpec, data } = state;
@@ -292,7 +297,7 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
292
297
  const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];
293
298
  if (currentValue != null && currentValue !== "") {
294
299
  vals[key] = "";
295
- edits.push({ rowIndex: row, column: key, value: "" });
300
+ edits.push({ rowIndex: row, column: key, value: "", row: data[row] });
296
301
  }
297
302
  }
298
303
  let op = updatedData[row] == null ? "$set" : "$merge";
@@ -345,7 +350,8 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
345
350
  },
346
351
  onSelectionEdited(value: any) {
347
352
  // Apply the same value to all selected cells
348
- const edits: { rowIndex: number; column: string; value: any }[] = [];
353
+ const edits: { rowIndex: number; column: string; value: any; row?: any }[] =
354
+ [];
349
355
  set((state) => {
350
356
  const { selection, updatedData, columnSpec, editable } = state;
351
357
  if (!editable) return {};
@@ -362,7 +368,7 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
362
368
  for (const col of colRange) {
363
369
  const key = columnSpec[col].key;
364
370
  vals[key] = value;
365
- edits.push({ rowIndex: row, column: key, value });
371
+ edits.push({ rowIndex: row, column: key, value, row: state.data[row] });
366
372
  }
367
373
  let op = updatedData[row] == null ? "$set" : "$merge";
368
374
  spec[row] = { [op]: vals };