@macrostrat/data-sheet 3.0.3 → 3.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 (80) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/cell-renderer.cjs +162 -0
  3. package/dist/cell-renderer.cjs.map +1 -0
  4. package/dist/cell-renderer.d.ts +8 -0
  5. package/dist/cell-renderer.js +162 -0
  6. package/dist/cell-renderer.js.map +1 -0
  7. package/dist/components/actions.cjs +2 -6
  8. package/dist/components/actions.cjs.map +1 -1
  9. package/dist/components/actions.js +1 -3
  10. package/dist/components/actions.js.map +1 -1
  11. package/dist/components/colors.cjs +4 -7
  12. package/dist/components/colors.cjs.map +1 -1
  13. package/dist/components/colors.js +1 -3
  14. package/dist/components/colors.js.map +1 -1
  15. package/dist/components/editor-popup.cjs +15 -19
  16. package/dist/components/editor-popup.cjs.map +1 -1
  17. package/dist/components/editor-popup.d.ts +1 -1
  18. package/dist/components/editor-popup.js +10 -12
  19. package/dist/components/editor-popup.js.map +1 -1
  20. package/dist/core.cjs +67 -207
  21. package/dist/core.cjs.map +1 -1
  22. package/dist/core.d.ts +4 -9
  23. package/dist/core.js +48 -185
  24. package/dist/core.js.map +1 -1
  25. package/dist/data-sheet.css +9 -9
  26. package/dist/index.cjs +16 -4
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +17 -8
  30. package/dist/index.js.map +1 -1
  31. package/dist/postgrest-table/data-loaders.cjs +109 -0
  32. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  33. package/dist/postgrest-table/data-loaders.d.ts +6 -0
  34. package/dist/postgrest-table/data-loaders.js +111 -2
  35. package/dist/postgrest-table/data-loaders.js.map +1 -1
  36. package/dist/postgrest-table/index.cjs +1 -0
  37. package/dist/postgrest-table/index.cjs.map +1 -1
  38. package/dist/postgrest-table/index.d.ts +2 -1
  39. package/dist/postgrest-table/index.js +2 -0
  40. package/dist/postgrest-table/index.js.map +1 -1
  41. package/dist/postgrest-table/lazy-loader-table.cjs +26 -0
  42. package/dist/postgrest-table/lazy-loader-table.cjs.map +1 -0
  43. package/dist/postgrest-table/lazy-loader-table.d.ts +3 -0
  44. package/dist/postgrest-table/lazy-loader-table.js +24 -0
  45. package/dist/postgrest-table/lazy-loader-table.js.map +1 -0
  46. package/dist/provider.cjs +59 -336
  47. package/dist/provider.cjs.map +1 -1
  48. package/dist/provider.d.ts +11 -65
  49. package/dist/provider.js +58 -336
  50. package/dist/provider.js.map +1 -1
  51. package/dist/types.d.ts +54 -0
  52. package/dist/utils/column-spec.cjs +6 -1
  53. package/dist/utils/column-spec.cjs.map +1 -1
  54. package/dist/utils/column-spec.js +6 -1
  55. package/dist/utils/column-spec.js.map +1 -1
  56. package/dist/utils/key-handling.cjs +26 -1
  57. package/dist/utils/key-handling.cjs.map +1 -1
  58. package/dist/utils/key-handling.d.ts +3 -2
  59. package/dist/utils/key-handling.js +27 -2
  60. package/dist/utils/key-handling.js.map +1 -1
  61. package/dist/zustand-store.cjs +320 -0
  62. package/dist/zustand-store.cjs.map +1 -0
  63. package/dist/zustand-store.d.ts +6 -0
  64. package/dist/zustand-store.js +318 -0
  65. package/dist/zustand-store.js.map +1 -0
  66. package/package.json +7 -6
  67. package/src/cell-renderer.ts +217 -0
  68. package/src/components/actions.ts +1 -3
  69. package/src/components/colors.ts +1 -4
  70. package/src/components/editor-popup.ts +9 -12
  71. package/src/core.ts +82 -254
  72. package/src/index.ts +3 -0
  73. package/src/postgrest-table/data-loaders.ts +151 -1
  74. package/src/postgrest-table/index.ts +2 -1
  75. package/src/postgrest-table/lazy-loader-table.ts +24 -0
  76. package/src/provider.ts +66 -483
  77. package/src/types.ts +66 -0
  78. package/src/utils/column-spec.ts +6 -1
  79. package/src/utils/key-handling.ts +31 -5
  80. package/src/zustand-store.ts +377 -0
