1 import { CellContext } from "@tanstack/react-table"
2 import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
3
4 import { useDataGridContext } from "../context"
5 import {
6 DataGridCellContext,
7 DataGridCellRenderProps,
8 DataGridCoordinates,
9 } from "../types"
10 import { isCellMatch, isSpecialFocusKey } from "../utils"
11
12 type UseDataGridCellOptions<TData, TValue> = {
13 context: CellContext<TData, TValue>
14 }
15
16 const textCharacterRegex = /^.$/u
17 const numberCharacterRegex = /^[0-9]$/u
18
19 export const useDataGridCell = <TData, TValue>({
20 context,
21 }: UseDataGridCellOptions<TData, TValue>) => {
22 const {
23 register,
24 control,
25 anchor,
26 setIsEditing,
27 setSingleRange,
28 setIsSelecting,
29 setRangeEnd,
30 getWrapperFocusHandler,
31 getWrapperMouseOverHandler,
32 getInputChangeHandler,
33 getIsCellSelected,
34 getIsCellDragSelected,
35 getCellMetadata,
36 } = useDataGridContext()
37
38 const { rowIndex, columnIndex } = context as DataGridCellContext<
39 TData,
40 TValue
41 >
42
43 const coords: DataGridCoordinates = useMemo(
44 () => ({ row: rowIndex, col: columnIndex }),
45 [rowIndex, columnIndex]
46 )
47
48 const { id, field, type, innerAttributes, inputAttributes } = useMemo(() => {
49 return getCellMetadata(coords)
50 }, [coords, getCellMetadata])
51
52 const [showOverlay, setShowOverlay] = useState(true)
53
54 const containerRef = useRef<HTMLDivElement>(null)
55 const inputRef = useRef<HTMLElement>(null)
56
57 const handleOverlayMouseDown = useCallback(
58 (e: React.MouseEvent) => {
59 e.preventDefault()
60 e.stopPropagation()
61
62 if (e.detail === 2) {
63 if (inputRef.current) {
64 setShowOverlay(false)
65
66 inputRef.current.focus()
67
68 return
69 }
70 }
71
72 if (e.shiftKey) {
73 // Only allow setting the rangeEnd if the column matches the anchor column.
74 // If not we let the function continue and treat the click as if the shift key was not pressed.
75 if (coords.col === anchor?.col) {
76 setRangeEnd(coords)
77 return
78 }
79 }
80
81 if (containerRef.current) {
82 setSingleRange(coords)
83 setIsSelecting(true)
84 containerRef.current.focus()
85 }
86 },
87 [coords, anchor, setRangeEnd, setSingleRange, setIsSelecting]
88 )
89
90 const handleBooleanInnerMouseDown = useCallback(
91 (e: React.MouseEvent<HTMLElement>) => {
92 e.preventDefault()
93 e.stopPropagation()
94
95 if (e.detail === 2) {
96 inputRef.current?.focus()
97 return
98 }
99
100 if (e.shiftKey) {
101 setRangeEnd(coords)
102 return
103 }
104
105 if (containerRef.current) {
106 setSingleRange(coords)
107 setIsSelecting(true)
108 containerRef.current.focus()
109 }
110 },
111 [setIsSelecting, setSingleRange, setRangeEnd, coords]
112 )
113
114 const handleInputBlur = useCallback(() => {
115 setShowOverlay(true)
116 setIsEditing(false)
117 }, [setIsEditing])
118
119 const handleInputFocus = useCallback(() => {
120 setShowOverlay(false)
121 setIsEditing(true)
122 }, [setIsEditing])
123
124 const validateKeyStroke = useCallback(
125 (key: string) => {
126 switch (type) {
127 case "togglable-number":
128 case "number":
129 return numberCharacterRegex.test(key)
130 case "text":
131 case "multiline-text":
132 return textCharacterRegex.test(key)
133 default:
134 // KeyboardEvents should not be forwareded to other types of cells
135 return false
136 }
137 },
138 [type]
139 )
140
141 const handleContainerKeyDown = useCallback(
142 (e: React.KeyboardEvent<HTMLDivElement>) => {
143 if (!inputRef.current || !validateKeyStroke(e.key) || !showOverlay) {
144 return
145 }
146
147 // Allow the user to undo/redo
148 if (e.key.toLowerCase() === "z" && (e.ctrlKey || e.metaKey)) {
149 return
150 }
151
152 // Allow the user to copy
153 if (e.key.toLowerCase() === "c" && (e.ctrlKey || e.metaKey)) {
154 return
155 }
156
157 // Allow the user to paste
158 if (e.key.toLowerCase() === "v" && (e.ctrlKey || e.metaKey)) {
159 return
160 }
161
162 if (e.key === "Enter") {
163 return
164 }
165
166 if (isSpecialFocusKey(e.nativeEvent)) {
167 return
168 }
169
170 inputRef.current.focus()
171 setShowOverlay(false)
172
173 if (inputRef.current instanceof HTMLInputElement) {
174 // Clear the current value
175 inputRef.current.value = ""
176
177 // Simulate typing the new key
178 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
179 window.HTMLInputElement.prototype,
180 "value"
181 )?.set
182 nativeInputValueSetter?.call(inputRef.current, e.key)
183
184 const event = new Event("input", { bubbles: true })
185 inputRef.current.dispatchEvent(event)
186 } else if (inputRef.current instanceof HTMLTextAreaElement) {
187 inputRef.current.value = ""
188
189 const nativeTextAreaValueSetter = Object.getOwnPropertyDescriptor(
190 window.HTMLTextAreaElement.prototype,
191 "value"
192 )?.set
193 nativeTextAreaValueSetter?.call(inputRef.current, e.key)
194
195 // Trigger input event to notify react-hook-form
196 const event = new Event("input", { bubbles: true })
197 inputRef.current.dispatchEvent(event)
198 }
199
200 // Prevent the original event from propagating
201 e.stopPropagation()
202 e.preventDefault()
203 },
204 [showOverlay, validateKeyStroke]
205 )
206
207 const isAnchor = useMemo(() => {
208 return anchor ? isCellMatch(coords, anchor) : false
209 }, [anchor, coords])
210
211 const fieldWithoutOverlay = useMemo(() => {
212 return type === "boolean"
213 }, [type])
214
215 useEffect(() => {
216 if (isAnchor && !containerRef.current?.contains(document.activeElement)) {
217 containerRef.current?.focus({ preventScroll: true })
218 }
219 }, [isAnchor])
220
221 const renderProps: DataGridCellRenderProps = {
222 container: {
223 field,
224 isAnchor,
225 isSelected: getIsCellSelected(coords),
226 isDragSelected: getIsCellDragSelected(coords),
227 showOverlay: fieldWithoutOverlay ? false : showOverlay,
228 innerProps: {
229 ref: containerRef,
230 onMouseOver: getWrapperMouseOverHandler(coords),
231 onMouseDown:
232 type === "boolean" ? handleBooleanInnerMouseDown : undefined,
233 onKeyDown: handleContainerKeyDown,
234 onFocus: getWrapperFocusHandler(coords),
235 ...innerAttributes,
236 },
237 overlayProps: {
238 onMouseDown: handleOverlayMouseDown,
239 },
240 },
241 input: {
242 ref: inputRef,
243 onBlur: handleInputBlur,
244 onFocus: handleInputFocus,
245 onChange: getInputChangeHandler(field),
246 ...inputAttributes,
247 },
248 }
249
250 return {
251 id,
252 field,
253 register,
254 control,
255 renderProps,
256 }
257 }