59 lines
2.5 KiB
JavaScript
59 lines
2.5 KiB
JavaScript
import { carouselClassNames } from '../Carousel';
|
|
export function pointerEventPlugin(options) {
|
|
let emblaApi;
|
|
let pointerEvent;
|
|
function documentDownListener(event) {
|
|
const targetDocument = emblaApi.containerNode().ownerDocument;
|
|
if (event.target) {
|
|
const targetNode = event.target;
|
|
if (targetNode.classList.contains(carouselClassNames.root) || emblaApi.containerNode().contains(targetNode)) {
|
|
pointerEvent = event;
|
|
}
|
|
}
|
|
targetDocument.removeEventListener('mousedown', documentDownListener);
|
|
targetDocument.removeEventListener('pointerdown', documentDownListener);
|
|
}
|
|
function pointerUpListener() {
|
|
const targetDocument = emblaApi.containerNode().ownerDocument;
|
|
targetDocument.addEventListener('mousedown', documentDownListener);
|
|
targetDocument.addEventListener('pointerdown', documentDownListener);
|
|
}
|
|
function clearPointerEvent() {
|
|
pointerEvent = undefined;
|
|
pointerUpListener();
|
|
}
|
|
function selectListener() {
|
|
if (pointerEvent) {
|
|
var _emblaApi_selectedScrollSnap;
|
|
const newIndex = (_emblaApi_selectedScrollSnap = emblaApi.selectedScrollSnap()) !== null && _emblaApi_selectedScrollSnap !== void 0 ? _emblaApi_selectedScrollSnap : 0;
|
|
options.onSelectViaDrag(pointerEvent, newIndex);
|
|
}
|
|
clearPointerEvent();
|
|
}
|
|
function init(emblaApiInstance, optionsHandler) {
|
|
emblaApi = emblaApiInstance;
|
|
// Initialize the listener for first mouse/pointerDown event
|
|
const targetDocument = emblaApi.containerNode().ownerDocument;
|
|
targetDocument.addEventListener('mousedown', documentDownListener);
|
|
targetDocument.addEventListener('pointerdown', documentDownListener);
|
|
emblaApi.on('pointerUp', pointerUpListener);
|
|
emblaApi.on('select', selectListener);
|
|
// Settle is used to clear pointer in cases where active index does not change
|
|
emblaApi.on('settle', clearPointerEvent);
|
|
}
|
|
function destroy() {
|
|
const targetDocument = emblaApi.containerNode().ownerDocument;
|
|
targetDocument.removeEventListener('mousedown', documentDownListener);
|
|
targetDocument.removeEventListener('pointerdown', documentDownListener);
|
|
emblaApi.off('pointerUp', pointerUpListener);
|
|
emblaApi.off('select', selectListener);
|
|
emblaApi.off('settle', clearPointerEvent);
|
|
}
|
|
return {
|
|
name: 'pointerEvent',
|
|
options,
|
|
init,
|
|
destroy
|
|
};
|
|
}
|