shlink-web-client/src/utils/helpers/pagination.ts

37 lines
1 KiB
TypeScript
Raw Normal View History

2020-08-22 19:32:48 +03:00
import { max, min, range } from 'ramda';
import { prettify } from './numbers';
2020-08-22 19:32:48 +03:00
2020-08-28 21:05:01 +03:00
const DELTA = 2;
2020-08-22 19:32:48 +03:00
export const ELLIPSIS = '...';
2020-08-28 21:05:01 +03:00
type Ellipsis = typeof ELLIPSIS;
export type NumberOrEllipsis = number | Ellipsis;
2020-08-22 19:32:48 +03:00
export const progressivePagination = (currentPage: number, pageCount: number): NumberOrEllipsis[] => {
const pages: NumberOrEllipsis[] = range(
2020-08-28 21:05:01 +03:00
max(DELTA, currentPage - DELTA),
min(pageCount - 1, currentPage + DELTA) + 1,
2020-08-22 19:32:48 +03:00
);
2020-08-28 21:05:01 +03:00
if (currentPage - DELTA > DELTA) {
2020-08-22 19:32:48 +03:00
pages.unshift(ELLIPSIS);
}
2020-08-28 21:05:01 +03:00
if (currentPage + DELTA < pageCount - 1) {
2020-08-22 19:32:48 +03:00
pages.push(ELLIPSIS);
}
pages.unshift(1);
pages.push(pageCount);
return pages;
};
2020-08-28 21:05:01 +03:00
export const pageIsEllipsis = (pageNumber: NumberOrEllipsis): pageNumber is Ellipsis => pageNumber === ELLIPSIS;
2020-08-22 19:32:48 +03:00
export const prettifyPageNumber = (pageNumber: NumberOrEllipsis): string =>
pageIsEllipsis(pageNumber) ? pageNumber : prettify(pageNumber);
2020-08-28 21:05:01 +03:00
export const keyForPage = (pageNumber: NumberOrEllipsis, index: number) => !pageIsEllipsis(pageNumber) ? `${pageNumber}` : `${pageNumber}_${index}`;