|
1 | | -import { ColumnDef, ColumnHelper, DeepKeys, RowData, createColumnHelper } from "@tanstack/react-table"; |
| 1 | +import { useSortable } from "@dnd-kit/sortable"; |
| 2 | +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; |
| 3 | +import { ColumnDef, ColumnHelper, DeepKeys, DisplayColumnDef, RowData, createColumnHelper } from "@tanstack/react-table"; |
| 4 | +import { ReactNode } from "react"; |
2 | 5 | import { DropdownColumnFilterOption } from "src/react-table"; |
| 6 | +import { faGripLines } from "@fortawesome/free-solid-svg-icons"; |
3 | 7 |
|
4 | 8 | interface ReactDataTableColumnHelper<TData extends RowData> extends ColumnHelper<TData> { |
5 | 9 | createEnumColumn: <TEnum extends string | number>( |
6 | 10 | columnKey: DeepKeys<TData>, |
7 | 11 | enumTranslations: Record<TEnum, string> | DropdownColumnFilterOption[], |
8 | 12 | columndDef?: Partial<ColumnDef<TData, TEnum>>, |
9 | 13 | ) => ColumnDef<TData, TEnum>; |
| 14 | + createDraggableColumn: ( |
| 15 | + columnKey: DeepKeys<TData>, |
| 16 | + columndDef: Omit<DisplayColumnDef<TData>, "id" | "cell">, |
| 17 | + isEnabled?: boolean, |
| 18 | + draggableElement?: ReactNode, |
| 19 | + ) => ColumnDef<TData>; |
10 | 20 | } |
11 | 21 |
|
12 | 22 | const createReactDataTableColumnHelper = <TData extends RowData>(): ReactDataTableColumnHelper<TData> => { |
13 | 23 | const columnHelper = createColumnHelper<TData>(); |
14 | 24 |
|
15 | 25 | columnHelper.accessor; |
16 | 26 |
|
| 27 | + const createDraggableColumn = ( |
| 28 | + columnKey: DeepKeys<TData>, |
| 29 | + columndDef: Omit<DisplayColumnDef<TData>, "id" | "cell">, |
| 30 | + isEnabled?: boolean, |
| 31 | + draggableElement?: ReactNode, |
| 32 | + ) => { |
| 33 | + const RowDragHandleCell = ({ rowId }: { rowId: string }) => { |
| 34 | + const { attributes, listeners, isDragging } = useSortable({ id: rowId }); |
| 35 | + |
| 36 | + return ( |
| 37 | + <span |
| 38 | + {...attributes} |
| 39 | + {...listeners} |
| 40 | + className={isEnabled === false ? "opacity-25" : "opacity-100"} |
| 41 | + style={{ cursor: isEnabled === false ? "auto" : isDragging ? "grabbing" : "grab" }} |
| 42 | + > |
| 43 | + {draggableElement ?? <FontAwesomeIcon icon={faGripLines} />} |
| 44 | + </span> |
| 45 | + ); |
| 46 | + }; |
| 47 | + |
| 48 | + return columnHelper.display({ |
| 49 | + ...columndDef, |
| 50 | + id: columnKey as string, |
| 51 | + cell: ({ row }) => <RowDragHandleCell rowId={row.id} />, |
| 52 | + }); |
| 53 | + }; |
| 54 | + |
17 | 55 | const res: ReactDataTableColumnHelper<TData> = { |
18 | 56 | ...columnHelper, |
| 57 | + createDraggableColumn, |
19 | 58 | createEnumColumn: (columnKey, enumTranslations, columndDef) => |
20 | 59 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
21 | 60 | columnHelper.accessor(columnKey as any, { |
|
0 commit comments