@rowsncolumns/grid 9.0.3 → 13.2.32

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 (208) hide show
  1. package/LICENSE.md +100 -0
  2. package/Readme.md +53 -59
  3. package/dist/cjs/Cell.d.ts +35 -0
  4. package/dist/cjs/Cell.d.ts.map +1 -0
  5. package/dist/cjs/Cell.js +29 -0
  6. package/dist/{CellOverlay.d.ts → cjs/CellOverlay.d.ts} +5 -5
  7. package/dist/cjs/CellOverlay.d.ts.map +1 -0
  8. package/dist/cjs/CellOverlay.js +126 -0
  9. package/dist/cjs/Context.d.ts +8 -0
  10. package/dist/cjs/Context.d.ts.map +1 -0
  11. package/dist/cjs/Context.js +13 -0
  12. package/dist/{FillHandle.d.ts → cjs/FillHandle.d.ts} +2 -1
  13. package/dist/cjs/FillHandle.d.ts.map +1 -0
  14. package/dist/cjs/FillHandle.js +26 -0
  15. package/dist/cjs/Grid.d.ts +558 -0
  16. package/dist/cjs/Grid.d.ts.map +1 -0
  17. package/dist/cjs/Grid.js +2446 -0
  18. package/dist/{GridLine.d.ts → cjs/GridLine.d.ts} +2 -1
  19. package/dist/cjs/GridLine.d.ts.map +1 -0
  20. package/dist/cjs/GridLine.js +10 -0
  21. package/dist/cjs/Image.d.ts +11 -0
  22. package/dist/cjs/Image.d.ts.map +1 -0
  23. package/dist/cjs/Image.js +57 -0
  24. package/dist/cjs/MemoizedGrid.d.ts +49 -0
  25. package/dist/cjs/MemoizedGrid.d.ts.map +1 -0
  26. package/dist/cjs/MemoizedGrid.js +105 -0
  27. package/dist/cjs/Selection.d.ts +5 -0
  28. package/dist/cjs/Selection.d.ts.map +1 -0
  29. package/dist/cjs/Selection.js +10 -0
  30. package/dist/{helpers.d.ts → cjs/helpers.d.ts} +59 -39
  31. package/dist/cjs/helpers.d.ts.map +1 -0
  32. package/dist/cjs/helpers.js +1409 -0
  33. package/dist/{hooks → cjs/hooks}/useCopyPaste.d.ts +3 -2
  34. package/dist/cjs/hooks/useCopyPaste.d.ts.map +1 -0
  35. package/dist/cjs/hooks/useCopyPaste.js +230 -0
  36. package/dist/{hooks → cjs/hooks}/useEditable.d.ts +21 -8
  37. package/dist/cjs/hooks/useEditable.d.ts.map +1 -0
  38. package/dist/cjs/hooks/useEditable.js +491 -0
  39. package/dist/{hooks → cjs/hooks}/useFilter.d.ts +3 -2
  40. package/dist/cjs/hooks/useFilter.d.ts.map +1 -0
  41. package/dist/cjs/hooks/useFilter.js +97 -0
  42. package/dist/{hooks → cjs/hooks}/useImage.d.ts +1 -0
  43. package/dist/cjs/hooks/useImage.d.ts.map +1 -0
  44. package/dist/cjs/hooks/useImage.js +80 -0
  45. package/dist/{hooks → cjs/hooks}/usePagination.d.ts +3 -2
  46. package/dist/cjs/hooks/usePagination.d.ts.map +1 -0
  47. package/dist/cjs/hooks/usePagination.js +53 -0
  48. package/dist/{hooks → cjs/hooks}/useSizer.d.ts +28 -29
  49. package/dist/cjs/hooks/useSizer.d.ts.map +1 -0
  50. package/dist/cjs/hooks/useSizer.js +176 -0
  51. package/dist/{hooks → cjs/hooks}/useTooltip.d.ts +2 -1
  52. package/dist/cjs/hooks/useTooltip.d.ts.map +1 -0
  53. package/dist/cjs/hooks/useTooltip.js +82 -0
  54. package/dist/{hooks → cjs/hooks}/useUndo.d.ts +2 -1
  55. package/dist/cjs/hooks/useUndo.d.ts.map +1 -0
  56. package/dist/cjs/hooks/useUndo.js +87 -0
  57. package/dist/cjs/index.d.ts +19 -0
  58. package/dist/cjs/index.d.ts.map +1 -0
  59. package/dist/cjs/index.js +29 -0
  60. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -0
  61. package/dist/{types.d.ts → cjs/types.d.ts} +8 -3
  62. package/dist/cjs/types.d.ts.map +1 -0
  63. package/dist/{types.js → cjs/types.js} +7 -8
  64. package/dist/cjs/utils.d.ts +9 -0
  65. package/dist/cjs/utils.d.ts.map +1 -0
  66. package/dist/cjs/utils.js +58 -0
  67. package/dist/cjs/vitest.config.d.ts +3 -0
  68. package/dist/cjs/vitest.config.d.ts.map +1 -0
  69. package/dist/cjs/vitest.config.js +24 -0
  70. package/dist/esm/Cell.d.ts +35 -0
  71. package/dist/esm/Cell.d.ts.map +1 -0
  72. package/dist/esm/Cell.js +24 -0
  73. package/dist/esm/CellOverlay.d.ts +21 -0
  74. package/dist/esm/CellOverlay.d.ts.map +1 -0
  75. package/dist/esm/CellOverlay.js +120 -0
  76. package/dist/esm/Context.d.ts +8 -0
  77. package/dist/esm/Context.d.ts.map +1 -0
  78. package/dist/esm/Context.js +9 -0
  79. package/dist/esm/FillHandle.d.ts +8 -0
  80. package/dist/esm/FillHandle.d.ts.map +1 -0
  81. package/dist/{FillHandle.js → esm/FillHandle.js} +5 -11
  82. package/dist/esm/Grid.d.ts +558 -0
  83. package/dist/esm/Grid.d.ts.map +1 -0
  84. package/dist/esm/Grid.js +2451 -0
  85. package/dist/esm/GridLine.d.ts +5 -0
  86. package/dist/esm/GridLine.d.ts.map +1 -0
  87. package/dist/esm/GridLine.js +7 -0
  88. package/dist/esm/Image.d.ts +11 -0
  89. package/dist/esm/Image.d.ts.map +1 -0
  90. package/dist/esm/Image.js +53 -0
  91. package/dist/esm/MemoizedGrid.d.ts +49 -0
  92. package/dist/esm/MemoizedGrid.d.ts.map +1 -0
  93. package/dist/esm/MemoizedGrid.js +98 -0
  94. package/dist/esm/Selection.d.ts +5 -0
  95. package/dist/esm/Selection.d.ts.map +1 -0
  96. package/dist/esm/Selection.js +7 -0
  97. package/dist/esm/helpers.d.ts +281 -0
  98. package/dist/esm/helpers.d.ts.map +1 -0
  99. package/dist/esm/helpers.js +1260 -0
  100. package/dist/esm/hooks/useCopyPaste.d.ts +53 -0
  101. package/dist/esm/hooks/useCopyPaste.d.ts.map +1 -0
  102. package/dist/{hooks → esm/hooks}/useCopyPaste.js +40 -46
  103. package/dist/esm/hooks/useEditable.d.ts +253 -0
  104. package/dist/esm/hooks/useEditable.d.ts.map +1 -0
  105. package/dist/esm/hooks/useEditable.js +482 -0
  106. package/dist/esm/hooks/useFilter.d.ts +69 -0
  107. package/dist/esm/hooks/useFilter.d.ts.map +1 -0
  108. package/dist/{hooks → esm/hooks}/useFilter.js +22 -42
  109. package/dist/esm/hooks/useImage.d.ts +13 -0
  110. package/dist/esm/hooks/useImage.d.ts.map +1 -0
  111. package/dist/esm/hooks/useImage.js +76 -0
  112. package/dist/esm/hooks/usePagination.d.ts +69 -0
  113. package/dist/esm/hooks/usePagination.d.ts.map +1 -0
  114. package/dist/esm/hooks/usePagination.js +47 -0
  115. package/dist/esm/hooks/useSizer.d.ts +114 -0
  116. package/dist/esm/hooks/useSizer.d.ts.map +1 -0
  117. package/dist/esm/hooks/useSizer.js +176 -0
  118. package/dist/esm/hooks/useTooltip.d.ts +43 -0
  119. package/dist/esm/hooks/useTooltip.d.ts.map +1 -0
  120. package/dist/esm/hooks/useTooltip.js +80 -0
  121. package/dist/esm/hooks/useUndo.d.ts +36 -0
  122. package/dist/esm/hooks/useUndo.d.ts.map +1 -0
  123. package/dist/{hooks → esm/hooks}/useUndo.js +16 -25
  124. package/dist/esm/index.d.ts +19 -0
  125. package/dist/esm/index.d.ts.map +1 -0
  126. package/dist/esm/index.js +17 -0
  127. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  128. package/dist/esm/types.d.ts +70 -0
  129. package/dist/esm/types.d.ts.map +1 -0
  130. package/dist/esm/types.js +68 -0
  131. package/dist/esm/utils.d.ts +9 -0
  132. package/dist/esm/utils.d.ts.map +1 -0
  133. package/dist/esm/utils.js +104 -0
  134. package/dist/esm/vitest.config.d.ts +3 -0
  135. package/dist/esm/vitest.config.d.ts.map +1 -0
  136. package/dist/esm/vitest.config.js +22 -0
  137. package/package.json +28 -29
  138. package/dist/Cell.d.ts +0 -23
  139. package/dist/Cell.js +0 -55
  140. package/dist/Cell.js.map +0 -1
  141. package/dist/CellOverlay.js +0 -116
  142. package/dist/CellOverlay.js.map +0 -1
  143. package/dist/FillHandle.js.map +0 -1
  144. package/dist/Grid.d.ts +0 -385
  145. package/dist/Grid.js +0 -1684
  146. package/dist/Grid.js.map +0 -1
  147. package/dist/GridLine.js +0 -13
  148. package/dist/GridLine.js.map +0 -1
  149. package/dist/Image.d.ts +0 -8
  150. package/dist/Image.js +0 -50
  151. package/dist/Image.js.map +0 -1
  152. package/dist/Selection.d.ts +0 -4
  153. package/dist/Selection.js +0 -9
  154. package/dist/Selection.js.map +0 -1
  155. package/dist/helpers.js +0 -1033
  156. package/dist/helpers.js.map +0 -1
  157. package/dist/hooks/useCopyPaste.js.map +0 -1
  158. package/dist/hooks/useEditable.js +0 -477
  159. package/dist/hooks/useEditable.js.map +0 -1
  160. package/dist/hooks/useFilter.js.map +0 -1
  161. package/dist/hooks/useImage.js +0 -42
  162. package/dist/hooks/useImage.js.map +0 -1
  163. package/dist/hooks/usePagination.js +0 -73
  164. package/dist/hooks/usePagination.js.map +0 -1
  165. package/dist/hooks/useSelection.d.ts +0 -175
  166. package/dist/hooks/useSelection.js +0 -980
  167. package/dist/hooks/useSelection.js.map +0 -1
  168. package/dist/hooks/useSizer.js +0 -150
  169. package/dist/hooks/useSizer.js.map +0 -1
  170. package/dist/hooks/useTooltip.js +0 -106
  171. package/dist/hooks/useTooltip.js.map +0 -1
  172. package/dist/hooks/useTouch.d.ts +0 -21
  173. package/dist/hooks/useTouch.js +0 -73
  174. package/dist/hooks/useTouch.js.map +0 -1
  175. package/dist/hooks/useUndo.js.map +0 -1
  176. package/dist/index.d.ts +0 -25
  177. package/dist/index.js +0 -61
  178. package/dist/index.js.map +0 -1
  179. package/dist/types.js.map +0 -1
  180. package/dist/utils.d.ts +0 -8
  181. package/dist/utils.js +0 -153
  182. package/dist/utils.js.map +0 -1
  183. package/src/Cell.tsx +0 -100
  184. package/src/CellOverlay.tsx +0 -191
  185. package/src/FillHandle.tsx +0 -37
  186. package/src/Grid.tsx +0 -2677
  187. package/src/GridLine.tsx +0 -23
  188. package/src/Image.tsx +0 -43
  189. package/src/Selection.tsx +0 -9
  190. package/src/helpers.ts +0 -1455
  191. package/src/hooks/useCopyPaste.ts +0 -265
  192. package/src/hooks/useEditable.tsx +0 -945
  193. package/src/hooks/useFilter.tsx +0 -233
  194. package/src/hooks/useImage.ts +0 -57
  195. package/src/hooks/usePagination.tsx +0 -153
  196. package/src/hooks/useSelection.ts +0 -1437
  197. package/src/hooks/useSizer.ts +0 -312
  198. package/src/hooks/useTooltip.tsx +0 -172
  199. package/src/hooks/useTouch.ts +0 -116
  200. package/src/hooks/useUndo.ts +0 -134
  201. package/src/index.tsx +0 -46
  202. package/src/tests/Grid.spec.tsx +0 -47
  203. package/src/tests/helpers.test.ts +0 -292
  204. package/src/tests/usePagination.test.ts +0 -28
  205. package/src/tests/useSelection.test.ts +0 -27
  206. package/src/tests/useUndo.test.ts +0 -73
  207. package/src/types.ts +0 -69
  208. package/src/utils.tsx +0 -287
