Repository URL to install this package:
|
Version:
4.0.76 ▾
|
import { TouchEventHandler, MouseEventHandler } from 'react'
import { isNonEmptyArray, fromIshToNumber } from 'exotic'
import { MediaCarouselProps, MediaCarouselStateType } from './typings'
const offsetCollection = {
startOffset: 0,
endOffset: 0,
itemWidth: 0,
offsetArray: [],
}
const handleTouchStart = (event: TouchEvent): void => {
offsetCollection.itemWidth = event.target.clientWidth
if (!isNonEmptyArray(event.touches) === true) {
offsetCollection.startOffset = event.touches[0].clientX
}
}
const handleTouchMove = (event: TouchEvent): void => {
if (!isNonEmptyArray(event.touches) === true) {
offsetCollection.offsetArray.push(event.touches[0].clientX)
}
}
const handleTouchEnd = (event: TouchEvent, state: MediaCarouselStateType, props: MediaCarouselProps): void => {
const arrayLength = offsetCollection.offsetArray.length
offsetCollection.endOffset = (offsetCollection.offsetArray[arrayLength - 1])
performSwipe(state, props)
}
const handleDragStart = (event: MouseEvent): void => {
event.preventDefault()
offsetCollection.itemWidth = event.target.clientWidth
offsetCollection.startOffset = event.clientX
}
const handleDragEnd = (event: MouseEvent, state: MediaCarouselStateType, props: MediaCarouselProps): void => {
offsetCollection.endOffset = event.clientX
performSwipe(state, props)
}
const performSwipe = (state: MediaCarouselStateType, props: MediaCarouselProps): void => {
const { step, toNext, toPrevious } = state
const { gridGap } = props
/**
* threshold for swiping: minimum limit 25% hence dividing it by 4
*/
const scrollLimit = step * (offsetCollection.itemWidth + fromIshToNumber(gridGap)) / 4
const offsetDifference = offsetCollection.startOffset - offsetCollection.endOffset
if (offsetDifference >= scrollLimit) {
toNext()
}
else if ((-offsetDifference) >= scrollLimit) {
toPrevious()
}
}
export {
handleTouchStart,
handleTouchMove,
handleTouchEnd,
handleDragStart,
handleDragEnd,
performSwipe,
}