/
Carousel.js
323 lines (286 loc) · 8.9 KB
/
Carousel.js
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
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import CarouselItem from './CarouselItem';
import { CarouselContext } from './CarouselContext';
import { mapToCssModules, omit } from './utils';
const SWIPE_THRESHOLD = 40;
const propTypes = {
/** the current active slide of the carousel */
activeIndex: PropTypes.number,
/** a function which should advance the carousel to the next slide (via activeIndex) */
next: PropTypes.func.isRequired,
/** a function which should advance the carousel to the previous slide (via activeIndex) */
previous: PropTypes.func.isRequired,
/** controls if the left and right arrow keys should control the carousel */
keyboard: PropTypes.bool,
/** If set to "hover", pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on
* mouseleave. If set to false, hovering over the carousel won't pause it.
*/
pause: PropTypes.oneOf(['hover', false]),
/** Autoplays the carousel after the user manually cycles the first item. If "carousel", autoplays the carousel on load. */
ride: PropTypes.oneOf(['carousel']),
/** the interval at which the carousel automatically cycles */
interval: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.bool,
]),
children: PropTypes.array,
/** called when the mouse enters the Carousel */
mouseEnter: PropTypes.func,
/** called when the mouse exits the Carousel */
mouseLeave: PropTypes.func,
/** controls whether the slide animation on the Carousel works or not */
slide: PropTypes.bool,
/** make the controls, indicators and captions dark on the Carousel */
dark: PropTypes.bool,
fade: PropTypes.bool,
/** Change underlying component's CSS base class name */
cssModule: PropTypes.object,
/** Add custom class */
className: PropTypes.string,
/** Enable touch support */
enableTouch: PropTypes.bool,
};
const propsToOmit = Object.keys(propTypes);
const defaultProps = {
interval: 5000,
pause: 'hover',
keyboard: true,
slide: true,
enableTouch: true,
fade: false,
};
class Carousel extends React.Component {
constructor(props) {
super(props);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.renderItems = this.renderItems.bind(this);
this.hoverStart = this.hoverStart.bind(this);
this.hoverEnd = this.hoverEnd.bind(this);
this.handleTouchStart = this.handleTouchStart.bind(this);
this.handleTouchEnd = this.handleTouchEnd.bind(this);
this.touchStartX = 0;
this.touchStartY = 0;
this.state = {
activeIndex: this.props.activeIndex,
direction: 'end',
indicatorClicked: false,
};
}
componentDidMount() {
// Set up the cycle
if (this.props.ride === 'carousel') {
this.setInterval();
}
// TODO: move this to the specific carousel like bootstrap. Currently it will trigger ALL carousels on the page.
document.addEventListener('keyup', this.handleKeyPress);
}
static getDerivedStateFromProps(nextProps, prevState) {
let newState = null;
let { activeIndex, direction, indicatorClicked } = prevState;
if (nextProps.activeIndex !== activeIndex) {
// Calculate the direction to turn
if (nextProps.activeIndex === activeIndex + 1) {
direction = 'end';
} else if (nextProps.activeIndex === activeIndex - 1) {
direction = 'start';
} else if (nextProps.activeIndex < activeIndex) {
direction = indicatorClicked ? 'start' : 'end';
} else if (nextProps.activeIndex !== activeIndex) {
direction = indicatorClicked ? 'end' : 'start';
}
newState = {
activeIndex: nextProps.activeIndex,
direction,
indicatorClicked: false,
};
}
return newState;
}
componentDidUpdate(prevProps, prevState) {
if (prevState.activeIndex === this.state.activeIndex) return;
this.setInterval();
}
componentWillUnmount() {
this.clearInterval();
document.removeEventListener('keyup', this.handleKeyPress);
}
handleKeyPress(evt) {
if (this.props.keyboard) {
if (evt.keyCode === 37) {
this.props.previous();
} else if (evt.keyCode === 39) {
this.props.next();
}
}
}
handleTouchStart(e) {
if (!this.props.enableTouch) {
return;
}
this.touchStartX = e.changedTouches[0].screenX;
this.touchStartY = e.changedTouches[0].screenY;
}
handleTouchEnd(e) {
if (!this.props.enableTouch) {
return;
}
const currentX = e.changedTouches[0].screenX;
const currentY = e.changedTouches[0].screenY;
const diffX = Math.abs(this.touchStartX - currentX);
const diffY = Math.abs(this.touchStartY - currentY);
// Don't swipe if Y-movement is bigger than X-movement
if (diffX < diffY) {
return;
}
if (diffX < SWIPE_THRESHOLD) {
return;
}
if (currentX < this.touchStartX) {
this.props.next();
} else {
this.props.previous();
}
}
getContextValue() {
return { direction: this.state.direction };
}
setInterval() {
// make sure not to have multiple intervals going...
this.clearInterval();
if (this.props.interval) {
this.cycleInterval = setInterval(() => {
this.props.next();
}, parseInt(this.props.interval, 10));
}
}
clearInterval() {
clearInterval(this.cycleInterval);
}
hoverStart(...args) {
if (this.props.pause === 'hover') {
this.clearInterval();
}
if (this.props.mouseEnter) {
this.props.mouseEnter(...args);
}
}
hoverEnd(...args) {
if (this.props.pause === 'hover') {
this.setInterval();
}
if (this.props.mouseLeave) {
this.props.mouseLeave(...args);
}
}
renderItems(carouselItems, className) {
const { slide } = this.props;
return (
<div className={className}>
{carouselItems.map((item, index) => {
const isIn = index === this.state.activeIndex;
return React.cloneElement(item, {
in: isIn,
slide: slide,
});
})}
</div>
);
}
render() {
const { cssModule, slide, className, dark, fade } = this.props;
const attributes = omit(this.props, propsToOmit);
const outerClasses = mapToCssModules(
classNames(
className,
'carousel',
fade && 'carousel-fade',
slide && 'slide',
dark && 'carousel-dark',
),
cssModule,
);
const innerClasses = mapToCssModules(
classNames('carousel-inner'),
cssModule,
);
// filter out booleans, null, or undefined
const children = this.props.children.filter(
(child) =>
child !== null && child !== undefined && typeof child !== 'boolean',
);
const slidesOnly = children.every((child) => child.type === CarouselItem);
// Rendering only slides
if (slidesOnly) {
return (
<div
{...attributes}
className={outerClasses}
onMouseEnter={this.hoverStart}
onMouseLeave={this.hoverEnd}
>
<CarouselContext.Provider value={this.getContextValue()}>
{this.renderItems(children, innerClasses)}
</CarouselContext.Provider>
</div>
);
}
// Rendering slides and controls
if (children[0] instanceof Array) {
const carouselItems = children[0];
const controlLeft = children[1];
const controlRight = children[2];
return (
<div
{...attributes}
className={outerClasses}
onMouseEnter={this.hoverStart}
onMouseLeave={this.hoverEnd}
>
<CarouselContext.Provider value={this.getContextValue()}>
{this.renderItems(carouselItems, innerClasses)}
{controlLeft}
{controlRight}
</CarouselContext.Provider>
</div>
);
}
// Rendering indicators, slides and controls
const indicators = children[0];
const wrappedOnClick = (e) => {
if (typeof indicators.props.onClickHandler === 'function') {
this.setState({ indicatorClicked: true }, () =>
indicators.props.onClickHandler(e),
);
}
};
const wrappedIndicators = React.cloneElement(indicators, {
onClickHandler: wrappedOnClick,
});
const carouselItems = children[1];
const controlLeft = children[2];
const controlRight = children[3];
return (
<div
{...attributes}
className={outerClasses}
onMouseEnter={this.hoverStart}
onMouseLeave={this.hoverEnd}
onTouchStart={this.handleTouchStart}
onTouchEnd={this.handleTouchEnd}
>
<CarouselContext.Provider value={this.getContextValue()}>
{wrappedIndicators}
{this.renderItems(carouselItems, innerClasses)}
{controlLeft}
{controlRight}
</CarouselContext.Provider>
</div>
);
}
}
Carousel.propTypes = propTypes;
Carousel.defaultProps = defaultProps;
export default Carousel;