@@ -1,1437 +0,0 @@
1
- import React, {
2
- useState,
3
- useCallback,
4
- useRef,
5
- useEffect,
6
- useMemo,
7
- useReducer,
8
- } from "react";
9
- import { SelectionArea, CellInterface, GridRef, AreaProps } from "./../Grid";
10
- import {
11
- findNextCellWithinBounds,
12
- Align,
13
- getBoundedCells,
14
- cellIdentifier,
15
- isEqualCells,
16
- clampIndex,
17
- HiddenType,
18
- findNextCellInDataRegion,
19
- selectionSpansCells,
20
- newSelectionFromDrag,
21
- clampCellCoords,
22
- cellRangeToBounds,
23
- } from "./../helpers";
24
- import {
25
- KeyCodes,
26
- Direction,
27
- MouseButtonCodes,
28
- SelectionPolicy,
29
- } from "./../types";
30
-
31
- export interface UseSelectionOptions {
32
- /**
33
- * Access grid functions
34
- */
35
- gridRef: React.MutableRefObject<GridRef | null>;
36
- /**
37
- * Initial selections
38
- */
39
- initialSelections?: SelectionArea[];
40
- /**
41
- * Option to set 0,0 as initially selected cell
42
- */
43
- initialActiveCell?: CellInterface | null;
44
- /**
45
- * No of columns in the grid
46
- */
47
- columnCount?: number;
48
- /**
49
- * No of rows in the grid
50
- */
51
- rowCount?: number;
52
- /**
53
- * Allow deselect a selected area
54
- */
55
- allowDeselectSelection?: boolean;
56
- /**
57
- * onFill
58
- */
59
- onFill?: (
60
- activeCell: CellInterface,
61
- selection: SelectionArea | null,
62
- selections: SelectionArea[]
63
- ) => void;
64
- /**
65
- * Hidden rows
66
- */
67
- isHiddenRow?: HiddenType;
68
- /**
69
- * Hidden columns
70
- */
71
- isHiddenColumn?: HiddenType;
72
- /**
73
- * Always scroll to active cell
74
- */
75
- alwaysScrollToActiveCell?: boolean;
76
- /**
77
- * Top bound of selection
78
- */
79
- selectionTopBound?: number;
80
- /**
81
- * Bottom bound
82
- */
83
- selectionBottomBound?: number;
84
- /**
85
- * Left bound
86
- */
87
- selectionLeftBound?: number;
88
- /**
89
- * Right bound
90
- */
91
- selectionRightBound?: number;
92
- /**
93
- * merged cells
94
- */
95
- mergedCells?: AreaProps[];
96
- /**
97
- * Mousedown
98
- */
99
- mouseDownInterceptor?: (
100
- e: React.MouseEvent<HTMLDivElement>,
101
- coords: CellInterface,
102
- start: React.MutableRefObject<CellInterface | null>,
103
- end: React.MutableRefObject<CellInterface | null>
104
- ) => boolean | undefined;
105
- mouseMoveInterceptor?: (
106
- e: globalThis.MouseEvent,
107
- coords: CellInterface,
108
- start: React.MutableRefObject<CellInterface | null>,
109
- end: React.MutableRefObject<CellInterface | null>
110
- ) => boolean | undefined;
111
- canSelectionSpanMergedCells?: (
112
- start: CellInterface,
113
- end: CellInterface
114
- ) => boolean;
115
- /**
116
- * Selection policy
117
- */
118
- selectionPolicy?: SelectionPolicy;
119
- /**
120
- * Value getter
121
- */
122
- getValue: (cell: CellInterface) => string | number | undefined;
123
- /**
124
- * New selection mode
125
- */
126
- newSelectionMode?: NewSelectionMode;
127
- /**
128
- * When selection is moved
129
- */
130
- onSelectionMove?: (from: SelectionArea, to: SelectionArea) => void;
131
- }
132
-
133
- export type NewSelectionMode = "clear" | "modify" | "append";
134
-
135
- export interface SelectionResults {
136
- /**
137
- * Active selected cell
138
- */
139
- activeCell: CellInterface | null;
140
- /**
141
- * Use this to invoke a new selection. All old selection will be cleared
142
- */
143
- newSelection: (coords: CellInterface) => void;
144
- /**
145
- * Use this to update selections without clearning old selection.
146
- */
147
- setSelections: (
148
- selections:
149
- | SelectionArea[]
150
- | ((selections: SelectionArea[]) => SelectionArea[])
151
- ) => void;
152
- /**
153
- * Modify selectio
154
- */
155
- modifySelection: (coords: CellInterface) => void;
156
- /**
157
- * Set the currently active cell
158
- */
159
- setActiveCell: (coords: CellInterface | null, shouldScroll?: boolean) => void;
160
- /**
161
- * Only saves internal state
162
- */
163
- setActiveCellState: (coords: CellInterface | null) => void;
164
- /**
165
- * Array of all selection bounds
166
- */
167
- selections: SelectionArea[];
168
- /**
169
- * Handler for mousedown, use to set activeCell
170
- */
171
- onMouseDown: (e: React.MouseEvent<HTMLDivElement>) => void;
172
- /**
173
- * Used to move selections based on pressed key
174
- */
175
- onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => void;
176
- /**
177
- * Mousedown event on fillhandle
178
- */
179
- fillHandleProps?: Record<string, (e: any) => void>;
180
- /**
181
- *
182
- * Fill selections
183
- */
184
- fillSelection: SelectionArea | null;
185
- /**
186
- * Clears the last selection
187
- */
188
- clearLastSelection: () => void;
189
- /**
190
- * Select all cells
191
- */
192
- selectAll: () => void;
193
- /**
194
- * Add a new selection
195
- */
196
- appendSelection: (start: CellInterface, end: CellInterface) => void;
197
- /**
198
- * Clear all current selections
199
- */
200
- clearSelections: () => void;
201
- /**
202
- * On Selection mousedown
203
- */
204
- onSelectionMouseDown?: (
205
- e: React.MouseEvent<HTMLDivElement>,
206
- cell: CellInterface | undefined,
207
- selection: SelectionArea | undefined,
208
- index: number | undefined,
209
- shouldClamp?: boolean
210
- ) => void;
211
- /**
212
- * Boolean to indicate if a selection is being dragged
213
- */
214
- isDragging?: boolean;
215
- /**
216
- * Currently dragged selection
217
- */
218
- draggedSelection?: SelectionArea;
219
- /**
220
- * The selection that user selected before beginning
221
- * the drag
222
- */
223
- initialDraggedSelection?: SelectionArea;
224
- }
225
-
226
- const EMPTY_SELECTION: SelectionArea[] = [];
227
- const defaultIsHidden = (i: number) => false;
228
- const defaultSelectionSpan = () => true;
229
- /**
230
- * Hook to enable selection in datagrid
231
- * @param initialSelection
232
- */
233
- const useSelection = ({
234
- gridRef,
235
- initialActiveCell = null,
236
- initialSelections = EMPTY_SELECTION,
237
- columnCount = 0,
238
- rowCount = 0,
239
- selectionPolicy = "multiple",
240
- newSelectionMode = "clear",
241
- allowDeselectSelection = true,
242
- onFill,
243
- isHiddenRow = defaultIsHidden,
244
- isHiddenColumn = defaultIsHidden,
245
- alwaysScrollToActiveCell = true,
246
- selectionTopBound = 0,
247
- selectionBottomBound = rowCount - 1,
248
- selectionLeftBound = 0,
249
- selectionRightBound = columnCount - 1,
250
- mouseDownInterceptor,
251
- mouseMoveInterceptor,
252
- mergedCells = [],
253
- canSelectionSpanMergedCells = defaultSelectionSpan,
254
- getValue,
255
- onSelectionMove,
256
- }: UseSelectionOptions): SelectionResults => {
257
- const [activeCell, setActiveCell] = useState<CellInterface | null>(
258
- initialActiveCell
259
- );
260
- const [selections, setSelections] =
261
- useState<SelectionArea[]>(initialSelections);
262
- const [fillSelection, setFillSelection] = useState<SelectionArea | null>(
263
- null
264
- );
265
- const selectionStart = useRef<CellInterface | null>(null);
266
- const selectionEnd = useRef<CellInterface | null>(null);
267
- const isSelecting = useRef<boolean>(false);
268
- const isFilling = useRef<boolean>(false);
269
- const firstActiveCell = useRef<CellInterface | null>(null);
270
-
271
- /* Drag drop selection */
272
- const [_, forceRender] = useReducer((s) => s + 1, 0);
273
- const isDragging = useRef<boolean>(false);
274
- const hasUserMovedSelection = useRef<boolean>(false);
275
- const initialDraggedSelection = useRef<SelectionArea>();
276
- const initialDraggedCell = useRef<CellInterface>();
277
- const draggedSelection = useRef<SelectionArea>();
278
- const draggedSelectionIndex = useRef<number>();
279
- /**
280
- * Need to store in ref because on mousemove and mouseup event that are
281
- * registered in document
282
- */
283
- const activeCellRef = useRef(activeCell);
284
- const activeSelectionsRef = useRef(selections);
285
- const mergedCellsRef = useRef(mergedCells);
286
-
287
- useEffect(() => {
288
- activeCellRef.current = activeCell;
289
- }, [activeCell]);
290
- useEffect(() => {
291
- activeSelectionsRef.current = selections;
292
- }, [selections]);
293
- useEffect(() => {
294
- mergedCellsRef.current = mergedCells;
295
- }, [mergedCells]);
296
-
297
- /* Check if cell is out of bounds */
298
- const isCellOutOfBounds = useCallback(
299
- (cell: CellInterface) => {
300
- return (
301
- cell.rowIndex < selectionTopBound ||
302
- cell.columnIndex < selectionLeftBound
303
- );
304
- },
305
- [selectionTopBound, selectionLeftBound]
306
- );
307
-
308
- /* New selection */
309
- const newSelection = (start: CellInterface, end: CellInterface = start) => {
310
- /* Validate bounds */
311
- if (isCellOutOfBounds(start)) {
312
- return;
313
- }
314
- selectionStart.current = start;
315
- selectionEnd.current = end;
316
- const bounds = selectionFromStartEnd(start, end);
317
- if (!bounds) return;
318
- const coords = { rowIndex: bounds.top, columnIndex: bounds.left };
319
- /* Keep track of first cell that was selected by user */
320
- setActiveCell(coords);
321
- if (newSelectionMode === "clear") {
322
- firstActiveCell.current = coords;
323
- clearSelections();
324
- } else if (newSelectionMode === "modify") {
325
- modifySelection(coords);
326
- } else {
327
- appendSelection(coords);
328
- }
329
- };
330
-
331
- /**
332
- * selection object from start, end
333
- * @param start
334
- * @param end
335
- */
336
- const selectionFromStartEnd = (start: CellInterface, end: CellInterface) => {
337
- if (!gridRef?.current) return null;
338
- const spanMerges = canSelectionSpanMergedCells?.(start, end);
339
- return cellRangeToBounds(
340
- start,
341
- end,
342
- spanMerges,
343
- gridRef.current.getCellBounds
344
- );
345
- };
346
-
347
- /* Modify current selection */
348
- const modifySelection = (coords: CellInterface, setInProgress?: boolean) => {
349
- if (selectionPolicy === "single") {
350
- return;
351
- }
352
- if (!selectionStart.current) return;
353
- if (isCellOutOfBounds(coords)) {
354
- return;
355
- }
356
- selectionEnd.current = coords;
357
- const bounds = selectionFromStartEnd(selectionStart.current, coords);
358
- if (!bounds) return;
359
-
360
- /**
361
- * 1. Multiple selections on mousedown/mousemove
362
- * 2. Move the activeCell to newly selection. Done by appendSelection
363
- */
364
- setSelections((prevSelection) => {
365
- const len = prevSelection.length;
366
- if (!len) {
367
- return [{ bounds, inProgress: setInProgress ? true : false }];
368
- }
369
- return prevSelection.map((sel, i) => {
370
- if (len - 1 === i) {
371
- return {
372
- ...sel,
373
- bounds,
374
- inProgress: setInProgress ? true : false,
375
- };
376
- }
377
- return sel;
378
- });
379
- });
380
- };
381
-
382
- /* Adds a new selection, CMD key */
383
- const appendSelection = (
384
- start: CellInterface,
385
- end: CellInterface = start
386
- ) => {
387
- if (selectionPolicy !== "multiple") {
388
- return;
389
- }
390
- if (!start) return;
391
- /* Validate bounds */
392
- if (isCellOutOfBounds(start)) {
393
- return;
394
- }
395
- selectionStart.current = start;
396
- selectionEnd.current = end;
397
- const bounds = selectionFromStartEnd(start, end);
398
- if (!bounds) return;
399
- setActiveCell({ rowIndex: bounds.top, columnIndex: bounds.left });
400
- setSelections((prev) => [...prev, { bounds }]);
401
- };
402
-
403
- const removeSelectionByIndex = useCallback(
404
- (index: number): SelectionArea[] => {
405
- const newSelection = selections.filter((_, idx) => idx !== index);
406
- setSelections(newSelection);
407
- return newSelection;
408
- },
409
- [selections]
410
- );
411
-
412
- const clearSelections = () => {
413
- setSelections(EMPTY_SELECTION);
414
- };
415
-
416
- const getPossibleActiveCellFromSelections = (
417
- selections: SelectionArea[]
418
- ): CellInterface | null => {
419
- if (!selections.length) return null;
420
- const { bounds } = selections[selections.length - 1];
421
- return {
422
- rowIndex: bounds.top,
423
- columnIndex: bounds.left,
424
- };
425
- };
426
-
427
- const cellIndexInSelection = (
428
- cell: CellInterface,
429
- selections: SelectionArea[]
430
- ) => {
431
- const id = cellIdentifier(
432
- Math.max(selectionTopBound, cell.rowIndex),
433
- Math.max(selectionLeftBound, cell.columnIndex)
434
- );
435
- return selections.findIndex((sel) => {
436
- const boundedCells = getBoundedCells(sel.bounds);
437
- return boundedCells.has(id);
438
- });
439
- };
440
-
441
- const cellEqualsSelection = (
442
- cell: CellInterface | null,
443
- selections: SelectionArea[]
444
- ): boolean => {
445
- if (cell === null) return false;
446
- return selections.some((sel) => {
447
- return (
448
- sel.bounds.left === cell.columnIndex &&
449
- sel.bounds.top === cell.rowIndex &&
450
- sel.bounds.right === cell.columnIndex &&
451
- sel.bounds.bottom === cell.rowIndex
452
- );
453
- });
454
- };
455
-
456
- const boundsSubsetOfSelection = (bounds: AreaProps, selection: AreaProps) => {
457
- return (
458
- bounds.top >= selection.top &&
459
- bounds.bottom <= selection.bottom &&
460
- bounds.left >= selection.left &&
461
- bounds.right <= selection.right
462
- );
463
- };
464
-
465
- /**
466
- * Triggers a new selection start
467
- */
468
- const handleMouseDown = useCallback(
469
- (e: React.MouseEvent<HTMLDivElement>) => {
470
- /* Exit early if grid is not initialized */
471
- if (!gridRef || !gridRef.current) return;
472
- const coords = gridRef.current.getCellCoordsFromOffset(
473
- e.nativeEvent.clientX,
474
- e.nativeEvent.clientY
475
- );
476
- if (!coords) return;
477
- /* Check if its context menu click */
478
- const isContextMenuClick = e.nativeEvent.which === MouseButtonCodes.right;
479
- if (isContextMenuClick) {
480
- const cellIndex = cellIndexInSelection(coords, selections);
481
- if (cellIndex !== -1) return;
482
- }
483
- const isShiftKey = e.nativeEvent.shiftKey;
484
- const isMetaKey = e.nativeEvent.ctrlKey || e.nativeEvent.metaKey;
485
- const allowMultiple = isMetaKey;
486
- const allowDeselect = allowDeselectSelection;
487
- const hasSelections = selections.length > 0;
488
- const isDeselecting = isMetaKey && allowDeselect;
489
-
490
- if (!isContextMenuClick && selectionPolicy !== "single") {
491
- document.addEventListener("mouseup", handleMouseUp);
492
- document.addEventListener("mousemove", handleMouseMove);
493
- }
494
-
495
- /* Activate selection mode */
496
- isSelecting.current = true;
497
-
498
- if (
499
- mouseDownInterceptor?.(e, coords, selectionStart, selectionEnd) ===
500
- false
501
- ) {
502
- return;
503
- }
504
-
505
- /* Shift key */
506
- if (isShiftKey) {
507
- modifySelection(coords);
508
- return;
509
- }
510
-
511
- /* Is the current cell same as active cell */
512
- const isSameAsActiveCell = isEqualCells(coords, activeCell);
513
-
514
- /* Command or Control key */
515
- if (activeCell && allowMultiple) {
516
- /**
517
- * User is adding activeCell to selection
518
- *
519
- * 1. User is selecting and not de-selecting
520
- * 2. User has not made any selection
521
- * 3. Trying to add active cell to selection
522
- */
523
- if (isSameAsActiveCell && (!isDeselecting || !hasSelections)) {
524
- return;
525
- }
526
-
527
- /**
528
- * User is manually trying to select multiple selections,
529
- * So add the current active cell to the list
530
- */
531
- if (isMetaKey && !hasSelections) {
532
- appendSelection(activeCell);
533
- }
534
-
535
- /**
536
- * Check if this cell has already been selected (only for manual deselect)
537
- * Remove it from selection
538
- *
539
- * Future enhancements -> Split selection, so that 1 cell can be removed from range
540
- */
541
- if (isMetaKey && allowDeselect) {
542
- const cellIndex = cellIndexInSelection(coords, selections);
543
- if (cellIndex !== -1) {
544
- const newSelection = removeSelectionByIndex(cellIndex);
545
- const nextActiveCell =
546
- getPossibleActiveCellFromSelections(newSelection);
547
- if (nextActiveCell !== null) {
548
- setActiveCell(nextActiveCell);
549
- }
550
- if (
551
- newSelection.length === 1 &&
552
- cellEqualsSelection(nextActiveCell, newSelection)
553
- ) {
554
- /* Since we only have 1 cell, lets clear the selections and only keep activeCell */
555
- clearSelections();
556
- }
557
- return;
558
- }
559
- }
560
-
561
- /**
562
- * TODO
563
- * 1. Ability to remove selection
564
- * 2. Ability to remove from selection area
565
- * 3. Ability to switch activeCell if its part of removed selection
566
- */
567
- appendSelection(coords);
568
- return;
569
- }
570
-
571
- /**
572
- * Scroll to the selected cell
573
- */
574
- if (alwaysScrollToActiveCell) {
575
- gridRef.current?.scrollToItem(coords);
576
- }
577
-
578
- /**
579
- * If user is selecting the same same,
580
- * let not trigger another state change
581
- */
582
- if (isSameAsActiveCell) return;
583
-
584
- /* Trigger new selection */
585
- newSelection(coords);
586
- },
587
- [
588
- activeCell,
589
- selections,
590
- selectionPolicy,
591
- allowDeselectSelection,
592
- alwaysScrollToActiveCell,
593
- rowCount,
594
- columnCount,
595
- newSelectionMode,
596
- ]
597
- );
598
-
599
- /**
600
- * Mousemove handler
601
- */
602
- const handleMouseMove = useCallback((e: globalThis.MouseEvent) => {
603
- /* Exit if user is not in selection mode */
604
- if (!isSelecting.current || !gridRef?.current) return;
605
-
606
- const coords = gridRef.current.getCellCoordsFromOffset(
607
- e.clientX,
608
- e.clientY
609
- );
610
-
611
- if (!coords) return;
612
-
613
- if (
614
- mouseMoveInterceptor?.(e, coords, selectionStart, selectionEnd) === false
615
- ) {
616
- return;
617
- }
618
-
619
- if (isEqualCells(firstActiveCell.current, coords)) {
620
- return clearSelections();
621
- }
622
-
623
- modifySelection(coords, true);
624
-
625
- gridRef.current?.scrollToItem(coords);
626
- }, []);
627
- /**
628
- * Mouse up handler
629
- */
630
- const handleMouseUp = useCallback(() => {
631
- /* Reset selection mode */
632
- isSelecting.current = false;
633
-
634
- /* Remove listener */
635
- document.removeEventListener("mousemove", handleMouseMove);
636
- document.removeEventListener("mouseup", handleMouseUp);
637
-
638
- /* Update last selection */
639
- setSelections((prevSelection) => {
640
- const len = prevSelection.length;
641
- if (!len) return EMPTY_SELECTION;
642
- return prevSelection.map((sel, i) => {
643
- if (len - 1 === i) {
644
- return {
645
- ...sel,
646
- inProgress: false,
647
- };
648
- }
649
- return sel;
650
- });
651
- });
652
- }, []);
653
-
654
- /**
655
- * Navigate selection using keyboard
656
- * @param direction
657
- * @param modify
658
- */
659
- const keyNavigate = useCallback(
660
- (direction: Direction, modify?: boolean, metaKeyPressed?: boolean) => {
661
- if (
662
- !selectionStart.current ||
663
- !selectionEnd.current ||
664
- !gridRef?.current ||
665
- !activeCell
666
- )
667
- return;
668
- const currentCell = modify ? selectionEnd.current : activeCell;
669
- var { rowIndex, columnIndex } = currentCell;
670
- const isMergedCell = gridRef?.current.isMergedCell({
671
- rowIndex,
672
- columnIndex,
673
- });
674
-
675
- const currentBounds = gridRef.current.getCellBounds({
676
- rowIndex,
677
- columnIndex,
678
- });
679
-
680
- switch (direction) {
681
- case Direction.Up:
682
- if (isMergedCell) rowIndex = currentBounds.top;
683
- rowIndex = clampIndex(
684
- Math.max(rowIndex - 1, selectionTopBound),
685
- isHiddenRow,
686
- direction
687
- );
688
- // Shift + Ctrl/Commmand
689
- // TODO: Scroll to last contentful cell
690
- if (metaKeyPressed) {
691
- const startCell = {
692
- ...currentCell,
693
- // Expand from the starting cell
694
- columnIndex: selectionStart.current.columnIndex,
695
- };
696
- rowIndex = findNextCellInDataRegion(
697
- startCell,
698
- getValue,
699
- isHiddenRow,
700
- direction,
701
- selectionTopBound
702
- );
703
- }
704
- break;
705
-
706
- case Direction.Down:
707
- if (isMergedCell) rowIndex = currentBounds.bottom;
708
- rowIndex = clampIndex(
709
- Math.min(rowIndex + 1, selectionBottomBound),
710
- isHiddenRow,
711
- direction
712
- );
713
- // Shift + Ctrl/Commmand
714
- if (metaKeyPressed) {
715
- const startCell = {
716
- ...currentCell,
717
- // Expand from the starting cell
718
- columnIndex: selectionStart.current.columnIndex,
719
- };
720
- rowIndex = findNextCellInDataRegion(
721
- startCell,
722
- getValue,
723
- isHiddenRow,
724
- direction,
725
- selectionBottomBound
726
- );
727
- }
728
- break;
729
-
730
- case Direction.Left:
731
- if (isMergedCell) columnIndex = currentBounds.left;
732
- columnIndex = clampIndex(
733
- Math.max(columnIndex - 1, selectionLeftBound),
734
- isHiddenColumn,
735
- direction
736
- );
737
- // Shift + Ctrl/Commmand
738
- if (metaKeyPressed) {
739
- const startCell = {
740
- ...currentCell,
741
- // Expand from the starting cell
742
- rowIndex: selectionStart.current.rowIndex,
743
- };
744
- columnIndex = findNextCellInDataRegion(
745
- startCell,
746
- getValue,
747
- isHiddenColumn,
748
- direction,
749
- selectionLeftBound
750
- );
751
- }
752
- break;
753
-
754
- case Direction.Right:
755
- if (isMergedCell) columnIndex = currentBounds.right;
756
- columnIndex = clampIndex(
757
- Math.min(columnIndex + 1, selectionRightBound),
758
- isHiddenColumn,
759
- direction
760
- );
761
- // Shift + Ctrl/Commmand
762
- if (metaKeyPressed) {
763
- const startCell = {
764
- ...currentCell,
765
- // Expand from the starting cell
766
- rowIndex: selectionStart.current.rowIndex,
767
- };
768
- columnIndex = findNextCellInDataRegion(
769
- startCell,
770
- getValue,
771
- isHiddenColumn,
772
- direction,
773
- selectionRightBound
774
- );
775
- }
776
- break;
777
- }
778
-
779
- const newBounds = gridRef.current.getCellBounds({
780
- rowIndex,
781
- columnIndex,
782
- });
783
- const coords = { rowIndex: newBounds.top, columnIndex: newBounds.left };
784
- const scrollToCell = modify
785
- ? selectionEnd.current.rowIndex === coords.rowIndex
786
- ? // Scroll to a column
787
- { columnIndex: coords.columnIndex }
788
- : // Scroll to row
789
- { rowIndex: coords.rowIndex }
790
- : // Scroll to cell
791
- { rowIndex, columnIndex };
792
-
793
- const isUserNavigatingToActiveCell = isEqualCells(
794
- firstActiveCell.current,
795
- coords
796
- );
797
-
798
- if (modify && !isUserNavigatingToActiveCell) {
799
- modifySelection(coords);
800
- } else {
801
- newSelection(coords);
802
- }
803
-
804
- /* Keep the item in view */
805
- gridRef.current.scrollToItem(scrollToCell);
806
- },
807
- [
808
- activeCell,
809
- isHiddenRow,
810
- isHiddenColumn,
811
- selectionLeftBound,
812
- selectionTopBound,
813
- selectionPolicy,
814
- newSelectionMode,
815
- ]
816
- );
817
-
818
- // ⌘A or ⌘+Shift+Space
819
- const selectAll = () => {
820
- selectionStart.current = {
821
- rowIndex: selectionTopBound,
822
- columnIndex: selectionLeftBound,
823
- };
824
- modifySelection({
825
- rowIndex: selectionBottomBound,
826
- columnIndex: selectionRightBound,
827
- });
828
- };
829
-
830
- // Ctrl+Space
831
- const selectColumn = useCallback(() => {
832
- if (!selectionEnd.current || !selectionStart.current) return;
833
- selectionStart.current = {
834
- rowIndex: selectionTopBound,
835
- columnIndex: selectionStart.current.columnIndex,
836
- };
837
- modifySelection({
838
- rowIndex: rowCount - 1,
839
- columnIndex: selectionEnd.current.columnIndex,
840
- });
841
- }, [selectionTopBound]);
842
-
843
- // Shift+Space
844
- const selectRow = useCallback(() => {
845
- if (!selectionEnd.current || !selectionStart.current) return;
846
- selectionStart.current = {
847
- rowIndex: selectionStart.current.rowIndex,
848
- columnIndex: selectionLeftBound,
849
- };
850
- modifySelection({
851
- rowIndex: selectionEnd.current.rowIndex,
852
- columnIndex: selectionRightBound,
853
- });
854
- }, [selectionLeftBound]);
855
-
856
- // Home
857
- const selectFirstCellInRow = () => {
858
- if (!selectionStart.current || !gridRef?.current) return;
859
- const cell = {
860
- rowIndex: selectionStart.current.rowIndex,
861
- columnIndex: selectionLeftBound,
862
- };
863
- newSelection(cell);
864
-
865
- gridRef?.current.scrollToItem(cell);
866
- };
867
- // End
868
- const selectLastCellInRow = () => {
869
- if (!selectionStart.current || !gridRef?.current) return;
870
- const cell = {
871
- rowIndex: selectionStart.current.rowIndex,
872
- columnIndex: selectionRightBound,
873
- };
874
- newSelection(cell);
875
- gridRef?.current.scrollToItem(cell);
876
- };
877
-
878
- // ⌘+Home
879
- const selectFirstCellInColumn = () => {
880
- if (!selectionStart.current || !gridRef?.current) return;
881
- const cell = {
882
- rowIndex: selectionTopBound,
883
- columnIndex: selectionStart.current.columnIndex,
884
- };
885
- newSelection(cell);
886
-
887
- gridRef?.current.scrollToItem(cell);
888
- };
889
- // ⌘+End
890
- const selectLastCellInColumn = () => {
891
- if (!selectionStart.current || !gridRef?.current) return;
892
- const cell = {
893
- rowIndex: rowCount - 1,
894
- columnIndex: selectionStart.current.columnIndex,
895
- };
896
- newSelection(cell);
897
- gridRef?.current.scrollToItem(cell);
898
- };
899
-
900
- // ⌘+Backspace
901
- const scrollToActiveCell = () => {
902
- if (!activeCell || !gridRef?.current) return;
903
- gridRef?.current.scrollToItem(activeCell, Align.smart);
904
- };
905
-
906
- // Page down
907
- const pageDown = () => {
908
- if (!activeCell || !gridRef?.current) return;
909
- const { visibleRowStartIndex, visibleRowStopIndex } =
910
- gridRef.current.getViewPort();
911
- const pageSize = visibleRowStopIndex - visibleRowStartIndex;
912
- const rowIndex = Math.min(activeCell.rowIndex + pageSize, rowCount - 1);
913
- const newActiveCell = {
914
- rowIndex,
915
- columnIndex: activeCell.columnIndex,
916
- };
917
- handleSetActiveCell(newActiveCell, false);
918
- /* Scroll to the new row */
919
- gridRef?.current.scrollToItem({ rowIndex }, Align.end);
920
- };
921
-
922
- // Page up
923
- const pageUp = () => {
924
- if (!activeCell || !gridRef?.current) return;
925
- const { visibleRowStartIndex, visibleRowStopIndex } =
926
- gridRef.current.getViewPort();
927
- const pageSize = visibleRowStopIndex - visibleRowStartIndex;
928
- const rowIndex = Math.max(
929
- activeCell.rowIndex - pageSize,
930
- selectionTopBound
931
- );
932
- const newActiveCell = {
933
- rowIndex,
934
- columnIndex: activeCell.columnIndex,
935
- };
936
- handleSetActiveCell(newActiveCell, false);
937
- /* Scroll to the new row */
938
- gridRef?.current.scrollToItem({ rowIndex }, Align.end);
939
- };
940
-
941
- // Page right
942
- const pageRight = () => {
943
- if (!activeCell || !gridRef?.current) return;
944
- const { visibleColumnStartIndex, visibleColumnStopIndex } =
945
- gridRef.current.getViewPort();
946
- const pageSize = visibleColumnStopIndex - visibleColumnStartIndex;
947
- const columnIndex = Math.min(
948
- activeCell.columnIndex + pageSize,
949
- selectionRightBound
950
- );
951
- const newActiveCell = {
952
- columnIndex,
953
- rowIndex: activeCell.rowIndex,
954
- };
955
- handleSetActiveCell(newActiveCell, false);
956
- /* Scroll to the new row */
957
- gridRef?.current.scrollToItem({ columnIndex }, Align.end);
958
- };
959
-
960
- // Page left
961
- const pageLeft = () => {
962
- if (!activeCell || !gridRef?.current) return;
963
- const { visibleColumnStartIndex, visibleColumnStopIndex } =
964
- gridRef.current.getViewPort();
965
- const pageSize = visibleColumnStopIndex - visibleColumnStartIndex;
966
- const columnIndex = Math.max(
967
- activeCell.columnIndex - pageSize,
968
- selectionLeftBound
969
- );
970
- const newActiveCell = {
971
- columnIndex,
972
- rowIndex: activeCell.rowIndex,
973
- };
974
- handleSetActiveCell(newActiveCell, false);
975
- /* Scroll to the new row */
976
- gridRef?.current.scrollToItem({ columnIndex }, Align.end);
977
- };
978
-
979
- const handleKeyDown = useCallback(
980
- (e: React.KeyboardEvent) => {
981
- if (!gridRef?.current) return;
982
- const isShiftKey = e.nativeEvent.shiftKey;
983
- const isAltKey = e.nativeEvent.altKey;
984
- const isMetaKey = e.nativeEvent.ctrlKey || e.nativeEvent.metaKey;
985
- switch (e.nativeEvent.which) {
986
- case KeyCodes.Right:
987
- keyNavigate(Direction.Right, isShiftKey, isMetaKey);
988
- e.preventDefault();
989
- break;
990
-
991
- case KeyCodes.Left:
992
- keyNavigate(Direction.Left, isShiftKey, isMetaKey);
993
- e.preventDefault();
994
- break;
995
-
996
- // Up
997
- case KeyCodes.Up:
998
- keyNavigate(Direction.Up, isShiftKey, isMetaKey);
999
- e.preventDefault();
1000
- break;
1001
-
1002
- case KeyCodes.Down:
1003
- keyNavigate(Direction.Down, isShiftKey, isMetaKey);
1004
- e.preventDefault();
1005
- break;
1006
-
1007
- case KeyCodes.A:
1008
- if (isMetaKey) {
1009
- selectAll();
1010
- }
1011
- e.preventDefault();
1012
- break;
1013
-
1014
- case KeyCodes.Home:
1015
- if (isMetaKey) {
1016
- selectFirstCellInColumn();
1017
- } else {
1018
- selectFirstCellInRow();
1019
- }
1020
- break;
1021
-
1022
- case KeyCodes.End:
1023
- if (isMetaKey) {
1024
- selectLastCellInColumn();
1025
- } else {
1026
- selectLastCellInRow();
1027
- }
1028
- break;
1029
-
1030
- case KeyCodes.BackSpace:
1031
- if (isMetaKey) scrollToActiveCell();
1032
- break;
1033
-
1034
- case KeyCodes.SPACE:
1035
- if (isMetaKey && isShiftKey) {
1036
- selectAll();
1037
- } else if (isMetaKey) {
1038
- selectColumn();
1039
- } else if (isShiftKey) {
1040
- selectRow();
1041
- }
1042
- break;
1043
-
1044
- case KeyCodes.Tab:
1045
- /* Cycle through the selections if selections.length > 0 */
1046
- if (selections.length && activeCell && gridRef) {
1047
- const { bounds } = selections[selections.length - 1];
1048
- const activeCellBounds = gridRef.current.getCellBounds(activeCell);
1049
- const direction = isShiftKey ? Direction.Left : Direction.Right;
1050
- const nextCell = findNextCellWithinBounds(
1051
- activeCellBounds,
1052
- bounds,
1053
- direction
1054
- );
1055
- if (nextCell) {
1056
- setActiveCell(nextCell);
1057
- if (gridRef.current) gridRef.current.scrollToItem(nextCell);
1058
- }
1059
- } else {
1060
- if (isShiftKey) {
1061
- keyNavigate(Direction.Left);
1062
- } else {
1063
- keyNavigate(Direction.Right);
1064
- }
1065
- }
1066
- e.preventDefault();
1067
- break;
1068
-
1069
- case KeyCodes.PageDown:
1070
- if (isAltKey) {
1071
- pageRight();
1072
- } else pageDown();
1073
- break;
1074
-
1075
- case KeyCodes.PageUp:
1076
- if (isAltKey) {
1077
- pageLeft();
1078
- } else pageUp();
1079
- break;
1080
- }
1081
- },
1082
- [
1083
- rowCount,
1084
- columnCount,
1085
- activeCell,
1086
- selections,
1087
- selectionPolicy,
1088
- newSelectionMode,
1089
- ]
1090
- );
1091
-
1092
- /**
1093
- * User modified active cell deliberately
1094
- */
1095
- const handleSetActiveCell = useCallback(
1096
- (coords: CellInterface | null, shouldScroll = true) => {
1097
- selectionStart.current = coords;
1098
- firstActiveCell.current = coords;
1099
- selectionEnd.current = coords;
1100
- setActiveCell(coords);
1101
- /* Scroll to the cell */
1102
- if (shouldScroll && coords && gridRef?.current) {
1103
- gridRef.current.scrollToItem(coords);
1104
- }
1105
- },
1106
- []
1107
- );
1108
-
1109
- const handleFillHandleMouseDown = useCallback(
1110
- (e: React.MouseEvent<HTMLDivElement>) => {
1111
- e.stopPropagation();
1112
- isFilling.current = true;
1113
- document.addEventListener("mousemove", handleFillHandleMouseMove);
1114
- document.addEventListener("mouseup", handleFillHandleMouseUp);
1115
- },
1116
- [selections]
1117
- );
1118
-
1119
- /**
1120
- * TODO
1121
- * 1. Fill does not extend to merged cells
1122
- */
1123
- const handleFillHandleMouseMove = useCallback((e: globalThis.MouseEvent) => {
1124
- /* Exit if user is not in selection mode */
1125
- if (!isFilling.current || !gridRef?.current || !activeCellRef.current)
1126
- return;
1127
-
1128
- const coords = gridRef.current.getCellCoordsFromOffset(
1129
- e.clientX,
1130
- e.clientY,
1131
- false
1132
- );
1133
- if (!coords) return;
1134
- const selections = activeSelectionsRef.current;
1135
- let bounds = selectionFromStartEnd(activeCellRef.current, coords);
1136
- const hasSelections = selections.length > 0;
1137
- const activeCellBounds = hasSelections
1138
- ? selections[selections.length - 1].bounds
1139
- : gridRef.current.getCellBounds(activeCellRef.current);
1140
- if (!bounds) return;
1141
-
1142
- const direction =
1143
- bounds.top < activeCellBounds.top
1144
- ? Direction.Up
1145
- : bounds.bottom > activeCellBounds.bottom
1146
- ? Direction.Down
1147
- : bounds.right > activeCellBounds.right
1148
- ? Direction.Right
1149
- : Direction.Left;
1150
-
1151
- if (direction === Direction.Right) {
1152
- bounds = {
1153
- ...activeCellBounds,
1154
- right: Math.min(selectionRightBound, bounds.right),
1155
- };
1156
- }
1157
-
1158
- if (direction === Direction.Up) {
1159
- bounds = {
1160
- ...activeCellBounds,
1161
- top: Math.max(selectionTopBound, bounds.top),
1162
- };
1163
- }
1164
-
1165
- if (direction === Direction.Left) {
1166
- bounds = {
1167
- ...activeCellBounds,
1168
- left: Math.max(selectionLeftBound, bounds.left),
1169
- };
1170
- }
1171
-
1172
- if (direction === Direction.Down) {
1173
- bounds = {
1174
- ...activeCellBounds,
1175
- bottom: Math.min(selectionBottomBound, bounds.bottom),
1176
- };
1177
- }
1178
-
1179
- /**
1180
- * If user moves back to the same selection, clear
1181
- */
1182
- if (
1183
- hasSelections &&
1184
- boundsSubsetOfSelection(bounds, selections[0].bounds)
1185
- ) {
1186
- setFillSelection(null);
1187
- return;
1188
- }
1189
-
1190
- setFillSelection({ bounds });
1191
-
1192
- gridRef.current.scrollToItem(coords);
1193
- }, []);
1194
-
1195
- /**
1196
- * When user releases mouse on the fill handle
1197
- */
1198
- const handleFillHandleMouseUp = useCallback((e: globalThis.MouseEvent) => {
1199
- isFilling.current = false;
1200
-
1201
- /* Remove listener */
1202
- document.removeEventListener("mousemove", handleFillHandleMouseMove);
1203
- document.removeEventListener("mouseup", handleFillHandleMouseUp);
1204
-
1205
- /* Exit early */
1206
- if (!gridRef || !activeCellRef.current) return;
1207
-
1208
- /* Update last selection */
1209
- let fillSelection: SelectionArea | null = null;
1210
-
1211
- setFillSelection((prev) => {
1212
- fillSelection = prev;
1213
- return null;
1214
- });
1215
-
1216
- /* Use ref, as we are binding to document */
1217
- const selections = activeSelectionsRef.current;
1218
- const activeCell = activeCellRef.current;
1219
- if (!activeCell || !fillSelection) return;
1220
-
1221
- const newBounds = (fillSelection as SelectionArea)?.bounds;
1222
- if (!newBounds) return;
1223
-
1224
- /* Focus on the grid */
1225
- gridRef.current?.focus();
1226
-
1227
- /* Callback */
1228
- onFill && onFill(activeCell, fillSelection, selections);
1229
-
1230
- /* Modify last selection */
1231
- setSelections((prevSelection) => {
1232
- const len = prevSelection.length;
1233
- if (!len) {
1234
- return [{ bounds: newBounds }];
1235
- }
1236
- return prevSelection.map((sel, i) => {
1237
- if (len - 1 === i) {
1238
- return {
1239
- ...sel,
1240
- bounds: newBounds,
1241
- };
1242
- }
1243
- return sel;
1244
- });
1245
- });
1246
- }, []);
1247
-
1248
- /**
1249
- * Remove the last selection from state
1250
- */
1251
- const handleClearLastSelection = useCallback(() => {
1252
- setSelections((prev) => prev.slice(0, -1));
1253
- }, []);
1254
-
1255
- const fillHandleProps = useMemo(() => {
1256
- return {
1257
- onMouseDown: handleFillHandleMouseDown,
1258
- };
1259
- }, [handleFillHandleMouseDown]);
1260
-
1261
- /**
1262
- * When user mouse downs on selection
1263
- */
1264
- const handleSelectionMouseDown = useCallback(
1265
- (
1266
- e: React.MouseEvent<HTMLDivElement>,
1267
- activeCell: CellInterface | undefined,
1268
- selection: SelectionArea | undefined,
1269
- index: number | undefined,
1270
- shouldClamp: boolean = true
1271
- ) => {
1272
- if (!gridRef.current) {
1273
- return;
1274
- }
1275
- let coords = gridRef.current.getCellCoordsFromOffset(
1276
- e.nativeEvent.clientX,
1277
- e.nativeEvent.clientY,
1278
- false // Todo
1279
- );
1280
- if (!coords) {
1281
- return;
1282
- }
1283
- /* Initial cell that is selected by user */
1284
- initialDraggedCell.current = coords;
1285
-
1286
- /* Make sure the coords do not extend selection bounds */
1287
- if (shouldClamp) {
1288
- coords = clampCellCoords(coords, activeCell, selection);
1289
- }
1290
-
1291
- /* Set selection */
1292
- if (activeCell) {
1293
- initialDraggedSelection.current = draggedSelection.current = {
1294
- bounds: gridRef.current.getCellBounds(activeCell),
1295
- };
1296
- }
1297
- if (selection) {
1298
- initialDraggedSelection.current = draggedSelection.current = selection;
1299
- draggedSelectionIndex.current = index;
1300
- }
1301
-
1302
- /* Set dragging flag */
1303
- isDragging.current = true;
1304
-
1305
- /* Listen to mousemove and mousedown events */
1306
- document.addEventListener("mouseup", handleSelectionMouseUp);
1307
- document.addEventListener("mousemove", handleSelectionMouseMove);
1308
-
1309
- /* Force a re-render */
1310
- forceRender();
1311
- },
1312
- [selectionTopBound, selectionLeftBound, rowCount, columnCount, selections]
1313
- );
1314
-
1315
- /**
1316
- * Ond drag move
1317
- */
1318
- const handleSelectionMouseMove = useCallback((e: globalThis.MouseEvent) => {
1319
- if (!gridRef?.current) return;
1320
- const coords = gridRef.current.getCellCoordsFromOffset(
1321
- e.clientX,
1322
- e.clientY
1323
- );
1324
- if (!coords) {
1325
- return;
1326
- }
1327
- if (!initialDraggedSelection.current || !initialDraggedCell.current) {
1328
- return;
1329
- }
1330
- /**
1331
- * Skip if user is moving the selection
1332
- * to the same starting position
1333
- */
1334
- if (
1335
- !hasUserMovedSelection.current &&
1336
- isEqualCells(initialDraggedCell.current, coords)
1337
- ) {
1338
- return;
1339
- }
1340
- let sel = newSelectionFromDrag(
1341
- initialDraggedSelection.current,
1342
- initialDraggedCell.current,
1343
- coords,
1344
- selectionTopBound,
1345
- selectionLeftBound,
1346
- rowCount,
1347
- columnCount
1348
- );
1349
- // Not required
1350
- // sel = { bounds : extendAreaToMergedCells(sel.bounds, mergedCellsRef.current) }
1351
- draggedSelection.current = sel;
1352
-
1353
- // User has now moved the selection,
1354
- hasUserMovedSelection.current = true;
1355
-
1356
- /* Scroll to the cell */
1357
- gridRef.current?.scrollToItem(coords);
1358
-
1359
- /* Re-render */
1360
- forceRender();
1361
- }, []);
1362
-
1363
- /**
1364
- * When drag/drop is complete
1365
- */
1366
- const handleSelectionMouseUp = useCallback(() => {
1367
- const sel = draggedSelection.current;
1368
- if (sel) {
1369
- /* Select the first cell in the selection area */
1370
- const coords = { rowIndex: sel.bounds.top, columnIndex: sel.bounds.left };
1371
- setActiveCell(coords);
1372
- /* Update selection start */
1373
- selectionStart.current = coords;
1374
-
1375
- if (selectionSpansCells(sel?.bounds)) {
1376
- setSelections((prev) => {
1377
- return prev.map((cur, index) => {
1378
- if (index === draggedSelectionIndex.current) {
1379
- return sel;
1380
- }
1381
- return cur;
1382
- });
1383
- });
1384
-
1385
- /* Update selection end */
1386
- selectionEnd.current = {
1387
- rowIndex: sel.bounds.bottom,
1388
- columnIndex: sel.bounds.right,
1389
- };
1390
- }
1391
- }
1392
-
1393
- if (initialDraggedSelection.current && sel) {
1394
- onSelectionMove?.(initialDraggedSelection.current, sel);
1395
- }
1396
-
1397
- /* Focus on the grid */
1398
- gridRef.current?.focus();
1399
-
1400
- /* Reset all references */
1401
- isDragging.current = false;
1402
- draggedSelection.current = void 0;
1403
- draggedSelectionIndex.current = void 0;
1404
- hasUserMovedSelection.current = false;
1405
-
1406
- /* Remove event handlers */
1407
- document.removeEventListener("mouseup", handleSelectionMouseUp);
1408
- document.removeEventListener("mousemove", handleSelectionMouseMove);
1409
-
1410
- /* Force render */
1411
- forceRender();
1412
- }, []);
1413
-
1414
- return {
1415
- activeCell,
1416
- selections,
1417
- isDragging: isDragging.current,
1418
- draggedSelection: draggedSelection.current,
1419
- initialDraggedSelection: initialDraggedSelection.current,
1420
- onSelectionMouseDown: handleSelectionMouseDown,
1421
- onMouseDown: handleMouseDown,
1422
- onKeyDown: handleKeyDown,
1423
- newSelection,
1424
- setSelections,
1425
- setActiveCell: handleSetActiveCell,
1426
- setActiveCellState: setActiveCell,
1427
- fillHandleProps,
1428
- fillSelection,
1429
- clearLastSelection: handleClearLastSelection,
1430
- modifySelection,
1431
- selectAll,
1432
- appendSelection,
1433
- clearSelections,
1434
- };
1435
- };
1436
-
1437
- export default useSelection;