ldc-groupe/resources/ts/back/Components/Table/DataTable.tsx

148 lines
6.1 KiB
TypeScript

// * Packages
import { useState } from "react";
import {
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { MoreHorizontal } from "lucide-react";
// * Components shadcn
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
// * Other
import { Model, Resource, Views } from "@/back/types/global";
import ModelActions from "@/back/Components/ModelActions";
import PaginationWrapper from "@/back/Components/Pagination/PaginationWrapper";
import useTrans from "@/hooks/use-translations";
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
export default function DataTable<TData, TValue>({
columns,
modelName,
modelsPaginate,
actions,
}: {
columns: ColumnDef<TData, TValue>[];
modelName: string;
modelsPaginate: Resource;
actions: Views;
}) {
const [sorting, setSorting] = useState<SortingState>([]);
const data = modelsPaginate.data as TData[];
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
state: {
sorting,
},
});
const noResultsTrans = useTrans("back.table_no_results");
return (
<>
<div className="rounded-md border">
<Table className="table-actions">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef
.header,
header.getContext(),
)}
</TableHead>
);
})}
<TableHead>
<DataTableFilterButton reset />
</TableHead>
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={
row.getIsSelected() && "selected"
}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="text-center"
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
<TableCell className="text-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="secondary"
size="icon"
>
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
>
<ModelActions
actions={actions}
modelName={modelName}
model={
row.original as Model
}
inColumn
/>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length + 1}
className="h-24 text-center"
>
{noResultsTrans}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<PaginationWrapper modelsPaginate={modelsPaginate.meta} />
</>
);
}