@@ -3,6 +3,7 @@ import React, {
3
3
createContext ,
4
4
forwardRef ,
5
5
HTMLAttributes ,
6
+ TouchEvent ,
6
7
useState ,
7
8
useEffect ,
8
9
useRef ,
@@ -50,6 +51,12 @@ export interface CCarouselProps extends HTMLAttributes<HTMLDivElement> {
50
51
* 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.
51
52
*/
52
53
pause ?: boolean | 'hover'
54
+ /**
55
+ * Whether the carousel should support left/right swipe interactions on touchscreen devices.
56
+ *
57
+ * @since 4.5.0
58
+ */
59
+ touch ?: boolean
53
60
/**
54
61
* Set type of the transition.
55
62
*/
@@ -84,6 +91,7 @@ export const CCarousel = forwardRef<HTMLDivElement, CCarouselProps>(
84
91
onSlid,
85
92
onSlide,
86
93
pause = 'hover' ,
94
+ touch = true ,
87
95
transition,
88
96
wrap = true ,
89
97
...rest
@@ -99,6 +107,7 @@ export const CCarousel = forwardRef<HTMLDivElement, CCarouselProps>(
99
107
const [ customInterval , setCustomInterval ] = useState < boolean | number > ( )
100
108
const [ direction , setDirection ] = useState < string > ( 'next' )
101
109
const [ itemsNumber , setItemsNumber ] = useState < number > ( 0 )
110
+ const [ touchPosition , setTouchPosition ] = useState < number | null > ( null )
102
111
const [ visible , setVisible ] = useState < boolean > ( )
103
112
104
113
useEffect ( ( ) => {
@@ -193,11 +202,38 @@ export const CCarousel = forwardRef<HTMLDivElement, CCarouselProps>(
193
202
}
194
203
}
195
204
205
+ const handleTouchMove = ( e : TouchEvent ) => {
206
+ const touchDown = touchPosition
207
+
208
+ if ( touchDown === null ) {
209
+ return
210
+ }
211
+
212
+ const currentTouch = e . touches [ 0 ] . clientX
213
+ const diff = touchDown - currentTouch
214
+
215
+ if ( diff > 5 ) {
216
+ handleControlClick ( 'next' )
217
+ }
218
+
219
+ if ( diff < - 5 ) {
220
+ handleControlClick ( 'prev' )
221
+ }
222
+
223
+ setTouchPosition ( null )
224
+ }
225
+
226
+ const handleTouchStart = ( e : TouchEvent ) => {
227
+ const touchDown = e . touches [ 0 ] . clientX
228
+ setTouchPosition ( touchDown )
229
+ }
230
+
196
231
return (
197
232
< div
198
233
className = { _className }
199
234
onMouseEnter = { _pause }
200
235
onMouseLeave = { cycle }
236
+ { ...( touch && { onTouchStart : handleTouchStart , onTouchMove : handleTouchMove } ) }
201
237
{ ...rest }
202
238
ref = { forkedRef }
203
239
>
@@ -262,6 +298,7 @@ CCarousel.propTypes = {
262
298
onSlid : PropTypes . func ,
263
299
onSlide : PropTypes . func ,
264
300
pause : PropTypes . oneOf ( [ false , 'hover' ] ) ,
301
+ touch : PropTypes . bool ,
265
302
transition : PropTypes . oneOf ( [ 'slide' , 'crossfade' ] ) ,
266
303
wrap : PropTypes . bool ,
267
304
}
0 commit comments