package/src/provider.ts CHANGED
@@ -1,117 +1,66 @@
1
- import { createContext, useContext, useEffect, useRef, useState } from "react";
1
+ import { SetStateAction, useEffect, useRef, useState } from "react";
2
2
  import h from "@macrostrat/hyper";
3
3
  import { createStore, StoreApi, useStore } from "zustand";
4
- import { createComputed } from "zustand-computed";
5
- import type {
6
- FocusedCellCoordinates,
7
- Region,
8
- Table2,
9
- } from "@blueprintjs/table";
4
+ import type { Region, Table } from "@blueprintjs/table";
5
+ import { generateColumnSpec } from "./utils";
6
+ import { createScopedStore } from "@macrostrat/data-components";
10
7
  import {
11
- ColumnSpec,
12
- ColumnSpecOptions,
13
- editorKeyHandler,
14
- generateColumnSpec,
15
- range,
16
- tableKeyHandler,
17
- } from "./utils";
18
- import update, { Spec } from "immutability-helper";
19
-
20
- export interface DataSheetCoreProps<T> {
21
- data: T[];
22
- columnSpec?: ColumnSpec[];
23
- editable?: boolean;
24
- enableColumnReordering?: boolean;
25
- defaultColumnWidth?: number;
26
- }
27
-
28
- export interface DataSheetState<T> {
29
- selection: Region[];
30
- columnSpec: ColumnSpec[];
31
- fillValueBaseCell: FocusedCellCoordinates | null;
32
- focusedCell: FocusedCellCoordinates | null;
33
- topLeftCell: FocusedCellCoordinates | null;
34
- deletedRows: Set<number>;
35
- // Sparse data structure for updated data
36
- updatedData: T[];
37
- initialized: boolean;
38
- columnWidthsIndex: Map<string, number>;
39
- }
40
-
41
- type DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;
42
-
43
- type StateUpdater<T> = T[] | ((state: T[]) => T[]);
44
-
45
- export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
46
- setSelection(selection: Region[]): void;
47
- onDragValue(cell: FocusedCellCoordinates | null): void;
48
- setUpdatedData(data: StateUpdater<T>): void;
49
- onCellEdited(rowIndex: number, columnName: string, value: any): void;
50
- onSelectionEdited(value: any): void;
51
- onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;
52
- onColumnWidthChanged(columnIndex: number, newWidth: number): void;
53
- moveFocusedCell(direction: "up" | "down" | "left" | "right"): void;
54
- deleteSelectedRows(): void;
55
- clearSelection(): void;
56
- resetChanges(): void;
57
- addRow(): void;
58
- initialize(props: DataSheetCoreProps<T>): void;
59
- onSelection(selection: Region[]): void;
60
- // Internal method used for infinite scrolling
61
- setVisibleCells(visibleCells: VisibleCells): void;
62
- scrollToRow(rowIndex: number): void;
63
- tableRef: React.MutableRefObject<Table2>;
64
- columnWidthsIndex: Map<string, number>;
65
- defaultColumnWidth: number;
66
- }
67
-
68
- export type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {
69
- children: React.ReactNode;
70
- columnSpecOptions?: ColumnSpecOptions<T>;
71
- };
72
-
73
- const DataSheetContext = createContext<StoreApi<DataSheetStore<any>>>(null);
74
-
75
- export interface VisibleCells {
76
- rowIndexStart: number;
77
- rowIndexEnd: number;
78
- }
8
+ DataSheetProviderProps,
9
+ DataSheetStore,
10
+ VisibleCells,
11
+ } from "./types.ts";
12
+ import { createZustandStore } from "./zustand-store.ts";
13
+ import { atomWithStore } from "jotai-zustand";
14
+ import { atom } from "jotai";
15
+
16
+ /** Create a Jotai scoped store */
17
+ const scope = createScopedStore();
18
+ const { useAtom, useAtomValue, useSetAtom } = scope;
19
+ export { useAtom, useAtomValue, useSetAtom };
20
+ export { atom };
21
+
22
+ export const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();
23
+
24
+ const storeWrapperAtom = atom((get) => {
25
+ return atomWithStore(get(storeAPIAtom));
26
+ });
27
+
28
+ /** This is the basis for all other atoms that manipulate the store. */
29
+ export const storeAtom = atom(
30
+ (get) => {
31
+ return get(get(storeWrapperAtom));
32
+ },
33
+ (get, set, action: SetStateAction<T>) => {
34
+ return set(get(storeWrapperAtom), action);
35
+ },
36
+ );
37
+
38
+ const initializeStoreAtom = atom(
39
+ null,
40
+ (get, set, payload: Partial<DataSheetStore<T>>) => {
41
+ set(storeAtom, (state) => {
42
+ return {
43
+ ...state,
44
+ ...payload,
45
+ };
46
+ });
47
+ },
48
+ );
79
49
 
