import { ModalDialogHandle } from '@mgcrea/react-native-modal-dialog' ; import React , { FunctionComponent , useCallback , useMemo , useRef , useState } from 'react' ; import { ActionSheetIOS , ActionSheetIOSOptions , Platform } from 'react-native' ; import { ActionSheet , ActionSheetProps } from './ActionSheet' ; export type ActionSheetContextValue = { showWithOptions : ( options : ActionSheetIOSOptions , callback : ( buttonIndex : number ) => void ) => void ; hide : ( ) => void ; } ; export const ActionSheetContext = React . createContext < ActionSheetContextValue > ( null ) ; export type ActionSheetProviderProps = Partial < Omit < ActionSheetProps , 'options' > > & { native ? : boolean ; } ; export const defaultProps = { native : true } ; export const ActionSheetProvider = ( { children , native = defaultProps . native , onButtonPress : propOnButtonPress , onCancel : propOnCancel , ... otherActionSheetProps } ) => { const modalDialogRef = useRef < ModalDialogHandle > ( null ) ; const [ globalOptions , setGlobalOptions ] = useState < ActionSheetIOSOptions > ( { options : [ ] } ) ; const latestCallback = useRef < ( ( buttonIndex : number ) => void ) | null > ( null ) ; const showWithOptions = useCallback ( ( options , callback ) => { if ( native && Platform . OS === 'ios' ) { ActionSheetIOS . showActionSheetWithOptions ( options , callback ) ; return ; } setGlobalOptions ( options ) ; latestCallback . current = callback ; if ( modalDialogRef . current ) { modalDialogRef . current . show ( ) ; } } , [ native ] ) ; const hide = useCallback ( ( ) => { if ( native && Platform . OS === 'ios' ) { return ; } if ( modalDialogRef . current ) { modalDialogRef . current . hide ( ) ; } } , [ native ] ) ; const contextValue = useMemo < ActionSheetContextValue > ( ( ) => { return { showWithOptions , hide } ; } , [ showWithOptions , hide ] ) ; const onButtonPress = useCallback ( ( buttonIndex ) => { if ( latestCallback . current ) { latestCallback . current ( buttonIndex ) ; } if ( propOnButtonPress ) { propOnButtonPress ( buttonIndex ) ; } hide ( ) ; } , [ hide , propOnButtonPress ] ) ; const onCancel = useCallback ( ( ) => { if ( propOnCancel ) { propOnCancel ( ) ; } hide ( ) ; } , [ hide , propOnCancel ] ) ; return ( < ActionSheetContext . Provider value = { contextValue } > { children } { ! native || Platform . OS !== 'ios' ? ( < ActionSheet ref = { modalDialogRef } { ... otherActionSheetProps } onButtonPress = { onButtonPress } onCancel = { onCancel } { ... globalOptions } />) : null} < /ActionSheetContext.Provider>); } ;