/
Paging.tsx
451 lines (389 loc) · 12.9 KB
/
Paging.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import * as React from 'react';
import { number, func } from 'prop-types';
import ArrowChevronRightIcon from '@skbkontur/react-icons/ArrowChevronRight';
import { isKeyArrowLeft, isKeyArrowRight, isKeyEnter } from '../../lib/events/keyboard/identifiers';
import { isIE } from '../ensureOldIEClassName';
import { locale } from '../LocaleProvider/decorators';
import { PagingLocale, PagingLocaleHelper } from './locale';
import PagingHelper from './PagingHelper';
import NavigationHelper from './NavigationHelper';
import { Nullable } from '../../typings/utility-types';
import tabListener from '../../lib/events/tabListener';
import { emptyHandler } from '../../lib/utils';
import styles from './Paging.module.less';
import { cx } from '../../lib/theming/Emotion';
import jsStyles from './Paging.styles';
import { ThemeConsumer } from '../ThemeConsumer';
import { ITheme } from '../../lib/theming/Theme';
import warning from 'warning';
const IGNORE_EVENT_TAGS = ['input', 'textarea'];
interface ItemComponentProps {
active: boolean;
children?: React.ReactNode;
className: string;
onClick: () => void;
pageNumber: number | 'forward';
tabIndex: number;
}
export interface PagingProps {
activePage: number;
/**
* Компонент обертки по умолчанию
* @default <span />
*/
component: React.ComponentType<ItemComponentProps>;
onPageChange: (pageNumber: number) => void;
pagesCount: number;
disabled?: boolean;
/**
* @deprecated используйте проп `caption` или `LocaleProvider`
*/
strings?: { forward: string };
/**
* Отключает навигационные подсказки.
* По-умолчанию подсказки появляются, когда доступно управление с клавиатуры
* (либо элемент в фокусе, либо globalListeners === true)
*/
withoutNavigationHint?: boolean;
caption?: string;
/**
* Глобальный слушатель **keyDown**, для навигации клавишами без фокуса на компоненте.
* Если на странице используется несколько элементов
* **Paging** с useGlobalListener === true, то обработчик keyDown будет вызываться
* на каждом из них. Такие случаи лучше обрабатывать отдельно.
*/
useGlobalListener: boolean;
}
export interface PagingState {
focusedByTab: boolean;
focusedItem: Nullable<ItemType>;
keyboardControl: boolean;
}
export type ItemType = number | '.' | 'forward';
@locale('Paging', PagingLocaleHelper)
export default class Paging extends React.Component<PagingProps, PagingState> {
public static defaultProps = {
component: ({ className, onClick, children }: any) => (
<span className={className} onClick={onClick} children={children} />
),
useGlobalListener: false,
};
public static propTypes = {};
public static isForward(pageNumber: number | 'forward'): boolean /* %checks */ {
return pageNumber === 'forward';
}
public state: PagingState = {
focusedByTab: false,
focusedItem: null,
keyboardControl: this.props.useGlobalListener,
};
private theme!: ITheme;
private readonly locale!: PagingLocale;
private addedGlobalListener: boolean = false;
private container: HTMLSpanElement | null = null;
public componentDidMount() {
const { useGlobalListener, strings } = this.props;
if (useGlobalListener) {
this.addGlobalListener();
}
warning(
strings === undefined,
'[Paging]: `strings` prop is deprecated, please use `caption` or `LocaleProvider` instead',
);
}
public componentWillReceiveProps(nextProps: PagingProps) {
if (this.props.useGlobalListener !== nextProps.useGlobalListener) {
this.setState({
keyboardControl: nextProps.useGlobalListener,
});
}
}
public componentDidUpdate(prevProps: PagingProps) {
if (!prevProps.useGlobalListener && this.props.useGlobalListener) {
this.addGlobalListener();
}
if (prevProps.useGlobalListener && !this.props.useGlobalListener) {
this.removeGlobalListener();
}
}
public componentWillUnmount() {
this.removeGlobalListener();
}
public render() {
return (
<ThemeConsumer>
{theme => {
this.theme = theme;
return this.renderMain();
}}
</ThemeConsumer>
);
}
private renderMain() {
return (
<span
tabIndex={0}
className={styles.paging}
onKeyDown={this.props.useGlobalListener ? undefined : this.handleKeyDown}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onMouseDown={this.handleMouseDown}
ref={this.refContainer}
>
{this.getItems().map(this.renderItem)}
</span>
);
}
private renderItem = (item: ItemType, index: number) => {
const focused = this.getFocusedItem() === item;
switch (item) {
case '.':
const key = `dots${index < 5 ? 'Left' : 'Right'}`;
return this.renderDots(key);
case 'forward':
const disabled = this.isItemDisabled(item);
return this.renderForwardLink(disabled, focused);
default:
const active = this.props.activePage === item;
return this.renderPageLink(item, active, focused);
}
};
private renderDots = (key: string) => {
return (
<span key={key} className={cx(styles.dots, jsStyles.dots(this.theme))}>
{'...'}
</span>
);
};
private renderForwardLink = (disabled: boolean, focused: boolean): JSX.Element => {
const classes = cx({
[styles.forwardLink]: true,
[jsStyles.forwardLink(this.theme)]: true,
[styles.focused]: focused,
[jsStyles.focused(this.theme)]: focused,
[styles.disabled]: disabled,
[jsStyles.disabled(this.theme)]: disabled,
});
const { component: Component, strings: { forward = this.locale.forward } = {}, caption } = this.props;
return (
<Component
key={'forward'}
active={false}
className={classes}
onClick={disabled ? emptyHandler : this.goForward}
tabIndex={-1}
pageNumber={'forward' as 'forward'}
>
{caption || forward}
<span className={styles.forwardIcon}>
<ArrowChevronRightIcon size="18px" />
</span>
</Component>
);
};
private renderPageLink = (pageNumber: number, active: boolean, focused: boolean): JSX.Element => {
const classes = cx({
[styles.pageLink]: true,
[jsStyles.pageLink(this.theme)]: true,
[styles.focused]: focused,
[jsStyles.focused(this.theme)]: focused,
[styles.active]: active,
[jsStyles.active(this.theme)]: active,
});
const Component = this.props.component;
const handleClick = () => this.goToPage(pageNumber);
return (
<span key={pageNumber} className={styles.pageLinkWrapper} onMouseDown={this.handleMouseDownPageLink}>
<Component active={active} className={classes} onClick={handleClick} tabIndex={-1} pageNumber={pageNumber}>
{pageNumber}
</Component>
{active && this.renderNavigationHint()}
</span>
);
};
private renderNavigationHint = () => {
if (this.props.withoutNavigationHint) {
return null;
}
const { keyboardControl } = this.state;
const canGoBackward = this.canGoBackward();
const canGoForward = this.canGoForward();
if (keyboardControl && (canGoBackward || canGoForward)) {
return (
<span className={cx(styles.pageLinkHint, jsStyles.pageLinkHint(this.theme))}>
<span className={canGoBackward ? '' : styles.transparent}>{'←'}</span>
<span>{NavigationHelper.getKeyName()}</span>
<span className={canGoForward ? '' : styles.transparent}>{'→'}</span>
</span>
);
}
return <div className={styles.pageLinkHintPlaceHolder} />;
};
private handleMouseDown = () => {
this.setState({ focusedByTab: false, focusedItem: null });
};
private handleMouseDownPageLink = () => {
if (isIE) {
// Клик по span внутри контейнера с tabindex="0" переносит фокус именно на этот span.
// Поэтому горячие клавиши работают пока span существует на странице.
setTimeout(() => this.container && this.container.focus(), 0);
}
};
private handleKeyDown = (e: KeyboardEvent | React.KeyboardEvent<HTMLElement>) => {
if (e.shiftKey) {
return;
}
const target = e.target;
const isArrowLeft = isKeyArrowLeft(e);
const isArrowRight = isKeyArrowRight(e);
if (
target instanceof Element &&
(IGNORE_EVENT_TAGS.includes(target.tagName.toLowerCase()) || (target as HTMLElement).isContentEditable)
) {
return;
}
if (NavigationHelper.checkKeyPressed(e) && isArrowLeft) {
this.setState({ focusedItem: null }, this.goBackward);
return;
}
if (NavigationHelper.checkKeyPressed(e) && isArrowRight) {
this.setState({ focusedItem: null }, this.goForward);
return;
}
if (this.container && this.container === e.target) {
if (isArrowLeft) {
this.setState({ focusedByTab: true }, this.moveFocusLeft);
return;
}
if (isArrowRight) {
this.setState({ focusedByTab: true }, this.moveFocusRight);
return;
}
if (isKeyEnter(e)) {
this.executeItemAction(this.getFocusedItem());
return;
}
}
};
private handleFocus = (e: React.FocusEvent<HTMLElement>) => {
if (this.props.disabled) {
return;
}
this.setState({ keyboardControl: true });
// focus event fires before keyDown eventlistener
// so we should check tabPressed in async way
process.nextTick(() => {
if (tabListener.isTabPressed) {
this.setState({ focusedByTab: true });
}
});
};
private handleBlur = () => {
this.setState({
focusedByTab: false,
keyboardControl: this.props.useGlobalListener || false,
});
};
private getItems = (): ItemType[] => {
return PagingHelper.getItems(this.props.activePage, this.props.pagesCount).concat('forward');
};
private getFocusedItem = (): Nullable<ItemType> => {
if (!this.state.focusedByTab) {
return null;
}
const { focusedItem } = this.state;
if (focusedItem && this.getItems().indexOf(focusedItem) !== -1 && this.isItemFocusable(focusedItem)) {
return focusedItem;
}
return this.props.activePage;
};
private isItemFocusable = (item: ItemType) => {
return !this.isItemDisabled(item);
};
private isItemDisabled = (item: ItemType) => {
switch (item) {
case '.':
return true;
case 'forward':
return !this.canGoForward();
default:
return false;
}
};
private executeItemAction = (item: Nullable<ItemType>) => {
if (item === 'forward') {
this.goForward();
}
if (typeof item === 'number') {
this.goToPage(item);
}
};
private moveFocusLeft = () => {
this.moveFocus(-1);
};
private moveFocusRight = () => {
this.moveFocus(1);
};
private moveFocus = (step: number) => {
const focusedItem = this.getFocusedItem();
const items = this.getItems();
let index = items.findIndex(x => x === focusedItem);
do {
index = (index + step + items.length) % items.length;
} while (!this.isItemFocusable(items[index]));
this.setState({ focusedItem: items[index] });
};
private canGoBackward = (): boolean => {
return this.props.activePage > 1;
};
private canGoForward = (): boolean => {
return this.props.activePage < this.props.pagesCount;
};
private goBackward = () => {
this.goToPage(this.props.activePage - 1);
};
private goForward = () => {
this.goToPage(this.props.activePage + 1);
};
private goToPage = (pageNumber: number) => {
if (1 <= pageNumber && pageNumber !== this.props.activePage && pageNumber <= this.props.pagesCount) {
this.props.onPageChange(pageNumber);
}
};
private addGlobalListener = () => {
if (this.addedGlobalListener) {
return;
}
document.addEventListener('keydown', this.handleKeyDown);
this.addedGlobalListener = true;
};
private removeGlobalListener = () => {
if (this.addedGlobalListener) {
document.removeEventListener('keydown', this.handleKeyDown);
this.addedGlobalListener = false;
}
};
private refContainer = (element: HTMLSpanElement | null) => {
this.container = element;
};
}
Paging.propTypes = {
/**
* Current active page
*/
activePage: number.isRequired,
/**
* React component that would be used for rendering items
*
* Usefull for router integration
*/
component: func,
/**
* Total page count
*/
pagesCount: number.isRequired,
/**
* Calls when page has been changed
*/
onPageChange: func.isRequired,
};