@macrostrat/data-sheet 3.1.0 → 4.0.0-dev2

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 (184) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/actions/builtin.cjs +56 -0
  3. package/dist/actions/builtin.cjs.map +1 -0
  4. package/dist/actions/builtin.d.ts +15 -0
  5. package/dist/actions/builtin.js +56 -0
  6. package/dist/actions/builtin.js.map +1 -0
  7. package/dist/actions/clipboard.cjs +250 -0
  8. package/dist/actions/clipboard.cjs.map +1 -0
  9. package/dist/actions/clipboard.d.ts +42 -0
  10. package/dist/actions/clipboard.js +250 -0
  11. package/dist/actions/clipboard.js.map +1 -0
  12. package/dist/actions/filters.cjs +123 -0
  13. package/dist/actions/filters.cjs.map +1 -0
  14. package/dist/actions/filters.d.ts +6 -0
  15. package/dist/actions/filters.js +123 -0
  16. package/dist/actions/filters.js.map +1 -0
  17. package/dist/actions/index.d.ts +6 -0
  18. package/dist/actions/selection.cjs +194 -0
  19. package/dist/actions/selection.cjs.map +1 -0
  20. package/dist/actions/selection.d.ts +40 -0
  21. package/dist/actions/selection.js +192 -0
  22. package/dist/actions/selection.js.map +1 -0
  23. package/dist/actions/toolbar.cjs +171 -0
  24. package/dist/actions/toolbar.cjs.map +1 -0
  25. package/dist/actions/toolbar.d.ts +10 -0
  26. package/dist/actions/toolbar.js +171 -0
  27. package/dist/actions/toolbar.js.map +1 -0
  28. package/dist/actions/toolbar.module.sass.cjs +22 -0
  29. package/dist/actions/toolbar.module.sass.cjs.map +1 -0
  30. package/dist/actions/toolbar.module.sass.js +20 -0
  31. package/dist/actions/toolbar.module.sass.js.map +1 -0
  32. package/dist/actions/types.d.ts +143 -0
  33. package/dist/cell-renderer.cjs +44 -41
  34. package/dist/cell-renderer.cjs.map +1 -1
  35. package/dist/cell-renderer.d.ts +1 -6
  36. package/dist/cell-renderer.js +45 -42
  37. package/dist/cell-renderer.js.map +1 -1
  38. package/dist/components/actions.module.sass.cjs +3 -3
  39. package/dist/components/actions.module.sass.js +2 -2
  40. package/dist/components/colors.cjs +20 -16
  41. package/dist/components/colors.cjs.map +1 -1
  42. package/dist/components/colors.d.ts +3 -2
  43. package/dist/components/colors.js +20 -16
  44. package/dist/components/colors.js.map +1 -1
  45. package/dist/components/editor-popup.cjs +4 -3
  46. package/dist/components/editor-popup.cjs.map +1 -1
  47. package/dist/components/editor-popup.js +4 -3
  48. package/dist/components/editor-popup.js.map +1 -1
  49. package/dist/components/index.d.ts +1 -0
  50. package/dist/components/main.module.sass.cjs +12 -12
  51. package/dist/components/main.module.sass.js +11 -11
  52. package/dist/components/text-areas.cjs +23 -18
  53. package/dist/components/text-areas.cjs.map +1 -1
  54. package/dist/components/text-areas.d.ts +8 -4
  55. package/dist/components/text-areas.js +20 -13
  56. package/dist/components/text-areas.js.map +1 -1
  57. package/dist/components/view-info.cjs +18 -0
  58. package/dist/components/view-info.cjs.map +1 -0
  59. package/dist/components/view-info.d.ts +1 -0
  60. package/dist/components/view-info.js +18 -0
  61. package/dist/components/view-info.js.map +1 -0
  62. package/dist/core.cjs +184 -156
  63. package/dist/core.cjs.map +1 -1
  64. package/dist/core.d.ts +14 -1
  65. package/dist/core.js +187 -157
  66. package/dist/core.js.map +1 -1
  67. package/dist/data-sheet.css +181 -43
  68. package/dist/index.cjs +43 -13
  69. package/dist/index.cjs.map +1 -1
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.js +43 -10
  72. package/dist/index.js.map +1 -1
  73. package/dist/main.module.sass.cjs +15 -14
  74. package/dist/main.module.sass.cjs.map +1 -1
  75. package/dist/main.module.sass.js +14 -13
  76. package/dist/main.module.sass.js.map +1 -1
  77. package/dist/notifications.cjs +19 -0
  78. package/dist/notifications.cjs.map +1 -0
  79. package/dist/notifications.d.ts +9 -0
  80. package/dist/notifications.js +19 -0
  81. package/dist/notifications.js.map +1 -0
  82. package/dist/postgrest-table/data-loaders.cjs +181 -104
  83. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  84. package/dist/postgrest-table/data-loaders.d.ts +52 -28
  85. package/dist/postgrest-table/data-loaders.js +181 -104
  86. package/dist/postgrest-table/data-loaders.js.map +1 -1
  87. package/dist/postgrest-table/index.cjs +205 -79
  88. package/dist/postgrest-table/index.cjs.map +1 -1
  89. package/dist/postgrest-table/index.d.ts +13 -16
  90. package/dist/postgrest-table/index.js +186 -58
  91. package/dist/postgrest-table/index.js.map +1 -1
  92. package/dist/postgrest-table/lazy-loader-table.cjs +18 -17
  93. package/dist/postgrest-table/lazy-loader-table.cjs.map +1 -1
  94. package/dist/postgrest-table/lazy-loader-table.d.ts +1 -1
  95. package/dist/postgrest-table/lazy-loader-table.js +17 -14
  96. package/dist/postgrest-table/lazy-loader-table.js.map +1 -1
  97. package/dist/postgrest-table/loading-utils.cjs +16 -0
  98. package/dist/postgrest-table/loading-utils.cjs.map +1 -0
  99. package/dist/postgrest-table/loading-utils.d.ts +13 -0
  100. package/dist/postgrest-table/loading-utils.js +16 -0
  101. package/dist/postgrest-table/loading-utils.js.map +1 -0
  102. package/dist/postgrest-table/main.module.sass.cjs +18 -13
  103. package/dist/postgrest-table/main.module.sass.cjs.map +1 -1
  104. package/dist/postgrest-table/main.module.sass.js +18 -13
  105. package/dist/postgrest-table/main.module.sass.js.map +1 -1
  106. package/dist/provider.cjs +58 -26
  107. package/dist/provider.cjs.map +1 -1
  108. package/dist/provider.js +57 -23
  109. package/dist/provider.js.map +1 -1
  110. package/dist/renderers/column-header-cell-postgrest.cjs +216 -0
  111. package/dist/renderers/column-header-cell-postgrest.cjs.map +1 -0
  112. package/dist/renderers/column-header-cell-postgrest.d.ts +13 -0
  113. package/dist/renderers/column-header-cell-postgrest.js +216 -0
  114. package/dist/renderers/column-header-cell-postgrest.js.map +1 -0
  115. package/dist/renderers/column-header-cell-postgrest.module.sass.cjs +23 -0
  116. package/dist/renderers/column-header-cell-postgrest.module.sass.cjs.map +1 -0
  117. package/dist/renderers/column-header-cell-postgrest.module.sass.js +22 -0
  118. package/dist/renderers/column-header-cell-postgrest.module.sass.js.map +1 -0
  119. package/dist/renderers/column-header-cell.cjs +103 -0
  120. package/dist/renderers/column-header-cell.cjs.map +1 -0
  121. package/dist/renderers/column-header-cell.d.ts +30 -0
  122. package/dist/renderers/column-header-cell.js +101 -0
  123. package/dist/renderers/column-header-cell.js.map +1 -0
  124. package/dist/renderers/index.d.ts +2 -0
  125. package/dist/table-updates/data-parameter.d.ts +14 -0
  126. package/dist/table-updates/filter.d.ts +16 -0
  127. package/dist/table-updates/index.d.ts +19 -0
  128. package/dist/types.cjs +9 -0
  129. package/dist/types.cjs.map +1 -0
  130. package/dist/types.d.ts +58 -4
  131. package/dist/types.js +9 -0
  132. package/dist/types.js.map +1 -0
  133. package/dist/utils/column-spec.cjs +9 -1
  134. package/dist/utils/column-spec.cjs.map +1 -1
  135. package/dist/utils/column-spec.d.ts +21 -0
  136. package/dist/utils/column-spec.js +9 -1
  137. package/dist/utils/column-spec.js.map +1 -1
  138. package/dist/utils/key-handling.cjs +141 -52
  139. package/dist/utils/key-handling.cjs.map +1 -1
  140. package/dist/utils/key-handling.d.ts +2 -3
  141. package/dist/utils/key-handling.js +142 -53
  142. package/dist/utils/key-handling.js.map +1 -1
  143. package/dist/zustand-store.cjs +216 -51
  144. package/dist/zustand-store.cjs.map +1 -1
  145. package/dist/zustand-store.js +197 -32
  146. package/dist/zustand-store.js.map +1 -1
  147. package/package.json +5 -5
  148. package/src/actions/builtin.ts +65 -0
  149. package/src/actions/clipboard.ts +350 -0
  150. package/src/actions/filters.ts +150 -0
  151. package/src/actions/index.ts +6 -0
  152. package/src/actions/selection.ts +271 -0
  153. package/src/actions/toolbar.module.sass +30 -0
  154. package/src/actions/toolbar.ts +212 -0
  155. package/src/actions/types.ts +159 -0
  156. package/src/cell-renderer.ts +55 -51
  157. package/src/components/colors.ts +22 -19
  158. package/src/components/editor-popup.ts +3 -2
  159. package/src/components/index.ts +1 -0
  160. package/src/components/main.module.sass +1 -0
  161. package/src/components/text-areas.ts +34 -19
  162. package/src/components/view-info.ts +17 -0
  163. package/src/core.ts +243 -170
  164. package/src/index.ts +1 -0
  165. package/src/main.module.sass +14 -2
  166. package/src/notifications.ts +22 -0
  167. package/src/postgrest-table/data-loaders.ts +300 -201
  168. package/src/postgrest-table/index.ts +258 -84
  169. package/src/postgrest-table/lazy-loader-table.ts +18 -17
  170. package/src/postgrest-table/loading-utils.ts +49 -0
  171. package/src/postgrest-table/main.module.sass +16 -0
  172. package/src/provider.ts +63 -20
  173. package/src/renderers/column-header-cell-postgrest.module.sass +71 -0
  174. package/src/renderers/column-header-cell-postgrest.ts +282 -0
  175. package/src/renderers/column-header-cell.ts +388 -0
  176. package/src/renderers/index.ts +2 -0
  177. package/src/table-updates/data-parameter.ts +44 -0
  178. package/src/table-updates/filter.ts +124 -0
  179. package/src/table-updates/index.ts +239 -0
  180. package/src/types.ts +58 -3
  181. package/src/utils/column-spec.ts +47 -0
  182. package/src/utils/key-handling.ts +181 -72
  183. package/src/zustand-store.ts +241 -36
  184. package/dist/provider.d.ts +0 -15
