aboutsummaryrefslogtreecommitdiff
path: root/src/components/common/Pager.tsx
blob: c65e2f6ab4761e60dd0cfbc027a7cec9f1113e61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Button, Icon, Row, Text } from '@umami/react-zen';
import { useMessages } from '@/components/hooks';
import { ChevronRight } from '@/components/icons';

export interface PagerProps {
  page: string | number;
  pageSize: string | number;
  count: string | number;
  onPageChange: (nextPage: number) => void;
  className?: string;
}

export function Pager({ page, pageSize, count, onPageChange }: PagerProps) {
  const { formatMessage, labels } = useMessages();
  const maxPage = pageSize && count ? Math.ceil(+count / +pageSize) : 0;
  const lastPage = page === maxPage;
  const firstPage = page === 1;

  if (count === 0 || !maxPage) {
    return null;
  }

  const handlePageChange = (value: number) => {
    const nextPage = +page + +value;

    if (nextPage > 0 && nextPage <= maxPage) {
      onPageChange(nextPage);
    }
  };

  if (maxPage === 1) {
    return null;
  }

  return (
    <Row alignItems="center" justifyContent="space-between" gap="3" flexGrow={1}>
      <Text>{formatMessage(labels.numberOfRecords, { x: count.toLocaleString() })}</Text>
      <Row alignItems="center" justifyContent="flex-end" gap="3">
        <Text>
          {formatMessage(labels.pageOf, {
            current: page.toLocaleString(),
            total: maxPage.toLocaleString(),
          })}
        </Text>
        <Row gap="1">
          <Button variant="outline" onPress={() => handlePageChange(-1)} isDisabled={firstPage}>
            <Icon size="sm" rotate={180}>
              <ChevronRight />
            </Icon>
          </Button>
          <Button variant="outline" onPress={() => handlePageChange(1)} isDisabled={lastPage}>
            <Icon size="sm">
              <ChevronRight />
            </Icon>
          </Button>
        </Row>
      </Row>
    </Row>
  );
}