-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathPagination.tsx
243 lines (233 loc) · 8.18 KB
/
Pagination.tsx
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
'use client';
import * as React from 'react';
import { Icon24ChevronCompactLeft, Icon24ChevronCompactRight } from '@vkontakte/icons';
import { useAdaptivity } from '../../hooks/useAdaptivity';
import { type PaginationPageType, usePagination } from '../../hooks/usePagination';
import type { HasComponent, HTMLAttributesWithRootRef } from '../../types';
import { RootComponent } from '../RootComponent/RootComponent';
import { VisuallyHidden } from '../VisuallyHidden/VisuallyHidden';
import {
type CustomPaginationNavigationButton,
PaginationNavigationButton,
type PaginationNavigationButtonProps,
} from './PaginationNavigationButton/PaginationNavigationButton';
import {
type CustomPaginationPageButtonProps,
PaginationPageButton,
} from './PaginationPage/PaginationPageButton';
import { PaginationPageEllipsis } from './PaginationPage/PaginationPageEllipsis';
import { getPageLabelDefault } from './utils';
import styles from './Pagination.module.css';
export interface PaginationProps extends Omit<HTMLAttributesWithRootRef<HTMLElement>, 'onChange'> {
/**
* Текущая страница.
*/
currentPage?: number;
/**
* Кол-во всегда видимых страниц по краям текущей страницы.
*/
siblingCount?: number;
/**
* Кол-во всегда видимых страниц в начале и в конце.
*/
boundaryCount?: number;
/**
* Общее кол-во страниц.
*/
totalPages?: number;
/**
* Блокировка всех кнопок.
*/
disabled?: boolean;
/**
* Декоративный текст для кнопки навигации назад.
*
* > Note: Экранные дикторы будут использовать `prevButtonLabel`.
*/
prevButtonCaption?: string;
/**
* Декоративный текст для кнопки навигации вперёд.
*
* > Note: Экранные дикторы будут использовать `nextButtonLabel`.
*/
nextButtonCaption?: string;
/**
* Задаёт стиль отображения кнопок навигации.
*
* - `icon` – показывать только иконку;
* - `caption` – показывать только подпись;
* - `both` – показывать и иконку, и подпись.
*/
navigationButtonsStyle?: PaginationNavigationButtonProps['style'];
/**
* [a11y] Метка для обозначения блока навигации.
*/
navigationLabel?: string;
navigationLabelComponent?: HasComponent['Component'];
/**
* [a11y] Метка для кнопки навигации назад.
*/
prevButtonLabel?: string;
/**
* [a11y] Метка для кнопки навигации вперёд.
*/
nextButtonLabel?: string;
/**
* [a11y] Функция для переопределения и/или локализации метки кнопки страницы.
*/
getPageLabel?: (isCurrent: boolean) => string;
onChange?: (page: number, event: React.MouseEvent<HTMLElement>) => void;
/**
* Функция для кастомного рендера кнопок страниц.
*
* > Note: `CustomPaginationPageButtonProps` наследует API [Tappable](https://vkcom.github.io/VKUI/#/Tappable).
*/
renderPageButton?: (props: CustomPaginationPageButtonProps) => React.ReactNode;
/**
Функция для кастомного рендера кнопок навигации `prev` и `next`.
*
* > Note: `CustomPaginationNavigationButton` наследует API [Button](https://vkcom.github.io/VKUI/#/Button).
*/
renderNavigationButton?: (props: CustomPaginationNavigationButton) => React.ReactNode;
/**
* Передает атрибут `data-testid` для кнопок страниц
*/
pageButtonTestId?: (day: PaginationPageType, active: boolean) => string;
/**
* Передает атрибут `data-testid` для кнопки `prev`
*/
prevButtonTestId?: string;
/**
* Передает атрибут `data-testid` для кнопки `next`
*/
nextButtonTestId?: string;
}
/**
* @see https://vkcom.github.io/VKUI/#/Pagination
*/
export const Pagination = ({
currentPage = 1,
siblingCount = 1,
boundaryCount = 1,
totalPages = 1,
disabled,
prevButtonCaption = 'Назад',
nextButtonCaption = 'Вперёд',
navigationButtonsStyle = 'icon',
getPageLabel = getPageLabelDefault,
navigationLabel = 'Навигация по страницам',
navigationLabelComponent = 'h2',
prevButtonLabel = 'Перейти на предыдущую страницу',
nextButtonLabel = 'Перейти на следующую страницу',
onChange,
renderPageButton,
pageButtonTestId,
prevButtonTestId,
nextButtonTestId,
renderNavigationButton,
...resetProps
}: PaginationProps): React.ReactNode => {
const pages = usePagination({
currentPage,
totalPages,
siblingCount,
boundaryCount,
});
const isFirstPage = currentPage === 1;
const isLastPage = currentPage === totalPages;
const prevPage = isFirstPage ? undefined : currentPage - 1;
const nextPage = isLastPage ? undefined : currentPage + 1;
const handlePrevClick = React.useCallback(
(event: React.MouseEvent<HTMLElement>) => {
if (onChange && prevPage !== undefined) {
onChange(prevPage, event);
}
},
[prevPage, onChange],
);
const handleClick = React.useCallback(
(event: React.MouseEvent<HTMLElement>) => {
const page: string = event.currentTarget.dataset.page || '1';
onChange?.(Number(page), event);
},
[onChange],
);
const handleNextClick = React.useCallback(
(event: React.MouseEvent<HTMLElement>) => {
if (onChange && nextPage !== undefined) {
onChange(nextPage, event);
}
},
[nextPage, onChange],
);
const { sizeY } = useAdaptivity();
const renderPages = React.useCallback(
(page: PaginationPageType) => {
const isCurrent = page === currentPage;
const dataTestId = pageButtonTestId?.(page, isCurrent);
switch (page) {
case 'start-ellipsis':
case 'end-ellipsis':
return (
<li key={page}>
<PaginationPageEllipsis disabled={disabled} data-testid={dataTestId} />
</li>
);
default: {
return (
<li key={page}>
<PaginationPageButton
getPageLabel={getPageLabel}
isCurrent={isCurrent}
onClick={handleClick}
disabled={disabled}
sizeY={sizeY}
renderPageButton={renderPageButton}
data-testid={dataTestId}
>
{page}
</PaginationPageButton>
</li>
);
}
}
},
[currentPage, disabled, getPageLabel, handleClick, renderPageButton, sizeY, pageButtonTestId],
);
return (
<RootComponent Component="nav" role="navigation" {...resetProps}>
<VisuallyHidden Component={navigationLabelComponent}>{navigationLabel}</VisuallyHidden>
<ul className={styles.list}>
<li className={styles.prevButtonContainer}>
<PaginationNavigationButton
type="prev"
style={navigationButtonsStyle}
caption={prevButtonCaption}
Icon={Icon24ChevronCompactLeft}
a11yLabel={prevButtonLabel}
disabled={isFirstPage || disabled}
onClick={handlePrevClick}
data-page={prevPage}
data-testid={prevButtonTestId}
renderNavigationButton={renderNavigationButton}
/>
</li>
{pages.map(renderPages)}
<li className={styles.nextButtonContainer}>
<PaginationNavigationButton
type="next"
style={navigationButtonsStyle}
caption={nextButtonCaption}
Icon={Icon24ChevronCompactRight}
a11yLabel={nextButtonLabel}
disabled={isLastPage || disabled}
onClick={handleNextClick}
data-page={nextPage}
data-testid={nextButtonTestId}
renderNavigationButton={renderNavigationButton}
/>
</li>
</ul>
</RootComponent>
);
};