import useTranslation from "next-translate/useTranslation"; import { useRouter } from "next/router"; import { connect } from "react-redux"; import { setCurrentPage } from "../../store/currentView/action"; const PaginationControl = (props) => { const { showNoOfRecords, orderBy, fieldSort, searchString, searchResultsObj, currentPage, spinnerState, getDocumentResults, setCurrentPage, } = props; let { t } = useTranslation(); const router = useRouter(); const { locale } = router; const pagesCount = Math.ceil( searchResultsObj["@odata.count"] / showNoOfRecords ); const getRange = (start, end) => { return Array(end - start + 1) .fill() .map((v, i) => i + start); }; const paginationNumbers = (currentPage, pageCount) => { let delta; if (pageCount <= 7) { // delta === 7: [1 2 3 4 5 6 7] delta = 7; } else { // delta === 2: [1 ... 4 5 6 ... 10] // delta === 4: [1 2 3 4 5 ... 10] //delta = currentPage > 4 && currentPage < pageCount - 3 ? 4 : 4; delta = currentPage > 4 && currentPage < pageCount - 3 ? 4 : 4; } const range = { start: Math.round(currentPage - delta / 2), end: Math.round(currentPage + delta / 2), }; if (range.start - 1 === 1 || range.end + 1 === pageCount) { range.start += 1; range.end += 1; } let pages = currentPage > delta ? getRange( Math.min(range.start, pageCount - delta), Math.min(range.end, pageCount) ) : getRange(1, Math.min(pageCount, delta + 1)); const withDots = (value, pair) => pages.length + 1 !== pageCount ? pair : [value]; if (pages[0] !== 1) { pages = withDots(1, [1, "..."]).concat(pages); } if (pages[pages.length - 1] < pageCount) { pages = pages.concat(withDots(pageCount, ["...", pageCount])); } return pages; }; const paginationArray = paginationNumbers( props.currentView.currentPage, pagesCount ); return ( <> {pagesCount > 1 && (
{props.currentView.currentPage != 1 ? ( { spinnerState(), setCurrentPage( props.currentView.currentPage - 1 ), getDocumentResults( props.currentView.currentPage - 1, orderBy, fieldSort ); }} > {t("common:previous-link-button")} ) : ( {t("common:previous-link-button")} )}
{paginationArray.map((e, i) => props.currentView.currentPage == e ? ( {e} ) : e == "..." ? ( {e} ) : ( { spinnerState(); setCurrentPage(e), getDocumentResults( e, orderBy, fieldSort ); }} > {e} ) )}
{props.currentView.currentPage < pagesCount ? ( { spinnerState(), setCurrentPage( props.currentView.currentPage + 1 ), getDocumentResults( props.currentView.currentPage + 1, orderBy, fieldSort ); }} > {t("common:next-link-button")} ) : ( {" "} {t("common:next-link-button")} )}
{t("common:pages-label")} {currentPage}{" "} {t("common:of-label")} {pagesCount}
)} ); }; const mapStateToProps = (state) => { return { currentView: state.currentView, }; }; const mapDispatchToProps = (dispatch) => { return { setCurrentPage: (currentPage) => { dispatch(setCurrentPage(currentPage)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(PaginationControl);