@macrostrat/data-sheet 3.0.4 → 4.0.0-dev1

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 (185) hide show
  1. package/CHANGELOG.md +20 -1
  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 +165 -0
  34. package/dist/cell-renderer.cjs.map +1 -0
  35. package/dist/cell-renderer.d.ts +3 -0
  36. package/dist/cell-renderer.js +165 -0
  37. package/dist/cell-renderer.js.map +1 -0
  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 +4 -3
  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 +201 -300
  63. package/dist/core.cjs.map +1 -1
  64. package/dist/core.d.ts +18 -10
  65. package/dist/core.js +204 -299
  66. package/dist/core.js.map +1 -1
  67. package/dist/data-sheet.css +190 -52
  68. package/dist/index.cjs +47 -8
  69. package/dist/index.cjs.map +1 -1
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.js +48 -9
  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 +14 -17
  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 +96 -344
  107. package/dist/provider.cjs.map +1 -1
  108. package/dist/provider.js +96 -343
  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 +108 -0
  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 +161 -47
  139. package/dist/utils/key-handling.cjs.map +1 -1
  140. package/dist/utils/key-handling.d.ts +3 -3
  141. package/dist/utils/key-handling.js +161 -47
  142. package/dist/utils/key-handling.js.map +1 -1
  143. package/dist/zustand-store.cjs +485 -0
  144. package/dist/zustand-store.cjs.map +1 -0
  145. package/dist/zustand-store.d.ts +6 -0
  146. package/dist/zustand-store.js +483 -0
  147. package/dist/zustand-store.js.map +1 -0
  148. package/package.json +6 -5
  149. package/src/actions/builtin.ts +65 -0
  150. package/src/actions/clipboard.ts +350 -0
  151. package/src/actions/filters.ts +150 -0
  152. package/src/actions/index.ts +6 -0
  153. package/src/actions/selection.ts +271 -0
  154. package/src/actions/toolbar.module.sass +30 -0
  155. package/src/actions/toolbar.ts +212 -0
  156. package/src/actions/types.ts +159 -0
  157. package/src/cell-renderer.ts +221 -0
  158. package/src/components/colors.ts +22 -19
  159. package/src/components/editor-popup.ts +3 -2
  160. package/src/components/index.ts +1 -0
  161. package/src/components/main.module.sass +1 -0
  162. package/src/components/text-areas.ts +34 -19
  163. package/src/components/view-info.ts +17 -0
  164. package/src/core.ts +273 -360
  165. package/src/index.ts +4 -0
  166. package/src/main.module.sass +14 -2
  167. package/src/notifications.ts +22 -0
  168. package/src/postgrest-table/data-loaders.ts +300 -201
  169. package/src/postgrest-table/index.ts +260 -86
  170. package/src/postgrest-table/lazy-loader-table.ts +18 -17
  171. package/src/postgrest-table/loading-utils.ts +49 -0
  172. package/src/postgrest-table/main.module.sass +16 -0
  173. package/src/provider.ts +110 -487
  174. package/src/renderers/column-header-cell-postgrest.module.sass +71 -0
  175. package/src/renderers/column-header-cell-postgrest.ts +282 -0
  176. package/src/renderers/column-header-cell.ts +388 -0
  177. package/src/renderers/index.ts +2 -0
  178. package/src/table-updates/data-parameter.ts +44 -0
  179. package/src/table-updates/filter.ts +124 -0
  180. package/src/table-updates/index.ts +239 -0
  181. package/src/types.ts +121 -0
  182. package/src/utils/column-spec.ts +47 -0
  183. package/src/utils/key-handling.ts +201 -66
  184. package/src/zustand-store.ts +582 -0
  185. package/dist/provider.d.ts +0 -69
