Raw
1 import { Table, VisibilityState } from "@tanstack/react-table"
2 import { useCallback, useMemo, useState } from "react"
3 import { FieldError, FieldErrors, FieldValues } from "react-hook-form"
4
5 import { DataGridMatrix } from "../models"
6 import { VisibilitySnapshot } from "../types"
7
8 export const useDataGridErrorHighlighting = <
9 TData,
10 TFieldValues extends FieldValues
11 >(
12 matrix: DataGridMatrix<TData, TFieldValues>,
13 grid: Table<TData>,
14 errors: FieldErrors<TFieldValues>
15 ) => {
16 const [isHighlighted, setIsHighlighted] = useState<boolean>(false)
17 const [visibilitySnapshot, setVisibilitySnapshot] =
18 useState<VisibilitySnapshot | null>(null)
19
20 const { flatRows } = grid.getRowModel()
21 const flatColumns = grid.getAllFlatColumns()
22
23 const errorPaths = findErrorPaths(errors)
24 const errorCount = errorPaths.length
25
26 const { rowsWithErrors, columnsWithErrors } = useMemo(() => {
27 const rowsWithErrors = new Set<number>()
28 const columnsWithErrors = new Set<number>()
29
30 errorPaths.forEach((errorPath) => {
31 const rowIndex = matrix.rowAccessors.findIndex(
32 (accessor) =>
33 accessor &&
34 (errorPath === accessor || errorPath.startsWith(`${accessor}.`))
35 )
36 if (rowIndex !== -1) {
37 rowsWithErrors.add(rowIndex)
38 }
39
40 const columnIndex = matrix.columnAccessors.findIndex(
41 (accessor) =>
42 accessor &&
43 (errorPath === accessor || errorPath.endsWith(`.${accessor}`))
44 )
45 if (columnIndex !== -1) {
46 columnsWithErrors.add(columnIndex)
47 }
48 })
49
50 return { rowsWithErrors, columnsWithErrors }
51 }, [errorPaths, matrix.rowAccessors, matrix.columnAccessors])
52
53 const toggleErrorHighlighting = useCallback(
54 (
55 currentRowVisibility: VisibilityState,
56 currentColumnVisibility: VisibilityState,
57 setRowVisibility: (visibility: VisibilityState) => void,
58 setColumnVisibility: (visibility: VisibilityState) => void
59 ) => {
60 if (isHighlighted) {
61 // Clear error highlights
62 if (visibilitySnapshot) {
63 setRowVisibility(visibilitySnapshot.rows)
64 setColumnVisibility(visibilitySnapshot.columns)
65 }
66 } else {
67 // Highlight errors
68 setVisibilitySnapshot({
69 rows: { ...currentRowVisibility },
70 columns: { ...currentColumnVisibility },
71 })
72
73 const rowsToHide = flatRows
74 .map((_, index) => {
75 return !rowsWithErrors.has(index) ? index : undefined
76 })
77 .filter((index): index is number => index !== undefined)
78
79 const columnsToHide = flatColumns
80 .map((column, index) => {
81 return !columnsWithErrors.has(index) && index !== 0
82 ? column.id
83 : undefined
84 })
85 .filter((id): id is string => id !== undefined)
86
87 setRowVisibility(
88 rowsToHide.reduce((acc, row) => ({ ...acc, [row]: false }), {})
89 )
90
91 setColumnVisibility(
92 columnsToHide.reduce(
93 (acc, column) => ({ ...acc, [column]: false }),
94 {}
95 )
96 )
97 }
98
99 setIsHighlighted((prev) => !prev)
100 },
101 [
102 isHighlighted,
103 visibilitySnapshot,
104 flatRows,
105 flatColumns,
106 rowsWithErrors,
107 columnsWithErrors,
108 ]
109 )
110
111 return {
112 errorCount,
113 isHighlighted,
114 toggleErrorHighlighting,
115 }
116 }
117
118 function findErrorPaths(
119 obj: FieldErrors | FieldError,
120 path: string[] = []
121 ): string[] {
122 if (typeof obj !== "object" || obj === null) {
123 return []
124 }
125
126 if ("message" in obj && "type" in obj) {
127 return [path.join(".")]
128 }
129
130 return Object.entries(obj).flatMap(([key, value]) =>
131 findErrorPaths(value, [...path, key])
132 )
133 }