80
- interface DataSheetComputedVals {
81
- hasUpdates: boolean;
82
- /** State for column widths (if resized).
83
- * This will reset if the columnSpec prop changes
84
- */
85
- columnWidths: number[];
86
- tableKeyHandler: (evt: React.KeyboardEvent) => void;
87
- editorKeyHandler: (evt: React.KeyboardEvent) => void;
88
- isSingleCellSelection?: boolean;
50
+ export function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {
51
+ const [store] = useState(() => {
52
+ return createStore<DataSheetStore<T>>(createZustandStore);
53
+ });
54
+ return h(
55
+ scope.Provider,
56
+ {
57
+ atoms: [[storeAPIAtom, store]],
58
+ },
59
+ h(DataSheetProviderInner, props),
60
+ );
89
61
  }
90
62
 
91
- export type DataSheetStore<T> = DataSheetComputedVals & DataSheetStoreMain<T>;
92
-
93
- const computed = createComputed(
94
- (state: DataSheetStoreMain<any>): DataSheetComputedVals => {
95
- const isSingleCellSelection = singleFocusedCell(state.selection) != null;
96
- return {
97
- hasUpdates: state.updatedData.length > 0 || state.deletedRows.size > 0,
98
- columnWidths: state.columnSpec.map(
99
- (col) =>
100
- state.columnWidthsIndex.get(col.key) ??
101
- col.width ??
102
- state.defaultColumnWidth,
103
- ),
104
- editorKeyHandler: (e: React.KeyboardEvent) =>
105
- editorKeyHandler(e, isSingleCellSelection),
106
- isSingleCellSelection,
107
- tableKeyHandler: (e: React.KeyboardEvent) => {
108
- tableKeyHandler(e, state);
109
- },
110
- };
111
- },
112
- ) as any;
113
-
114
- export function DataSheetProvider<T>({
63
+ export function DataSheetProviderInner<T>({
115
64
  children,
116
65
  data,
117
66
  columnSpec,
@@ -125,274 +74,28 @@ export function DataSheetProvider<T>({
125
74
  rowIndexEnd: 0,
126
75
  });
127
76
 
128
- const tableRef = useRef<Table2>(null);
77
+ const tableRef = useRef<Table>(null);
129
78
 
130
- const [store] = useState(() => {
131
- const spec = columnSpec || generateColumnSpec(data, columnSpecOptions);
132
- return createStore<DataSheetStore<T>>(
133
- computed((set): DataSheetStore<T> => {
134
- return {
135
- data,
136
- columnSpec: spec,
137
- defaultColumnWidth,
138
- editable,
139
- deletedRows: new Set<number>(),
140
- selection: [],
141
- fillValueBaseCell: null,
142
- updatedData: [],
143
- focusedCell: null,
144
- topLeftCell: null,
145
- initialized: false,
146
- tableRef,
147
- // This is a placeholder
148
- enableColumnReordering: false,
149
- setSelection(selection: Region[]) {
150
- set(updateSelection(selection));
151
- },
152
- columnWidthsIndex: new Map<string, number>(),
153
- moveFocusedCell(direction: "up" | "down" | "left" | "right") {
154
- set((state) => {
155
- const { topLeftCell } = state;
156
- if (topLeftCell == null) return {};
157
- let { col, row } = topLeftCell;
158
- switch (direction) {
159
- case "up":
160
- row = Math.max(0, row - 1);
161
- break;
162
- case "down":
163
- row = Math.min(
164
- row + 1,
165
- Math.max(state.data.length, state.updatedData.length) - 1,
166
- );
167
- break;
168
- case "left":
169
- col = Math.max(0, col - 1);
170
- break;
171
- case "right":
172
- col = Math.min(col + 1, state.columnSpec.length - 1);
173
- break;
174
- }
175
- const region: Region = { cols: [col, col], rows: [row, row] };
176
- return updateSelection([region]);
177
- });
178
- },
179
- addRow(row: Partial<T> = {} as T) {
180
- /** Add a new row. If there is a selection, use the last row index to determine
181
- * where to insert the new row. Otherwise, append to the end of the data. */
182
- set((state) => {
183
- const { updatedData, data, selection } = state;
184
- const lastRowIndex =
185
- getLastRowIndex(selection) ??
186
- Math.max(data.length, updatedData.length) - 1;
187
- // If there is a selection, insert the new row after the last selected row
188
- const spec: Spec<any> = {
189
- $splice: [[lastRowIndex + 1, 0, row]],
190
- };
191
- console.log(spec);
192
-
193
- return {
194
- updatedData: update(updatedData, spec),
195
- };
196
- });
197
- },
198
- setUpdatedData(data: StateUpdater<T>) {
199
- if (Array.isArray(data)) {
200
- set({ updatedData: data });
201
- } else {
202
- set((state) => {
203
- return { updatedData: data(state.updatedData) };
204
- });
205
- }
206
- },
207
- deleteSelectedRows() {
208
- // Remove selected rows from the data and updatedData arrays
209
- set((state) => {
210
- const { selection, deletedRows } = state;
211
- const rowIndices = getRowIndices(selection);
212
-
213
- // Delete rows from both updatedData and data
214
- const newDeletedRows = new Set(deletedRows);
215
- for (const rowIndex of rowIndices) {
216
- newDeletedRows.add(rowIndex);
217
- }
218
-
219
- // Remove selected rows and reset selection
220
- return {
221
- deletedRows: newDeletedRows,
222
- selection: [],
223
- focusedCell: null,
224
- topLeftCell: null,
225
- fillValueBaseCell: null,
226
- };
227
- });
228
- },
229
- resetChanges() {
230
- // Reset the updated data to the initial data
231
- set((state) => ({
232
- updatedData: [],
233
- deletedRows: new Set<number>(),
234
- columnWidths: new Map<string, number>(),
235
- selection: [],
236
- focusedCell: null,
237
- topLeftCell: null,
238
- fillValueBaseCell: null,
239
- }));
240
- },
241
- onColumnWidthChanged(columnIx: number, newWidth: number) {
242
- set((state) => {
243
- const { columnSpec, columnWidthsIndex } = state;
244
- const colKey = columnSpec[columnIx].key;
245
- const newColumnWidths = new Map(columnWidthsIndex);
246
- newColumnWidths.set(colKey, newWidth);
247
- return { columnWidthsIndex: newColumnWidths };
248
- });
249
- },
250
- setVisibleCells(visibleCells: VisibleCells) {
251
- // Visible cells are used for infinite scrolling
252
- // Right now we don't store this in the state
253
- visibleCellsRef.current = visibleCells;
254
- },
255
- onDragValue(cell: FocusedCellCoordinates | null) {
256
- set({ fillValueBaseCell: cell });
257
- },
258
- onCellEdited(rowIndex: number, columnName: string, value: any) {
259
- set((state) => {
260
- const { editable, updatedData, data } = state;
261
- if (!editable) return {};
262
- let rowSpec: any;
263
-
264
- // Check to see if the new value is the same as the old one
265
- if (value !== data[rowIndex]?.[columnName]) {
266
- const rowOp = updatedData[rowIndex] != null ? "$merge" : "$set";
267
- rowSpec = { [rowOp]: { [columnName]: value } };
268
- } else {
269
- rowSpec = { $unset: [columnName] };
270
- }
271
- const spec: Spec<T[]> = { [rowIndex]: rowSpec };
272
- return { updatedData: update(updatedData, spec) };
273
- });
274
- },
275
- initialize(props: DataSheetCoreProps<T>) {
276
- set({ ...props, initialized: true });
277
- },
278
- clearSelection() {
279
- set((state) => {
280
- // Delete all selected cells
281
- const { selection, updatedData, columnSpec, data } = state;
282
- let spec = {};
283
- for (const region of selection) {
284
- console.log("Clearing region", region);
285
- const { cols, rows } = region;
286
- const rowRange = range(rows ?? [0, updatedData.length - 1]);
287
- const colRange = range(cols ?? [0, columnSpec.length - 1]);
288
- for (const row of rowRange) {
289
- let vals = {};
290
- for (const col of colRange) {
291
- const key = columnSpec[col].key;
292
- const currentValue =
293
- updatedData[row]?.[key] ?? data[row]?.[key];
294
- if (currentValue != null && currentValue !== "") {
295
- vals[key] = "";
296
- }
297
- }
298
- let op = updatedData[row] == null ? "$set" : "$merge";
299
- spec[row] = { [op]: vals };
300
- }
301
- }
302
- return {
303
- updatedData: update(updatedData, spec),
304
- };
305
- });
306
- },
307
- onSelection(selection: Region[]) {
308
- set((state) => {
309
- if (
310
- selectionEquals(selection, state.selection) &&
311
- singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode
312
- ) {
313
- // If the selection is the same as the current selection, remove the selection.
314
- // In practice this only happens for whole-row and whole-column selections
315
- return {
316
- selection: [],
317
- focusedCell: null,
318
- topLeftCell: null,
319
- fillValueBaseCell: null,
320
- };
321
- }
322
-
323
- let spec = updateSelection(selection);
324
- if (state.fillValueBaseCell != null) {
325
- spec.updatedData = fillValues(state, selection);
326
- }
327
- return spec;
328
- });
329
- },
330
- onSelectionEdited(value: any) {
331
- // Apply the same value to all selected cells
332
- set((state) => {
333
- const { selection, updatedData, columnSpec, editable } = state;
334
- if (!editable) return {};
335
- let spec = {};
336
- for (const region of selection) {
337
- const { cols, rows } = region;
338
- const rowRange = range(rows ?? [0, updatedData.length - 1]);
339
- const colRange = range(cols ?? [0, columnSpec.length - 1]);
340
- for (const row of rowRange) {
341
- let vals = {};
342
- for (const col of colRange) {
343
- const key = columnSpec[col].key;
344
- vals[key] = value;
345
- }
346
- let op = updatedData[row] == null ? "$set" : "$merge";
347
- spec[row] = { [op]: vals };
348
- }
349
- }
350
- return {
351
- updatedData: update(updatedData, spec),
352
- };
353
- });
354
- },
355
- onColumnsReordered(
356
- oldIndex: number,
357
- newIndex: number,
358
- length: number,
359
- ) {
360
- set((state) => {
361
- if (!state.enableColumnReordering) return {};
362
- const { columnSpec } = state;
363
- const newSpec = [...columnSpec];
364
- const removed = newSpec.splice(oldIndex, length);
365
- newSpec.splice(newIndex, 0, ...removed);
366
- return { columnSpec: newSpec };
367
- });
368
- },
369
- scrollToRow(rowIndex: number) {
370
- if (tableRef.current == null) return;
371
- tableRef.current.scrollToRegion({
372
- rows: [rowIndex, rowIndex],
373
- });
374
- },
375
- };
376
- }),
377
- );
378
- });
79
+ const initializeStore = scope.useSetAtom(initializeStoreAtom);
379
80
 
380
81
  // Not sure how required this initialization is
381
82
  useEffect(() => {
382
- const { initialize } = store.getState();
383
- initialize({
384
- data,
83
+ initializeStore({
385
84
  columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),
386
85
  editable,
387
86
  enableColumnReordering,
87
+ data,
88
+ defaultColumnWidth,
89
+ tableRef,
90
+ visibleCellsRef,
388
91
  });
389
92
  }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);
390
93
 
391
- return h(DataSheetContext.Provider, { value: store }, children);
94
+ return children;
392
95
  }
393
96
 
394
97
  export function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {
395
- const store = useContext(DataSheetContext);
98
+ const store = scope.useAtomValue(storeAPIAtom);
396
99
  if (!store) {
397
100
  throw new Error("Missing DataSheetProvider");
398
101
  }
@@ -405,123 +108,3 @@ export function useSelector<T = any, A = any>(
405
108
  const store = useStoreAPI<T>();
406
109
  return useStore(store, selector);
407
110
  }
408
-
409
- function updateSelection<T>(selection: Region[]) {
410
- const focusedCell = singleFocusedCell(selection);
411
- let spec: Partial<DataSheetState<T>> = {
412
- selection,
413
- focusedCell,
414
- topLeftCell: topLeftCell(selection),
415
- };
416
- if (focusedCell != null) {
417
- spec.fillValueBaseCell = null;
418
- }
419
- return spec;
420
- }
421
-
422
- function getLastRowIndex(regions: Region[]): number | null {
423
- /** Get the last row index from a selection of regions */
424
- if (regions == null || regions.length === 0) return null;
425
- let lastRow = -1;
426
- for (const region of regions) {
427
- const { rows } = region;
428
- if (rows == null || rows.length !== 2) continue;
429
- lastRow = Math.max(lastRow, rows[1]);
430
- }
431
- if (lastRow < 0) {
432
- /** If no valid rows are found, return null */
433
- return null;
434
- }
435
- return lastRow;
436
- }
437
-
438
- function getRowIndices(regions: Region[]): number[] {
439
- /** Get the row indices from a selection of regions */
440
- if (regions == null || regions.length === 0) return [];
441
- const rowIndices = new Set<number>();
442
- for (const region of regions) {
443
- const { rows } = region;
444
- if (rows == null || rows.length !== 2) continue;
445
- for (let i = rows[0]; i <= rows[1]; i++) {
446
- rowIndices.add(i);
447
- }
448
- }
449
- return Array.from(rowIndices).sort((a, b) => a - b);
450
- }
451
-
452
- export function topLeftCell(
453
- regions: Region[],
454
- requireSolitaryCell: boolean = false,
455
- ): FocusedCellCoordinates | null {
456
- /** Top left cell of a ranged selection */
457
- if (regions == null) return null;
458
- const [region] = regions;
459
- if (region == null) return null;
460
- const { cols, rows } = region;
461
- if (cols == null || rows == null) return null;
462
- if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))
463
- return null;
464
- return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };
465
- }
466
-
467
- function selectionEquals(a: Region[], b: Region[]): boolean {
468
- /** Check if two selections are equal */
469
- if (a.length !== b.length) return false;
470
- for (let i = 0; i < a.length; i++) {
471
- const regionA = a[i];
472
- const regionB = b[i];
473
-
474
- const colsA = regionA.cols ?? [];
475
- const colsB = regionB.cols ?? [];
476
-
477
- const rowsA = regionA.rows ?? [];
478
- const rowsB = regionB.rows ?? [];
479
-
480
- if (
481
- colsA.length !== colsB.length ||
482
- rowsA.length !== rowsB.length ||
483
- colsA[0] !== colsB[0] ||
484
- colsA[1] !== colsB[1] ||
485
- rowsA[0] !== rowsB[0] ||
486
- rowsA[1] !== rowsB[1]
487
- ) {
488
- return false;
489
- }
490
- }
491
- return true;
492
- }
493
-
494
- export function singleFocusedCell(
495
- sel: Region[],
496
- ): FocusedCellCoordinates | null {
497
- /** Derive a single focused cell from a selected region, if possible */
498
- if (sel?.length !== 1) return null;
499
- return topLeftCell(sel, true);
500
- }
501
-
502
- function fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {
503
- const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;
504
-
505
- // Prepare regions by unnesting columns
506
- let regions = selection.map((region) => {
507
- const { cols, rows } = region;
508
- // Get the first column (maybe should be the last)
509
- const [col] = cols;
510
- return { cols: [col, col], rows };
511
- });
512
-
513
- // Fill values downwards
514
- if (!editable || fillValueBaseCell == null) return updatedData;
515
- const { col, row } = fillValueBaseCell;
516
- const key = columnSpec[col].key;
517
- const value = updatedData[row]?.[key] ?? data[row][key];
518
- const spec = {};
519
- for (const region of regions) {
520
- const { cols, rows } = region;
521
- for (const row of range(rows)) {
522
- let op = updatedData[row] == null ? "$set" : "$merge";
523
- spec[row] = { [op]: { [key]: value } };
524
- }
525
- }
526
- return update(updatedData, spec);
527
- }
package/src/types.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type {
2
+ FocusedCellCoordinates,
3
+ Region,
4
+ Table2,
5
+ } from "@blueprintjs/table";
6
+ import { ColumnSpec, ColumnSpecOptions } from "./utils";
7
+
8
+ export interface DataSheetCoreProps<T> {
9
+ data: T[];
10
+ columnSpec?: ColumnSpec[];
11
+ editable?: boolean;
12
+ enableColumnReordering?: boolean;
13
+ defaultColumnWidth?: number;
14
+ }
15
+
16
+ export interface DataSheetState<T> {
17
+ selection: Region[];
18
+ columnSpec: ColumnSpec[];
19
+ fillValueBaseCell: FocusedCellCoordinates | null;
20
+ focusedCell: FocusedCellCoordinates | null;
21
+ topLeftCell: FocusedCellCoordinates | null;
22
+ deletedRows: Set<number>;
23
+ // Sparse data structure for updated data
24
+ updatedData: T[];
25
+ initialized: boolean;
26
+ columnWidthsIndex: Map<string, number>;
27
+ }
28
+
29
+ type DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;
30
+ export type StateUpdater<T> = T[] | ((state: T[]) => T[]);
31
+
32
+ export interface DataSheetStoreMain<T> extends DataSheetVals<T> {
33
+ setSelection(selection: Region[]): void;
34
+ onDragValue(event: MouseEvent): void;
35
+ setUpdatedData(data: StateUpdater<T>): void;
36
+ onCellEdited(rowIndex: number, columnName: string, value: any): void;
37
+ onSelectionEdited(value: any): void;
38
+ onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;
39
+ onColumnWidthChanged(columnIndex: number, newWidth: number): void;
40
+ moveFocusedCell(direction: "up" | "down" | "left" | "right"): void;
41
+ deleteSelectedRows(): void;
42
+ clearSelection(): void;
43
+ resetChanges(): void;
44
+ addRow(): void;
45
+ initialize(props: Partial<DataSheetStoreMain<T>>): void;
46
+ onSelection(selection: Region[]): void;
47
+ // Internal method used for infinite scrolling
48
+ setVisibleCells(visibleCells: VisibleCells): void;
49
+ scrollToRow(rowIndex: number): void;
50
+ tableRef: React.MutableRefObject<Table2>;
51
+ visibleCellsRef: React.MutableRefObject<VisibleCells>;
52
+ columnWidthsIndex: Map<string, number>;
53
+ defaultColumnWidth: number;
54
+ }
55
+
56
+ export type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {
57
+ children: React.ReactNode;
58
+ columnSpecOptions?: ColumnSpecOptions<T>;
59
+ };
60
+
61
+ export interface VisibleCells {
62
+ rowIndexStart: number;
63
+ rowIndexEnd: number;
64
+ }
65
+
66
+ export type DataSheetStore<T> = DataSheetStoreMain<T>;
@@ -133,7 +133,12 @@ export function generateColumnSpec<T>(
133
133
  options: ColumnSpecOptions<T>,
134
134
  ): ColumnSpec[] {
135
135
  /** Generate a column spec from a dataset */
136
- const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;
136
+ const {
137
+ overrides = {},
138
+ nRows = 10,
139
+ omitColumns,
140
+ includeColumns,
141
+ } = options ?? {};
137
142
 
138
143
  if (data == null) return [];
139
144