-
Notifications
You must be signed in to change notification settings - Fork 32
/
pagination.tsx
193 lines (180 loc) · 7.46 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
import React, {
Children, ComponentProps, FC, ReactElement,
cloneElement, useEffect, useRef, useState, createRef
} from 'react'
import {
EbayFakeMenuButton,
EbayFakeMenuButtonItem as Item
} from '../ebay-fake-menu-button'
import classNames from 'classnames'
import { debounce } from '../common/debounce'
import { calcPageState, getMaxWidth } from './helpers'
import { filterBy } from '../common/component-utils'
import { PaginationItemType } from './pagination-item'
import { ItemState, PaginationVariant } from './types'
import { EbayIcon } from '../ebay-icon'
import { EbayEventHandler } from '../common/event-utils/types'
export type PaginationProps = Omit<ComponentProps<'nav'>, 'onSelect'> & {
id?: string;
a11yPreviousText?: string;
a11yNextText?: string;
a11yCurrentText?: string;
onPrevious?: EbayEventHandler;
onNext?: EbayEventHandler;
onSelect?: EbayEventHandler<{ value: string, index: number }>;
variant?: PaginationVariant;
fluid?: boolean;
};
const EbayPagination: FC<PaginationProps> = ({
id = 'ebay-pagination',
className,
a11yCurrentText = 'Pagination - Current Page',
a11yPreviousText = 'Previous page',
a11yNextText = 'Next page',
variant = 'show-range',
fluid = false,
onPrevious = () => {},
onNext = () => {},
onSelect = () => {},
children,
...rest
}) => {
const paginationContainerRef = useRef<HTMLUnknownElement>(null)
const childPageRefs = useRef([])
childPageRefs.current = Children.map(children, createRef)
const totalPages = filterBy(children, ({ props }) => props.type === undefined || props.type === 'page').length
const itemWidthRef = useRef<number>(0)
const arrowWidthRef = useRef<number>(0)
const getNumOfVisiblePageItems = () => {
const pageArrowWidth = arrowWidthRef.current || childPageRefs.current[0]?.current?.offsetWidth
arrowWidthRef.current = pageArrowWidth // cache arrow width since it should be static
const pageItemWidth = itemWidthRef.current || childPageRefs.current[1]?.current?.offsetWidth
itemWidthRef.current = pageItemWidth // cache item width since it should be static
return pageItemWidth ?
Math.floor((getMaxWidth(paginationContainerRef.current) - pageArrowWidth * 2) / pageItemWidth) :
0
}
const [page, setPage] = useState<ItemState[]>([])
const [selectedIndex, setSelectedIndex] = useState<number>(0)
// selectedPageIndexFromDotMenu: override pageIndex on pagination with dot menu value
const updatePages = (selectedPageIndexFromDotMenu?: number) => {
const selectedPageIndex = selectedPageIndexFromDotMenu || childPageRefs.current.findIndex(pageRef =>
pageRef.current?.getAttribute('aria-current') === 'page'
)
const visiblePageItems = getNumOfVisiblePageItems()
const pageState = calcPageState(
selectedPageIndex,
visiblePageItems,
totalPages,
variant
)
setSelectedIndex(selectedPageIndex)
setPage(['hidden', ...pageState])
}
useEffect(() => {
const debouncedUpdate = debounce(updatePages, 16)
updatePages()
window.addEventListener('resize', () => debouncedUpdate())
return () => {
window.removeEventListener('resize', () => debouncedUpdate())
}
}, [children])
const createChildItems = (itemType: PaginationItemType): ReactElement[] => {
let pageIndex = 0
const firstDotItems : ReactElement[] = []
const secondDotItems : ReactElement[] = []
const allDotItems : ReactElement[] = []
const firstDot = page.indexOf('dots')
const lastDot = page.lastIndexOf('dots')
return Children.map(children, (item: ReactElement, index) => {
const { type = 'page', current, disabled, href, children: text } = item.props
const isDot = page[index] === 'dots'
const key = `${id}-item-${index}`
const hide = page[index] === 'hidden'
const isSeparator = isDot && type === 'page'
const newProps = {
current, disabled, href,
type: isSeparator ? 'separator' : type,
children: isDot ? <EbayIcon name="overflowHorizontal24" focusable={false} /> : text,
pageIndex: type === 'page' ? pageIndex++ : undefined,
key,
hide,
onPrevious, onNext, onSelect, a11yPreviousText, a11yNextText,
ref: childPageRefs.current[index]
}
// include hidden numbers & number of (...)itself
if ((hide || isDot) && type === 'page') {
const itemComponent = (
<Item
key={key}
href={href}
onClick={
event => {
if (!href) {
event.preventDefault()
}
const currentTarget = event.currentTarget as HTMLElement
onSelect(event as any, { value: currentTarget?.innerText || '', index: pageIndex })
updatePages(Number(currentTarget?.innerText))
}
}
>
{text}
</Item>
)
if (firstDot === lastDot) {
allDotItems.push(itemComponent)
}
if (selectedIndex - 2 > firstDot && index < selectedIndex) {
firstDotItems.push(itemComponent)
}
if (selectedIndex + 2 < lastDot && index > selectedIndex) {
secondDotItems.push(itemComponent)
}
}
if (itemType === 'page' && isDot && variant === 'overflow') {
let childComponent = allDotItems
if (firstDot !== lastDot) {
childComponent = index === 2 ? firstDotItems : secondDotItems
}
return (
<li key={key}>
<span className="pagination__item" role="separator">
<EbayFakeMenuButton
a11yText="Menu"
borderless
variant="overflow"
noToggleIcon
>
{childComponent}
</EbayFakeMenuButton>
</span>
</li>
)
}
return itemType === type ? cloneElement(item, newProps) : null
})
}
const headingId = `${id}-pagination-heading`
return (
<nav
{...rest}
role="navigation"
className={classNames(className, 'pagination', { 'pagination--fluid': fluid })}
aria-labelledby={headingId}
ref={paginationContainerRef}
>
<span aria-live="polite" role="status">
<h2 className="clipped" id={headingId}>
{a11yCurrentText}
</h2>
</span>
{createChildItems('previous')}
<ol className="pagination__items">
{createChildItems('page')}
</ol>
{createChildItems('next')}
</nav>
)
}
export default EbayPagination