import { useMemo, useState } from "react";
import { Table, type TableSortDescriptor } from "@peppermint-design/devreadykit-custom";
type Customer = {
id: string;
name: string;
total: number;
};
const customers: Customer[] = [
{ id: "1", name: "Andrew Martin", total: 760 },
{ id: "2", name: "Jessica Taylor", total: 540 },
];
export default function SortableTable() {
const [sortDescriptor, setSortDescriptor] = useState<TableSortDescriptor>({
column: "name",
direction: "ascending",
});
const sortedCustomers = useMemo(() => {
const items = [...customers];
const multiplier = sortDescriptor.direction === "ascending" ? 1 : -1;
return items.sort((a, b) =>
sortDescriptor.column === "total"
? (a.total - b.total) * multiplier
: a.name.localeCompare(b.name) * multiplier,
);
}, [sortDescriptor]);
return (
<Table sortDescriptor={sortDescriptor} onSortChange={setSortDescriptor}>
<Table.Header>
<Table.Head id="name" label="Customer" allowsSorting isRowHeader />
<Table.Head id="total" label="Lifetime value" allowsSorting align="right" />
</Table.Header>
<Table.Body items={sortedCustomers}>
{(customer) => (
<Table.Row id={customer.id}>
<Table.Cell>{customer.name}</Table.Cell>
<Table.Cell align="right">${customer.total.toLocaleString()}</Table.Cell>
</Table.Row>
)}
</Table.Body>
</Table>
);
}