ldc-supportweb/resources/ts/back/Components/Table/DataTable.tsx
2026-04-24 16:53:58 +02:00

122 lines
3.6 KiB
TypeScript

// * Packages
import { useState } from "react";
import {
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
// * Components shadcn
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
// * Other
import { DefaultModel, Resource, Views } from "@/back/types/global";
import ModelActions from "@/back/Components/ModelActions";
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
import PaginationWrapper from "@/back/Components/Pagination/PaginationWrapper";
import useTrans from "@/hooks/use-translations";
export default function DataTable<TData, TValue>({
columns,
modelRoute,
modelsPaginate,
actions,
}: {
columns: ColumnDef<TData, TValue>[];
modelRoute: string;
modelsPaginate: Resource;
actions: Views | null;
}) {
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("uwil-backend::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>
);
})}
{actions && (
<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>
))}
{actions && (
<TableCell className="text-end">
<ModelActions
actions={actions}
modelRoute={modelRoute}
model={row.original as DefaultModel}
inDialog
/>
</TableCell>
)}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length + 1}
className="h-24 text-center"
>
{noResultsTrans}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<PaginationWrapper modelsPaginate={modelsPaginate.meta} />
</>
);
}