import type { ReactNode } from "react"; import type { SortingState } from "@tanstack/react-table"; import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react"; import { TableHead } from "@/app/components/ui/table"; import { cn } from "@/app/lib/utils"; export type SortDirection = false | "asc" | "desc"; /** The header sort button shared by DataTable and SortableHead. */ export function SortButton({ direction, numeric, onClick, children, }: { direction: SortDirection; numeric?: boolean; onClick: React.MouseEventHandler | undefined; children: ReactNode; }) { return ( ); } export const ariaSort = (d: SortDirection) => d === "asc" ? "ascending" : d === "desc" ? "descending" : "none"; /** Sortable header cell for hand-built tables; cycles none -> asc -> desc -> none. */ export function SortableHead({ label, sortKey, sorting, onSortingChange, className, }: { label: ReactNode; sortKey: string; sorting: SortingState; onSortingChange: (sorting: SortingState) => void; className?: string; }) { const current = sorting[0]?.id === sortKey ? sorting[0] : undefined; const direction: SortDirection = current ? (current.desc ? "desc" : "asc") : false; const next: SortingState = !current ? [{ id: sortKey, desc: false }] : current.desc ? [] : [{ id: sortKey, desc: true }]; return ( onSortingChange(next)}> {label} ); } type SortValue = string | number | null | undefined; /** Sorts rows in the browser by the active sort; numbers numerically, text with localeCompare, empties last. */ export function sortRows(rows: T[], sorting: SortingState, getters: Record SortValue>): T[] { const s = sorting[0]; const get = s && getters[s.id]; if (!get) return rows; const dir = s.desc ? -1 : 1; return [...rows].sort((a, b) => { const x = get(a); const y = get(b); if (x == null || x === "") return y == null || y === "" ? 0 : 1; if (y == null || y === "") return -1; return dir * (typeof x === "number" && typeof y === "number" ? x - y : String(x).localeCompare(String(y))); }); }