1import type {
2 Cell,
3 Column,
4 ColumnDef,
5 Header,
6 HeaderGroup,
7 Row,
8 SortingState,
9 Table,
10} from "@tanstack/react-table";
11import {
12 flexRender,
13 getCoreRowModel,
14 getSortedRowModel,
15 useReactTable,
16} from "@tanstack/react-table";
17import { atom, useAtom } from "jotai";
18import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react";
19import type { HTMLAttributes, ReactNode } from "react";
20import { createContext, memo, useCallback, useContext } from "react";
21import { Button } from "@/components/ui/button";
22import {
23 DropdownMenu,
24 DropdownMenuContent,
25 DropdownMenuItem,
26 DropdownMenuTrigger,
27} from "@/components/ui/dropdown-menu";
28import {
29 TableBody as TableBodyRaw,
30 TableCell as TableCellRaw,
31 TableHeader as TableHeaderRaw,
32 TableHead as TableHeadRaw,
33 Table as TableRaw,
34 TableRow as TableRowRaw,
35} from "@/components/ui/table";
36import { cn } from "@/lib/utils";
37
38export type { ColumnDef } from "@tanstack/react-table";
39
40const sortingAtom = atom<SortingState>([]);
41
42export const TableContext = createContext<{
43 data: unknown[];
44 columns: ColumnDef<unknown, unknown>[];
45 table: Table<unknown> | null;
46}>({
47 data: [],
48 columns: [],
49 table: null,
50});
51
52export type TableProviderProps<TData, TValue> = {
53 columns: ColumnDef<TData, TValue>[];
54 data: TData[];
55 children: ReactNode;
56 className?: string;
57};
58
59export function TableProvider<TData, TValue>({
60 columns,
61 data,
62 children,
63 className,
64}: TableProviderProps<TData, TValue>) {
65 const [sorting, setSorting] = useAtom(sortingAtom);
66 const table = useReactTable({
67 data,
68 columns,
69 getCoreRowModel: getCoreRowModel(),
70 getSortedRowModel: getSortedRowModel(),
71 onSortingChange: (updater) => {
72 // @ts-expect-error updater is a function that returns a sorting object
73 const newSorting = updater(sorting);
74
75 setSorting(newSorting);
76 },
77 state: {
78 sorting,
79 },
80 });
81
82 return (
83 <TableContext.Provider
84 value={{
85 data,
86 columns: columns as never,
87 table: table as never,
88 }}
89 >
90 <TableRaw className={className}>{children}</TableRaw>
91 </TableContext.Provider>
92 );
93}
94
95export type TableHeadProps = {
96 header: Header<unknown, unknown>;
97 className?: string;
98};
99
100export const TableHead = memo(({ header, className }: TableHeadProps) => (
101 <TableHeadRaw className={className} key={header.id}>
102 {header.isPlaceholder
103 ? null
104 : flexRender(header.column.columnDef.header, header.getContext())}
105 </TableHeadRaw>
106));
107
108TableHead.displayName = "TableHead";
109
110export type TableHeaderGroupProps = {
111 headerGroup: HeaderGroup<unknown>;
112 children: (props: { header: Header<unknown, unknown> }) => ReactNode;
113};
114
115export const TableHeaderGroup = ({
116 headerGroup,
117 children,
118}: TableHeaderGroupProps) => (
119 <TableRowRaw key={headerGroup.id}>
120 {headerGroup.headers.map((header) => children({ header }))}
121 </TableRowRaw>
122);
123
124export type TableHeaderProps = {
125 className?: string;
126 children: (props: { headerGroup: HeaderGroup<unknown> }) => ReactNode;
127};
128
129export const TableHeader = ({ className, children }: TableHeaderProps) => {
130 const { table } = useContext(TableContext);
131
132 return (
133 <TableHeaderRaw className={className}>
134 {table?.getHeaderGroups().map((headerGroup) => children({ headerGroup }))}
135 </TableHeaderRaw>
136 );
137};
138
139export interface TableColumnHeaderProps<TData, TValue>
140 extends HTMLAttributes<HTMLDivElement> {
141 column: Column<TData, TValue>;
142 title: string;
143}
144
145export function TableColumnHeader<TData, TValue>({
146 column,
147 title,
148 className,
149}: TableColumnHeaderProps<TData, TValue>) {
150 // Extract inline event handlers to prevent unnecessary re-renders
151 const handleSortAsc = useCallback(() => {
152 column.toggleSorting(false);
153 }, [column]);
154
155 const handleSortDesc = useCallback(() => {
156 column.toggleSorting(true);
157 }, [column]);
158
159 if (!column.getCanSort()) {
160 return <div className={cn(className)}>{title}</div>;
161 }
162
163 return (
164 <div className={cn("flex items-center space-x-2", className)}>
165 <DropdownMenu>
166 <DropdownMenuTrigger asChild>
167 <Button
168 className="-ml-3 h-8 data-[state=open]:bg-accent"
169 size="sm"
170 variant="ghost"
171 >
172 <span>{title}</span>
173 {column.getIsSorted() === "desc" ? (
174 <ArrowDownIcon className="ml-2 h-4 w-4" />
175 ) : column.getIsSorted() === "asc" ? (
176 <ArrowUpIcon className="ml-2 h-4 w-4" />
177 ) : (
178 <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
179 )}
180 </Button>
181 </DropdownMenuTrigger>
182 <DropdownMenuContent align="start">
183 <DropdownMenuItem onClick={handleSortAsc}>
184 <ArrowUpIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
185 Asc
186 </DropdownMenuItem>
187 <DropdownMenuItem onClick={handleSortDesc}>
188 <ArrowDownIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
189 Desc
190 </DropdownMenuItem>
191 </DropdownMenuContent>
192 </DropdownMenu>
193 </div>
194 );
195}
196
197export type TableCellProps = {
198 cell: Cell<unknown, unknown>;
199 className?: string;
200};
201
202export const TableCell = ({ cell, className }: TableCellProps) => (
203 <TableCellRaw className={className}>
204 {flexRender(cell.column.columnDef.cell, cell.getContext())}
205 </TableCellRaw>
206);
207
208export type TableRowProps = {
209 row: Row<unknown>;
210 children: (props: { cell: Cell<unknown, unknown> }) => ReactNode;
211 className?: string;
212};
213
214export const TableRow = ({ row, children, className }: TableRowProps) => (
215 <TableRowRaw
216 className={className}
217 data-state={row.getIsSelected() && "selected"}
218 key={row.id}
219 >
220 {row.getVisibleCells().map((cell) => children({ cell }))}
221 </TableRowRaw>
222);
223
224export type TableBodyProps = {
225 children: (props: { row: Row<unknown> }) => ReactNode;
226 className?: string;
227};
228
229export const TableBody = ({ children, className }: TableBodyProps) => {
230 const { columns, table } = useContext(TableContext);
231 const rows = table?.getRowModel().rows;
232
233 return (
234 <TableBodyRaw className={className}>
235 {rows?.length ? (
236 rows.map((row) => children({ row }))
237 ) : (
238 <TableRowRaw>
239 <TableCellRaw className="h-24 text-center" colSpan={columns.length}>
240 No results.
241 </TableCellRaw>
242 </TableRowRaw>
243 )}
244 </TableBodyRaw>
245 );
246};
247