Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pagination to account history #543

Merged
merged 3 commits into from
Aug 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 73 additions & 8 deletions src/app/components/AccountHistory.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useAppDispatch, useAppSelector, useTranslations } from "hooks";
import {
useAppDispatch,
useAppSelector,
usePagination,
useTranslations,
} from "hooks";
import { DexterToast } from "./DexterToaster";
import { PairInfo } from "alphadex-sdk-js/lib/models/pair-info";
import "../styles/table.css";
Expand Down Expand Up @@ -30,6 +35,7 @@ import {
import Papa from "papaparse";
import HoverGradientButton from "./HoverGradientButton";
import { twMerge } from "tailwind-merge";
import Pagination from "./Pagination";

import {
setHideOtherPairs,
Expand Down Expand Up @@ -97,6 +103,7 @@ export function AccountHistory() {
const account = useAppSelector(
(state) => state.radix?.selectedAccount?.address
);

const pairAddress = useAppSelector((state) => state.pairSelector.address);

useEffect(() => {
Expand Down Expand Up @@ -202,6 +209,10 @@ function ActionButton({

function DisplayTable() {
const t = useTranslations();
const tableContainerRef = useRef<HTMLDivElement>(null);
const [paginationLeft, setPaginationLeft] = useState(0);

const timeoutRef = useRef<number | null>(0);
const selectedTable = useAppSelector(
(state) => state.accountHistory.selectedTable
);
Expand All @@ -214,8 +225,16 @@ function DisplayTable() {
const combinedOrderHistory = useAppSelector(selectCombinedOrderHistory);
const combinedOpenOrders = useAppSelector(selectCombinedOpenOrders);

const paginationConf = usePagination(
hideOtherPairs ? orderHistory : combinedOrderHistory
);

const { paginatedData: filteredRowsForOrderHistory, setCurrentPage } =
paginationConf;

const handleToggleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setHideOtherPairs(e.target.checked));
setCurrentPage(0);
};

const tableToShow = useMemo(() => {
Expand All @@ -230,9 +249,6 @@ function DisplayTable() {
};

case Tables.ORDER_HISTORY:
const filteredRowsForOrderHistory = hideOtherPairs
? orderHistory
: combinedOrderHistory;
return {
headers: headers[Tables.ORDER_HISTORY],
rows: <OrderHistoryRows data={filteredRowsForOrderHistory} />,
Expand All @@ -246,15 +262,50 @@ function DisplayTable() {
}
}, [
openOrders,
orderHistory,
selectedTable,
hideOtherPairs,
combinedOrderHistory,
filteredRowsForOrderHistory,
combinedOpenOrders,
]);

useEffect(() => {
const tableRefNode = tableContainerRef.current;

function calcPaginationLeftOffset() {
if (tableRefNode !== null) {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}

timeoutRef.current = window.setTimeout(() => {
if (tableContainerRef.current) {
const scrollLeft = tableContainerRef.current.scrollLeft;
const containerWidth = tableContainerRef.current.offsetWidth;
const leftPosition = scrollLeft + containerWidth / 2;

setPaginationLeft(leftPosition);
}
}, 300);
}
}

calcPaginationLeftOffset();
if (tableRefNode) {
tableRefNode.addEventListener("scroll", calcPaginationLeftOffset);
}

window.addEventListener("resize", calcPaginationLeftOffset);
return () => {
if (tableRefNode) {
tableRefNode.removeEventListener("scroll", calcPaginationLeftOffset);
}

window.removeEventListener("resize", calcPaginationLeftOffset);
};
}, []);

return (
<div className="overflow-x-auto scrollbar-none">
<div ref={tableContainerRef} className="overflow-x-auto scrollbar-none">
<div className="flex flex-col md:items-end xs:items-start">
<label className="label cursor-pointer">
<input
Expand Down Expand Up @@ -282,7 +333,8 @@ function DisplayTable() {
</span>
</label>
</div>
<table className="table table-zebra table-xs !mt-0 mb-16 w-full max-w-[100%]">

<table className="table table-zebra table-xs !mt-0 w-full max-w-[100%]">
<thead>
<tr className="h-12">
{tableToShow.headers.map((header, i) => (
Expand All @@ -298,6 +350,7 @@ function DisplayTable() {
</thead>
<tbody>
{tableToShow.rows}

{selectedTable === Tables.ORDER_HISTORY && (
<tr className="!bg-transparent">
<td className="lg:hidden">
Expand All @@ -313,6 +366,18 @@ function DisplayTable() {
)}
</tbody>
</table>
<div className="mb-8">
{selectedTable === Tables.ORDER_HISTORY && (
<div className="relative h-8">
<div
className="absolute -translate-x-1/2"
style={{ left: `${paginationLeft}px` }}
>
<Pagination {...paginationConf} />
</div>
</div>
)}
</div>
</div>
);
}
Expand Down
147 changes: 147 additions & 0 deletions src/app/components/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { useEffect, useRef, useState } from "react";

interface PaginationProps {
currentPage: number;
pageSize: number;
setPageSize: (idx: number) => void;
setCurrentPage: (idx: number) => void;
totalDataLength: number;
}

const MAX_BUTTONS = 6;
const PAGINATION_OPTIONS = [10, 20, 50, 100];

const Pagination: React.FC<PaginationProps> = ({
currentPage,
totalDataLength,
setCurrentPage,
setPageSize,
pageSize,
}) => {
const totalPages = Math.ceil(totalDataLength / pageSize);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);

const dropdownRef = useRef<HTMLDivElement>(null);

useEffect(() => {
if (isDropdownOpen) {
const detectClose = (e: MouseEvent) => {
if (
isDropdownOpen &&
dropdownRef.current &&
!dropdownRef.current.contains(e.target as Node)
) {
setIsDropdownOpen(false);
}
};
window.addEventListener("mousedown", detectClose);
return () => window.removeEventListener("mousedown", detectClose);
}
return () => {};
}, [isDropdownOpen]);

function renderPaginationButton(idx: number) {
return (
<div
key={`pagination-button-${idx}`}
onClick={() => setCurrentPage(idx)}
role="button"
className={`${
currentPage === idx ? "bg-dexter-green rounded-full text-black" : ""
} hover:bg-dexter-green hover:text-black p-1 hover:rounded-full h-6 w-6 text-center opacity-90 hover:opacity-100`}
>
{idx + 1}
</div>
);
}

const renderPaginationButtons = () => {
if (totalPages <= MAX_BUTTONS) {
return Array.from({ length: totalPages }, (_, i) =>
renderPaginationButton(i)
);
}

const pages = [];
const siblingCount = Math.max(1, Math.floor((MAX_BUTTONS - 3) / 2));
const showLeftEllipsis = currentPage > siblingCount + 1;
const showRightEllipsis = currentPage < totalPages - siblingCount - 1;

pages.push(renderPaginationButton(0)); // Always show the first page

if (showLeftEllipsis) {
pages.push("...");
}

const leftSibling = Math.max(1, currentPage - siblingCount);
const rightSibling = Math.min(totalPages - 1, currentPage + siblingCount);
for (let i = leftSibling; i <= rightSibling; i++) {
pages.push(renderPaginationButton(i));
}

if (showRightEllipsis) {
pages.push("...");
}

pages.push(renderPaginationButton(totalPages)); // Always show the last page

return pages;
};

if (totalPages === 0) return null;

return (
<div className="flex flex-row itemcs-center space-x-4 relative">
<div className="relative">
{/* !TODO: Uncomment after design iteration */}
{/* <button
onClick={() => {
setIsDropdownOpen(!isDropdownOpen);
}}
className="flex border text-xs border-gray-200 flex-row items-center"
>
<div className="pl-2">{pageSize}</div>
<div>
<div className="w-6 h-8"></div>
<Image
src="/chevron-down.svg"
alt="chevron down"
width="25"
height="25"
/>
</div>
</button> */}
{isDropdownOpen && (
<div
ref={dropdownRef}
className="absolute left-0 bg-dexter-grey-light text-white z-[1000] text-bold "
>
{PAGINATION_OPTIONS.map((item, idx) => (
<div
onClick={(e: React.MouseEvent) => {
const target = e.target as HTMLElement;
setIsDropdownOpen(false);
setPageSize(Number(target.innerText ?? 0));
setCurrentPage(0);
}}
className={`${
pageSize === item
? "bg-dexter-green opacity-90 text-white "
: ""
} hover:bg-dexter-green cursor-pointer px-4 py-2 hover:opacity-100 opacity-90 text-center text-xs`}
key={`${idx}-${item}`}
>
{item}
</div>
))}
</div>
)}
</div>
<div className="flex flex-row items-center justify-normal space-x-2 text-xs">
{renderPaginationButtons()}
</div>
</div>
);
};

export default Pagination;
43 changes: 42 additions & 1 deletion src/app/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { useDispatch, useSelector } from "react-redux";
import type { TypedUseSelectorHook } from "react-redux";
import type { RootState, AppDispatch } from "./state/store";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
getLocalStoragePaginationValue,
setLocalStoragePaginationValue,
} from "utils";

// https://redux-toolkit.js.org/tutorials/typescript#define-typed-hooks
export const useAppDispatch: () => AppDispatch = useDispatch;
Expand Down Expand Up @@ -30,3 +34,40 @@ export const useHydrationErrorFix = () => {

return isClient;
};

export function usePagination<T>(data: T[], paginationId?: string) {
const [currentPage, setCurrentPage] = useState(0);

const [pageSize, setPageSize] = useState(
getLocalStoragePaginationValue() ?? 20
);
const totalDataLength = useMemo(() => data.length, [data]);

const startIndex = useMemo(
() => currentPage * pageSize,
[currentPage, pageSize]
);
const endIndex = useMemo(() => startIndex + pageSize, [startIndex, pageSize]);

const paginatedData = useMemo(
() => data.slice(startIndex, endIndex),
[data, startIndex, endIndex]
);

const updatePsize = useCallback(
(psize: number) => {
setLocalStoragePaginationValue(psize, paginationId);
setPageSize(psize);
},
[paginationId, setPageSize]
);

return {
currentPage,
setCurrentPage,
pageSize,
setPageSize: updatePsize,
paginatedData,
totalDataLength,
};
}
23 changes: 23 additions & 0 deletions src/app/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,26 @@ export function shortenWalletAddress(address: string): string {
const lastPart = address.slice(-20);
return `${firstPart}...${lastPart}`;
}

export function setLocalStoragePaginationValue(pageSize: number, id?: string) {
if (typeof window === "undefined") return undefined;

window.localStorage.setItem(
`pagination:${id ?? window.location.pathname}`,
dcts marked this conversation as resolved.
Show resolved Hide resolved
String(pageSize)
);
}

export function getLocalStoragePaginationValue(id?: string) {
if (typeof window === "undefined") return undefined;

const existingValue = window.localStorage.getItem(
`pagination:${id ?? window.location.pathname}`
);
if (existingValue !== null) {
const pageNumber = Number(existingValue);
return pageNumber < 1 ? 10 : pageNumber;
}

return undefined;
}
Loading