Raw
1 import React, { useCallback } from "react"
2 import type {
3 FieldValues,
4 Path,
5 PathValue,
6 UseFormGetValues,
7 UseFormSetValue,
8 } from "react-hook-form"
9 import {
10 DataGridBulkUpdateCommand,
11 DataGridMatrix,
12 DataGridQueryTool,
13 DataGridUpdateCommand,
14 } from "../models"
15 import { DataGridCoordinates } from "../types"
16
17 type UseDataGridKeydownEventOptions<TData, TFieldValues extends FieldValues> = {
18 containerRef: React.RefObject<HTMLDivElement>
19 matrix: DataGridMatrix<TData, TFieldValues>
20 anchor: DataGridCoordinates | null
21 rangeEnd: DataGridCoordinates | null
22 isEditing: boolean
23 scrollToCoordinates: (
24 coords: DataGridCoordinates,
25 direction: "horizontal" | "vertical" | "both"
26 ) => void
27 setTrapActive: (active: boolean) => void
28 setSingleRange: (coordinates: DataGridCoordinates | null) => void
29 setRangeEnd: (coordinates: DataGridCoordinates | null) => void
30 onEditingChangeHandler: (value: boolean) => void
31 getValues: UseFormGetValues<TFieldValues>
32 setValue: UseFormSetValue<TFieldValues>
33 execute: (command: DataGridUpdateCommand | DataGridBulkUpdateCommand) => void
34 undo: () => void
35 redo: () => void
36 queryTool: DataGridQueryTool | null
37 getSelectionValues: (
38 fields: string[]
39 ) => PathValue<TFieldValues, Path<TFieldValues>>[]
40 setSelectionValues: (fields: string[], values: string[]) => void
41 restoreSnapshot: () => void
42 createSnapshot: (coords: DataGridCoordinates) => void
43 }
44
45 const ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]
46 const VERTICAL_KEYS = ["ArrowUp", "ArrowDown"]
47
48 export const useDataGridKeydownEvent = <
49 TData,
50 TFieldValues extends FieldValues
51 >({
52 containerRef,
53 matrix,
54 anchor,
55 rangeEnd,
56 isEditing,
57 setTrapActive,
58 scrollToCoordinates,
59 setSingleRange,
60 setRangeEnd,
61 onEditingChangeHandler,
62 getValues,
63 setValue,
64 execute,
65 undo,
66 redo,
67 queryTool,
68 getSelectionValues,
69 setSelectionValues,
70 restoreSnapshot,
71 createSnapshot,
72 }: UseDataGridKeydownEventOptions<TData, TFieldValues>) => {
73 const handleKeyboardNavigation = useCallback(
74 (e: KeyboardEvent) => {
75 if (!anchor) {
76 return
77 }
78
79 const type = matrix.getCellType(anchor)
80
81 /**
82 * If the user is currently editing a cell, we don't want to
83 * handle the keyboard navigation.
84 *
85 * If the cell is of type boolean, we don't want to ignore the
86 * keyboard navigation, as we want to allow the user to navigate
87 * away from the cell directly, as you cannot "enter" a boolean cell.
88 */
89 if (isEditing && type !== "boolean") {
90 return
91 }
92
93 const direction = VERTICAL_KEYS.includes(e.key)
94 ? "vertical"
95 : "horizontal"
96
97 /**
98 * If the user performs a horizontal navigation, we want to
99 * use the anchor as the basis for the navigation.
100 *
101 * If the user performs a vertical navigation, the bases depends
102 * on the type of interaction. If the user is holding shift, we want
103 * to use the rangeEnd as the basis. If the user is not holding shift,
104 * we want to use the anchor as the basis.
105 */
106 const basis =
107 direction === "horizontal" ? anchor : e.shiftKey ? rangeEnd : anchor
108
109 const updater =
110 direction === "horizontal"
111 ? setSingleRange
112 : e.shiftKey
113 ? setRangeEnd
114 : setSingleRange
115
116 if (!basis) {
117 return
118 }
119
120 const { row, col } = basis
121
122 const handleNavigation = (coords: DataGridCoordinates) => {
123 e.preventDefault()
124 e.stopPropagation()
125
126 scrollToCoordinates(coords, direction)
127 updater(coords)
128 }
129
130 const next = matrix.getValidMovement(
131 row,
132 col,
133 e.key,
134 e.metaKey || e.ctrlKey
135 )
136
137 handleNavigation(next)
138 },
139 [
140 isEditing,
141 anchor,
142 rangeEnd,
143 scrollToCoordinates,
144 setSingleRange,
145 setRangeEnd,
146 matrix,
147 ]
148 )
149
150 const handleTabKey = useCallback(
151 (e: KeyboardEvent) => {
152 if (!anchor) {
153 return
154 }
155
156 e.preventDefault()
157 e.stopPropagation()
158
159 const { row, col } = anchor
160
161 const key = e.shiftKey ? "ArrowLeft" : "ArrowRight"
162 const direction = "horizontal"
163
164 const next = matrix.getValidMovement(
165 row,
166 col,
167 key,
168 e.metaKey || e.ctrlKey
169 )
170
171 scrollToCoordinates(next, direction)
172 setSingleRange(next)
173 },
174 [anchor, scrollToCoordinates, setSingleRange, matrix]
175 )
176
177 const handleUndo = useCallback(
178 (e: KeyboardEvent) => {
179 e.preventDefault()
180
181 if (e.shiftKey) {
182 redo()
183 return
184 }
185
186 undo()
187 },
188 [redo, undo]
189 )
190
191 const handleSpaceKeyBoolean = useCallback(
192 (anchor: DataGridCoordinates) => {
193 const end = rangeEnd ?? anchor
194
195 const fields = matrix.getFieldsInSelection(anchor, end)
196
197 const prev = getSelectionValues(fields) as boolean[]
198
199 const allChecked = prev.every((value) => value === true)
200 const next = Array.from({ length: prev.length }, () => !allChecked)
201
202 const command = new DataGridBulkUpdateCommand({
203 fields,
204 next,
205 prev,
206 setter: setSelectionValues,
207 })
208
209 execute(command)
210 },
211 [rangeEnd, matrix, getSelectionValues, setSelectionValues, execute]
212 )
213
214 const handleSpaceKeyTextOrNumber = useCallback(
215 (anchor: DataGridCoordinates) => {
216 const field = matrix.getCellField(anchor)
217 const input = queryTool?.getInput(anchor)
218
219 if (!field || !input) {
220 return
221 }
222
223 createSnapshot(anchor)
224
225 const current = getValues(field as Path<TFieldValues>)
226 const next = ""
227
228 const command = new DataGridUpdateCommand({
229 next,
230 prev: current,
231 setter: (value) => {
232 setValue(field as Path<TFieldValues>, value, {
233 shouldDirty: true,
234 shouldTouch: true,
235 })
236 },
237 })
238
239 execute(command)
240
241 input.focus()
242 },
243 [matrix, queryTool, getValues, execute, setValue, createSnapshot]
244 )
245
246 const handleSpaceKeyTogglableNumber = useCallback(
247 (anchor: DataGridCoordinates) => {
248 const field = matrix.getCellField(anchor)
249 const input = queryTool?.getInput(anchor)
250
251 if (!field || !input) {
252 return
253 }
254
255 createSnapshot(anchor)
256
257 const current = getValues(field as Path<TFieldValues>)
258 let checked = current.checked
259
260 // If the toggle is not disabled, then we want to uncheck the toggle.
261 if (!current.disabledToggle) {
262 checked = false
263 }
264
265 const next = { ...current, quantity: "", checked }
266
267 const command = new DataGridUpdateCommand({
268 next,
269 prev: current,
270 setter: (value) => {
271 setValue(field as Path<TFieldValues>, value, {
272 shouldDirty: true,
273 shouldTouch: true,
274 })
275 },
276 })
277
278 execute(command)
279
280 input.focus()
281 },
282 [matrix, queryTool, getValues, execute, setValue, createSnapshot]
283 )
284
285 const handleSpaceKey = useCallback(
286 (e: KeyboardEvent) => {
287 if (!anchor || isEditing) {
288 return
289 }
290
291 e.preventDefault()
292
293 const type = matrix.getCellType(anchor)
294
295 if (!type) {
296 return
297 }
298
299 switch (type) {
300 case "boolean":
301 handleSpaceKeyBoolean(anchor)
302 break
303 case "togglable-number":
304 handleSpaceKeyTogglableNumber(anchor)
305 break
306 case "number":
307 case "text":
308 handleSpaceKeyTextOrNumber(anchor)
309 break
310 }
311 },
312 [
313 anchor,
314 isEditing,
315 matrix,
316 handleSpaceKeyBoolean,
317 handleSpaceKeyTextOrNumber,
318 handleSpaceKeyTogglableNumber,
319 ]
320 )
321
322 const handleMoveOnEnter = useCallback(
323 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
324 const direction = e.shiftKey ? "ArrowUp" : "ArrowDown"
325
326 const pos = matrix.getValidMovement(
327 anchor.row,
328 anchor.col,
329 direction,
330 false
331 )
332
333 if (anchor.row !== pos.row || anchor.col !== pos.col) {
334 setSingleRange(pos)
335 scrollToCoordinates(pos, "vertical")
336 } else {
337 // If the the user is at the last cell, we want to focus the container of the cell.
338 const container = queryTool?.getContainer(anchor)
339
340 container?.focus()
341 }
342
343 onEditingChangeHandler(false)
344 },
345 [
346 queryTool,
347 matrix,
348 scrollToCoordinates,
349 setSingleRange,
350 onEditingChangeHandler,
351 ]
352 )
353
354 const handleEditOnEnter = useCallback(
355 (anchor: DataGridCoordinates) => {
356 const input = queryTool?.getInput(anchor)
357
358 if (!input) {
359 return
360 }
361
362 input.focus()
363 onEditingChangeHandler(true)
364 },
365 [queryTool, onEditingChangeHandler]
366 )
367
368 /**
369 * Handles the enter key for text and number cells.
370 *
371 * The behavior is as follows:
372 * - If the cell is currently not being edited, start editing the cell.
373 * - If the cell is currently being edited, move to the next cell.
374 */
375 const handleEnterKeyTextOrNumber = useCallback(
376 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
377 if (isEditing) {
378 handleMoveOnEnter(e, anchor)
379 return
380 }
381
382 handleEditOnEnter(anchor)
383 },
384 [handleMoveOnEnter, handleEditOnEnter, isEditing]
385 )
386
387 /**
388 * Handles the enter key for boolean cells.
389 *
390 * The behavior is as follows:
391 * - If the cell is currently undefined, set it to true.
392 * - If the cell is currently a boolean, invert the value.
393 * - After the value has been set, move to the next cell.
394 */
395 const handleEnterKeyBoolean = useCallback(
396 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
397 const field = matrix.getCellField(anchor)
398
399 if (!field) {
400 return
401 }
402
403 const current = getValues(field as Path<TFieldValues>)
404 let next: boolean
405
406 if (typeof current === "boolean") {
407 next = !current
408 } else {
409 next = true
410 }
411
412 const command = new DataGridUpdateCommand({
413 next,
414 prev: current,
415 setter: (value) => {
416 setValue(field as Path<TFieldValues>, value, {
417 shouldDirty: true,
418 shouldTouch: true,
419 })
420 },
421 })
422
423 execute(command)
424 handleMoveOnEnter(e, anchor)
425 },
426 [execute, getValues, handleMoveOnEnter, matrix, setValue]
427 )
428
429 const handleEnterKey = useCallback(
430 (e: KeyboardEvent) => {
431 if (!anchor) {
432 return
433 }
434
435 e.preventDefault()
436
437 const type = matrix.getCellType(anchor)
438
439 switch (type) {
440 case "togglable-number":
441 case "text":
442 case "number":
443 handleEnterKeyTextOrNumber(e, anchor)
444 break
445 case "boolean": {
446 handleEnterKeyBoolean(e, anchor)
447 break
448 }
449 }
450 },
451 [anchor, matrix, handleEnterKeyTextOrNumber, handleEnterKeyBoolean]
452 )
453
454 const handleDeleteKeyTogglableNumber = useCallback(
455 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
456 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
457 const prev = getSelectionValues(fields)
458
459 const next = prev.map((value) => ({
460 ...value,
461 quantity: "",
462 checked: value.disableToggle ? value.checked : false,
463 }))
464
465 const command = new DataGridBulkUpdateCommand({
466 fields,
467 next,
468 prev,
469 setter: setSelectionValues,
470 })
471
472 execute(command)
473 },
474 [matrix, getSelectionValues, setSelectionValues, execute]
475 )
476
477 const handleDeleteKeyTextOrNumber = useCallback(
478 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
479 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
480 const prev = getSelectionValues(fields)
481 const next = Array.from({ length: prev.length }, () => "")
482
483 const command = new DataGridBulkUpdateCommand({
484 fields,
485 next,
486 prev,
487 setter: setSelectionValues,
488 })
489
490 execute(command)
491 },
492 [matrix, getSelectionValues, setSelectionValues, execute]
493 )
494
495 const handleDeleteKeyBoolean = useCallback(
496 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
497 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
498 const prev = getSelectionValues(fields)
499 const next = Array.from({ length: prev.length }, () => false)
500
501 const command = new DataGridBulkUpdateCommand({
502 fields,
503 next,
504 prev,
505 setter: setSelectionValues,
506 })
507
508 execute(command)
509 },
510 [execute, getSelectionValues, matrix, setSelectionValues]
511 )
512
513 const handleDeleteKey = useCallback(
514 (e: KeyboardEvent) => {
515 if (!anchor || !rangeEnd || isEditing) {
516 return
517 }
518
519 e.preventDefault()
520
521 const type = matrix.getCellType(anchor)
522
523 if (!type) {
524 return
525 }
526
527 switch (type) {
528 case "text":
529 case "number":
530 handleDeleteKeyTextOrNumber(anchor, rangeEnd)
531 break
532 case "boolean":
533 handleDeleteKeyBoolean(anchor, rangeEnd)
534 break
535 case "togglable-number":
536 handleDeleteKeyTogglableNumber(anchor, rangeEnd)
537 break
538 }
539 },
540 [
541 anchor,
542 rangeEnd,
543 isEditing,
544 matrix,
545 handleDeleteKeyTextOrNumber,
546 handleDeleteKeyBoolean,
547 handleDeleteKeyTogglableNumber,
548 ]
549 )
550
551 const handleEscapeKey = useCallback(
552 (e: KeyboardEvent) => {
553 if (!anchor || !isEditing) {
554 return
555 }
556
557 e.preventDefault()
558 e.stopPropagation()
559
560 // try to restore the previous value
561 restoreSnapshot()
562
563 // Restore focus to the container element
564 const container = queryTool?.getContainer(anchor)
565 container?.focus()
566 },
567 [queryTool, isEditing, anchor, restoreSnapshot]
568 )
569
570 const handleSpecialFocusKeys = useCallback(
571 (e: KeyboardEvent) => {
572 if (!containerRef || isEditing) {
573 return
574 }
575
576 const focusableElements = getFocusableElements(containerRef)
577
578 const focusElement = (element: HTMLElement | null) => {
579 if (element) {
580 setTrapActive(false)
581 element.focus()
582 }
583 }
584
585 switch (e.key) {
586 case ".":
587 focusElement(focusableElements.cancel)
588 break
589 case ",":
590 focusElement(focusableElements.shortcuts)
591 break
592 default:
593 break
594 }
595 },
596 [isEditing, setTrapActive, containerRef]
597 )
598
599 const handleKeyDownEvent = useCallback(
600 (e: KeyboardEvent) => {
601 if (ARROW_KEYS.includes(e.key)) {
602 handleKeyboardNavigation(e)
603 return
604 }
605
606 if (e.key === "z" && (e.metaKey || e.ctrlKey)) {
607 handleUndo(e)
608 return
609 }
610
611 if (e.key === " ") {
612 handleSpaceKey(e)
613 return
614 }
615
616 if (e.key === "Delete" || e.key === "Backspace") {
617 handleDeleteKey(e)
618 return
619 }
620
621 if (e.key === "Enter") {
622 handleEnterKey(e)
623 return
624 }
625
626 if (e.key === "Escape") {
627 handleEscapeKey(e)
628 return
629 }
630
631 if (e.key === "Tab") {
632 handleTabKey(e)
633 return
634 }
635 },
636 [
637 handleEscapeKey,
638 handleKeyboardNavigation,
639 handleUndo,
640 handleSpaceKey,
641 handleEnterKey,
642 handleDeleteKey,
643 handleTabKey,
644 ]
645 )
646
647 return {
648 handleKeyDownEvent,
649 handleSpecialFocusKeys,
650 }
651 }
652
653 function getFocusableElements(ref: React.RefObject<HTMLDivElement>) {
654 const focusableElements = Array.from(
655 document.querySelectorAll<HTMLElement>(
656 "[tabindex], a, button, input, select, textarea"
657 )
658 )
659
660 const currentElementIndex = focusableElements.indexOf(ref.current!)
661
662 const shortcuts =
663 currentElementIndex > 0 ? focusableElements[currentElementIndex - 1] : null
664
665 let cancel = null
666 for (let i = currentElementIndex + 1; i < focusableElements.length; i++) {
667 if (!ref.current!.contains(focusableElements[i])) {
668 cancel = focusableElements[i]
669 break
670 }
671 }
672
673 return { shortcuts, cancel }
674 }