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 handleSpaceKeyText = 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 input.focus()
225 },
226 [matrix, queryTool, createSnapshot]
227 )
228
229 const handleSpaceKeyNumber = useCallback(
230 (anchor: DataGridCoordinates) => {
231 const field = matrix.getCellField(anchor)
232 const input = queryTool?.getInput(anchor)
233
234 if (!field || !input) {
235 return
236 }
237
238 createSnapshot(anchor)
239
240 const current = getValues(field as Path<TFieldValues>)
241 const next = ""
242
243 const command = new DataGridUpdateCommand({
244 next,
245 prev: current,
246 setter: (value) => {
247 setValue(field as Path<TFieldValues>, value, {
248 shouldDirty: true,
249 shouldTouch: true,
250 })
251 },
252 })
253
254 execute(command)
255
256 input.focus()
257 },
258 [matrix, queryTool, getValues, execute, setValue, createSnapshot]
259 )
260
261 const handleSpaceKeyTogglableNumber = useCallback(
262 (anchor: DataGridCoordinates) => {
263 const field = matrix.getCellField(anchor)
264 const input = queryTool?.getInput(anchor)
265
266 if (!field || !input) {
267 return
268 }
269
270 createSnapshot(anchor)
271
272 const current = getValues(field as Path<TFieldValues>)
273 let checked = current.checked
274
275 // If the toggle is not disabled, then we want to uncheck the toggle.
276 if (!current.disabledToggle) {
277 checked = false
278 }
279
280 const next = { ...current, quantity: "", checked }
281
282 const command = new DataGridUpdateCommand({
283 next,
284 prev: current,
285 setter: (value) => {
286 setValue(field as Path<TFieldValues>, value, {
287 shouldDirty: true,
288 shouldTouch: true,
289 })
290 },
291 })
292
293 execute(command)
294
295 input.focus()
296 },
297 [matrix, queryTool, getValues, execute, setValue, createSnapshot]
298 )
299
300 const handleSpaceKey = useCallback(
301 (e: KeyboardEvent) => {
302 if (!anchor || isEditing) {
303 return
304 }
305
306 e.preventDefault()
307
308 const type = matrix.getCellType(anchor)
309
310 if (!type) {
311 return
312 }
313
314 switch (type) {
315 case "boolean":
316 handleSpaceKeyBoolean(anchor)
317 break
318 case "togglable-number":
319 handleSpaceKeyTogglableNumber(anchor)
320 break
321 case "text":
322 case "multiline-text":
323 handleSpaceKeyText(anchor)
324 break
325 case "number":
326 handleSpaceKeyNumber(anchor)
327 break
328 }
329 },
330 [
331 anchor,
332 isEditing,
333 matrix,
334 handleSpaceKeyBoolean,
335 handleSpaceKeyText,
336 handleSpaceKeyNumber,
337 handleSpaceKeyTogglableNumber,
338 ]
339 )
340
341 const handleMoveOnEnter = useCallback(
342 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
343 const direction = e.shiftKey ? "ArrowUp" : "ArrowDown"
344
345 const pos = matrix.getValidMovement(
346 anchor.row,
347 anchor.col,
348 direction,
349 false
350 )
351
352 if (anchor.row !== pos.row || anchor.col !== pos.col) {
353 setSingleRange(pos)
354 scrollToCoordinates(pos, "vertical")
355 } else {
356 // If the user is at the last cell, we want to focus the container of the cell.
357 const container = queryTool?.getContainer(anchor)
358
359 container?.focus()
360 }
361
362 onEditingChangeHandler(false)
363 },
364 [
365 queryTool,
366 matrix,
367 scrollToCoordinates,
368 setSingleRange,
369 onEditingChangeHandler,
370 ]
371 )
372
373 const handleEditOnEnter = useCallback(
374 (anchor: DataGridCoordinates) => {
375 const input = queryTool?.getInput(anchor)
376
377 if (!input) {
378 return
379 }
380
381 input.focus()
382 onEditingChangeHandler(true)
383 },
384 [queryTool, onEditingChangeHandler]
385 )
386
387 /**
388 * Handles the enter key for text and number cells.
389 *
390 * The behavior is as follows:
391 * - If the cell is currently not being edited, start editing the cell.
392 * - If the cell is currently being edited, move to the next cell.
393 */
394 const handleEnterKeyTextOrNumber = useCallback(
395 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
396 if (isEditing) {
397 handleMoveOnEnter(e, anchor)
398 return
399 }
400
401 handleEditOnEnter(anchor)
402 },
403 [handleMoveOnEnter, handleEditOnEnter, isEditing]
404 )
405
406 /**
407 * Handles the enter key for multiline-text cells.
408 *
409 * The behavior is as follows:
410 * - If Shift+Enter is pressed while editing, allow the newline (don't prevent default).
411 * - If Enter is pressed while editing (without Shift), move to the next cell.
412 * - If the cell is currently not being edited, start editing the cell.
413 */
414 const handleEnterKeyMultilineText = useCallback(
415 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
416 if (isEditing) {
417 if (e.shiftKey) {
418 return
419 }
420
421 handleMoveOnEnter(e, anchor)
422 return
423 }
424
425 handleEditOnEnter(anchor)
426 },
427 [handleMoveOnEnter, handleEditOnEnter, isEditing]
428 )
429
430 /**
431 * Handles the enter key for boolean cells.
432 *
433 * The behavior is as follows:
434 * - If the cell is currently undefined, set it to true.
435 * - If the cell is currently a boolean, invert the value.
436 * - After the value has been set, move to the next cell.
437 */
438 const handleEnterKeyBoolean = useCallback(
439 (e: KeyboardEvent, anchor: DataGridCoordinates) => {
440 const field = matrix.getCellField(anchor)
441
442 if (!field) {
443 return
444 }
445
446 const current = getValues(field as Path<TFieldValues>)
447 let next: boolean
448
449 if (typeof current === "boolean") {
450 next = !current
451 } else {
452 next = true
453 }
454
455 const command = new DataGridUpdateCommand({
456 next,
457 prev: current,
458 setter: (value) => {
459 setValue(field as Path<TFieldValues>, value, {
460 shouldDirty: true,
461 shouldTouch: true,
462 })
463 },
464 })
465
466 execute(command)
467 handleMoveOnEnter(e, anchor)
468 },
469 [execute, getValues, handleMoveOnEnter, matrix, setValue]
470 )
471
472 const handleEnterKey = useCallback(
473 (e: KeyboardEvent) => {
474 if (!anchor) {
475 return
476 }
477
478 const type = matrix.getCellType(anchor)
479
480 if (type === "multiline-text" && isEditing && e.shiftKey) {
481 return
482 }
483
484 e.preventDefault()
485
486 switch (type) {
487 case "multiline-text":
488 handleEnterKeyMultilineText(e, anchor)
489 break
490 case "togglable-number":
491 case "text":
492 case "number":
493 handleEnterKeyTextOrNumber(e, anchor)
494 break
495 case "boolean": {
496 handleEnterKeyBoolean(e, anchor)
497 break
498 }
499 }
500 },
501 [
502 anchor,
503 matrix,
504 isEditing,
505 handleEnterKeyTextOrNumber,
506 handleEnterKeyBoolean,
507 handleEnterKeyMultilineText,
508 ]
509 )
510
511 const handleDeleteKeyTogglableNumber = useCallback(
512 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
513 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
514 const prev = getSelectionValues(fields)
515
516 const next = prev.map((value) => ({
517 ...value,
518 quantity: "",
519 checked: value.disableToggle ? value.checked : false,
520 }))
521
522 const command = new DataGridBulkUpdateCommand({
523 fields,
524 next,
525 prev,
526 setter: setSelectionValues,
527 })
528
529 execute(command)
530 },
531 [matrix, getSelectionValues, setSelectionValues, execute]
532 )
533
534 const handleDeleteKeyTextOrNumber = useCallback(
535 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
536 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
537 const prev = getSelectionValues(fields)
538 const next = Array.from({ length: prev.length }, () => "")
539
540 const command = new DataGridBulkUpdateCommand({
541 fields,
542 next,
543 prev,
544 setter: setSelectionValues,
545 })
546
547 execute(command)
548 },
549 [matrix, getSelectionValues, setSelectionValues, execute]
550 )
551
552 const handleDeleteKeyBoolean = useCallback(
553 (anchor: DataGridCoordinates, rangeEnd: DataGridCoordinates) => {
554 const fields = matrix.getFieldsInSelection(anchor, rangeEnd)
555 const prev = getSelectionValues(fields)
556 const next = Array.from({ length: prev.length }, () => false)
557
558 const command = new DataGridBulkUpdateCommand({
559 fields,
560 next,
561 prev,
562 setter: setSelectionValues,
563 })
564
565 execute(command)
566 },
567 [execute, getSelectionValues, matrix, setSelectionValues]
568 )
569
570 const handleDeleteKey = useCallback(
571 (e: KeyboardEvent) => {
572 if (!anchor || !rangeEnd || isEditing) {
573 return
574 }
575
576 e.preventDefault()
577
578 const type = matrix.getCellType(anchor)
579
580 if (!type) {
581 return
582 }
583
584 switch (type) {
585 case "text":
586 case "multiline-text":
587 case "number":
588 handleDeleteKeyTextOrNumber(anchor, rangeEnd)
589 break
590 case "boolean":
591 handleDeleteKeyBoolean(anchor, rangeEnd)
592 break
593 case "togglable-number":
594 handleDeleteKeyTogglableNumber(anchor, rangeEnd)
595 break
596 }
597 },
598 [
599 anchor,
600 rangeEnd,
601 isEditing,
602 matrix,
603 handleDeleteKeyTextOrNumber,
604 handleDeleteKeyBoolean,
605 handleDeleteKeyTogglableNumber,
606 ]
607 )
608
609 const handleEscapeKey = useCallback(
610 (e: KeyboardEvent) => {
611 if (!anchor || !isEditing) {
612 return
613 }
614
615 e.preventDefault()
616 e.stopPropagation()
617
618 // try to restore the previous value
619 restoreSnapshot()
620
621 // Restore focus to the container element
622 const container = queryTool?.getContainer(anchor)
623 container?.focus()
624 },
625 [queryTool, isEditing, anchor, restoreSnapshot]
626 )
627
628 const handleSpecialFocusKeys = useCallback(
629 (e: KeyboardEvent) => {
630 if (!containerRef || isEditing) {
631 return
632 }
633
634 const focusableElements = getFocusableElements(containerRef)
635
636 const focusElement = (element: HTMLElement | null) => {
637 if (element) {
638 setTrapActive(false)
639 element.focus()
640 }
641 }
642
643 switch (e.key) {
644 case ".":
645 focusElement(focusableElements.cancel)
646 break
647 case ",":
648 focusElement(focusableElements.shortcuts)
649 break
650 default:
651 break
652 }
653 },
654 [isEditing, setTrapActive, containerRef]
655 )
656
657 const handleKeyDownEvent = useCallback(
658 (e: KeyboardEvent) => {
659 if (ARROW_KEYS.includes(e.key)) {
660 handleKeyboardNavigation(e)
661 return
662 }
663
664 if (e.key === "z" && (e.metaKey || e.ctrlKey)) {
665 handleUndo(e)
666 return
667 }
668
669 if (e.key === " ") {
670 handleSpaceKey(e)
671 return
672 }
673
674 if (e.key === "Delete" || e.key === "Backspace") {
675 handleDeleteKey(e)
676 return
677 }
678
679 if (e.key === "Enter") {
680 handleEnterKey(e)
681 return
682 }
683
684 if (e.key === "Escape") {
685 handleEscapeKey(e)
686 return
687 }
688
689 if (e.key === "Tab") {
690 handleTabKey(e)
691 return
692 }
693 },
694 [
695 handleEscapeKey,
696 handleKeyboardNavigation,
697 handleUndo,
698 handleSpaceKey,
699 handleEnterKey,
700 handleDeleteKey,
701 handleTabKey,
702 ]
703 )
704
705 return {
706 handleKeyDownEvent,
707 handleSpecialFocusKeys,
708 }
709 }
710
711 function getFocusableElements(ref: React.RefObject<HTMLDivElement>) {
712 const focusableElements = Array.from(
713 document.querySelectorAll<HTMLElement>(
714 "[tabindex], a, button, input, select, textarea"
715 )
716 )
717
718 const currentElementIndex = focusableElements.indexOf(ref.current!)
719
720 const shortcuts =
721 currentElementIndex > 0 ? focusableElements[currentElementIndex - 1] : null
722
723 let cancel: HTMLElement | null = null
724 for (let i = currentElementIndex + 1; i < focusableElements.length; i++) {
725 if (!ref.current!.contains(focusableElements[i])) {
726 cancel = focusableElements[i]
727 break
728 }
729 }
730
731 return { shortcuts, cancel }
732 }