|
1
|
import type { Column, Table } from "@tanstack/react-table" |
|
2
|
import { useCallback } from "react" |
|
3
|
import type { FieldValues } from "react-hook-form" |
|
4
|
|
|
5
|
import { DataGridMatrix } from "../models" |
|
6
|
import { GridColumnOption } from "../types" |
|
7
|
|
|
8
|
export function useDataGridColumnVisibility< |
|
9
|
TData, |
|
10
|
TFieldValues extends FieldValues |
|
11
|
>(grid: Table<TData>, matrix: DataGridMatrix<TData, TFieldValues>) { |
|
12
|
const columns = grid.getAllLeafColumns() |
|
13
|
|
|
14
|
const columnOptions: GridColumnOption[] = columns.map((column) => ({ |
|
15
|
id: column.id, |
|
16
|
name: getColumnName(column), |
|
17
|
checked: column.getIsVisible(), |
|
18
|
disabled: !column.getCanHide(), |
|
19
|
})) |
|
20
|
|
|
21
|
const handleToggleColumn = useCallback( |
|
22
|
(index: number) => (value: boolean) => { |
|
23
|
const column = columns[index] |
|
24
|
|
|
25
|
if (!column.getCanHide()) { |
|
26
|
return |
|
27
|
} |
|
28
|
|
|
29
|
matrix.toggleColumn(index, value) |
|
30
|
column.toggleVisibility(value) |
|
31
|
}, |
|
32
|
[columns, matrix] |
|
33
|
) |
|
34
|
|
|
35
|
const handleResetColumns = useCallback(() => { |
|
36
|
grid.setColumnVisibility({}) |
|
37
|
}, [grid]) |
|
38
|
|
|
39
|
const optionCount = columnOptions.filter((c) => !c.disabled).length |
|
40
|
const isDisabled = optionCount === 0 |
|
41
|
|
|
42
|
return { |
|
43
|
columnOptions, |
|
44
|
handleToggleColumn, |
|
45
|
handleResetColumns, |
|
46
|
isDisabled, |
|
47
|
} |
|
48
|
} |
|
49
|
|
|
50
|
function getColumnName<TData>(column: Column<TData, unknown>): string { |
|
51
|
const id = column.columnDef.id |
|
52
|
const enableHiding = column.columnDef.enableHiding |
|
53
|
const meta = column?.columnDef.meta as { name?: string } | undefined |
|
54
|
|
|
55
|
if (!id) { |
|
56
|
throw new Error( |
|
57
|
"Column is missing an id, which is a required field. Please provide an id for the column." |
|
58
|
) |
|
59
|
} |
|
60
|
|
|
61
|
if (process.env.NODE_ENV === "development" && !meta?.name && enableHiding) { |
|
62
|
console.warn( |
|
63
|
`Column "${id}" does not have a name. You should add a name to the column definition. Falling back to the column id.` |
|
64
|
) |
|
65
|
} |
|
66
|
|
|
67
|
return meta?.name || id |
|
68
|
} |