1 import { useCallback, useState } from "react"
2 import { FieldValues, Path, UseFormReturn } from "react-hook-form"
3 import { DataGridMatrix } from "../models"
4 import { DataGridCellSnapshot, DataGridCoordinates } from "../types"
5
6 type UseDataGridCellSnapshotOptions<TData, TFieldValues extends FieldValues> = {
7 matrix: DataGridMatrix<TData, TFieldValues>
8 form: UseFormReturn<TFieldValues>
9 }
10
11 export const useDataGridCellSnapshot = <
12 TData,
13 TFieldValues extends FieldValues
14 >({
15 matrix,
16 form,
17 }: UseDataGridCellSnapshotOptions<TData, TFieldValues>) => {
18 const [snapshot, setSnapshot] =
19 useState<DataGridCellSnapshot<TFieldValues> | null>(null)
20
21 const { getValues, setValue } = form
22
23 /**
24 * Creates a snapshot of the current cell value.
25 */
26 const createSnapshot = useCallback(
27 (cell: DataGridCoordinates | null) => {
28 if (!cell) {
29 return null
30 }
31
32 const field = matrix.getCellField(cell)
33
34 if (!field) {
35 return null
36 }
37
38 const value = getValues(field as Path<TFieldValues>)
39
40 setSnapshot((curr) => {
41 /**
42 * If there already exists a snapshot for this field, we don't want to create a new one.
43 * A case where this happens is when the user presses the space key on a field. In that case
44 * we create a snapshot of the value before its destroyed by the space key.
45 */
46 if (curr?.field === field) {
47 return curr
48 }
49
50 return { field, value }
51 })
52 },
53 [getValues, matrix]
54 )
55
56 /**
57 * Restores the cell value from the snapshot if it exists.
58 */
59 const restoreSnapshot = useCallback(() => {
60 if (!snapshot) {
61 return
62 }
63
64 const { field, value } = snapshot
65
66 requestAnimationFrame(() => {
67 setValue(field as Path<TFieldValues>, value)
68 })
69 }, [setValue, snapshot])
70
71 return {
72 createSnapshot,
73 restoreSnapshot,
74 }
75 }