1 import { CellContext } from "@tanstack/react-table"
2 import { useMemo } from "react"
3 import { FieldError, FieldErrors, get } from "react-hook-form"
4
5 import { useDataGridContext } from "../context"
6 import { DataGridCellContext, DataGridRowError } from "../types"
7
8 type UseDataGridCellErrorOptions<TData, TValue> = {
9 context: CellContext<TData, TValue>
10 }
11
12 export const useDataGridCellError = <TextData, TValue>({
13 context,
14 }: UseDataGridCellErrorOptions<TextData, TValue>) => {
15 const { errors, getCellErrorMetadata, navigateToField } = useDataGridContext()
16
17 const { rowIndex, columnIndex } = context as DataGridCellContext<
18 TextData,
19 TValue
20 >
21
22 const { accessor, field } = useMemo(() => {
23 return getCellErrorMetadata({ row: rowIndex, col: columnIndex })
24 }, [rowIndex, columnIndex, getCellErrorMetadata])
25
26 const rowErrorsObject: FieldErrors | undefined =
27 accessor && columnIndex === 0 ? get(errors, accessor) : undefined
28
29 const rowErrors: DataGridRowError[] = []
30
31 function collectErrors(
32 errorObject: FieldErrors | FieldError | undefined,
33 baseAccessor: string
34 ) {
35 if (!errorObject) {
36 return
37 }
38
39 if (isFieldError(errorObject)) {
40 // Handle a single FieldError directly
41 const message = errorObject.message
42
43 const to = () => navigateToField(baseAccessor)
44
45 if (message) {
46 rowErrors.push({ message, to })
47 }
48 } else {
49 // Traverse nested objects
50 Object.keys(errorObject).forEach((key) => {
51 const nestedError = errorObject[key]
52 const fieldAccessor = `${baseAccessor}.${key}`
53
54 if (nestedError && typeof nestedError === "object") {
55 collectErrors(nestedError, fieldAccessor)
56 }
57 })
58 }
59 }
60
61 if (rowErrorsObject && accessor) {
62 collectErrors(rowErrorsObject, accessor)
63 }
64
65 const cellError: FieldError | undefined = field
66 ? get(errors, field)
67 : undefined
68
69 return {
70 errors,
71 rowErrors,
72 cellError,
73 }
74 }
75
76 function isFieldError(errors: FieldErrors | FieldError): errors is FieldError {
77 return typeof errors === "object" && "message" in errors && "type" in errors
78 }