-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcarousel.tsx
231 lines (204 loc) · 8.09 KB
/
carousel.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
import React, { Children, ComponentProps, FC, SyntheticEvent, useEffect, useRef, useState } from 'react'
import classNames from 'classnames'
import CarouselControlButton from './carousel-control-button'
import CarouselList from './carousel-list'
import { ListItemRef } from './types'
import { animateCarouselLoop, getMaxOffset, getNextIndex, getOffset, getSlide } from './helpers'
import { debounce } from '../common/debounce'
import { EbayIcon } from '../ebay-icon'
import reactDom from 'react-dom'
// Make sure to support React 16
const flushSync = reactDom.flushSync || (callback => callback())
export type CarouselProps = ComponentProps<'div'> & {
className?: string;
gap?: number;
index?: number; // Scroll to index slide
imageTreatment?: boolean; // Image slide?
itemsPerSlide?: number; // number of slides to be displayed
a11yPreviousText?: string;
a11yNextText?: string;
a11yPauseText?: string;
a11yPlayText?: string;
autoplay?: boolean | number;
onNext?: (event: React.SyntheticEvent) => void;
onPrevious?: (event: React.SyntheticEvent) => void;
onScroll?: ({ index }) => void;
onSlide?: ({ slide }) => void;
onPlay?: (event: React.SyntheticEvent) => void
onPause?: (event: React.SyntheticEvent) => void
};
const EbayCarousel: FC<CarouselProps> = ({
gap = 16,
index = 0,
itemsPerSlide: _itemsPerSlide,
a11yPreviousText,
a11yNextText,
a11yPauseText,
a11yPlayText,
autoplay,
onScroll = () => {},
onNext = () => {},
onPrevious = () => {},
onSlide = () => {},
onPlay = () => {},
onPause = () => {},
className,
children,
...rest
}) => {
const [activeIndex, setActiveIndex] = useState(index)
const [slideWidth, setSlideWidth] = useState(0)
const [offset, setOffset] = useState(0)
const [isUserInteracting, setIsUserInteracting] = useState(false)
const containerRef = useRef<HTMLDivElement | null>(null)
const itemsRef = useRef<Array<ListItemRef | null>>([])
const itemCount = Children.count(children)
const itemsPerSlide = Math.floor(_itemsPerSlide) || undefined
const isSingleSlide = itemCount <= itemsPerSlide
const isAutoplayEnabled = Boolean(autoplay)
const prevControlDisabled = isSingleSlide || (offset === 0 && !isAutoplayEnabled)
const nextControlDisabled =
isSingleSlide || (offset === getMaxOffset(itemsRef.current, slideWidth) && !isAutoplayEnabled)
const handleResize = () => {
if (!containerRef.current) return
const { width: containerWidth } = containerRef.current.getBoundingClientRect()
setSlideWidth(containerWidth)
}
useEffect(() => {
window.addEventListener('resize', debounce(handleResize, 16))
return () => {
window.removeEventListener('resize', debounce(handleResize, 16))
}
}, [])
// During autoplay animation, we manually set the offset positions, so we temporarily disable
// until the animation is complete
const [disableOffsetCalculation, setDisableOffsetCalculation] = useState(false)
useEffect(() => {
if (!disableOffsetCalculation) {
setOffset(getOffset(itemsRef.current, activeIndex, slideWidth))
}
}, [activeIndex, slideWidth, disableOffsetCalculation])
useEffect(() => {
if (index >= 0 && index <= itemCount - 1) {
setActiveIndex(index)
}
}, [index])
useEffect(() => {
itemsRef.current = itemsRef.current.splice(0, itemCount)
}, [children])
useEffect(() => {
const { width: containerWidth } = containerRef.current.getBoundingClientRect()
setSlideWidth(containerWidth)
}, [containerRef.current])
const [paused, setPaused] = useState(false)
useEffect(() => {
const isReducedMotion = Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches)
setPaused(isReducedMotion)
}, [])
const togglePlayback = (event) => {
setPaused(!paused)
if (paused) {
onPlay(event)
} else {
onPause(event)
}
}
// Use ref to keep track of the active index inside the interval callback
const activeIndexRef = useRef(activeIndex)
activeIndexRef.current = activeIndex
const updateActiveIndex = (direction, itemsToShow) => {
const currentIndex = activeIndexRef.current
const nextIndex = getNextIndex(
direction, currentIndex, itemsRef.current, slideWidth, itemsToShow)
const slide = getSlide(currentIndex, itemsToShow, nextIndex)
onSlide({ slide })
if (isAutoplayEnabled) {
animateCarouselLoop({
direction,
nextIndex,
currentIndex,
itemsRef,
slideWidth,
gap,
onAnimationStart: () => setDisableOffsetCalculation(true),
onAnimationEnd: () => setDisableOffsetCalculation(false)
})
}
// Use flushSync to update the active index synchronously so it properly trigger the animation on autoplay
flushSync(() => setActiveIndex(nextIndex))
}
useEffect(() => {
if (!isAutoplayEnabled || paused || isUserInteracting) {
return
}
const autoplayTimeout = typeof autoplay === 'number' ? autoplay : 4000
const interval = setInterval(() => {
updateActiveIndex('RIGHT', itemsPerSlide)
}, autoplayTimeout)
return () => clearInterval(interval)
}, [isAutoplayEnabled, paused, itemsPerSlide, isUserInteracting])
const handleControlClick = (event: SyntheticEvent<HTMLButtonElement>, { direction }) => {
updateActiveIndex(direction, itemsPerSlide)
if (direction === 'LEFT') {
onPrevious(event)
} else {
onNext(event)
}
}
const handleStartInteraction = () => setIsUserInteracting(true)
const handleEndInteraction = () => setIsUserInteracting(false)
return (
<div
className={classNames('carousel', className,
{
'carousel--slides': itemsPerSlide,
'carousel--peek': itemsPerSlide % 1 === 0,
'carousel__autoplay': isAutoplayEnabled
})}
{...rest}>
<div
ref={containerRef}
className="carousel__container"
onFocusCapture={handleStartInteraction}
onMouseEnter={handleStartInteraction}
onTouchStartCapture={handleStartInteraction}
onBlurCapture={handleEndInteraction}
onMouseLeave={handleEndInteraction}
onTouchEndCapture={handleEndInteraction}>
<CarouselControlButton
label={a11yPreviousText}
type="prev"
disabled={prevControlDisabled}
onClick={handleControlClick} />
<CarouselList
itemsRef={itemsRef}
offset={offset}
gap={gap}
itemsPerSlide={itemsPerSlide}
nextControlDisabled={nextControlDisabled}
isAutoplayEnabled={isAutoplayEnabled}
activeIndex={activeIndex}
onScroll={onScroll}
onSetActiveIndex={setActiveIndex}
slideWidth={slideWidth}>
{children}
</CarouselList>
<CarouselControlButton
type="next"
label={a11yNextText}
disabled={nextControlDisabled}
onClick={handleControlClick} />
{isAutoplayEnabled ? (
<button
className="carousel__playback"
type="button"
onClick={togglePlayback}
aria-label={paused ? a11yPlayText : a11yPauseText}>
<EbayIcon name={paused ? 'play24' : 'pause24'} />
</button>
) : null}
</div>
</div>
)
}
export default EbayCarousel