package/src/provider.ts CHANGED
@@ -1,117 +1,83 @@
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 { 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(event: MouseEvent): 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);
8
+ DataSheetProviderProps,
9
+ DataSheetState,
10
+ DataSheetStore,
11
+ } from "./types.ts";
12
+ import { createZustandStore } from "./zustand-store.ts";
13
+ import { atomWithStore } from "jotai-zustand";
14
+ import { toasterAtom } from "./notifications.ts";
15
+ import { TableAction } from "./actions";
16
+ import { atom } from "jotai";
17
+
18
+ /** Create a Jotai scoped store */
19
+ export const ctx = createScopedStore();
20
+
21
+ export const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();
22
+
23
+ const storeWrapperAtom = atom((get) => {
24
+ const _storeAPIAtom = get(storeAPIAtom);
25
+ if (_storeAPIAtom == null) {
26
+ return undefined;
27
+ }
28
+ return atomWithStore(_storeAPIAtom);
29
+ });
30
+
31
+ /** This is the basis for all other atoms that manipulate the store. */
32
+ export const storeAtom = atom(
33
+ (get) => {
34
+ const storeWrapper = get(storeWrapperAtom);
35
+ if (storeWrapper == null) {
36
+ return undefined;
37
+ }
38
+ return get(storeWrapper);
39
+ },
40
+ (get, set, action: SetStateAction<T>) => {
41
+ const storeWrapper = get(storeWrapperAtom);
42
+ if (storeWrapper == null) {
43
+ throw new Error("Missing DataSheetProvider");
44
+ }
45
+ return set(storeWrapper, action);
46
+ },
47
+ );
48
+
49
+ const initializeStoreAtom = atom(
50
+ null,
51
+ (get, set, payload: Partial<DataSheetStore<T>>) => {
52
+ set(storeAtom, (state) => {
53
+ return {
54
+ ...state,
55
+ ...payload,
56
+ };
57
+ });
58
+ },
59
+ );
74
60
 
75
- export interface VisibleCells {
76
- rowIndexStart: number;
77
- rowIndexEnd: number;
78
- }
61
+ export const tableActionsAtom = atom<TableAction[]>([]);
79
62
 
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;
63
+ export function DataSheetProvider<T>(props: DataSheetProviderProps<T>) {
64
+ const { toaster, ...rest } = props;
65
+ const [store] = useState(() => {
66
+ return createStore<DataSheetStore<T>>(createZustandStore);
67
+ });
68
+ return h(
69
+ ctx.Provider,
70
+ {
71
+ atoms: [
72
+ [storeAPIAtom, store],
73
+ [toasterAtom, toaster],
74
+ ],
75
+ },
76
+ h(DataSheetProviderInner, rest),
77
+ );
89
78
  }
