import React, { useState, useEffect } from 'react'; import { AccessibilityInfo, LayoutChangeEvent } from 'react-native'; import { Box } from '../Box'; import { Text } from '../Text'; import { useTheme } from '../../theme/ThemeProvider'; import SwipeThumb from './components/SwipeThumb'; import { LoadingContainer } from '../Loading/LoadingContainer'; export interface ISwipeButton { title: string; disabled?: boolean; disableResetOnTap?: boolean; enableReverseSwipe?: boolean; forceReset?: () => void; loading?: boolean; height?: number; onSwipeFail?: () => void; onSwipeStart?: () => void; onSwipeSuccess: () => void; resetAfterSuccessAnimDelay?: number; resetAfterSuccessAnimDuration?: number; shouldResetAfterSuccess?: boolean; swipeSuccessThreshold?: number; // Ex: 60. Swipping 60% will be considered as successful swipe thumbIconWidth?: number; } export const SwipeButton = ({ title, disabled = false, height = 50, loading, ...rest }: ISwipeButton) => { const [layoutWidth, setLayoutWidth] = useState(0); const [screenReaderEnabled, setScreenReaderEnabled] = useState(false); const [isUnmounting, setIsUnmounting] = useState(false); const { fonts, colors } = useTheme(); /** * Retrieve layoutWidth to set maximum swipeable area. * Correct layout width will be received only after first render but we need it before render. * So render SwipeThumb only if layoutWidth > 0 */ const onLayoutContainer = async (event: LayoutChangeEvent) => { if (isUnmounting || layoutWidth) return; setLayoutWidth(event.nativeEvent.layout.width); }; useEffect(() => { const handleScreenReaderToggled = (isEnabled: boolean) => { if (isUnmounting || screenReaderEnabled === isEnabled) return; setScreenReaderEnabled(isEnabled); }; setIsUnmounting(false); const suscription = AccessibilityInfo.addEventListener( 'change', handleScreenReaderToggled ); AccessibilityInfo.isScreenReaderEnabled().then((isEnabled) => { if (isUnmounting) { return; } setScreenReaderEnabled(isEnabled); }); return () => { setIsUnmounting(true); suscription.remove(); }; }, [isUnmounting, screenReaderEnabled]); return ( {loading ? ( ) : ( {title} )} {layoutWidth > 0 && ( )} ); };