From 296fff4ad1da44ca502f059d4026a76bd52fb93a Mon Sep 17 00:00:00 2001 From: Mikhail Eshchenko Date: Tue, 9 Jan 2024 14:30:10 +0700 Subject: [PATCH] fix(Pagination): fix total page calculation --- src/components/Pagination/Pagination.tsx | 24 ++++++++++++++++++++---- src/components/Pagination/utils.ts | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/components/Pagination/Pagination.tsx b/src/components/Pagination/Pagination.tsx index e93b3a6b05..2a236643fe 100644 --- a/src/components/Pagination/Pagination.tsx +++ b/src/components/Pagination/Pagination.tsx @@ -13,10 +13,13 @@ import { } from './components'; import {usePagination} from './hooks/usePagination'; import type {PaginationProps} from './types'; +import {getResultPage, getResultTotal} from './utils'; import './Pagination.scss'; const b = blockNew('pagination'); +const DEFAULT_TOTAL = 1; +const DEFAULT_PAGE = 1; export const Pagination = ({ page, @@ -35,7 +38,20 @@ export const Pagination = ({ const size = mobile ? 'l' : 'm'; const compact = mobile ? true : propCompact; - const {items, numberOfPages} = usePagination({page, pageSize, total, mobile}); + const resultTotal = getResultTotal(total, DEFAULT_TOTAL); + const resultPage = getResultPage({ + page, + total: resultTotal, + pageSize, + defaultPage: DEFAULT_PAGE, + }); + + const {items, numberOfPages} = usePagination({ + page: resultPage, + pageSize, + total: resultTotal, + mobile, + }); const pagination = items .map((item) => { @@ -79,7 +95,7 @@ export const Pagination = ({ key={item.action} size={size} item={item} - page={page} + page={resultPage} pageSize={pageSize} onUpdate={onUpdate} compact={compact} @@ -107,11 +123,11 @@ export const Pagination = ({ {pageSizeOptions && ( )} diff --git a/src/components/Pagination/utils.ts b/src/components/Pagination/utils.ts index 67f701a2bf..6bf098ba7c 100644 --- a/src/components/Pagination/utils.ts +++ b/src/components/Pagination/utils.ts @@ -51,3 +51,23 @@ function getDesktopNumerationList(page: number, numberOfPages: number) { export function getNumberOfPages(pageSize: number, total = 0) { return Math.floor((total - 1) / pageSize) + 1; } + +export function getResultTotal(total: number | undefined, defaultTotal: number) { + return total === undefined || total > 0 ? total : defaultTotal; +} + +export function getResultPage({ + page, + total, + pageSize, + defaultPage, +}: { + page: number; + total: number | undefined; + pageSize: number; + defaultPage: number; +}) { + return page > 0 && (total === undefined || page <= getNumberOfPages(pageSize, total)) + ? page + : defaultPage; +}