90
79
 
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>({
80
+ export function DataSheetProviderInner<T>({
115
81
  children,
116
82
  data,
117
83
  columnSpec,
@@ -120,282 +86,27 @@ export function DataSheetProvider<T>({
120
86
  enableColumnReordering,
121
87
  defaultColumnWidth = 150,
122
88
  }: DataSheetProviderProps<T>) {
123
- const visibleCellsRef = useRef<VisibleCells>({
124
- rowIndexStart: 0,
125
- rowIndexEnd: 0,
126
- });
89
+ const tableRef = useRef<Table>(null);
127
90
 
128
- const tableRef = useRef<Table2>(null);
129
-
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(event: MouseEvent) {
256
- set((state) => {
257
- return { fillValueBaseCell: state.focusedCell };
258
- });
259
- event.preventDefault();
260
- },
261
- onCellEdited(rowIndex: number, columnName: string, value: any) {
262
- set((state) => {
263
- const { editable, updatedData, data } = state;
264
- if (!editable) return {};
265
- let rowSpec: any;
266
-
267
- // Check to see if the new value is the same as the old one
268
- if (value !== data[rowIndex]?.[columnName]) {
269
- const rowOp = updatedData[rowIndex] != null ? "$merge" : "$set";
270
- rowSpec = { [rowOp]: { [columnName]: value } };
271
- } else {
272
- rowSpec = { $unset: [columnName] };
273
- }
274
- const spec: Spec<T[]> = { [rowIndex]: rowSpec };
275
- return { updatedData: update(updatedData, spec) };
276
- });
277
- },
278
- initialize(props: DataSheetCoreProps<T>) {
279
- set({ ...props, initialized: true });
280
- },
281
- clearSelection() {
282
- set((state) => {
283
- // Delete all selected cells
284
- const { selection, updatedData, columnSpec, data } = state;
285
- let spec = {};
286
- for (const region of selection) {
287
- console.log("Clearing region", region);
288
- const { cols, rows } = region;
289
- const rowRange = range(rows ?? [0, updatedData.length - 1]);
290
- const colRange = range(cols ?? [0, columnSpec.length - 1]);
291
- for (const row of rowRange) {
292
- let vals = {};
293
- for (const col of colRange) {
294
- const key = columnSpec[col].key;
295
- const currentValue =
296
- updatedData[row]?.[key] ?? data[row]?.[key];
297
- if (currentValue != null && currentValue !== "") {
298
- vals[key] = "";
299
- }
300
- }
301
- let op = updatedData[row] == null ? "$set" : "$merge";
302
- spec[row] = { [op]: vals };
303
- }
304
- }
305
- return {
306
- updatedData: update(updatedData, spec),
307
- };
308
- });
309
- },
310
- onSelection(selection: Region[]) {
311
- set((state) => {
312
- if (
313
- selectionEquals(selection, state.selection) &&
314
- singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode
315
- ) {
316
- // If the selection is the same as the current selection, remove the selection.
317
- // In practice this only happens for whole-row and whole-column selections
318
- return {
319
- selection: [],
320
- focusedCell: null,
321
- topLeftCell: null,
322
- fillValueBaseCell: null,
323
- };
324
- }
325
-
326
- let spec = updateSelection(selection);
327
- if (state.fillValueBaseCell != null) {
328
- spec.updatedData = fillValues(state, selection);
329
- }
330
- return spec;
331
- });
332
- },
333
- onSelectionEdited(value: any) {
334
- // Apply the same value to all selected cells
335
- set((state) => {
336
- const { selection, updatedData, columnSpec, editable } = state;
337
- if (!editable) return {};
338
- let spec = {};
339
- for (const region of selection) {
340
- const { cols, rows } = region;
341
- const rowRange = range(rows ?? [0, updatedData.length - 1]);
342
- const colRange = range(cols ?? [0, columnSpec.length - 1]);
343
- for (const row of rowRange) {
344
- let vals = {};
345
- for (const col of colRange) {
346
- const key = columnSpec[col].key;
347
- vals[key] = value;
348
- }
349
- let op = updatedData[row] == null ? "$set" : "$merge";
350
- spec[row] = { [op]: vals };
351
- }
352
- }
353
- return {
354
- updatedData: update(updatedData, spec),
355
- };
356
- });
357
- },
358
- onColumnsReordered(
359
- oldIndex: number,
360
- newIndex: number,
361
- length: number,
362
- ) {
363
- set((state) => {
364
- if (!state.enableColumnReordering) return {};
365
- const { columnSpec } = state;
366
- const newSpec = [...columnSpec];
367
- const removed = newSpec.splice(oldIndex, length);
368
- newSpec.splice(newIndex, 0, ...removed);
369
- return { columnSpec: newSpec };
370
- });
371
- },
372
- scrollToRow(rowIndex: number) {
373
- if (tableRef.current == null) return;
374
- tableRef.current.scrollToRegion({
375
- rows: [rowIndex, rowIndex],
376
- });
377
- },
378
- };
379
- }),
380
- );
381
- });
91
+ const initializeStore = ctx.useSet(initializeStoreAtom);
382
92
 
383
93
  // Not sure how required this initialization is
384
94
  useEffect(() => {
385
- const { initialize } = store.getState();
386
- initialize({
387
- data,
95
+ initializeStore({
388
96
  columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),
389
97
  editable,
390
98
  enableColumnReordering,
99
+ data,
100
+ defaultColumnWidth,
101
+ tableRef,
391
102
  });
392
103
  }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);
393
104
 
394
- return h(DataSheetContext.Provider, { value: store }, children);
105
+ return children;
395
106
  }
396
107
 
