diff --git a/src/components/generic/Table/index.tsx b/src/components/generic/Table/index.tsx index fa9c9d25..0803202e 100755 --- a/src/components/generic/Table/index.tsx +++ b/src/components/generic/Table/index.tsx @@ -1,4 +1,5 @@ -import { ChevronUpIcon } from "lucide-react"; +import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"; +import React, { useState } from "react"; export interface TableProps { headings: Heading[]; @@ -12,6 +13,49 @@ export interface Heading { } export const Table = ({ headings, rows }: TableProps): JSX.Element => { + const [sortColumn, setSortColumn] = useState("Last Heard"); + const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); + + const headingSort = (title: string) => { + if (sortColumn === title) { + setSortOrder(sortOrder === "asc" ? "desc" : "asc"); + } else { + setSortColumn(title); + setSortOrder("asc"); + } + }; + + const sortedRows = rows.slice().sort((a, b) => { + if (!sortColumn) return 0; + + const columnIndex = headings.findIndex((h) => h.title === sortColumn); + const aValue = a[columnIndex].props.children; + const bValue = b[columnIndex].props.children; + + // Custom comparison for 'Last Heard' column + if (sortColumn === "Last Heard") { + const aTimestamp = a[columnIndex].props.timestamp; + const bTimestamp = b[columnIndex].props.timestamp; + + if (aTimestamp < bTimestamp) { + return sortOrder === "asc" ? -1 : 1; + } + if (aTimestamp > bTimestamp) { + return sortOrder === "asc" ? 1 : -1; + } + return 0; + } + + // Default comparison for other columns + if (aValue < bValue) { + return sortOrder === "asc" ? -1 : 1; + } + if (aValue > bValue) { + return sortOrder === "asc" ? 1 : -1; + } + return 0; + }); + return ( @@ -25,11 +69,12 @@ export const Table = ({ headings, rows }: TableProps): JSX.Element => { ? "cursor-pointer hover:brightness-hover active:brightness-press" : "" }`} + onClick={() => heading.sortable && headingSort(heading.title)} >
{heading.title} - {heading.sortable && ( - + {sortColumn === heading.title && ( + <>{sortOrder === "asc" ? : } )}
@@ -37,7 +82,7 @@ export const Table = ({ headings, rows }: TableProps): JSX.Element => { - {rows.map((row, index) => ( + {sortedRows.map((row, index) => ( {row.map((item, index) => (