Pagination.js
69 lines
| 1 | const { __ } = wp.i18n; |
| 2 | const { Card, CardBody, Flex, FlexBlock, Button, ButtonGroup } = wp.components; |
| 3 | const { useState, useEffect } = wp.element; |
| 4 | |
| 5 | export default ({ page, setPage, perPage, total, totalPages }) => { |
| 6 | // do we have prev/next |
| 7 | const [hasPrevious, setHasPrevious] = useState(false); |
| 8 | const [hasNext, setHasNext] = useState(false); |
| 9 | |
| 10 | // end and start cursors |
| 11 | const [end, setEnd] = useState(0); |
| 12 | const [start, setStart] = useState(0); |
| 13 | |
| 14 | // set end and start |
| 15 | useEffect(() => { |
| 16 | setEnd(Math.min(perPage * page, total)); |
| 17 | setStart(perPage * (page - 1) + 1); |
| 18 | }, [perPage, page, total]); |
| 19 | |
| 20 | // update page when pagination is clicked |
| 21 | const nextPage = () => { |
| 22 | setPage(Math.min(totalPages, page + 1)); |
| 23 | }; |
| 24 | const prevPage = () => { |
| 25 | setPage(Math.max(page - 1, 0)); |
| 26 | }; |
| 27 | |
| 28 | // set prev/next |
| 29 | useEffect(() => { |
| 30 | setHasPrevious(page - 1 > 0); |
| 31 | setHasNext(totalPages >= page + 1); |
| 32 | }, [page, totalPages]); |
| 33 | |
| 34 | return ( |
| 35 | <Card size="large" className="presto-card pagination"> |
| 36 | <CardBody className="presto-flow"> |
| 37 | <Flex> |
| 38 | <FlexBlock> |
| 39 | {sprintf( |
| 40 | __("Showing %1s to %2s of %3s", "presto-player"), |
| 41 | start, |
| 42 | end, |
| 43 | total |
| 44 | )} |
| 45 | </FlexBlock> |
| 46 | <FlexBlock> |
| 47 | <Flex justify="flex-end"> |
| 48 | { |
| 49 | <ButtonGroup> |
| 50 | <Button |
| 51 | isSecondary |
| 52 | disabled={!hasPrevious} |
| 53 | onClick={prevPage} |
| 54 | > |
| 55 | {__("Previous", "presto-player")} |
| 56 | </Button> |
| 57 | <Button isSecondary disabled={!hasNext} onClick={nextPage}> |
| 58 | {__("Next", "presto-player")} |
| 59 | </Button> |
| 60 | </ButtonGroup> |
| 61 | } |
| 62 | </Flex> |
| 63 | </FlexBlock> |
| 64 | </Flex> |
| 65 | </CardBody> |
| 66 | </Card> |
| 67 | ); |
| 68 | }; |
| 69 |