TanStackTableHeadSort.tsx53 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import { type Column } from '@tanstack/react-table' |
| 4 | import type { ReactNode } from 'react' |
| 5 | import { cn, TableHeadSort } from 'ui' |
| 6 | |
| 7 | interface TanStackTableHeadSortProps<TData, TValue> { |
| 8 | column: Column<TData, TValue> |
| 9 | children: ReactNode |
| 10 | className?: string |
| 11 | } |
| 12 | |
| 13 | /** |
| 14 | * Shared TanStack adapter for the `TableHeadSort` primitive. |
| 15 | * Prefer this in TanStack tables instead of wiring `TableHeadSort` manually. |
| 16 | */ |
| 17 | export const TanStackTableHeadSort = <TData, TValue>({ |
| 18 | column, |
| 19 | children, |
| 20 | className, |
| 21 | }: TanStackTableHeadSortProps<TData, TValue>) => { |
| 22 | if (!column.getCanSort()) { |
| 23 | return <div className={cn(className)}>{children}</div> |
| 24 | } |
| 25 | |
| 26 | const sort = column.getIsSorted() |
| 27 | const currentSort = sort ? `${column.id}:${sort}` : '' |
| 28 | |
| 29 | const handleSortChange = () => { |
| 30 | if (!sort) { |
| 31 | column.toggleSorting(false) |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | if (sort === 'asc') { |
| 36 | column.toggleSorting(true) |
| 37 | return |
| 38 | } |
| 39 | |
| 40 | column.clearSorting() |
| 41 | } |
| 42 | |
| 43 | return ( |
| 44 | <TableHeadSort |
| 45 | column={column.id} |
| 46 | currentSort={currentSort} |
| 47 | onSortChange={handleSortChange} |
| 48 | className={className} |
| 49 | > |
| 50 | {children} |
| 51 | </TableHeadSort> |
| 52 | ) |
| 53 | } |