1 import {
2 CellContext,
3 ColumnDefTemplate,
4 createColumnHelper,
5 HeaderContext,
6 } from "@tanstack/react-table"
7 import { FieldValues } from "react-hook-form"
8
9 import { DataGridColumnType, FieldFunction } from "../types"
10
11 type DataGridHelperColumnsProps<TData, TFieldValues extends FieldValues> = {
12 /**
13 * The id of the column.
14 */
15 id: string
16 /**
17 * The name of the column, shown in the column visibility menu.
18 */
19 name?: string
20 /**
21 * The header template for the column.
22 */
23 header: ColumnDefTemplate<HeaderContext<TData, unknown>> | undefined
24 /**
25 * The cell template for the column.
26 */
27 cell: ColumnDefTemplate<CellContext<TData, unknown>> | undefined
28 /**
29 * Callback to set the field path for each cell in the column.
30 * If a callback is not provided, or returns null, the cell will not be editable.
31 */
32 field?: FieldFunction<TData, TFieldValues>
33 /**
34 * Whether the column cannot be hidden by the user.
35 *
36 * @default false
37 */
38 disableHiding?: boolean
39 /**
40 * The size of the column in pixels.
41 */
42 size?: number
43 /**
44 * The minimum size of the column in pixels.
45 */
46 minSize?: number
47 /**
48 * The maximum size of the column in pixels.
49 */
50 maxSize?: number
51 } & (
52 | {
53 field: FieldFunction<TData, TFieldValues>
54 type: DataGridColumnType
55 }
56 | { field?: null | undefined; type?: never }
57 )
58
59 export function createDataGridHelper<
60 TData,
61 TFieldValues extends FieldValues
62 >() {
63 const columnHelper = createColumnHelper<TData>()
64
65 return {
66 column: ({
67 id,
68 name,
69 header,
70 cell,
71 disableHiding = false,
72 field,
73 type,
74 size,
75 minSize,
76 maxSize,
77 }: DataGridHelperColumnsProps<TData, TFieldValues>) =>
78 columnHelper.display({
79 id,
80 header,
81 cell,
82 enableHiding: !disableHiding,
83 size,
84 minSize,
85 maxSize,
86 meta: {
87 name,
88 field,
89 type,
90 },
91 }),
92 }
93 }