react-native#ActionSheetIOS TypeScript Examples

The following examples show how to use react-native#ActionSheetIOS. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Helpers.ts    From react-native-ios-context-menu with MIT License 6 votes vote down vote up
export function asyncActionSheetConfirm(config: {
  title        : string; 
  message      : string; 
  confirmText  : string; 
  isDestructive?: boolean;
}){
  const isDestructive = config.isDestructive ?? false;

  return new Promise(resolve => {
    ActionSheetIOS.showActionSheetWithOptions({
      title  : config.title,
      message: config.message,

      options: ['Cancel', config.confirmText],
      cancelButtonIndex: 0,
      ...(isDestructive && {
        destructiveButtonIndex: 1,
      }),
    }, (buttonIndex) => {
      resolve((buttonIndex === 1));
    });
  });
}
Example #2
Source File: Helpers.ts    From react-native-ios-context-menu with MIT License 5 votes vote down vote up
export function asyncActionSheet(config: ActionSheetIOSOptions){
  return new Promise(resolve => {
    ActionSheetIOS.showActionSheetWithOptions(config, (buttonIndex) => {
      resolve(buttonIndex);
    });
  });
}
Example #3
Source File: CustomPicker.tsx    From hive-keychain-mobile with MIT License 5 votes vote down vote up
CustomPicker = ({
  list,
  selectedValue,
  onSelected,
  prefix,
  prompt,
  style,
  labelCreator,
  dropdownIconColor,
  iosTextStyle,
}: Props) => {
  const styles = getDimensionedStyles();
  switch (Platform.OS) {
    case 'ios':
      return (
        <TouchableOpacity
          style={[styles.iosContainer, style]}
          onPress={() => {
            ActionSheetIOS.showActionSheetWithOptions(
              {
                options: labelCreator ? list.map((e) => labelCreator(e)) : list,
              },
              (index) => {
                onSelected(list[index]);
              },
            );
          }}>
          <Text style={[styles.iosLabel, iosTextStyle]}>{`${
            prefix ? prefix : ''
          }${
            labelCreator ? labelCreator(selectedValue) : selectedValue
          }`}</Text>
          <Text style={iosTextStyle}>{'\u25BC'}</Text>
        </TouchableOpacity>
      );
    default:
      return (
        <Picker
          style={[styles.picker, style]}
          selectedValue={selectedValue}
          prompt={prompt}
          dropdownIconColor={dropdownIconColor || 'black'}
          onValueChange={onSelected}>
          {list.map((item, i) => {
            return (
              <Picker.Item
                key={i}
                label={`${prefix ? prefix : ''}${
                  labelCreator ? labelCreator(item) : item
                }`}
                value={item}
              />
            );
          })}
        </Picker>
      );
  }
}
Example #4
Source File: EmailAddressItem.tsx    From lexicon with MIT License 4 votes vote down vote up
export default function EmailAddressItem(props: Props) {
  const styles = useStyles();
  const { colors } = useTheme();

  const { emailAddress, type, onSetLoading } = props;

  const [showOptions, setShowOptions] = useState(false);

  const storage = useStorage();
  const username = storage.getItem('user')?.username || '';

  const ios = Platform.OS === 'ios';

  const {
    setPrimaryEmail,
    loading: setPrimaryEmailLoading,
  } = useSetPrimaryEmail({
    variables: {
      selectedEmail: emailAddress,
      username,
    },
    onError: (error) => {
      errorHandlerAlert(error);
    },
    refetchQueries: [
      {
        query: PROFILE,
        variables: { username },
      },
    ],
  });

  const { deleteEmail, loading: deleteEmailLoading } = useDeleteEmail({
    variables: {
      selectedEmail: emailAddress,
      username,
    },
    onCompleted: () => {
      Alert.alert(
        'Success!',
        t('{emailAddress} has been successfully deleted', { emailAddress }),
        [{ text: t('Got it') }],
      );
    },
    onError: (error) => {
      errorHandlerAlert(error);
    },
    refetchQueries: [
      {
        query: PROFILE,
        variables: { username },
      },
    ],
  });

  const onSetPrimaryEmail = () => {
    if (!ios) {
      setShowOptions(false);
    }
    setPrimaryEmail();
  };

  const onDeleteEmail = () => {
    if (!ios) {
      setShowOptions(false);
    }
    deleteEmail();
  };

  const showAlert = () =>
    Alert.alert(
      t('Delete Email?'),
      t('Are you sure you want to delete this email address?'),
      [
        {
          text: t('Cancel'),
          onPress: () => {
            if (!ios) {
              setShowOptions(false);
            }
          },
        },
        {
          text: t('Delete'),
          onPress: onDeleteEmail,
        },
      ],
    );

  const onPressMoreVert = () => {
    if (ios) {
      ActionSheetIOS.showActionSheetWithOptions(
        {
          options:
            type === 'SECONDARY'
              ? SecondaryEmailOptions
              : UnconfirmedEmailOptions,
          cancelButtonIndex: type === 'SECONDARY' ? 2 : 1,
          destructiveButtonIndex: type === 'SECONDARY' ? 1 : 0,
        },
        (btnIndex) => {
          if (btnIndex === 0 && type === 'SECONDARY') {
            onSetPrimaryEmail();
          } else if (
            (btnIndex === 0 && type === 'UNCONFIRMED') ||
            (btnIndex === 1 && type === 'SECONDARY')
          ) {
            showAlert();
          }
        },
      );
    } else {
      setShowOptions(true);
    }
  };

  if (setPrimaryEmailLoading || deleteEmailLoading) {
    onSetLoading(true);
  }

  return (
    <>
      <>
        <View style={styles.container}>
          <View style={styles.content}>
            <Text>{emailAddress}</Text>
            {type === 'PRIMARY' && (
              <Text size="s" color="textLight" style={styles.primary}>
                {t('Primary Email Address')}
              </Text>
            )}
            {type === 'UNCONFIRMED' && (
              <Text size="s" color="textLight" style={styles.primary}>
                {t('Unverified')}
              </Text>
            )}
          </View>
          {type !== 'PRIMARY' &&
            (deleteEmailLoading ? (
              <ActivityIndicator />
            ) : (
              <TouchableOpacity
                onPress={onPressMoreVert}
                hitSlop={{ top: 15, bottom: 15, left: 15, right: 15 }}
              >
                <Icon name="MoreVert" color={colors.textLighter} />
              </TouchableOpacity>
            ))}
        </View>
        <Divider />
      </>
      {!ios && (
        <Modal visible={showOptions} animationType="fade" transparent={true}>
          <TouchableWithoutFeedback onPressOut={() => setShowOptions(false)}>
            <View style={styles.androidModalContainer}>
              {type === 'SECONDARY' && (
                <TouchableOpacity
                  style={styles.buttonContainer}
                  onPress={onSetPrimaryEmail}
                >
                  <Text style={styles.text} color="pureBlack" size="s">
                    {t('Set as primary')}
                  </Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity
                style={styles.buttonContainer}
                onPress={showAlert}
              >
                <Text style={styles.text} color="error" size="s">
                  {t('Delete')}
                </Text>
              </TouchableOpacity>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      )}
    </>
  );
}
Example #5
Source File: Notifications.tsx    From lexicon with MIT License 4 votes vote down vote up
export default function Notifications() {
  const styles = useStyles();
  const { colors } = useTheme();

  const ios = Platform.OS === 'ios';

  const { navigate } = useNavigation<StackNavProp<'Notifications'>>();

  const navToPostDetail = (postDetailParams: StackParamList['PostDetail']) => {
    navigate('PostDetail', postDetailParams);
  };

  const navToMessageDetail = (
    messageDetailParams: StackParamList['MessageDetail'],
  ) => {
    navigate('MessageDetail', messageDetailParams);
  };

  const navToUserInformation = (
    userInformationParams: StackParamList['UserInformation'],
  ) => {
    navigate('UserInformation', userInformationParams);
  };

  const [page, setPage] = useState<number>(1);
  const [isLoadMore, setIsLoadMore] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string>('');
  const [showMore, setShowMore] = useState<boolean>(false);
  const [loadMorePolicy, setLoadMorePolicy] = useState<boolean>(false);

  const { data, loading, error, refetch, fetchMore } = useNotification({
    variables: { page },
    onError: (error) => {
      setErrorMsg(errorHandler(error, true));
    },
    nextFetchPolicy: loadMorePolicy ? 'cache-first' : 'no-cache',
  });

  const { markAsRead, loading: markAsReadLoading } = useMarkRead({
    onError: () => {},
  });

  const { singleBadge } = useSingleBadge({
    onCompleted: () => {
      refetch({ page: 1 });
    },
  });

  const onRefresh = () => {
    refetch();
  };

  const onPressMore = () => {
    if (ios) {
      ActionSheetIOS.showActionSheetWithOptions(
        {
          options: ['Mark All as Read', 'Cancel'],
          cancelButtonIndex: 1,
        },
        async (btnIndex) => {
          if (btnIndex === 0) {
            await markAsRead();
            refetch({ page: 1 });
          }
        },
      );
    } else {
      setShowMore(true);
    }
  };

  let rawNotifications = data?.notification.notifications ?? [];
  let handledNotifications = notificationHandler(
    rawNotifications,
    navToPostDetail,
    navToMessageDetail,
    navToUserInformation,
  );

  useEffect(() => {
    if (
      data?.notification.totalRowsNotifications === handledNotifications.length
    ) {
      setIsLoadMore(false);
    } else {
      setIsLoadMore(true);
    }
  }, [data, handledNotifications]);

  if (error) {
    return <LoadingOrError message={errorMsg} />;
  }

  if (handledNotifications.length < 1) {
    if (loading) {
      return <LoadingOrError loading />;
    }
    return <LoadingOrError message={t('No Notifications available')} />;
  }

  const loadMore = () => {
    setLoadMorePolicy(true);
    if (!isLoadMore || loading) {
      return;
    }
    const nextPage = page + 1;
    fetchMore({
      variables: { page: nextPage },
    }).then(() => {
      setLoadMorePolicy(false);
      setPage(nextPage);
    });
  };

  const getItem = (data: Array<NotificationDataType>, index: number) =>
    data[index];

  const getItemCount = (data: Array<NotificationDataType>) => data.length;

  const getItemLayout = (data: NotificationDataType, index: number) => ({
    length: 78.7,
    offset: 78.7 * index,
    index,
  });

  const keyExtractor = ({ id }: NotificationDataType) => `notif-${id}`;

  function renderItem({ item }: { item: NotificationDataType }) {
    const {
      id,
      topicId,
      name,
      message,
      createdAt,
      hasIcon,
      seen,
      onPress,
    } = item;

    return (
      <NotificationItem
        name={name}
        message={message}
        createdAt={createdAt}
        isMessage={hasIcon}
        seen={seen}
        onPress={() => {
          if (item.badgeId) {
            onPress(item.badgeId);
            singleBadge({ variables: { id: item.badgeId } });
          } else {
            onPress(topicId);
            markAsRead({ variables: { notificationId: id } }).then(() =>
              refetch({ page: 1 }),
            );
          }
        }}
      />
    );
  }

  return (
    <>
      <SafeAreaView style={styles.container}>
        <CustomHeader
          title={t('Notifications')}
          rightIcon="More"
          onPressRight={onPressMore}
          isLoading={markAsReadLoading}
        />
        <VirtualizedList
          data={handledNotifications}
          refreshControl={
            <RefreshControl
              refreshing={loading}
              onRefresh={onRefresh}
              tintColor={colors.primary}
            />
          }
          getItem={getItem}
          getItemCount={getItemCount}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
          getItemLayout={getItemLayout}
          onEndReached={loadMore}
          ListFooterComponent={
            <FooterLoadingIndicator isHidden={!isLoadMore} />
          }
          style={styles.notificationContainer}
        />
      </SafeAreaView>
      <TouchableOpacity>
        {!ios && data && (
          <Modal visible={showMore} animationType="fade" transparent={true}>
            <TouchableWithoutFeedback onPressOut={() => setShowMore(false)}>
              <View style={styles.androidModalContainer}>
                <TouchableOpacity
                  style={styles.modalButtonContainer}
                  onPress={() => {
                    markAsRead().then(() => refetch({ page: 1 }));
                    setShowMore(false);
                  }}
                >
                  <Text style={styles.modalText} color="pureBlack" size="l">
                    {t('Mark All as Read')}
                  </Text>
                </TouchableOpacity>
              </View>
            </TouchableWithoutFeedback>
          </Modal>
        )}
      </TouchableOpacity>
    </>
  );
}