Table Component Updated the Sort Logic

This commit is contained in:
2025-11-13 15:59:43 +05:30
parent 688d830ee9
commit 4973f94b2a
3 changed files with 135 additions and 413 deletions
+29 -30
View File
@@ -1,4 +1,5 @@
---
import { Icon } from "astro-icon/components";
import type { TableProps } from "../types/table/types";
import { cn } from "../utils/cn";
@@ -76,8 +77,8 @@ const id = `table-${Math.random().toString(36).slice(2, 9)}`;
<div class="wr:flex wr:items-center wr:gap-1">
<span>{col.label}</span>
{col.sortable && (
<iconify-icon
icon="solar:sort-vertical-bold-duotone"
<Icon
name="solar:sort-vertical-line-duotone"
class="wr:text-lg wr:text-gray-400 sort-indicator"
/>
)}
@@ -164,8 +165,7 @@ const id = `table-${Math.random().toString(36).slice(2, 9)}`;
let rowsPerPage = pagignations
? parseInt(pageSizeSelector.value)
: 9999;
let sortKey = null;
let sortOrder = "asc";
let sort = {};
let totalRows = data.length;
let currentData = [...data];
@@ -326,8 +326,7 @@ const id = `table-${Math.random().toString(36).slice(2, 9)}`;
const result = await fetchDataFn({
page: currentPage,
pageSize: rowsPerPage,
sortKey,
sortOrder,
sort,
search: searchInput?.value || "",
});
currentData = result.data;
@@ -344,16 +343,21 @@ const id = `table-${Math.random().toString(36).slice(2, 9)}`;
}
// sort locally if needed
if (sortKey !== null) {
const colKey = columns[sortKey]?.key;
if (colKey) {
currentData.sort((a, b) => {
const aVal = String(a[colKey] ?? "");
const bVal = String(b[colKey] ?? "");
if (aVal < bVal) return sortOrder === "asc" ? -1 : 1;
if (aVal > bVal) return sortOrder === "asc" ? 1 : -1;
return 0;
});
if (Object.keys(sort).length !== 0) {
for (const key in sort) {
const colKey = key;
const colSortOrder = sort[key];
if (colKey) {
currentData.sort((a, b) => {
const aVal = String(a[colKey] ?? "");
const bVal = String(b[colKey] ?? "");
if (aVal < bVal)
return colSortOrder === "asc" ? -1 : 1;
if (aVal > bVal)
return colSortOrder === "asc" ? 1 : -1;
return 0;
});
}
}
}
@@ -430,23 +434,18 @@ const id = `table-${Math.random().toString(36).slice(2, 9)}`;
// 🧭 Sorting
sortHeaders.forEach((th, index) => {
th.addEventListener("click", () => {
if (sortKey === index)
sortOrder = sortOrder === "asc" ? "desc" : "asc";
else {
sortKey = index;
sortOrder = "asc";
const key = th.dataset.sortKey;
let sortOrder = "asc";
if (sort.hasOwnProperty(key)) {
sortOrder = sort[key] === "asc" ? "desc" : "asc";
sort[key] = sortOrder;
} else {
sort[key] = sortOrder;
}
sortHeaders.forEach((h) =>
h
.querySelector(".sort-indicator")
?.setAttribute(
"icon",
"solar:sort-vertical-bold-duotone",
),
);
th.querySelector(".sort-indicator")?.setAttribute(
"icon",
"data-icon",
sortOrder === "asc"
? "solar:sort-up-bold-duotone"
: "solar:sort-down-bold-duotone",