import React from "react"; import { Box, Button, Flex, Select } from "@chakra-ui/react"; import { Link, useHistory, useLocation } from "react-router-dom"; function PaginationToolbar({ isLoading, totalCount, numPerPage = 30, ...props }) { const { search } = useLocation(); const history = useHistory(); const currentOffset = parseInt(new URLSearchParams(search).get("offset")) || 0; const currentPageIndex = Math.floor(currentOffset / numPerPage); const currentPageNumber = currentPageIndex + 1; const numTotalPages = totalCount ? Math.ceil(totalCount / numPerPage) : null; const prevPageSearchParams = new URLSearchParams(search); const prevPageOffset = currentOffset - numPerPage; prevPageSearchParams.set("offset", prevPageOffset); const prevPageUrl = "?" + prevPageSearchParams.toString(); const nextPageSearchParams = new URLSearchParams(search); const nextPageOffset = currentOffset + numPerPage; nextPageSearchParams.set("offset", nextPageOffset); const nextPageUrl = "?" + nextPageSearchParams.toString(); // We disable the buttons if we don't know how many total items there are, // and therefore don't know how far navigation can go. We'll additionally // show a loading spinner if `isLoading` is true. (But it's possible the // buttons might be enabled, even if `isLoading` is true, because maybe // something _else_ is loading. `isLoading` is designed to tell us whether // waiting _might_ give us the data we need!) const prevPageIsDisabled = totalCount == null || prevPageOffset < 0; const nextPageIsDisabled = totalCount == null || nextPageOffset >= totalCount; const goToPageNumber = React.useCallback( (newPageNumber) => { const newPageIndex = newPageNumber - 1; const newPageOffset = newPageIndex * numPerPage; const newPageSearchParams = new URLSearchParams(search); newPageSearchParams.set("offset", newPageOffset); history.push({ search: newPageSearchParams.toString() }); }, [search, history, numPerPage] ); return ( {numTotalPages && ( Page of {numTotalPages} )} ); } function PageNumberSelect({ currentPageNumber, numTotalPages, onChange, ...props }) { const allPageNumbers = Array.from({ length: numTotalPages }, (_, i) => i + 1); const handleChange = React.useCallback( (e) => onChange(Number(e.target.value)), [onChange] ); return ( ); } export default PaginationToolbar;