397
108
  export function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {
398
- const store = useContext(DataSheetContext);
109
+ const store = ctx.useValue(storeAPIAtom);
399
110
  if (!store) {
400
111
  throw new Error("Missing DataSheetProvider");
401
112
  }
@@ -408,123 +119,35 @@ export function useSelector<T = any, A = any>(
408
119
  const store = useStoreAPI<T>();
409
120
  return useStore(store, selector);
410
121
  }
122
+ /** Atoms for efficient sub-selection of state */
411
123
 
412
- function updateSelection<T>(selection: Region[]) {
413
- const focusedCell = singleFocusedCell(selection);
414
- let spec: Partial<DataSheetState<T>> = {
415
- selection,
416
- focusedCell,
417
- topLeftCell: topLeftCell(selection),
418
- };
419
- if (focusedCell != null) {
420
- spec.fillValueBaseCell = null;
421
- }
422
- return spec;
423
- }
424
-
425
- function getLastRowIndex(regions: Region[]): number | null {
426
- /** Get the last row index from a selection of regions */
427
- if (regions == null || regions.length === 0) return null;
428
- let lastRow = -1;
429
- for (const region of regions) {
430
- const { rows } = region;
431
- if (rows == null || rows.length !== 2) continue;
432
- lastRow = Math.max(lastRow, rows[1]);
433
- }
434
- if (lastRow < 0) {
435
- /** If no valid rows are found, return null */
436
- return null;
437
- }
438
- return lastRow;
439
- }
440
-
441
- function getRowIndices(regions: Region[]): number[] {
442
- /** Get the row indices from a selection of regions */
443
- if (regions == null || regions.length === 0) return [];
444
- const rowIndices = new Set<number>();
445
- for (const region of regions) {
446
- const { rows } = region;
447
- if (rows == null || rows.length !== 2) continue;
448
- for (let i = rows[0]; i <= rows[1]; i++) {
449
- rowIndices.add(i);
450
- }
451
- }
452
- return Array.from(rowIndices).sort((a, b) => a - b);
453
- }
454
-
455
- export function topLeftCell(
456
- regions: Region[],
457
- requireSolitaryCell: boolean = false,
458
- ): FocusedCellCoordinates | null {
459
- /** Top left cell of a ranged selection */
460
- if (regions == null) return null;
461
- const [region] = regions;
462
- if (region == null) return null;
463
- const { cols, rows } = region;
464
- if (cols == null || rows == null) return null;
465
- if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))
466
- return null;
467
- return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };
468
- }
469
-
470
- function selectionEquals(a: Region[], b: Region[]): boolean {
471
- /** Check if two selections are equal */
472
- if (a.length !== b.length) return false;
473
- for (let i = 0; i < a.length; i++) {
474
- const regionA = a[i];
475
- const regionB = b[i];
476
-
477
- const colsA = regionA.cols ?? [];
478
- const colsB = regionB.cols ?? [];
479
-
480
- const rowsA = regionA.rows ?? [];
481
- const rowsB = regionB.rows ?? [];
124
+ export const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);
482
125
 
483
- if (
484
- colsA.length !== colsB.length ||
485
- rowsA.length !== rowsB.length ||
486
- colsA[0] !== colsB[0] ||
487
- colsA[1] !== colsB[1] ||
488
- rowsA[0] !== rowsB[0] ||
489
- rowsA[1] !== rowsB[1]
490
- ) {
491
- return false;
492
- }
493
- }
494
- return true;
495
- }
496
-
497
- export function singleFocusedCell(
498
- sel: Region[],
499
- ): FocusedCellCoordinates | null {
500
- /** Derive a single focused cell from a selected region, if possible */
501
- if (sel?.length !== 1) return null;
502
- return topLeftCell(sel, true);
503
- }
504
-
505
- function fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {
506
- const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;
507
-
508
- // Prepare regions by unnesting columns
509
- let regions = selection.map((region) => {
510
- const { cols, rows } = region;
511
- // Get the first column (maybe should be the last)
512
- const [col] = cols;
513
- return { cols: [col, col], rows };
514
- });
126
+ export const tableDataAtom = atom(
127
+ (get) => {
128
+ return get(storeAtom)?.data ?? [];
129
+ },
130
+ (get, set, newData: any[]) => {
131
+ set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {
132
+ console.log("Updating table data", newData);
133
+ if (
134
+ state.data.length == 0 &&
135
+ newData.length > 0 &&
136
+ state.columnSpec.length == 0
137
+ ) {
138
+ console.log("Generating column spec from data");
139
+ /** We haven't yet generated the column spec, and we need to do so. TODO: we may be able to forestall this with loading state */
140
+ return {
141
+ ...state,
142
+ columnSpec: generateColumnSpec(newData, state.columnSpecOptions),
143
+ data: newData,
144
+ };
145
+ }
515
146
 
516
- // Fill values downwards
517
- if (!editable || fillValueBaseCell == null) return updatedData;
518
- const { col, row } = fillValueBaseCell;
519
- const key = columnSpec[col].key;
520
- const value = updatedData[row]?.[key] ?? data[row][key];
521
- const spec = {};
522
- for (const region of regions) {
523
- const { cols, rows } = region;
524
- for (const row of range(rows)) {
525
- let op = updatedData[row] == null ? "$set" : "$merge";
526
- spec[row] = { [op]: { [key]: value } };
527
- }
528
- }
529
- return update(updatedData, spec);
530
- }
147
+ return {
148
+ ...state,
149
+ data: newData,
150
+ };
151
+ });
152
+ },
153
+ );