-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
useCarouselContextEvents.ts
64 lines (53 loc) · 2.1 KB
/
useCarouselContextEvents.ts
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
import {useCallback, useRef} from 'react';
import type {SetStateAction} from 'react';
import {useSharedValue} from 'react-native-reanimated';
function useCarouselContextEvents(setShouldShowArrows: (show?: SetStateAction<boolean>) => void) {
const scale = useRef(1);
const isScrollEnabled = useSharedValue(true);
/**
* Toggles the arrows visibility
*/
const onRequestToggleArrows = useCallback(
(showArrows?: boolean) => {
if (showArrows === undefined) {
setShouldShowArrows((prevShouldShowArrows) => !prevShouldShowArrows);
return;
}
setShouldShowArrows(showArrows);
},
[setShouldShowArrows],
);
/**
* This callback is passed to the MultiGestureCanvas/Lightbox through the AttachmentCarouselPagerContext.
* It is used to react to zooming/pinching and (mostly) enabling/disabling scrolling on the pager,
* as well as enabling/disabling the carousel buttons.
*/
const handleScaleChange = useCallback(
(newScale: number) => {
if (newScale === scale.current) {
return;
}
scale.current = newScale;
const newIsScrollEnabled = newScale === 1;
if (isScrollEnabled.value === newIsScrollEnabled) {
return;
}
// eslint-disable-next-line react-compiler/react-compiler
isScrollEnabled.value = newIsScrollEnabled;
onRequestToggleArrows(newIsScrollEnabled);
},
[isScrollEnabled, onRequestToggleArrows],
);
/**
* This callback is passed to the MultiGestureCanvas/Lightbox through the AttachmentCarouselPagerContext.
* It is used to trigger touch events on the pager when the user taps on the MultiGestureCanvas/Lightbox.
*/
const handleTap = useCallback(() => {
if (!isScrollEnabled.value) {
return;
}
onRequestToggleArrows();
}, [isScrollEnabled.value, onRequestToggleArrows]);
return {handleTap, handleScaleChange, scale};
}
export default useCarouselContextEvents;