Skip to content

Commit

Permalink
Fix: set event listeners to be passive for the lighthouse audit (#613)
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertHebel authored Jul 22, 2020
1 parent 6ff4d16 commit d3352e6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 22 deletions.
47 changes: 27 additions & 20 deletions react-carousel/src/components/Carousel.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,18 @@ const Carousel = (props) => {
* It resets clicked index, dragOffset and dragStart values in state.
* @param {event} event event
*/
const onMouseUpTouchEnd = useCallback(
(event) => {
if (slideMovement.dragStart !== null) {
event.preventDefault();
props.onChange(props.nearestSlideIndex);
setSlideMovement({
clicked: null,
dragOffset: 0,
dragStart: null,
dragEnd: null,
});
}
},
[setTransitionEnabled, setSlideMovement, slideMovement],
);
const onMouseUpTouchEnd = useCallback(() => {
if (slideMovement.dragStart !== null) {
props.onChange(props.nearestSlideIndex);
setSlideMovement({
clicked: null,
dragOffset: 0,
dragStart: null,
dragEnd: null,
});
}
setTransitionEnabled(true);
}, [setTransitionEnabled, setSlideMovement, slideMovement]);

useOnResize({
carouselRef,
Expand Down Expand Up @@ -180,14 +177,24 @@ const Carousel = (props) => {
});
}, [props.transformOffset]);

useEventListener('mouseup', () => {
setTransitionEnabled(true);
useEventListener('mouseup', onMouseUpTouchEnd, {
passive: true,
capture: true,
});
useEventListener('mouseup', onMouseUpTouchEnd);

useEventListener('touchstart', simulateEvent, carouselRef.current);
useEventListener(
'touchstart',
simulateEvent,
{ passive: true, capture: true },
carouselRef.current,
);
useEventListener('touchmove', simulateEvent, carouselRef.current);
useEventListener('touchend', simulateEvent, carouselRef.current);
useEventListener(
'touchend',
simulateEvent,
{ passive: true, capture: true },
carouselRef.current,
);

carouselPlugins?.forEach((plugin) =>
typeof plugin === 'function' ? plugin() : plugin.plugin && plugin.plugin(),
Expand Down
4 changes: 2 additions & 2 deletions react-carousel/src/hooks/useEventListener.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useRef } from 'react';

function useEventListener(eventName, handler, element = window) {
function useEventListener(eventName, handler, options = {}, element = window) {
// Create a ref that stores handler
const savedHandler = useRef();

Expand All @@ -22,7 +22,7 @@ function useEventListener(eventName, handler, element = window) {
const eventListener = (event) => savedHandler.current(event);

// Add event listener
element.addEventListener(eventName, eventListener);
element.addEventListener(eventName, eventListener, options);

// Remove event listener on cleanup
return () => {
Expand Down

0 comments on commit d3352e6

Please sign in to comment.