From 83c3fa302adbc4c3adf63c59cfe87b51d83ecbcb Mon Sep 17 00:00:00 2001 From: Pinapelz Date: Mon, 5 May 2025 00:57:58 -0700 Subject: qol: make sub table sortable by different metrics --- src/components/SubscriberTable/SubscriberTable.tsx | 91 ++++++++++++++++++---- 1 file changed, 77 insertions(+), 14 deletions(-) diff --git a/src/components/SubscriberTable/SubscriberTable.tsx b/src/components/SubscriberTable/SubscriberTable.tsx index 6c19e44..c308aee 100644 --- a/src/components/SubscriberTable/SubscriberTable.tsx +++ b/src/components/SubscriberTable/SubscriberTable.tsx @@ -1,4 +1,5 @@ -import React from "react"; +"use client"; +import React, { useState } from "react"; import ChannelRow from "./SubscriberTableRow"; interface ChannelDataProp { @@ -19,13 +20,49 @@ interface SubscriberDataTableProp { timestamp: string; } +type SortKey = keyof ChannelDataProp | "rank"; + const DataTable = ({ channel_data, timestamp }: SubscriberDataTableProp) => { - if (!channel_data) { - return null; - } + const [sortKey, setSortKey] = useState("subscribers"); + const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); + const [indexName, setIndexName] = useState("RANK"); + + const handleSort = (key: SortKey) => { + if (sortKey === key) { + setSortOrder(sortOrder === "asc" ? "desc" : "asc"); + } else { + setSortKey(key); + setSortOrder("desc"); + } + if (key === "sub_org") { + setIndexName("INDEX"); + } else { + setIndexName("RANK"); + } + }; + + const sortedData = [...channel_data].sort((a, b) => { + let aValue: any, bValue: any; + if (sortKey === "rank") { + aValue = channel_data.indexOf(a) + 1; + bValue = channel_data.indexOf(b) + 1; + } else { + aValue = a[sortKey as keyof ChannelDataProp]; + bValue = b[sortKey as keyof ChannelDataProp]; + } + if (typeof aValue === "string") { + return sortOrder === "asc" + ? aValue.localeCompare(bValue) + : bValue.localeCompare(aValue); + } + return sortOrder === "asc" ? aValue - bValue : bValue - aValue; + }); return ( <> +
+ Limited data shown on mobile view! +
{
@@ -48,39 +85,65 @@ const DataTable = ({ channel_data, timestamp }: SubscriberDataTableProp) => { scope="col" className="py-1 px-1 sm:px-3 hidden sm:table-cell" > - RANK + {indexName} - - - - {channel_data.map((channel, index) => ( + {sortedData.map((channel, index) => ( { export default DataTable; export type { SubscriberDataTableProp }; -export type { ChannelDataProp }; +export type { ChannelDataProp }; \ No newline at end of file -- cgit v1.2.3
+ CHANNEL handleSort("sub_org")} > GROUP + {sortKey === "sub_org" && ( + {sortOrder === "asc" ? "▲" : "▼"} + )} handleSort("video_count")} > VIDEO COUNT + {sortKey === "video_count" && ( + {sortOrder === "asc" ? "▲" : "▼"} + )} handleSort("views")} > VIEW COUNT + {sortKey === "views" && ( + {sortOrder === "asc" ? "▲" : "▼"} + )} + handleSort("subscribers")} + > SUBSCRIBERS + {sortKey === "subscribers" && ( + {sortOrder === "asc" ? "▲" : "▼"} + )} + handleSort("diff_1d")} + > DIFF (24H)