react-native#Modal TypeScript Examples

The following examples show how to use react-native#Modal. 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: FullScreenLoadingIndicator.tsx    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
_FullScreenLoadingIndicator: React.FC<FullScreenLoadingIndicatorProps> = (
  props,
) => {
  return (
    <Modal visible={props.visible} animationType="fade" transparent>
      <View style={_styles.container}>
        <View style={_styles.box}>
          <ActivityIndicator color={'white'} size="large" />
        </View>
      </View>
    </Modal>
  );
}
Example #2
Source File: ChangeLanguageModal.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
ChangeLanguageModal = ({ isVisible, toggleChangeLanguage }: Props) => {
  return (
    <Modal
      visible={isVisible}
      animationType="slide"
      transparent
      onRequestClose={() => toggleChangeLanguage(false)}
    >
      <View style={styles.container}>
        <HeaderButton type="close" onPress={() => toggleChangeLanguage(false)} />
        <ChangeLanguage toggleChangeLanguage={toggleChangeLanguage} />
      </View>

    </Modal>
  );
}
Example #3
Source File: MapModal.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
MapModal = () => {
  const dispatch = useDispatch();
  const {
    showMap: { visible, region, properties },
  } = useSelector<Store, GeneralReducer>(state => state.general);
  const {
    strings: {
      scanHome: { inDate, fromHour },
    },
  } = useSelector<Store, LocaleReducer>(state => state.locale);

  const [date, hour] = useMemo(() => {
    const time = moment(properties?.fromTime);
    return [time.format('DD.MM.YY'), time.format('HH:mm')];
  }, [properties?.fromTime]);

  return (
    <Modal visible={visible} animationType="slide">
      <HeaderButton type="close" onPress={() => dispatch({ type: HIDE_MAP_MODAL })} />

      <View style={styles.headerContainer}>
        <Icon source={require('../../../assets/main/exposuresSmall.png')} width={27} height={17} customStyles={styles.headerIcon} />
        <Text bold style={styles.place} numberOfLines={20}>{properties?.Place || ''}</Text>
        <Text style={styles.aroundTime}>{`${inDate} ${date} ${fromHour} ${hour}`}</Text>
      </View>

      <MapView
        style={styles.mapStyle}
        region={region}
      >
        <Marker
          coordinate={region}
          image={require('../../../assets/main/mapMarker.png')}
        />
      </MapView>

    </Modal>
  );
}
Example #4
Source File: ShowImageModal.tsx    From lexicon with MIT License 6 votes vote down vote up
export function ShowImageModal(props: Props) {
  const styles = useStyles();

  const { show, userImage, onPressCancel } = props;

  return (
    <Modal
      visible={show}
      presentationStyle="overFullScreen"
      transparent
      statusBarTranslucent
      onRequestClose={onPressCancel}
    >
      <View style={styles.modalContainer}>
        <StatusBar style={'light'} />
        <CachedImage
          isBackground
          source={userImage}
          style={styles.imageDetail}
          visible={show}
          setVisible={onPressCancel}
        />
      </View>
    </Modal>
  );
}
Example #5
Source File: ForceUpdate.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
ForceUpdate = ({ isVisible, shouldForce, strings: { forceUpdate: { title, subTitle, desc, dontForceDesc } } }: Props) => {
  const appStoreUrl = 'https://itunes.apple.com/us/app/id1503224314?ls=1&mt=8';
  const playStoreUrl = 'https://play.google.com/store/apps/details?id=com.hamagen';

  const closeModal = () => store().dispatch({ type: HIDE_FORCE_UPDATE });

  return (
    <Modal
      visible={isVisible}
      transparent
      animationType="slide"
      onRequestClose={shouldForce ? () => {} : closeModal}
    >
      <View style={styles.container}>
        {
          !shouldForce && (
            <HeaderButton type="close" onPress={closeModal} />
          )
        }

        <View style={{ alignItems: 'center' }}>
          <Text style={styles.title} bold>{title}</Text>
          <Text style={styles.subTitle} bold>{subTitle}</Text>
          <Text style={styles.text}>{shouldForce ? desc : dontForceDesc}</Text>
        </View>

        <ActionButton text={title} onPress={() => Linking.openURL(IS_IOS ? appStoreUrl : playStoreUrl)} />
      </View>
    </Modal>
  );
}
Example #6
Source File: GeneralWebview.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
GeneralWebview = ({ isVisible, locale, externalUrls, closeWebview, usageType }: Props) => {
  return (
    <Modal
      visible={isVisible}
      transparent
      animationType="slide"
      onRequestClose={closeWebview}
    >
      <View style={styles.container}>
        <WebviewHeader closeModal={closeWebview} />

        <WebView
          style={{ flex: 1 }}
          source={{ uri: usageType === USAGE_PRIVACY ? externalUrls.privacyTerms[locale] : externalUrls.usageTerms[locale] }}
          startInLoadingState
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          allowsBackForwardNavigationGestures
          allowsInlineMediaPlayback
        />
      </View>
    </Modal>
  );
}
Example #7
Source File: GoogleTimeLine.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
FetchHistoryModal = ({ isVisible, isLoggedIn, webViewRef, onMessage, closeModal }: FetchHistoryModalProps) => {
  return (
    <Modal
      visible={isVisible}
      animationType="slide"
      onRequestClose={isLoggedIn ? () => { } : closeModal}
    >
      <View style={styles.container}>
        <WebviewHeader hideClose={isLoggedIn} closeModal={closeModal} />

        <WebView
          style={{ flex: 1, width: SCREEN_WIDTH }}
          ref={webViewRef}
          source={{ uri: 'https://accounts.google.com/signin/v2/identifier?service=accountsettings&flowName=GlifWebSignIn&flowEntry=ServiceLogin', }}
          startInLoadingState
          onMessage={onMessage}
          injectedJavaScript={`(function() {
            if(window.location.href.startsWith('https://myaccount.google.com/?utm_source=sign_in_no_continue')) {
                window.ReactNativeWebView.postMessage("LOGGED_IN");
            }
            })();`
          }
          originWhitelist={['*']}
        />
      </View>
    </Modal>
  );
}
Example #8
Source File: Loader.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
Loader = ({ isVisible }: Props) => {
  return (
    <Modal
      visible={isVisible}
      animationType="fade"
      transparent
      onRequestClose={() => {}}
    >
      <View style={styles.backdrop}>
        <ActivityIndicator size="large" />
      </View>
    </Modal>
  );
}
Example #9
Source File: ThemeSelectorModal.tsx    From natds-rn with ISC License 6 votes vote down vote up
ThemeSelectorModal = ({
  modalVisible, themeNames, activeTheme, changeTheme, setModalVisible
}) => (
  <Modal animationType="slide" visible={modalVisible}>
    <ModalContainer>
      <Title>Available Themes:</Title>
      <View style={{ width: '100%' }}>
        {
          themeNames.map((themeName, index) => (
            <SwitchWithLabel
              key={index.toString()}
              onChange={() => changeTheme(themeName)}
              isLast={index === themeNames.length - 1}
              label={themeName}
              isActive={activeTheme === themeName}
            />
          ))
        }
      </View>
      <View style={{ marginTop: 20, width: '100%' }}>
        <Button onPress={() => setModalVisible(!modalVisible)} text="Close" />
      </View>
    </ModalContainer>
  </Modal>
)
Example #10
Source File: DatePicker.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
ModalWrapper = ({labelDict, children, selectedDate, buttonText}: ModalWrapperProps) => {
  const {data, toggleModal} = useContext(FormContext);
  return (
    <>
      <Modal animationType="slide" transparent visible={data.modalVisible}>
        <Box style={styles.centeredView}>
          <Box style={styles.iosPicker}>
            {children}
            <Button
              variant="text"
              onPress={() => {
                toggleModal(false);
              }}
              text={buttonText}
            />
          </Box>
        </Box>
      </Modal>
      <ButtonSelect
        variant="buttonSelect"
        iconName="icon-down-arrow"
        onPress={() => {
          toggleModal(true);
        }}
        text={`${labelDict[selectedDate]}`}
      />
    </>
  );
}
Example #11
Source File: ImageModal.tsx    From sellflow with MIT License 6 votes vote down vote up
export default function ImageModal(props: Props) {
  let { activeIndex, images, isVisible, setVisible } = props;
  let { isRTL } = useTheme();
  let imagesUrls = images.map((url) => ({ url }));

  let renderHeader = () => (
    <IconButton
      icon={isRTL ? 'chevron-right' : 'chevron-left'}
      color={COLORS.white}
      size={35}
      onPress={() => setVisible(false)}
      style={styles.headerIcon}
    />
  );

  return (
    <Modal
      visible={isVisible}
      transparent={true}
      onDismiss={() => setVisible(false)}
    >
      <ImageViewer
        index={activeIndex}
        imageUrls={imagesUrls}
        enableSwipeDown
        onSwipeDown={() => setVisible(false)}
        renderHeader={renderHeader}
        useNativeDriver={true}
      />
    </Modal>
  );
}
Example #12
Source File: DefaultOverlay.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
DefaultOverlay = (
  props: React.PropsWithChildren<DefaultOverlayProps>,
) => {
  const {modalProps, children, text, textStyle, theme} = props;
  return (
    <View style={styles.centeredView}>
      <Modal
        animationType="fade"
        transparent
        statusBarTranslucent
        {...modalProps}>
        <View style={styles.container}>
          <View style={styles.background}>
            {children === undefined ? <Spinner /> : children}
            <View style={[styles.textContainer]}>
              {text === undefined ? null : (
                <Text style={[{top: theme.spacing * 10}, textStyle]}>
                  {text}
                </Text>
              )}
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}
Example #13
Source File: Webview.tsx    From wuhan2020-frontend-react-native-app with MIT License 5 votes vote down vote up
function WebViewModal({
  uri,
  title,
  visible,
  onClose,
}: {
  uri: string;
  title: string;
  visible: boolean;
  onClose: () => void;
}) {
  const [loadingWebview, setLoading] = useState(true);

  return (
    <Modal
      animationType="fade"
      presentationStyle="pageSheet"
      visible={visible}
      onDismiss={onClose}
      onRequestClose={onClose}>
      <View style={{ padding: 16, justifyContent: 'space-between' }}>
        <View style={{ height: height - 150 }}>
          <H1 title={title} />
          {loadingWebview ? (
            <View style={{ paddingVertical: 20 }}>
              <Loader />
            </View>
          ) : null}
          <WebView
            onLoad={() => setLoading(true)}
            onLoadEnd={() => setLoading(false)}
            source={{ uri }}
          />
        </View>
        <View>
          <Button
            buttonStyle={styles.button}
            title="关闭预览"
            onPress={onClose}
          />
        </View>
      </View>
    </Modal>
  );
}
Example #14
Source File: ActionSheet.tsx    From lexicon with MIT License 5 votes vote down vote up
export function ActionSheet(props: Props) {
  const styles = useStyles();

  const {
    options,
    cancelButtonIndex,
    actionItemOnPress,
    onClose,
    visible,
    animationType = 'none',
    transparent = true,
    style,
    ...otherProps
  } = props;

  //reorder cancel item
  const cancelOption =
    cancelButtonIndex != null && options.splice(cancelButtonIndex, 1);
  cancelOption && options.push(cancelOption[0]);

  const firstItemIndex = 0;
  const lastItemNoCancelIndex = options.length - (!cancelOption ? 1 : 2);
  const lastItemIndex = cancelOption ? options.length - 1 : -1;

  return (
    <Modal
      visible={visible}
      animationType={animationType}
      transparent={transparent}
      {...otherProps}
    >
      <TouchableWithoutFeedback onPressOut={onClose}>
        <SafeAreaView style={[styles.container, style]}>
          {options.map(({ label, disabled }, index) => (
            <ActionSheetItem
              key={`actionItem-${index}`}
              label={label}
              disabled={disabled}
              onPress={() => {
                !disabled && actionItemOnPress(index);
                !disabled && onClose();
              }}
              isTop={index === firstItemIndex}
              isBottom={index === lastItemNoCancelIndex}
              isCancelOption={index === lastItemIndex}
            />
          ))}
        </SafeAreaView>
      </TouchableWithoutFeedback>
    </Modal>
  );
}
Example #15
Source File: LeaveRequestSuccess.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
render() {
    const {theme} = this.props;
    const mainView = (
      <View
        style={[
          {
            paddingBottom: theme.spacing * 5,
            paddingHorizontal: theme.spacing * 4,
          },
          styles.rootView,
        ]}>
        <View style={styles.contentView}>
          <View style={{paddingVertical: theme.spacing * 6}}>
            <Icon
              name={'check-circle-outline'}
              style={{
                fontSize: theme.typography.largeIconSize,
                color: theme.palette.secondary,
              }}
            />
          </View>
          <Text
            style={{
              color: theme.palette.secondary,
              fontSize: theme.typography.headerFontSize,
              paddingBottom: theme.spacing * 6,
            }}>
            {'Completed'}
          </Text>
          <Text style={styles.text}>
            {'Leave Request Has Been Successfully Submitted.'}
          </Text>
        </View>
        <View>
          <IconButton
            iconProps={{
              name: 'home',
              style: {
                color: theme.typography.secondaryColor,
                fontSize: theme.typography.largeIconSize,
              },
            }}
            buttonProps={{
              onPress: this.onPressHome,
              style: {backgroundColor: theme.palette.primary},
              rounded: true,
              large: true,
            }}
          />
        </View>
      </View>
    );
    return (
      <SafeAreaLayout>
        {Platform.OS === 'ios' ? (
          mainView
        ) : (
          <Modal
            animationType="fade"
            statusBarTranslucent
            visible={true}
            onRequestClose={this.onRequestClose}>
            {mainView}
          </Modal>
        )}
      </SafeAreaLayout>
    );
  }
Example #16
Source File: Hospital.tsx    From wuhan2020-frontend-react-native-app with MIT License 5 votes vote down vote up
function Hospital({ item }: PropTypes) {
  const { supplies } = item;
  const [visible, setVisible] = useState(false);
  return (
    <Card title={item.name}>
      <View style={styles.subtitleContainer}>
        <Text style={[styles.subtitle, { fontSize: 14 }]}>
          {item.city} - {item.province || ''}
        </Text>
        <Text style={styles.subtitle}>{item.district}</Text>
      </View>
      <View style={styles.supplyContainer}>
        <View>
          {supplies.slice(0, 3).map(supply => (
            <Supply item={supply} />
          ))}
          {supplies.length - 3 > 0 ? (
            <Text style={styles.supplyInfo}>
              +{supplies.length - 3}项其他物资
            </Text>
          ) : null}
        </View>
      </View>
      <View style={{ paddingHorizontal: 30, paddingTop: 10 }}>
        <Button
          type="outline"
          title="查看详情"
          onPress={() => setVisible(true)}
        />
        <Modal
          animationType="fade"
          presentationStyle="formSheet"
          transparent={false}
          onDismiss={() => {
            setVisible(false);
          }}
          onRequestClose={() => {
            setVisible(false);
          }}
          visible={visible}>
          <View style={{ padding: 16, justifyContent: 'space-between' }}>
            <View style={{ height: height - 150 }}>
              <HospitalDetail item={item} />
            </View>
            <View>
              <Button
                title="关闭详情"
                onPress={() => {
                  setVisible(false);
                }}
              />
            </View>
          </View>
        </Modal>
      </View>
    </Card>
  );
}
Example #17
Source File: Product.component.tsx    From react-native-woocommerce with MIT License 5 votes vote down vote up
render(): JSX.Element {
      const {
        product: { name, images, description, price, average_rating: rating },
        imagesShown,
        handleShowImages,
      } = this.props;

      return (
        <View style={styles.wrapper}>
          <Carousel
            ref={this._setCarousel}
            sliderWidth={screenWidth}
            sliderHeight={screenWidth}
            itemWidth={screenWidth - 60}
            data={this._mapImages(images)}
            renderItem={this._renderImageItem(handleShowImages)}
            hasParallaxImages
          />
          <View style={styles.detail}>
            <Text style={styles.textTitle}>{name}</Text>
            <Text style={styles.textPrice}>{toAmount(price)}</Text>
            <HTML
              html={description}
              textSelectable
            />
            <View style={styles.rating}>
              <Text style={styles.textSubHeading}>Rating:</Text>
              <Text style={styles.textRating}>{rating}</Text>
              <Rating
                readonly
                imageSize={20}
                startingValue={Number(rating)}
              />
            </View>
          </View>
          <Modal visible={imagesShown} transparent>
            {this._renderImages(images, handleShowImages)}
          </Modal>
        </View>
      );
    }
Example #18
Source File: News.tsx    From wuhan2020-frontend-react-native-app with MIT License 5 votes vote down vote up
function Entry(props: EntryPropsType) {
  const [visible, setVisible] = useState(false);
  const [loadingWebview, setLoading] = useState(true);
  return (
    <View>
      <ListItem
        onPress={() => setVisible(true)}
        Component={TouchableOpacity}
        title={
          <Text style={{ fontWeight: '800' }}>
            {props.content.slice(0, 50)}
          </Text>
        }
        subtitle={
          <View
            style={{
              paddingTop: 4,
              flexDirection: 'row',
              justifyContent: 'space-between',
            }}>
            <Text style={{ fontSize: 12 }}>时间: {props.sendTime}</Text>
            <Text style={{ fontSize: 12 }}>来源: {props.fromName}</Text>
          </View>
        }
        rightIcon={{ name: 'unfold-more' }}
      />
      <Modal
        animationType="fade"
        presentationStyle="pageSheet"
        visible={visible}
        onDismiss={() => {
          setVisible(false);
        }}
        onRequestClose={() => {
          setVisible(false);
        }}>
        <View style={{ padding: 16, justifyContent: 'space-between' }}>
          <View style={{ height: height - 150 }}>
            {loadingWebview ? (
              <ActivityIndicator size="large" color="red" />
            ) : null}
            <WebView
              onLoad={() => setLoading(true)}
              onLoadEnd={() => setLoading(false)}
              source={{ uri: props.url }}
            />
          </View>
          <View>
            <Button
              buttonStyle={styles.button}
              title="关闭预览"
              onPress={() => {
                setVisible(false);
              }}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
}
Example #19
Source File: RecommendationList.tsx    From wuhan2020-frontend-react-native-app with MIT License 5 votes vote down vote up
function Entry(props: EntryPropsType) {
  const [visible, setVisible] = useState(false);
  const [loadingWebview, setLoading] = useState(true);

  return (
    <View>
      <ListItem
        onPress={() => setVisible(true)}
        Component={TouchableOpacity}
        title={<Text style={{ fontWeight: '800' }}>{props.title}</Text>}
        subtitle={
          <Text style={{ fontSize: 12, paddingTop: 3 }}>
            修改时间:
            {formatDate(props.modifyTime)} from {props.operator}
          </Text>
        }
        leftAvatar={{ source: { uri: props.imgUrl } }}
        rightIcon={{ name: 'unfold-more' }}
      />
      <Modal
        animationType="fade"
        presentationStyle="pageSheet"
        visible={visible}
        onDismiss={() => {
          setVisible(false);
        }}
        onRequestClose={() => {
          setVisible(false);
        }}>
        <View style={{ padding: 16, justifyContent: 'space-between' }}>
          {loadingWebview ? (
            <ActivityIndicator size="large" color="red" />
          ) : null}
          <View style={{ height: height - 150 }}>
            <WebView
              onLoad={() => setLoading(true)}
              onLoadEnd={() => setLoading(false)}
              source={{ uri: props.linkUrl }}
            />
          </View>
          <View>
            <Button
              buttonStyle={styles.button}
              title="关闭预览"
              onPress={() => {
                setVisible(false);
              }}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
}
Example #20
Source File: Timeline.tsx    From wuhan2020-frontend-react-native-app with MIT License 5 votes vote down vote up
function Entry(props: EntryPropsType) {
  const [visible, setVisible] = useState(false);
  return (
    <View>
      <ListItem
        onPress={() => setVisible(true)}
        Component={TouchableOpacity}
        title={<Text style={{ fontWeight: '800' }}>{props.title}</Text>}
        subtitle={`${props.summary.slice(0, 50)}...`}
        leftAvatar={
          <View>
            {props.latest ? (
              <Badge
                value="最新"
                status="error"
                textStyle={{ fontSize: 13, fontWeight: 'bold' }}
              />
            ) : null}
            <Text style={{ fontSize: 13, fontWeight: 'bold' }}>
              {props.pubDateStr}
            </Text>
            <Text style={{ fontSize: 12, color: '#717171' }}>
              {formatTime(props.modifyTime)}
            </Text>
          </View>
        }
        rightAvatar={
          <View style={{ justifyContent: 'flex-end', alignItems: 'flex-end' }}>
            <Text style={{ fontSize: 12, color: '#717171' }}>
              {props.infoSource}
            </Text>
          </View>
        }
      />
      <Modal
        animationType="fade"
        presentationStyle="pageSheet"
        visible={visible}
        onDismiss={() => {
          setVisible(false);
        }}
        onRequestClose={() => {
          setVisible(false);
        }}>
        <View style={{ padding: 16, justifyContent: 'space-between' }}>
          <View style={{ height: height - 150 }}>
            <Text
              style={{ fontSize: 20, fontWeight: 'bold', paddingBottom: 20 }}>
              {props.title}
            </Text>
            <Text style={{ fontSize: 16, lineHeight: 22 }}>
              {props.summary}
            </Text>

            <View style={{ alignSelf: 'flex-end', paddingTop: 20 }}>
              <Text style={{ fontWeight: '800' }}>
                新闻来源:{props.infoSource}
              </Text>
              <Text style={{ fontWeight: '800' }}>
                时间:{props.pubDateStr}
              </Text>
            </View>
          </View>

          <View>
            <Button
              buttonStyle={styles.button}
              title="关闭预览"
              onPress={() => {
                setVisible(false);
              }}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
}
Example #21
Source File: Detail.component.tsx    From RNWCShop with GNU General Public License v3.0 5 votes vote down vote up
render(): JSX.Element {
    const {
      product,
      imagesShown,
      handleShowImages,
      addToCart = () => {}
    } = this.props;
    const {
      name,
      images,
      description,
      price,
      average_rating: rating
    } = product;

    return (
      <ScrollView style={styles.wrapper}>
        <Carousel
          ref={this._setCarousel}
          sliderWidth={screenWidth}
          sliderHeight={screenWidth}
          itemWidth={screenWidth - 60}
          data={this._mapImages(images)}
          renderItem={this._renderImageItem(handleShowImages)}
          hasParallaxImages
        />
        <View style={styles.detail}>
          <Text style={styles.textTitle}>{name}</Text>
          <Text style={styles.textPrice}>{toAmount(price)}</Text>
          <HTML html={description} textSelectable />
          <View style={styles.rating}>
            <Text style={styles.textSubHeading}>Rating:</Text>
            <Text style={styles.textRating}>{rating}</Text>
            <Rating readonly imageSize={20} startingValue={Number(rating)} />
          </View>
          <Button
            icon={{
              name: 'cart-plus',
              type: 'font-awesome-5',
              color: 'white',
              size: 16
            }}
            title="Add to cart"
            onPress={(): void => addToCart(product)}
          />
        </View>
        <Modal visible={imagesShown} transparent>
          {this._renderImages(images, handleShowImages)}
        </Modal>
      </ScrollView>
    );
  }
Example #22
Source File: InfoModal.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
InfoModal = ({ strings, firstPointDate, closeModal, showModal }: InfoModalProps) => {
  const {
    scanHome: {
      noExposures: {
        infoModal: {
          textBodyPt1,
          textBodyPt2
        }
      }
    }
  } = strings;

  return (
    <Modal
      animationType="fade"
      onRequestClose={closeModal}
      visible={showModal}
    >
      <TouchableWithoutFeedback onPress={closeModal}>
        <ImageBackground
          resizeMode="cover"
          style={styles.imageContainer}
          source={require('../../../assets/main/infoModalBG.png')}
        >
          <View style={[styles.container]}>
            <TouchableOpacity style={styles.closeBtnContainer} hitSlop={HIT_SLOP} onPress={closeModal}>
              <Icon source={require('../../../assets/onboarding/close.png')} width={19} />
            </TouchableOpacity>
            <Icon
              source={require('../../../assets/main/moreInfoBig.png')}
              width={31}
              customStyles={styles.infoIcon}
            />
            <Text>
              <Text style={styles.infoText}>{textBodyPt1.trim()}</Text>
              <Text style={styles.infoText} bold>{` ${firstPointDate} `}</Text>
              <Text style={styles.infoText}>{textBodyPt2.trim()}</Text>
            </Text>
          </View>
        </ImageBackground>
      </TouchableWithoutFeedback>
    </Modal>
  );
}
Example #23
Source File: ForceTerms.tsx    From hamagen-react-native with MIT License 5 votes vote down vote up
ForceTerms = ({ isVisible, isRTL, strings, onSeeTerms, onApprovedTerms }: Props) => {
  const animRef = useRef<any>(null);
  const [isTOUAccepted, setIsTOUAccepted] = useState(false);

  const { forceTerms: { title, desc, approve } } = strings;

  const onPress = () => {
    if (!isTOUAccepted) {
      animRef.current.shake(1000);
    } else {
      onApprovedTerms();
    }
  };

  return (
    <Modal
      visible={isVisible}
      transparent
      animationType="slide"
      onRequestClose={() => {}}
    >
      <View style={styles.container}>
        <View style={{ alignItems: 'center' }}>
          <Icon source={require('../../assets/main/noData.png')} width={115} customStyles={{ marginBottom: 25 }} />
          <Text style={styles.title} bold>{title}</Text>
          <Text style={styles.text}>{desc}</Text>
        </View>

        <View style={{ alignItems: 'center' }}>
          <Animatable.View ref={animRef} style={{ marginBottom: 25 }}>
            <TermsOfUse
              isRTL={isRTL}
              strings={strings}
              value={isTOUAccepted}
              onValueSelected={value => setIsTOUAccepted(value)}
              toggleWebview={onSeeTerms}
            />
          </Animatable.View>

          <ActionButton text={approve} onPress={onPress} containerStyle={{ marginBottom: 20, opacity: isTOUAccepted ? 1 : 0.6 }} />
        </View>
      </View>
    </Modal>
  );
}
Example #24
Source File: AutoComplete.tsx    From react-native-paper-form-builder with MIT License 5 votes vote down vote up
function AutoComplete(props: AutoCompleteProps) {
  const {visible, setVisible, textInputProps, options, field} = props;
  const theme = useTheme();
  const styles = useMemo(
    () =>
      StyleSheet.create({
        containerStyle: {
          flex: 1,
        },
        searchStyle: {
          padding: 20,
        },
      }),
    [],
  );
  const [selectedValue, setSelectedValue] = useState(field.value);
  const [search, setSearch] = useState('');

  return (
    <Modal visible={visible} onDismiss={() => setVisible(false)}>
      <Surface style={styles.containerStyle}>
        <Appbar.Header>
          <Appbar.Action 
            testID={`${ props.textInputProps?.testID }Close`}
            icon={'close'}
            onPress={() => setVisible(false)} />
          <Appbar.Content title={textInputProps?.label} />
          <Appbar.Action
            testID={`${ props.textInputProps?.testID }Check`}
            icon={'check'}
            disabled={!selectedValue}
            onPress={() => {
              field.onChange(selectedValue);
              setVisible(false);
            }}
          />
        </Appbar.Header>
        <SafeAreaView style={styles.containerStyle}>
          <View style={styles.searchStyle}>
            <Searchbar
              testID={`${ props.textInputProps?.testID }SearchBar`}
              value={search}
              onChangeText={setSearch}
              placeholder={props.textInputProps?.placeholder ? props.textInputProps.placeholder : `Search ${ textInputProps?.label ?? "" }`}
            />
          </View>
          <FlatList
            data={options.filter(
              (option) =>
                option.label.toLowerCase().indexOf(search.toLowerCase()) !== -1,
            )}
            renderItem={({item}) => (
              <List.Item
                title={item.label}
                onPress={() => {
                  setSelectedValue(`${item.value}`);
                }}
                titleStyle={{
                  color:
                    `${item.value}` === selectedValue
                      ? theme.colors.primary
                      : theme.colors.text,
                }}
              />
            )}
            ItemSeparatorComponent={() => <Divider />}
            keyExtractor={(item) => `${item.value}`}
          />
        </SafeAreaView>
      </Surface>
    </Modal>
  );
}
Example #25
Source File: FullScreenLoadingIndicator.test.tsx    From rn-clean-architecture-template with MIT License 5 votes vote down vote up
it('test visible', () => {
  const props: FullScreenLoadingIndicatorProps = {
    visible: true,
  };
  const instance = renderer.create(<FullScreenLoadingIndicator {...props} />);
  expect(instance.root.findByType(Modal).props?.visible).toBeTruthy();
});
Example #26
Source File: SearchModal.tsx    From sellflow with MIT License 4 votes vote down vote up
export default function SearchModal(props: Props) {
  let [searchText, setSearchText] = useState('');
  let [debouncedSearchText, setDebouncedSearchtext] = useState('');
  let { isVisible, setVisible, onItemPress, onSubmit } = props;
  let { isRTL } = useTheme();

  let {
    searchProducts,
    results,
    loading: searchLoading,
  } = useSearchProductsQuery();
  let { data: recentSearch } = useGetRecentSearch();
  let { setRecentSearch } = useSetRecentSearch();
  let {
    data: { countryCode },
  } = useDefaultCountry();

  useEffect(() => {
    const timeout = setTimeout(() => {
      if (searchText !== '') {
        setDebouncedSearchtext(searchText);
      }
    }, 250);
    return () => clearTimeout(timeout);
  }, [searchText]);

  useEffect(() => {
    searchProducts({
      variables: {
        first: 10,
        searchText: debouncedSearchText,
        country: countryCode,
      },
    });
  }, [countryCode, debouncedSearchText, searchProducts]);

  let renderList = (props: {
    recent?: Array<Product>;
    results?: Array<Product>;
  }) => {
    let { recent, results } = props;

    let onClickRecent = (item: Product) => setSearchText(item.title);
    let onClickResult = (item: Product) => {
      onItemPress(item);
      setVisible(false);
    };

    return (
      <FlatList
        data={(recent && recent) || (results && results) || null}
        renderItem={({ item }) => {
          return (
            <TouchableOpacity
              onPress={() => {
                if (recent) {
                  onClickRecent(item);
                }
                if (results) {
                  onClickResult(item);
                }
              }}
            >
              <Text style={styles.searchResults}>{item.title}</Text>
            </TouchableOpacity>
          );
        }}
        keyExtractor={(_, index) => index.toString()}
      />
    );
  };

  return (
    <>
      <Modal
        visible={isVisible}
        animated={true}
        animationType="slide"
        onRequestClose={() => setVisible(false)}
      >
        <SafeAreaView style={styles.flex}>
          <View style={styles.searchInputContainer}>
            <IconButton
              icon={isRTL ? 'chevron-right' : 'chevron-left'}
              style={styles.closeIcon}
              color={COLORS.primaryColor}
              onPress={() => {
                setVisible(false);
                setSearchText('');
              }}
            />
            <SearchInput
              placeholder={t('Find by brand, category, etc.')}
              style={styles.searchInput}
              autoFocus={true}
              autoCapitalize="none"
              value={searchText}
              onChangeText={(value) => setSearchText(value)}
              onSubmitEditing={() => {
                if (searchText !== '') {
                  setRecentSearch({
                    variables: {
                      search: searchText,
                    },
                  });
                  setVisible(false);
                  onSubmit(searchText);
                  setSearchText('');
                }
              }}
            />
          </View>
          <View style={styles.searchResultList}>
            <Text style={styles.labelText}>
              {!searchText ? t('Recent Searches') : t('Search Results')}
            </Text>
            {searchLoading ? (
              <ActivityIndicator />
            ) : searchText !== '' ? (
              renderList({ results })
            ) : (
              renderList({ recent: recentSearch.recentSearch })
            )}
          </View>
        </SafeAreaView>
      </Modal>
    </>
  );
}
Example #27
Source File: FlutterwaveCheckout.tsx    From flutterwave-react-native with MIT License 4 votes vote down vote up
FlutterwaveCheckout: React.FC<FlutterwaveCheckoutProps> = function FlutterwaveCheckout(props) {
  const {link, visible, onRedirect, onAbort} = props;
  const [show, setShow] = React.useState<boolean>(false);
  const webviewRef = React.useRef<WebView | null>(null);
  const animation = React.useRef<Animated.Value>(new Animated.Value(0));

  const animateIn = React.useCallback(() => {
    setShow(true);
    Animated.timing(animation.current, {
      toValue: 1,
      duration: 700,
      easing: Easing.in(Easing.elastic(0.72)),
      useNativeDriver: false,
    }).start();
  }, []);

  const animateOut = React.useCallback((): Promise<void> => {
    return new Promise(resolve => {
      Animated.timing(animation.current, {
        toValue: 0,
        duration: 400,
        useNativeDriver: false,
      }).start(() => {
        setShow(false);
        resolve();
      });
    })
  }, []);

  const handleReload = React.useCallback(() => {
    if (webviewRef.current) {
      webviewRef.current.reload();
    }
  }, []);

  const handleAbort = React.useCallback((confirmed: boolean = false) => {
    if (!confirmed) {
      Alert.alert('', 'Are you sure you want to cancel this payment?', [
        {text: 'No'},
        {
          text: 'Yes, Cancel',
          style: 'destructive',
          onPress: () => handleAbort(true),
        },
      ]);
      return;
    }
    // remove tx_ref and dismiss
    animateOut().then(onAbort);
  }, [onAbort, animateOut]);

  const handleNavigationStateChange = React.useCallback((ev: WebViewNavigation): boolean => {
    // cregex to check if redirect has occured on completion/cancel
    const rx = /\/flutterwave\.com\/rn-redirect/;
    // Don't end payment if not redirected back
    if (!rx.test(ev.url)) {
      return true;
    }
    // dismiss modal
    animateOut().then(() => {
      if (onRedirect) {
        onRedirect(getRedirectParams(ev.url))
      }
    });
    return false;
  }, [onRedirect]);

  const doAnimate = React.useCallback(() => {
    if (visible === show) {
      return;
    }
    if (visible) {
      return animateIn();
    }
    animateOut().then(() => {});
  }, [visible, show, animateOut, animateIn]);

  React.useEffect(() => {
    doAnimate();
    return () => {};
  }, [doAnimate]);

  const marginTop = animation.current.interpolate({
    inputRange: [0, 1],
    outputRange: [windowHeight, 0],
  });
  const opacity = animation.current.interpolate({
    inputRange: [0, 0.3, 1],
    outputRange: [0, 1, 1],
  });

  return (
    <Modal
      transparent={true}
      animated={false}
      hardwareAccelerated={false}
      visible={show}>
      <FlutterwaveCheckoutBackdrop onPress={() => handleAbort()} animation={animation.current} />
      <Animated.View
        style={[
          styles.webviewContainer,
          {
            marginTop,
            opacity
          }
        ]}
        testID='flw-checkout-dialog'
      >
        <WebView
          ref={webviewRef}
          source={{uri: link || ''}}
          style={styles.webview}
          startInLoadingState={true}
          scalesPageToFit={true}
          javaScriptEnabled={true}
          onShouldStartLoadWithRequest={handleNavigationStateChange}
          renderError={() => <FlutterwaveCheckoutError hasLink={!!link} onTryAgain={handleReload} />}
          renderLoading={() => <FlutterwaveCheckoutLoader />}
        />
      </Animated.View>
    </Modal>
  )
}
Example #28
Source File: App.tsx    From SQL-Play with GNU Affero General Public License v3.0 4 votes vote down vote up
App: React.FC = () => {
  const [tableData, setTableData] = useState<tableDataNode>({
    header: [],
    rows: [[]],
  }); // header rows with value

  const tableWidths = useRef<Array<number>>([]);
  const [inputValue, setInputValue] = useState<string>(
    'SELECT * FROM employees',
  );
  const [loaderVisibility, setLoaderVisibility] = useState<boolean>(false);
  const [isPremium, setIsPremium] = useState<boolean>(false);
  const [premiumModalOpen, setPremiumModalOpen] = useState<boolean>(false);
  const {load, adLoaded} = useInterstitialAd(getInterstitialId(), adConfig);
  const styles = useDynamicValue(dynamicStyles);

  const showAd = async () => {
    if (!shouldShowAd()) return;

    if (adLoaded) return;
    try {
      load();
    } catch (error) {
      console.log('failed to load ad', error);
    }
  };

  const runQuery = async () => {
    Keyboard.dismiss();
    setLoaderVisibility(true);
    await insertUserCommand(inputValue); // store the command in db
    try {
      /** Show add if user is not premium */
      if (!isPremium) {
        showAd();
      }
      // execute the query
      const res: any = await ExecuteUserQuery(inputValue);

      const len: number = res.rows.length;

      // console.log(res.rows);
      if (len === 0) {
        setLoaderVisibility(false);
        Snackbar.show({text: 'Query Executed!'});
        return;
      }
      const header: string[] = Object.keys(res.rows.item(0)).reverse();
      const rowsArr: any[] = [];

      for (let i = 0; i < len; i++) {
        let row = res.rows.item(i);
        rowsArr.push(Object.values(row).reverse());
      }
      // pass the header and result arr to get the largest widths of their respective column
      tableWidths.current = await getLargestWidths([header, ...rowsArr]);
      // console.log(([header, ...rowsArr]));

      setLoaderVisibility(false);
      // console.log(rowsArr);

      setTableData({header: header, rows: rowsArr});
    } catch (error) {
      setLoaderVisibility(false);
      Alert.alert('Error in DB', error?.message);
    }
  };

  useEffect(() => {
    const init = async () => {
      const isPremRes = await getIsPremium();
      setIsPremium(isPremRes);
      // Setup ad only when user is not premium
      if (!isPremRes) {
      }
      await SplashScreen.hide({fade: true});
    };
    init();
    // return () => {};
  }, []);

  return (
    <ColorSchemeProvider>
      <BottomSheetModalProvider>
        <SafeAreaProvider>
          <StatusBar
            barStyle="dark-content"
            backgroundColor="#c8b900"
            translucent
          />
          <GoPremium
            modalState={premiumModalOpen}
            setModalState={setPremiumModalOpen}
            isPremium={isPremium}
            setIsPremium={setIsPremium}
          />
          <KeyboardAvoidingView
            style={{flex: 1}}
            {...(Platform.OS === 'ios' && {behavior: 'padding'})}
            keyboardVerticalOffset={Platform.select({
              ios: 0,
              android: 500,
            })}
          >
            <View style={styles.statusBar} />

            <Modal visible={loaderVisibility} transparent={true}>
              <View style={styles.modalStyle}>
                <ActivityIndicator size={50} color="gold" />
              </View>
            </Modal>
            <View testID="query-runner" style={styles.outerContainer}>
              <AppBar
                premiumModalOpen={premiumModalOpen}
                setPremiumModalOpen={setPremiumModalOpen}
                setInputValue={setInputValue}
                isPremium={isPremium}
                setIsPremium={setIsPremium}
              />
              <View style={styles.innercontainer}>
                <InputContainer
                  setPremiumModalOpen={setPremiumModalOpen}
                  inputValue={inputValue}
                  setInputValue={setInputValue}
                  isPremium={isPremium}
                />
                {!!tableData.header.length && (
                  <Table {...tableData} tableWidths={tableWidths} />
                )}
              </View>

              <RunButton runQuery={runQuery} />
            </View>
          </KeyboardAvoidingView>
        </SafeAreaProvider>
      </BottomSheetModalProvider>
    </ColorSchemeProvider>
  );
}
Example #29
Source File: GoPremium.tsx    From SQL-Play with GNU Affero General Public License v3.0 4 votes vote down vote up
GoPremium: FC<Props> = ({
  modalState,
  setModalState,
  setIsPremium,
  isPremium,
}) => {
  const [purchaseProcessing, setPurchaseProcessing] = useState(false);
  const [localizedPrice, setlocalizedPrice] = useState('');

  const getItems = async (): Promise<void> => {
    try {
      const result: boolean = await RNIap.initConnection();
      console.log('connection initialised', result);
      /** If there is no skus return here */
      if (!itemSkus) {
        return;
      }
      const products: Product[] = await RNIap.getProducts(itemSkus);
      console.log('Products', products);
      setlocalizedPrice(products[0].localizedPrice);

      purchaseUpdate = purchaseUpdatedListener(async purchase => {
        const receipt: string = purchase.transactionReceipt;
        if (receipt) {
          try {
            await finishTransaction(purchase);
            Alert.alert(
              'Purchase complete',
              'Thanks for purchasing, Now you can enjoy the premium benefits ',
            );
            /** make it affect on all app  */
            savePremium();
            setIsPremium(true);
            setPurchaseProcessing(false);
          } catch (ackErr) {
            console.warn('ackErr', ackErr);
          }
        }
      });

      purchaseError = purchaseErrorListener(error => {
        console.log('purchaseErrorListener', error);
        setPurchaseProcessing(false);
        // Alert.alert('purchase error', JSON.stringify(error.message));
      });
      // const consumed = await RNIap.consumeAllItemsAndroid();
      // console.log('consumed all items?', consumed);
    } catch (err) {
      console.log(err.code, err.message);
      setPurchaseProcessing(false);
    }
  };

  useEffect(() => {
    getItems();
    () => {
      //remove the listerners on component unmount
      return () => {
        if (purchaseUpdate) {
          purchaseUpdate.remove();
        }
        if (purchaseError) {
          purchaseError.remove();
        }
        RNIap.endConnection();
      };
    };
  }, []);

  const buyPremium = async (): Promise<void> => {
    try {
      if (!itemSkus) {
        return;
      }
      setPurchaseProcessing(true);
      await RNIap.requestPurchase(itemSkus[0]);
      console.log('Purchase success');
    } catch (err) {
      console.log(err.code, err.message);
    }
  };

  const handleRestore = async (): Promise<void> => {
    try {
      setPurchaseProcessing(true);
      const success = await restorePremium();
      if (success) {
        Alert.alert(
          'Purchase complete',
          'Thanks for purchasing, Now you can enjoy the premium benefits ',
        );

        setIsPremium(true);
      } else {
        Alert.alert('Failed to restore your purchase');
      }
      setPurchaseProcessing(false);
    } catch (error) {
      setPurchaseProcessing(false);
      console.log(error);
      Alert.alert('Failed to restore your purchase', error);
    }
  };
  return (
    <Modal
      visible={modalState}
      animationType="slide"
      presentationStyle="fullScreen"
      onRequestClose={() => setModalState(false)}
    >
      <ScrollView contentContainerStyle={{height: height}}>
        <SafeAreaView style={styles.container}>
          <View>
            <View style={styles.closeBtnContainer}>
              <Icon
                name="close"
                size={30}
                onPress={() => setModalState(false)}
              />
            </View>
            <View style={styles.header}>
              <Image
                style={styles.logo}
                accessibilityLabel="SQL Play premium logo"
                source={require('../images/sqlpro.png')}
              />
              <Text style={styles.title}>
                Go Premium to {'\n'}unlock all features
              </Text>
            </View>
            <Image
              style={styles.image}
              source={require('../images/autocomplete.png')}
              accessibilityLabel="Image of showing autocomplete"
              resizeMode="contain"
            />
            <View style={styles.featureTxtContainer}>
              <Icon name="check-decagram" color={darkYellow} size={24} />
              <Text style={styles.featureTxt}> Ads Free</Text>
            </View>
            <View style={styles.featureTxtContainer}>
              <Icon name="check-decagram" color={darkYellow} size={24} />
              <Text style={styles.featureTxt}> Export Tables</Text>
            </View>
            <View style={styles.featureTxtContainer}>
              <Icon name="check-decagram" color={darkYellow} size={24} />
              <Text style={styles.featureTxt}> Query History</Text>
            </View>
            <View style={styles.featureTxtContainer}>
              <Icon name="check-decagram" color={darkYellow} size={24} />
              <Text style={styles.featureTxt}> Autocomplete</Text>
            </View>
            <View style={styles.featureTxtContainer}>
              <Icon name="check-decagram" color={darkYellow} size={24} />
              <Text style={styles.featureTxt}> Swipe Gestures</Text>
            </View>
          </View>
          <View>
            <TouchableOpacity
              style={styles.buyBtn}
              onPress={buyPremium}
              disabled={isPremium}
            >
              {!purchaseProcessing ? (
                <Text style={styles.buyBtnTxt}>
                  {isPremium
                    ? 'Sweet! You have Premium'
                    : `Buy Now for ${localizedPrice}`}
                </Text>
              ) : (
                <View style={styles.loaderContainer}>
                  <ActivityIndicator color="#fcfcfc" />
                </View>
              )}
            </TouchableOpacity>
            {!isPremium && (
              <TouchableOpacity onPress={handleRestore}>
                <Text style={styles.restoreBtn}>Restore Purchase</Text>
              </TouchableOpacity>
            )}
          </View>
        </SafeAreaView>
      </ScrollView>
    </Modal>
  );
}