@@ -1,59 +1,148 @@
1
1
  import type { KeyboardEvent } from "react";
2
- import { storeAPIAtom, storeAtom } from "../provider";
2
+ import { storeAPIAtom, storeAtom, tableActionsAtom } from "../provider";
3
3
  import type { DataSheetStoreMain } from "../types";
4
4
  import { atom } from "jotai";
5
5
  import { singleFocusedCell } from "../zustand-store.ts";
6
+ import { buildActionContext, runActionWrapper } from "../actions";
7
+ import { HotkeyConfig } from "@blueprintjs/core";
8
+ import { toasterAtom } from "../notifications.ts";
6
9
 
7
- export const tableKeyHandlerAtom = atom((get) => {
10
+ type HotkeyActionRunner = (
11
+ e: KeyboardEvent,
12
+ state: DataSheetStoreMain<any>,
13
+ setState: (state: Partial<DataSheetStoreMain<any>>) => void,
14
+ ) => void | Promise<void>;
15
+
16
+ const isEditableAtom = atom((get) => {
17
+ const store = get(storeAtom);
18
+ return store?.editable ?? false;
19
+ });
20
+
21
+ const hasSelectionAtom = atom((get) => {
22
+ const store = get(storeAtom);
23
+ const selection = store?.selection ?? [];
24
+ return selection.length > 0;
25
+ });
26
+
27
+ export const tableHotkeysAtom = atom<HotkeyConfig[]>((get) => {
8
28
  const store = get(storeAPIAtom);
9
- return (e: KeyboardEvent) => {
10
- // Kind of a ridiculous hack to get the store from the atom.
11
- const state = store.getState();
12
- tableKeyHandler(e, state);
29
+ const toaster = get(toasterAtom);
30
+ const editable = get(isEditableAtom);
31
+
32
+ /** Set up hotkeys for table actions */
33
+ const tableActions = get(tableActionsAtom);
34
+
35
+ if (store == null) return [];
36
+ const keyHandler = (
37
+ actionRunner: HotkeyActionRunner,
38
+ ): HotkeyConfig["onKeyDown"] => {
39
+ return (e) => {
40
+ // Kind of a ridiculous hack to get the store from the atom.
41
+ const state = store.getState();
42
+ const setState = store.setState;
43
+ try {
44
+ const res = actionRunner(e, state, setState);
45
+ if (res instanceof Promise) {
46
+ res
47
+ .then(() => {})
48
+ .catch((err) => {
49
+ console.error(err);
50
+ handleError(toaster, err);
51
+ });
52
+ }
53
+ } catch (err) {
54
+ handleError(toaster, err);
55
+ }
56
+ };
13
57
  };
14
- });
15
58
 
16
- export function tableKeyHandler<T>(
17
- e: KeyboardEvent,
18
- state: DataSheetStoreMain<T>,
19
- ) {
20
- // General key event
21
- if (e.key === "Escape") {
22
- // Clear selection on Escape
23
- state.setSelection([]);
24
- e.preventDefault();
25
- e.stopPropagation();
26
- }
27
- // Clear selection on Backspace or Delete
28
- if (e.key === "Backspace" || e.key === "Delete") {
29
- // Clear selection on Backspace or Delete
30
- state.clearSelection();
31
- e.preventDefault();
32
- }
33
- // Handle arrow keys for navigation
34
- if (e.key in directionMap) {
35
- // Handle arrow key navigation
36
- const direction = directionMap[e.key];
37
- state.moveFocusedCell(direction);
38
- // Prevent default scrolling behavior
39
- e.preventDefault();
40
- }
41
- if (e.key === "Tab") {
42
- state.moveFocusedCell(e.shiftKey ? "left" : "right");
43
- e.preventDefault();
59
+ function handleError(toaster, err) {
60
+ toaster.show({
61
+ message: `${err}`,
62
+ intent: "danger",
63
+ });
44
64
  }
45
- if (e.key === "Enter") {
46
- state.moveFocusedCell("down");
47
- e.preventDefault();
48
- }
49
- }
50
65
 
51
- const directionMap = {
52
- ArrowUp: "up",
53
- ArrowDown: "down",
54
- ArrowLeft: "left",
55
- ArrowRight: "right",
56
- };
66
+ const directionCombos = ["up", "down", "left", "right"].map((dir) => {
67
+ return {
68
+ combo: dir,
69
+ group: "Navigation",
70
+ label: "Move focus " + dir,
71
+ preventDefault: true,
72
+ onKeyDown: keyHandler((e, state) => {
73
+ state.moveFocusedCell(dir);
74
+ }),
75
+ };
76
+ });
77
+
78
+ /** TODO: merge a bit more with the actions config */
79
+
80
+ const actionsCombos = tableActions
81
+ .map((action) => {
82
+ if (action.hotkey == null) return null;
83
+ return {
84
+ combo: action.hotkey,
85
+ label: action.name,
86
+ group: action.group ?? "Actions",
87
+ preventDefault: true,
88
+ disabled: action.requiresEditable !== false && !editable,
89
+ onKeyDown(event: KeyboardEvent<any>): any {
90
+ const state = store.getState();
91
+ const setState = store.setState;
92
+ runActionWrapper(action, state, setState, toaster);
93
+ },
94
+ } as any as HotkeyConfig;
95
+ })
96
+ .filter(Boolean) as HotkeyConfig[];
97
+
98
+ return [
99
+ {
100
+ combo: "esc",
101
+ label: "Clear selection",
102
+ group: "Selection",
103
+ allowInInput: true,
104
+ onKeyDown: keyHandler((e, state) => {
105
+ if (state.selection.length == 0) {
106
+ // Focus goes back to parent
107
+ return;
108
+ }
109
+ state.setSelection([]);
110
+ e.preventDefault();
111
+ e.stopPropagation();
112
+ }),
113
+ },
114
+ {
115
+ combo: "backspace",
116
+ label: "Clear selection",
117
+ group: "Selection",
118
+ allowInInput: true,
119
+ disabled: !editable,
120
+ onKeyDown: keyHandler((e, state) => {
121
+ state.clearSelection();
122
+ }),
123
+ },
124
+ {
125
+ combo: "tab",
126
+ label: "Move focus right (or left with shift)",
127
+ group: "Navigation",
128
+ allowInInput: true,
129
+ onKeyDown: keyHandler((e, state) => {
130
+ state.moveFocusedCell(e.shiftKey ? "left" : "right");
131
+ }),
132
+ },
133
+ {
134
+ combo: "enter",
135
+ label: "Move focus down",
136
+ group: "Navigation",
137
+ allowInInput: true,
138
+ onKeyDown: keyHandler((e, state) => {
139
+ state.moveFocusedCell("down");
140
+ }),
141
+ },
142
+ ...directionCombos,
143
+ ...actionsCombos,
144
+ ];
145
+ });
57
146
 
58
147
  const selectionAtom = atom((get) => {
59
148
  const store = get(storeAtom);
@@ -72,13 +161,13 @@ export const editorKeyHandlerAtom = atom((get) => {
72
161
  };
73
162
  });
74
163
 
75
- function editorKeyHandler(e: KeyboardEvent, isSingleCellSelection: boolean) {
164
+ function editorKeyHandler(
165
+ e: KeyboardEvent<HTMLInputElement>,
166
+ isSingleCellSelection: boolean,
167
+ ) {
76
168
  /** Get a key handler for inline cell editing */
77
169
 
78
- // if (e.key == "Enter" || e.key == "Tab") {
79
- // e.target.blur();
80
- // return;
81
- // }
170
+ const target = e.target as HTMLInputElement;
82
171
 
83
172
  let shouldCaptureEventForInlineEditing = true;
84
173
 
@@ -98,39 +187,41 @@ function editorKeyHandler(e: KeyboardEvent, isSingleCellSelection: boolean) {
98
187
  }
99
188
 
100
189
  if (!shouldCaptureEventForInlineEditing) {
101
- e.target.blur();
190
+ target.blur();
102
191
  e.preventDefault();
103
192
  return;
104
193
  }
105
194
 
106
- const shouldPropagate = handleSpecialKeys(e);
195
+ const shouldPropagate = shouldPropagateKeystroke(e);
107
196
  if (!shouldPropagate) {
108
197
  e.stopPropagation();
198
+ //e.preventDefault();
109
199
  } else {
110
- e.target.blur();
111
- //e.target.parentNode.dispatchEvent(new KeyboardEvent("keydown", e));
200
+ // we blur the editor and dispatch a keydown event on the parent to propagate the event to the table
201
+ e.preventDefault();
202
+ target.blur();
203
+ //console.log(tableElement);
204
+ //tableElement.focus();
205
+ //target.parentNode?.dispatchEvent(e);
206
+ target.parentNode?.dispatchEvent(new KeyboardEvent("keydown", e));
112
207
  }
113
208
  }
114
209
 
115
- export function multiLineTextKeyHandler(evt: InputEvent) {
116
- if (evt.key === "Enter") {
117
- //evt.preventDefault();
118
- evt.stopPropagation();
119
- return;
120
- }
121
-
122
- if (evt.key === "Escape") {
123
- evt.preventDefault();
124
- return;
210
+ function shouldPropagateKeystroke(evt: KeyboardEvent): boolean {
211
+ if (evt.target.selectionStart == evt.target.selectionEnd) {
212
+ // We don't have anything selected, so we can propagate the event potentially
213
+ // Propagate copy and paste events even if there is no selection, since they might want to copy/paste an entire row/column based on the focused cell.
214
+ if (evt.key === "c" || evt.key === "v" || evt.key === "x") {
215
+ if (evt.ctrlKey || evt.metaKey) {
216
+ return true;
217
+ }
218
+ }
125
219
  }
126
220
 
127
- const shouldPropagate = handleSpecialKeys(evt);
128
- if (!shouldPropagate) {
129
- evt.stopPropagation();
221
+ if (evt.key === "ArrowUp" || evt.key === "ArrowDown") {
222
+ return true;
130
223
  }
131
- }
132
224
 
133
- function handleSpecialKeys(evt: KeyboardEvent): boolean {
134
225
  const target = evt.target;
135
226
  if (
136
227
  (evt.key === "ArrowLeft" ||
@@ -138,7 +229,6 @@ function handleSpecialKeys(evt: KeyboardEvent): boolean {
138
229
  evt.key === "ArrowDown") &&
139
230
  target.selectionStart === 0
140
231
  ) {
141
- target.blur();
142
232
  return true;
143
233
  }
144
234
 
@@ -150,9 +240,28 @@ function handleSpecialKeys(evt: KeyboardEvent): boolean {
150
240
  evt.key === "ArrowDown") &&
151
241
  target.selectionStart === evt.target.value.length
152
242
  ) {
153
- target.blur();
154
243
  return true;
155
244
  }
156
245
 
157
246
  return false;
158
247
  }
248
+
249
+ export function multiLineTextKeyHandler(evt: InputEvent) {
250
+ if (evt.key === "Enter") {
251
+ //evt.preventDefault();
252
+ evt.stopPropagation();
253
+ return;
254
+ }
255
+
256
+ if (evt.key === "Escape") {
257
+ evt.preventDefault();
258
+ return;
259
+ }
260
+
261
+ const shouldPropagate = shouldPropagateKeystroke(evt);
262
+ if (!shouldPropagate) {
263
+ evt.stopPropagation();
264
+ } else {
265
+ evt.target.blur();
266
+ }
267
+ }
@@ -3,29 +3,45 @@ import {
3
3
  DataSheetStore,
4
4
  DataSheetStoreMain,
5
5
  StateUpdater,
6
+ TableElementStatus,
6
7
  VisibleCells,
7
8
  } from "./types.ts";
8
- import type { FocusedCellCoordinates, Region } from "@blueprintjs/table";
9
+ import {
10
+ type FocusedCellCoordinates,
11
+ type Region,
12
+ RegionCardinality,
13
+ } from "@blueprintjs/table";
9
14
  import { range } from "./utils";
10
15
  import update, { Spec } from "immutability-helper";
16
+ import {
17
+ getSelectedColumnKeys,
18
+ getSelectedRowIndices,
19
+ getSelectionCardinality,
20
+ computeFilteredRowIndices,
21
+ computeTransformedRowIndices,
22
+ } from "./actions";
11
23
 
12
24
  export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
13
25
  return {
26
+ /** All the data in the table */
14
27
  data: [],
28
+ updatedData: [],
29
+ rowStatus: [],
15
30
  columnSpec: [],
16
31
  defaultColumnWidth: 150,
17
32
  editable: false,
18
- deletedRows: new Set<number>(),
19
33
  selection: [],
20
34
  fillValueBaseCell: null,
21
- updatedData: [],
22
35
  focusedCell: null,
23
36
  topLeftCell: null,
24
37
  initialized: false,
25
38
  tableRef: null,
26
- visibleCellsRef: null,
27
39
  // This is a placeholder
28
40
  enableColumnReordering: false,
41
+ activeFilters: new Map<string, { filter: any; state: any }>(),
42
+ columnSorts: [],
43
+ clipboardProxy: null,
44
+ filteredRowIndices: null,
29
45
  setSelection(selection: Region[]) {
30
46
  set(updateSelection(selection));
31
47
  },
@@ -60,18 +76,23 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
60
76
  /** Add a new row. If there is a selection, use the last row index to determine
61
77
  * where to insert the new row. Otherwise, append to the end of the data. */
62
78
  set((state) => {
63
- const { updatedData, data, selection } = state;
79
+ const { updatedData, data, selection, rowStatus } = state;
80
+
64
81
  const lastRowIndex =
65
82
  getLastRowIndex(selection) ??
66
83
  Math.max(data.length, updatedData.length) - 1;
67
- // If there is a selection, insert the new row after the last selected row
68
- const spec: Spec<any> = {
69
- $splice: [[lastRowIndex + 1, 0, row]],
70
- };
71
- console.log(spec);
84
+ // Use $set at a specific index to correctly extend the sparse array.
85
+ // $splice fails when the target index exceeds the array length.
86
+ const newIndex = lastRowIndex + 1;
72
87
 
73
88
  return {
74
- updatedData: update(updatedData, spec),
89
+ updateData: insertItemAtIndex(updatedData, newIndex, row as T),
90
+ data: insertItemAtIndex(data, newIndex, row as T),
91
+ rowStatus: insertItemAtIndex(
92
+ rowStatus,
93
+ newIndex,
94
+ TableElementStatus.ADDED,
95
+ ),
75
96
  };
76
97
  });
77
98
  },
@@ -91,32 +112,56 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
91
112
  const rowIndices = getRowIndices(selection);
92
113
 
93
114
  // Delete rows from both updatedData and data
94
- const newDeletedRows = new Set(deletedRows);
95
- for (const rowIndex of rowIndices) {
96
- newDeletedRows.add(rowIndex);
115
+
116
+ // If rows are in addedRows, we just delete them outright from the data and updatedData arrays
117
+ const { addedRows } = state;
118
+
119
+ const rowsNewlyDeleted = new Set(rowIndices);
120
+
121
+ // We outright remove rows that have not been added to the data array
122
+ const rowsToRemoveFromDataArrays = new Set(
123
+ rowIndices.filter(
124
+ (d) => state.rowStatus[d] == TableElementStatus.ADDED,
125
+ ),
126
+ );
127
+ // ...otherwise we set them to 'deleted'
128
+ const rowsToMarkAsDeleted = rowsNewlyDeleted.difference(
129
+ rowsToRemoveFromDataArrays,
130
+ );
131
+
132
+ let data = state.data;
133
+ let updatedData = state.updatedData;
134
+ let rowStatus = state.rowStatus;
135
+ if (rowsToMarkAsDeleted.size > 0) {
136
+ let spec: Spec<TableElementStatus[]> = {};
137
+ for (const ix of rowsToMarkAsDeleted) {
138
+ spec[ix] = { $set: TableElementStatus.DELETED };
139
+ }
140
+ rowStatus = update(rowStatus, spec);
141
+ }
142
+
143
+ if (rowsToRemoveFromDataArrays.size > 0) {
144
+ const filterFunc = (_, i) => !rowsToRemoveFromDataArrays.has(i);
145
+ data = data.filter(filterFunc);
146
+ updatedData = updatedData.filter(filterFunc);
147
+ rowStatus = rowStatus.filter(filterFunc);
97
148
  }
98
149
 
99
150
  // Remove selected rows and reset selection
100
151
  return {
101
- deletedRows: newDeletedRows,
102
152
  selection: [],
153
+ data,
154
+ updatedData,
155
+ rowStatus,
103
156
  focusedCell: null,
104
157
  topLeftCell: null,
105
158
  fillValueBaseCell: null,
106
159
  };
107
160
  });
108
161
  },
109
- resetChanges() {
162
+ resetChanges(regions?: Region[]) {
110
163
  // Reset the updated data to the initial data
111
- set((state) => ({
112
- updatedData: [],
113
- deletedRows: new Set<number>(),
114
- columnWidths: new Map<string, number>(),
115
- selection: [],
116
- focusedCell: null,
117
- topLeftCell: null,
118
- fillValueBaseCell: null,
119
- }));
164
+ set((state) => resetChangesForSelection(state, regions));
120
165
  },
121
166
  onColumnWidthChanged(columnIx: number, newWidth: number) {
122
167
  set((state) => {
@@ -127,13 +172,6 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
127
172
  return { columnWidthsIndex: newColumnWidths };
128
173
  });
129
174
  },
130
- setVisibleCells(visibleCells: VisibleCells) {
131
- // Visible cells are used for infinite scrolling
132
- // Right now we don't store this in the state
133
- const ref = get().visibleCellsRef;
134
- if (ref == null) return;
135
- ref.current = visibleCells;
136
- },
137
175
  onDragValue(event: MouseEvent) {
138
176
  set((state) => {
139
177
  return { fillValueBaseCell: state.focusedCell };
@@ -157,20 +195,20 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
157
195
  return { updatedData: update(updatedData, spec) };
158
196
  });
159
197
  },
160
- initialize(props: Partial<DataSheetStoreMain<T>>) {
161
- set({ ...props, initialized: true });
162
- },
163
198
  clearSelection() {
164
199
  set((state) => {
165
200
  // Delete all selected cells
166
201
  const { selection, updatedData, columnSpec, data } = state;
167
202
  let spec = {};
168
203
  for (const region of selection) {
169
- console.log("Clearing region", region);
170
204
  const { cols, rows } = region;
171
205
  const rowRange = range(rows ?? [0, updatedData.length - 1]);
172
206
  const colRange = range(cols ?? [0, columnSpec.length - 1]);
173
207
  for (const row of rowRange) {
208
+ // Don't clear row if it has been deleted
209
+ const rowIsDeleted =
210
+ state.rowStatus[row] === TableElementStatus.DELETED;
211
+ if (rowIsDeleted) continue;
174
212
  let vals = {};
175
213
  for (const col of colRange) {
176
214
  const key = columnSpec[col].key;
@@ -253,6 +291,85 @@ export function createZustandStore<T>(set, get): DataSheetStoreMain<T> {
253
291
  rows: [rowIndex, rowIndex],
254
292
  });
255
293
  },
294
+ setFilter(filterId: string, filter: any, filterState: any) {
295
+ set((state) => {
296
+ const newFilters = new Map<string, { filter: any; state: any }>(
297
+ state.activeFilters,
298
+ );
299
+ newFilters.set(filterId, { filter, state: filterState });
300
+ return {
301
+ activeFilters: newFilters,
302
+ filteredRowIndices: computeTransformedRowIndices(
303
+ state.data,
304
+ state.updatedData,
305
+ newFilters,
306
+ state.columnSorts,
307
+ ),
308
+ };
309
+ });
310
+ },
311
+ removeFilter(filterId: string) {
312
+ set((state) => {
313
+ const newFilters = new Map<string, { filter: any; state: any }>(
314
+ state.activeFilters,
315
+ );
316
+ newFilters.delete(filterId);
317
+ return {
318
+ activeFilters: newFilters,
319
+ filteredRowIndices: computeTransformedRowIndices(
320
+ state.data,
321
+ state.updatedData,
322
+ newFilters,
323
+ state.columnSorts,
324
+ ),
325
+ };
326
+ });
327
+ },
328
+ clearFilters() {
329
+ set((state) => ({
330
+ activeFilters: new Map<string, { filter: any; state: any }>(),
331
+ filteredRowIndices: computeTransformedRowIndices(
332
+ state.data,
333
+ state.updatedData,
334
+ new Map(),
335
+ state.columnSorts,
336
+ ),
337
+ }));
338
+ },
339
+ setColumnSort(key: string, ascending: boolean | null) {
340
+ set((state) => {
341
+ let newSorts;
342
+ if (ascending == null) {
343
+ newSorts = state.columnSorts.filter((s) => s.key !== key);
344
+ } else {
345
+ const without = state.columnSorts.filter((s) => s.key !== key);
346
+ newSorts = [...without, { key, ascending }];
347
+ }
348
+ return {
349
+ columnSorts: newSorts,
350
+ filteredRowIndices: computeTransformedRowIndices(
351
+ state.data,
352
+ state.updatedData,
353
+ state.activeFilters,
354
+ newSorts,
355
+ ),
356
+ };
357
+ });
358
+ },
359
+ clearColumnSorts() {
360
+ set((state) => ({
361
+ columnSorts: [],
362
+ filteredRowIndices: computeTransformedRowIndices(
363
+ state.data,
364
+ state.updatedData,
365
+ state.activeFilters,
366
+ [],
367
+ ),
368
+ }));
369
+ },
370
+ setClipboardProxy(proxy) {
371
+ set({ clipboardProxy: proxy });
372
+ },
256
373
  };
257
374
  }
258
375
 
@@ -375,3 +492,91 @@ function fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {
375
492
  }
376
493
  return update(updatedData, spec);
377
494
  }
495
+
496
+ function resetChangesForSelection<T>(
497
+ state: DataSheetStore<T>,
498
+ selection: Region[],
499
+ ): Partial<DataSheetStore<T>> {
500
+ const emptySelection = {
501
+ selection: [],
502
+ focusedCell: null,
503
+ topLeftCell: null,
504
+ fillValueBaseCell: null,
505
+ };
506
+
507
+ const { data } = state;
508
+ const cardinality =
509
+ getSelectionCardinality(selection ?? []) ?? RegionCardinality.FULL_TABLE;
510
+
511
+ const rowStatus = [...state.rowStatus];
512
+ const updatedData = [...state.updatedData];
513
+ const addedRows = new Set<number>();
514
+
515
+ // Global reset
516
+ switch (cardinality) {
517
+ case RegionCardinality.FULL_TABLE:
518
+ for (let i = 0; i < rowStatus.length; i++) {
519
+ if (rowStatus[i] === TableElementStatus.ADDED) {
520
+ addedRows.add(i);
521
+ }
522
+ }
523
+
524
+ return {
525
+ updatedData: [],
526
+ rowStatus: [],
527
+ data: data.filter((_, i) => !addedRows.has(i)),
528
+ ...emptySelection,
529
+ };
530
+ case RegionCardinality.FULL_COLUMNS:
531
+ case RegionCardinality.CELLS:
532
+ /** Columns or cells. Note, these only work the same because we don't
533
+ * allow column deletion, only unsetting all values.
534
+ */
535
+ const columnKeys = getSelectedColumnKeys(selection, state.columnSpec);
536
+ const spec: Spec<Record<string, any>[]> = {};
537
+ const rowIndices =
538
+ cardinality == RegionCardinality.FULL_COLUMNS
539
+ ? Array.from({ length: updatedData.length }, (_, i) => i)
540
+ : getSelectedRowIndices(selection);
541
+ for (const row of rowIndices) {
542
+ if (updatedData[row] == null) continue;
543
+ spec[row] = { $unset: columnKeys };
544
+ }
545
+ // TODO: if we allow column addition/deletion, this will require more adjustment
546
+ return {
547
+ updatedData: update(updatedData, spec),
548
+ ...emptySelection,
549
+ };
550
+ case RegionCardinality.FULL_ROWS:
551
+ for (const row of getSelectedRowIndices(selection)) {
552
+ updatedData[row] = undefined;
553
+ if (state.rowStatus[row] === TableElementStatus.DELETED) {
554
+ rowStatus[row] = undefined;
555
+ } else if (state.rowStatus[row] === TableElementStatus.ADDED) {
556
+ addedRows.add(row);
557
+ }
558
+ }
559
+
560
+ const removeCandidateRows = (arr: any[]) => {
561
+ return arr.filter((d, i) => !addedRows.has(i));
562
+ };
563
+
564
+ return {
565
+ updatedData: removeCandidateRows(updatedData),
566
+ data: removeCandidateRows(state.data),
567
+ rowStatus: removeCandidateRows(rowStatus),
568
+ ...emptySelection,
569
+ };
570
+ }
571
+ }
572
+
573
+ function insertItemAtIndex<T>(arr: T[], index: number, item: T) {
574
+ if (arr.length < index) {
575
+ const newArr = [...arr];
576
+ newArr.length = index;
577
+ newArr[index] = item;
578
+ return newArr;
579
+ }
580
+
581
+ return [...arr.slice(0, index), item, ...arr.slice(index)];
582
+ }
@@ -1,15 +0,0 @@
1
- import { StoreApi } from 'zustand';
2
- import { DataSheetProviderProps, DataSheetStore } from './types.ts';
3
- import { atom } from 'jotai';
4
- declare const useAtom: any, useAtomValue: any, useSetAtom: any;
5
- export { useAtom, useAtomValue, useSetAtom };
6
- export { atom };
7
- export declare const storeAPIAtom: import('jotai').PrimitiveAtom<StoreApi<DataSheetStore<any>>> & {
8
- init: StoreApi<DataSheetStore<any>>;
9
- };
10
- /** This is the basis for all other atoms that manipulate the store. */
11
- export declare const storeAtom: import('jotai').WritableAtom<DataSheetStore<any>, [action: any], void>;
12
- export declare function DataSheetProvider<T>(props: DataSheetProviderProps<T>): import('react').DetailedReactHTMLElement<import('react').InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>;
13
- export declare function DataSheetProviderInner<T>({ children, data, columnSpec, columnSpecOptions, editable, enableColumnReordering, defaultColumnWidth, }: DataSheetProviderProps<T>): import('react').ReactNode;
14
- export declare function useStoreAPI<T>(): StoreApi<DataSheetStore<T>>;
15
- export declare function useSelector<T = any, A = any>(selector: (state: DataSheetStore<T> & DataSheetComputedVals) => A): A;