react-native#BackHandler JavaScript Examples

The following examples show how to use react-native#BackHandler. 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: Blocked.js    From InstagramClone with Apache License 2.0 6 votes vote down vote up
export default function Blocked() {
    useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', () => true)
        return () =>
            BackHandler.removeEventListener('hardwareBackPress', () => true)
    }, [])

    return (
        <View style={{ height: '100%' }}>

            <View style={{ justifyContent: 'center', alignItems: 'center', height: '90%' }}>

                <Feather name="stop-circle" size={150} color="red" style={{ position: 'absolute' }} />
                <Text style={[{ textAlign: 'center', paddingHorizontal: 40, fontSize: 20, marginTop: 400, width: '100%' }]}>Your account has been blocked</Text>

            </View>
        </View>
    )
}
Example #2
Source File: HandleBack.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
exitAlert = () => {
  Alert.alert(
    'Confirm exit',
    'Do you want to quit the app?'
    [
      {text: 'CANCEL',onPress: () =>{} ,style: 'cancel'},
      {text: 'OK', onPress: () => BackHandler.exitApp()}
    ]
  );
  return true
}
Example #3
Source File: ReduxNavigation.js    From gDoctor with MIT License 6 votes vote down vote up
componentDidMount () {
    if (Platform.OS === 'ios') return
    BackHandler.addEventListener('hardwareBackPress', () => {
      const { dispatch, nav } = this.props
      // change to whatever is your first screen, otherwise unpredictable results may occur
      if (nav.routes.length === 1 && (nav.routes[0].routeName === 'LaunchScreen')) {
        return false
      }
      // if (shouldCloseApp(nav)) return false
      dispatch({ type: 'Navigation/BACK' })
      return true
    })
  }
Example #4
Source File: LoggedIn.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
async componentDidMount() {
      this.intervalID = setInterval( () => {
        this.setState({
          hour : moment().format('hh:mm A'),
          day : moment().format('dddd'),
          monthYear : moment().format('D MMMM YYYY'),
        })
      },1000)
      this.requestLocationPermission();
      this.checkClockInStatus();
      this.checkSickSubmit();
      this.loadData();
      this.checkClockInDouble();
      this.loadDataDivision();
      this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.onBack);
    }
Example #5
Source File: GifSearch.js    From react-native-gif-search with ISC License 6 votes vote down vote up
componentDidMount() {
      this.refreshGifs()
      if (this.props.onBackPressed != null){
          BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
      }
      if (this.numColumns > 1) {   
          Dimensions.addEventListener('change', () => {
              this.setState({gifSize: Dimensions.get('window').width / this.numColumns - 15})
          })     
      }
  }
Example #6
Source File: AppNavigator.js    From haven with MIT License 6 votes vote down vote up
componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress');

    if (this.unsubscribeFromBranch) {
      this.unsubscribeFromBranch();
      this.unsubscribeFromBranch = null;
    }

    if (this.removeNotificationListener) {
      this.removeNotificationListener();
    }

    if (this.removeNotificationOpenedListener) {
      this.removeNotificationOpenedListener();
    }
  }
Example #7
Source File: GameHome.js    From FlappyFace with MIT License 6 votes vote down vote up
onExitApp() {
    SoundPlayer.playSoundFile('die', 'wav');
    Animated.timing(this.onLoad, {
      duration: 1000,
      toValue: 0,
      useNativeDriver: true,
    }).start(() => {
      Animated.timing(this.onPlay, {
        duration: 1000,
        toValue: -1,
        useNativeDriver: true,
      }).start(() => {
        BackHandler.exitApp();
      });
    });
  }
Example #8
Source File: ReduxNavigation.js    From Alfredo-Mobile with MIT License 6 votes vote down vote up
componentDidMount () {
    if (Platform.OS === 'ios') return
    BackHandler.addEventListener('hardwareBackPress', () => {
      const { dispatch, nav } = this.props
      // change to whatever is your first screen, otherwise unpredictable results may occur
      if (nav.routes.length === 1 && (nav.routes[0].routeName === 'LaunchScreen')) {
        return false
      }
      // if (shouldCloseApp(nav)) return false
      dispatch({ type: 'Navigation/BACK' })
      return true
    })
  }
Example #9
Source File: Meetings.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
componentDidMount(){
        BackHandler.addEventListener('hardwareBackPress', this.onBack);
      }
Example #10
Source File: index.js    From tcap-mobile with GNU General Public License v3.0 5 votes vote down vote up
componentWillUnmount() {
      BackHandler.removeEventListener('hardwareBackPress', this._handleBackButton);
  }
Example #11
Source File: ApprovalPage.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
componentWillUnmount() {
      BackHandler.removeEventListener('hardwareBackPress', this.onBack);
    }
Example #12
Source File: index.js    From tcap-mobile with GNU General Public License v3.0 5 votes vote down vote up
componentDidMount() {
      BackHandler.addEventListener('hardwareBackPress', this._handleBackButton);
      this.loadData();
  }
Example #13
Source File: ClockInHistory.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.onBack);
      }
Example #14
Source File: ExportMnemonicWordScreen.js    From RRWallet with MIT License 5 votes vote down vote up
componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.handleBackPress);
  }
Example #15
Source File: index.js    From bluezone-app with GNU General Public License v3.0 5 votes vote down vote up
componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onGoBack);
  }
Example #16
Source File: ReduxNavigation.js    From Alfredo-Mobile with MIT License 5 votes vote down vote up
componentWillUnmount () {
    if (Platform.OS === 'ios') return
    BackHandler.removeEventListener('hardwareBackPress', undefined)
  }
Example #17
Source File: AnnouncementDetails.js    From react-native-todolist with MIT License 5 votes vote down vote up
componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
    }
Example #18
Source File: ExportMnemonicWordScreen.js    From RRWallet with MIT License 5 votes vote down vote up
componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.handleBackPress);
  }
Example #19
Source File: ApprovalPage.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
async componentDidMount(){
      BackHandler.addEventListener('hardwareBackPress', this.onBack);
      this.loadData();  
    }
Example #20
Source File: GifSearch.js    From react-native-gif-search with ISC License 5 votes vote down vote up
componentWillUnmount() {
      if (this.props.onBackPressed != null){
          BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
      }
  }
Example #21
Source File: ReduxNavigation.js    From gDoctor with MIT License 5 votes vote down vote up
componentWillUnmount () {
    if (Platform.OS === 'ios') return
    BackHandler.removeEventListener('hardwareBackPress', undefined)
  }
Example #22
Source File: tools.js    From lx-music-mobile with Apache License 2.0 5 votes vote down vote up
exitApp = BackHandler.exitApp
Example #23
Source File: index.js    From bluezone-app with GNU General Public License v3.0 5 votes vote down vote up
componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onGoBack);
  }
Example #24
Source File: HandleBack.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
removeAndroidBackButtonHandler = () => {
  BackHandler.removeEventListener('hardwareBackPress', () => {});
}
Example #25
Source File: GridImageViewer.js    From react-native-grid-image-viewer with MIT License 4 votes vote down vote up
GridImageView = ({
  data,
  headers = null,
  renderGridImage = null,
  renderModalImage = null,
  transparent = 0.8,
  heightOfGridImage = Dimensions.get('window').height / 5.5,
}) => {
  const [modal, setModal] = useState({visible: false, data: 0});
  const ref = useRef();
  var key = 0;

  const {StatusBarManager} = NativeModules;
  const STATUSBAR_HEIGHT =
    Platform.OS === 'ios' ? 20 : StatusBarManager.HEIGHT - 20;
  const [height, setHeight] = useState(STATUSBAR_HEIGHT);

  const onCloseModal = () => {
    setModal({visible: false, data: 0});
  };

  useEffect(() => {
    if (Platform.OS === 'ios') {
      StatusBarManager.getHeight((statusBarHeight) => {
        setHeight(statusBarHeight.height);
      });
    }
    BackHandler.addEventListener('hardwareBackPress', onCloseModal);
    return () => {
      BackHandler.removeEventListener('hardwareBackPress', onCloseModal);
    };
  }, []);

  const Component = ({style = {flex: 1}}) => {
    return (
      <ScrollView
        showsHorizontalScrollIndicator={false}
        ref={ref}
        style={{...style}}
        snapToInterval={Dimensions.get('window').width}
        decelerationRate="fast"
        pagingEnabled
        horizontal>
        {data.map((item, key) => (
          <View key={key}>
            {renderModalImage !== null ? (
              renderModalImage(item, {
                ...styles.img_modal,
                backgroundColor: `rgba(0, 0, 0, ${transparent})`,
              })
            ) : (
              <Image
                style={{
                  ...styles.img_modal,
                  backgroundColor: `rgba(0, 0, 0, ${transparent})`,
                }}
                source={{
                  uri: item,
                  ...(headers == null || headers == undefined || headers == {}
                    ? {}
                    : {method: 'POST', headers}),
                }}
              />
            )}
          </View>
        ))}
      </ScrollView>
    );
  };

  return (
    <View style={styles.background}>
      <Modal
        // propagateSwipe={true}
        animationType="slide"
        transparent={true}
        visible={modal.visible}
        onRequestClose={onCloseModal}>
        <Component />

        <View style={{...styles.cross, top: height + 5}}>
          <TouchableOpacity
            onPress={() => {
              setModal({visible: false, data: 0});
            }}>
            <Cross />
          </TouchableOpacity>
        </View>
      </Modal>

      <FlatList
        contentContainerStyle={{paddingBottom: 40}}
        data={data}
        renderItem={({index}) => {
          if (data.length <= index * 3) {
            return null;
          }
          return (
            <View style={styles.unit}>
              <View style={[styles.unit_item, {height: heightOfGridImage}]}>
                {data.length > index * 3 ? (
                  <TouchableOpacity
                    onPress={() => {
                      setModal({visible: true, data: index * 3});

                      setTimeout(() => {
                        ref.current.scrollTo({
                          x: Dimensions.get('window').width * index * 3,
                          y: 0,
                          animated: false,
                        });
                      }, 1);
                    }}
                    style={[styles.unit_item, {height: heightOfGridImage}]}>
                    {renderGridImage !== null ? (
                      renderGridImage(data[index * 3], styles.img)
                    ) : (
                      <Image
                        style={styles.img}
                        source={{
                          uri: data[index * 3],
                          ...(headers == null ||
                          headers == undefined ||
                          headers == {}
                            ? {}
                            : {method: 'POST', headers}),
                        }}
                      />
                    )}
                  </TouchableOpacity>
                ) : null}
              </View>
              <View style={[styles.unit_item, {height: heightOfGridImage}]}>
                {data.length > index * 3 + 1 ? (
                  <TouchableOpacity
                    onPress={() => {
                      setModal({visible: true, data: index * 3 + 1});

                      setTimeout(() => {
                        ref.current.scrollTo({
                          x: Dimensions.get('window').width * (index * 3 + 1),
                          y: 0,
                          animated: false,
                        });
                      }, 1);
                    }}
                    style={[styles.unit_item, {height: heightOfGridImage}]}>
                    {renderGridImage !== null ? (
                      renderGridImage(data[index * 3 + 1], styles.img)
                    ) : (
                      <Image
                        style={styles.img}
                        source={{
                          uri: data[index * 3 + 1],
                          ...(headers == null ||
                          headers == undefined ||
                          headers == {}
                            ? {}
                            : {method: 'POST', headers}),
                        }}
                      />
                    )}
                  </TouchableOpacity>
                ) : null}
              </View>
              <View style={[styles.unit_item, {height: heightOfGridImage}]}>
                {data.length > index * 3 + 2 ? (
                  <TouchableOpacity
                    onPress={() => {
                      setModal({visible: true, data: index * 3 + 2});

                      setTimeout(() => {
                        ref.current.scrollTo({
                          x: Dimensions.get('window').width * (index * 3 + 2),
                          y: 0,
                          animated: false,
                        });
                      }, 1);
                    }}
                    style={[styles.unit_item, {height: heightOfGridImage}]}>
                    {renderGridImage !== null ? (
                      renderGridImage(data[index * 3 + 2], styles.img)
                    ) : (
                      <Image
                        style={styles.img}
                        source={{
                          uri: data[index * 3 + 2],
                          ...(headers == null ||
                          headers == undefined ||
                          headers == {}
                            ? {}
                            : {method: 'POST', headers}),
                        }}
                      />
                    )}
                  </TouchableOpacity>
                ) : null}
              </View>
            </View>
          );
        }}
        keyExtractor={(item) => {
          key++;
          return key.toString();
        }}
        style={styles.flatlist}
      />
    </View>
  );
}
Example #26
Source File: Bookmarks.js    From Turbo-Browser with MIT License 4 votes vote down vote up
Bookmarks = ({ navigation, route }) => {
  
  const styleTypes = ['default','dark-content', 'light-content'];
  const [styleStatusBar, setStyleStatusBar] = useState(styleTypes[1]);

  const [rippleOverflow, setRippleOverflow] = useState(false);

  const [optionsAlertOpen, setOptionsAlertOpen] = useState(false);

  const [searchValue, setSearchValue] = useState("");
  const [filtereHistoryList, setFiltereHistoryList] = useState([null]);

  const [historyValue, setHistoryValue] = useState([null]);
  const [searchVisible, setSearchVisible] = useState(false);

  const lottieOpacity = useRef(new Animated.Value(1)).current;

  const showToast = () => {
    ToastAndroid.show("Bookmarks cleared", ToastAndroid.SHORT);
  };

  const se1 = () => {
    navigation.goBack();
  }

  const se2 = () => {
    navigation.navigate('Incognito', { name: "Incognito" });
  }

  const se3 = () => {
    navigation.navigate('Home', { name: "Home" });
  }

  const se4 = async () => {
    try {
      await AsyncStorage.removeItem("bookmarksKey");
      setHistoryValue([null]);
      setTimeout(() => {
        Animated.timing(
          lottieOpacity,
          {
            toValue: 0,
            duration: 10,
            useNativeDriver: true,
          }
        ).start();
        setTimeout(() => {
          Animated.timing(
            lottieOpacity,
            {
              toValue: 1,
              duration: 400,
              useNativeDriver: true,
            }
          ).start();
        }, 20);
      }, 100);
    } catch (error) {
      // error
    }
    showToast();
  }

  const se5 = () => {
    setOptionsAlertOpen(true);
  }

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeListener("keyboardDidShow", _keyboardDidShow);
      Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
    };
  }, []);

  const _keyboardDidShow = () => {
    Animated.timing(
      lottieOpacity,
      {
        toValue: 0,
        duration: 10,
        useNativeDriver: true,
      }
    ).start();
  };

  const _keyboardDidHide = () => {
    setSearchValue("");
    setTimeout(() => {
      Animated.timing(
        lottieOpacity,
        {
          toValue: 1,
          duration: 400,
          useNativeDriver: true,
        }
      ).start();
    }, 100);
  };

  function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr.filter(Boolean);
  }

  function filterByValue(array, string) {
    return array.filter(element => element.includes(string.toLowerCase()));
  }

  const getHistoryValue = async () => {
    try {
      const value = await AsyncStorage.getItem("bookmarksKey");
      if(value !== null) {
        setHistoryValue(remove_duplicates(value.split("~")));
      }
    } catch(error) {
      // error
    }
  }

  useEffect(() => {
    navigation.addListener('focus',
    () => {
      getHistoryValue();
    }
    );
  }, []);

  const openWebsite = (url) => {
    navigation.navigate('Search', { name: `turbo/${url}` });  
  }

  const searchSubmitted = (searchString) => {
    setSearchVisible(false);
  }

  useEffect(() => {
    setSearchValue(searchValue);
    if(historyValue[0] !== null) {
      setFiltereHistoryList(filterByValue(historyValue, searchValue));
    }
    // setFiltereHistoryList(filterByValue(historyValue, searchValue));
  }, [searchValue]);

  const onSearchChangeText = async (text) => {
    setSearchValue(text);
  }

  return (
    <SafeAreaView>
    <StatusBar backgroundColor="#ffffff" barStyle={styleStatusBar} />

    <Modal
      isOpen={optionsAlertOpen} 
      onClosed={() => {setOptionsAlertOpen(false)}} 
      style={[styles.modal, styles.modal8]} 
      position={"bottom"} 
      backdropPressToClose={true} 
      swipeToClose={false}
      backdropOpacity={0.2} 
      backButtonClose={true}
      coverScreen={true} 
      animationDuration={200}
    >
      <View style={styles.optionAlertCont_MAIN}>

        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('History', { name: "History" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              History
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('Settings', { name: "Bookmarks" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              Settings
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('Help', { name: "Bookmarks" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              FAQs
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1_B}>
          <TouchableOpacity onPress={() => {
            BackHandler.exitApp();
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              Exit App
            </Text>
          </TouchableOpacity>
        </View>

        <View style={styles.optionAlertCont_opt_icon_1}>
          <TouchableOpacity style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            paddingBottom: 10,
            marginBottom: 4,
          }} onPress={() => {setOptionsAlertOpen(false)}}>
            {/* <FontAwesome style={styles.optionAlertCont_opt_icon_2} name="chevron-down"/> */}
            <Image 
              source={require("../assets/arrowDown2.png")} 
              style={{
                height: 26,
                width: 26,
              }}
            />
          </TouchableOpacity>
        </View>
        
      </View>
    </Modal>

    <View style={styles.historyMainContainer}>

      <View style={styles.history_title_1}>
        {
          searchVisible ?
          <>
          <View style={styles.history1_INPUT_C}>
            <TextInput 
              style={{
                color: "#767474FE",
                fontSize: 16,
                fontFamily: "Helvetica",
                marginLeft: 20,
                flexGrow: 1,
                marginTop: -10,
                paddingTop: -10,
                marginBottom: -10,
                paddingBottom: -10,
                maxWidth: 240,
              }}
              value={searchValue}
              onChangeText={(text) => onSearchChangeText(text)}
              autoFocus={true}
              editable={searchVisible}
              onSubmitEditing={() => {searchSubmitted(searchValue)}}
              placeholderTextColor="#CECFCFFF"
              placeholder="Search Bookmarks"
            />
          </View>
          </>
          :
          <>
          <TouchableOpacity onPress={() => {navigation.goBack()}}>
          <View style={styles.history1_AA}>
            <IonicIcon name="arrow-back" style={styles.history_title_1A_icon}/>
          </View>
          </TouchableOpacity>
          <View style={styles.history1_BB}>
            <Text style={styles.history_title_1B_txt}>Bookmarks</Text>
          </View>
          </>
        }
        {
          searchVisible ?
          <>
          <TouchableOpacity onPress={() => {
          setSearchVisible(!searchVisible);
          }}>
            <View style={styles.history1_CC}>
              <IonicIcon name="close" style={styles.history_title_1C_icon}/>
            </View>
          </TouchableOpacity>
          </>
          :
          <>
          <TouchableOpacity onPress={() => {
          setSearchVisible(!searchVisible);
          }}>
            <View style={styles.history1_CC}>
              <IonicIcon name="search" style={styles.history_title_1C_icon}/>
            </View>
          </TouchableOpacity>
          </>
        }
      </View>
      <LinearGradient colors={['#EDEEEEFE', '#FFFFFFFF']} style={styles.linearGradient_1}></LinearGradient>

      <View style={styles.history_style_2}>

        {
          searchVisible ?
          <>
            {
              filtereHistoryList.map((value, index) => {
                return (
                  <View style={styles.his_s22_A} key={index}>
                    <TouchableNativeFeedback
                      background={TouchableNativeFeedback.Ripple("#BBB9B9FE", rippleOverflow)}
                      onPress={() => {
                        openWebsite(value);
                      }}
                    >
                      <View style={styles.his_s22_B}>
                        <Text style={styles.his_s22_C_TXT}>{value}</Text>
                      </View>
                    </TouchableNativeFeedback>
                  </View>
                )
              })
            }
          </>
          :
          <>
            {
              historyValue[0] == null ?
              <>
              <View style={styles.lottieViewContainer}>
              <Animated.View
                style={{
                  opacity: lottieOpacity
                }}
              >
              <LottieView
                  style={styles.lottieAnimation}
                  source={require('../assets/629-empty-box.json')}
                  autoSize={true}
                  autoPlay
                  loop
                />
                <Text style={styles.lottieText}>Your bookmarks appear here</Text>
                </Animated.View>
              </View>
              </>
              :
              <>
                {
                  historyValue.map((value, index) => {
                    return (
                      <View style={styles.his_s22_A} key={index}>
                        <TouchableNativeFeedback
                          background={TouchableNativeFeedback.Ripple("#BBB9B9FE", rippleOverflow)}
                          onPress={() => {
                            openWebsite(value);
                          }}
                        >
                          <View style={styles.his_s22_B}>
                            <Text style={styles.his_s22_C_TXT}>{value}</Text>
                          </View>
                        </TouchableNativeFeedback>
                      </View>
                    )
                  })
                }
              </>
            }
          </>
        }

      </View>

      <View style={styles.history_style_3}>

        <TouchableOpacity onPress={se1} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="arrow-back"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se2} style={styles.sea_3_item}>
          <View style={{
            display: "flex",
            alignItems: "center",
          }}>
            <Image style={styles.sea3__3_icon_img} source={require("../assets/incognito.png")} />
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se3} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="home-outline"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se4} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="trash-outline"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se5} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="grid-outline"/>
          </View>
        </TouchableOpacity>

      </View>
    
    </View>
    </SafeAreaView>
  );

}
Example #27
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
ForgetPwd = ({ navigation }) => {
    const [email, setEmail] = useState('')
    const [code, setCode] = useState('')
    const [token, setToken] = useState('')
    const [password, setPassword] = useState('')
    const [confirmPassword, setConfirmPassword] = useState('')
    const [slideIndex, setSlideIndex] = useState(0)
    const [showAlert, setShowAlert] = useState(false)
    const [showProgressBar, setShowProgressBar] = useState(false)

    const passwordInput = useRef()
    const swiper = useRef()

    useFocusEffect(
        useCallback(() => {
            BackHandler.addEventListener(
                'hardwareBackPress',
                goToPreviousScreen
            )

            return () =>
                BackHandler.removeEventListener(
                    'hardwareBackPress',
                    goToPreviousScreen
                )
        }, [slideIndex])
    )

    const showLoadingAlert = () => {
        setShowAlert(true)
        setShowProgressBar(true)
    }

    const goToPreviousScreen = () => {
        if (slideIndex === 0) {
            navigation.goBack()
            return true
        }
        const newSlideIndex = slideIndex - 1

        swiper.current.scrollToIndex({ index: newSlideIndex })
        setSlideIndex(newSlideIndex)

        return true
    }

    const goToNextScreen = () => {
        const newSlideIndex = slideIndex + 1

        swiper.current.scrollToIndex({ index: newSlideIndex })
        setSlideIndex(newSlideIndex)
    }

    const sendUserToken = async () => {
        showLoadingAlert()

        const response = await sendCode({ email })

        if (response.status === 200) {
            console.warn(response)
            goToNextScreen()
            setShowAlert(false)
        } else {
            console.warn(response)
            Alert.alert(
                translate('forgetPwd.invalidEmail'),
                translate('forgetPwd.tryAgain')
            )
            setShowAlert(false)
        }
    }

    const confirmUserToken = async () => {
        if (code === '') {
            Alert.alert(
                translate('getToken.errorMessages.verificationCodeBlank')
            )
            return
        }

        showLoadingAlert()

        const response = await confirmCode({ code })

        if (response.status === 200) {
            setToken(response.data.reset_password_token)
            goToNextScreen()
            setShowAlert(false)
        } else {
            Alert.alert(translate('getToken.invalidCode'))
            setShowAlert(false)
        }
    }

    const handleResetPassword = async () => {
        if (password.length < 8 || confirmPassword.length < 8) {
            Alert.alert(translate('changePwd.errorMessages.shortPwd'))
            return
        }

        showLoadingAlert()

        const reset = {
            reset_password_token: token,
            password,
            password_confirmation: confirmPassword,
        }

        const response = await resetPassword(reset)

        if (response.status === 200) {
            Alert.alert(translate('forgetPwd.passwordChanged'))
            setShowAlert(false)
            navigation.navigate('Login')
        } else {
            Alert.alert(
                translate('forgetPwd.differentsPass'),
                translate('forgetPwd.tryAgain')
            )
            setShowAlert(false)
        }
    }

    return (
        <>
            <SafeAreaView style={{ flex: 0, backgroundColor: '#5DD39E' }} />
            <GradientBackground>
                <KeyboardScrollView>
                    <SwiperFlatList
                        showPagination={false}
                        disableGesture
                        ref={swiper}
                    >
                        <ScreenView>
                            <PasswordIcon
                                height={scale(68)}
                                width={scale(68)}
                                fill='#ffffff'
                            />

                            <PageTitle>
                                {translate('forgetPwd.title')}
                            </PageTitle>

                            <LabelWrapper>
                                <TextLabel>
                                    {translate('forgetPwd.informEmail')}
                                </TextLabel>
                            </LabelWrapper>

                            <SnowInput
                                placeholder={translate('login.email')}
                                returnKeyType='next'
                                keyboardType='email-address'
                                maxLength={100}
                                onChangeText={(text) => setEmail(text)}
                                onSubmitEditing={() => sendUserToken()}
                            />

                            <Touch
                                onPress={() =>
                                    // console.warn(email)
                                    // goToNextScreen()
                                    sendUserToken()
                                }
                            >
                                <SnowButton>
                                    <Label>
                                        {translate('forgetPwd.sendButton')}
                                    </Label>
                                </SnowButton>
                            </Touch>
                        </ScreenView>

                        <ScreenView>
                            <PageTitle>{translate('getToken.title')}</PageTitle>

                            <LabelWrapper>
                                <TextLabel>
                                    {translate('getToken.verificationCodeSent')}
                                </TextLabel>
                            </LabelWrapper>

                            <LabelWrapper>
                                <TextLabel>
                                    {translate('getToken.spamCheckWarning')}
                                </TextLabel>
                            </LabelWrapper>

                            <SnowInput
                                placeholder={translate(
                                    'getToken.inputVerificationCode'
                                )}
                                autoCorrect={false}
                                maxLength={10}
                                onChangeText={(text) => setCode(text)}
                                onSubmitEditing={() => confirmUserToken()}
                            />

                            <Touch
                                onPress={() =>
                                    // goToNextScreen()
                                    confirmUserToken()
                                }
                            >
                                <SnowButton>
                                    <Label>
                                        {translate('getToken.confirm')}
                                    </Label>
                                </SnowButton>
                            </Touch>
                        </ScreenView>

                        <ScreenView>
                            <PageTitle>
                                {translate('changePwd.title')}
                            </PageTitle>

                            <SnowInput
                                placeholder={translate('changePwd.newPwd')}
                                autoCorrect={false}
                                secureTextEntry
                                returnKeyType='next'
                                maxLength={100}
                                onChangeText={(text) => setPassword(text)}
                                onSubmitEditing={() =>
                                    passwordInput.current.focus()
                                }
                            />

                            <SnowInput
                                placeholder={translate('changePwd.confirmPwd')}
                                autoCorrect={false}
                                secureTextEntry
                                returnKeyType='next'
                                maxLength={100}
                                ref={passwordInput}
                                onChangeText={(text) =>
                                    setConfirmPassword(text)
                                }
                                onSubmitEditing={() => handleResetPassword()}
                            />

                            <Touch
                                onPress={() =>
                                    // console.log(token)
                                    handleResetPassword()
                                }
                            >
                                <SnowButton>
                                    <Label>
                                        {translate('changePwd.changeButton')}
                                    </Label>
                                </SnowButton>
                            </Touch>
                        </ScreenView>
                    </SwiperFlatList>

                    <ButtonBack onPress={() => goToPreviousScreen()}>
                        <Feather
                            name='chevron-left'
                            size={scale(40)}
                            color='#ffffff'
                        />
                    </ButtonBack>
                </KeyboardScrollView>

                <CoolAlert
                    show={showAlert}
                    showProgress={showProgressBar}
                    title={
                        showProgressBar ? translate('getToken.loading') : null
                    }
                    closeOnTouchOutside={!showProgressBar}
                    closeOnHardwareBackPress={false}
                    showConfirmButton={!showProgressBar}
                />
            </GradientBackground>
        </>
    )
}
Example #28
Source File: History.js    From Turbo-Browser with MIT License 4 votes vote down vote up
History = ({ navigation, route }) => {
  
  const styleTypes = ['default','dark-content', 'light-content'];
  const [styleStatusBar, setStyleStatusBar] = useState(styleTypes[1]);

  const [rippleOverflow, setRippleOverflow] = useState(false);

  const [optionsAlertOpen, setOptionsAlertOpen] = useState(false);

  const [searchValue, setSearchValue] = useState("");
  const [filtereHistoryList, setFiltereHistoryList] = useState([null]);

  const [historyValue, setHistoryValue] = useState([null]);
  const [searchVisible, setSearchVisible] = useState(false);

  const lottieOpacity = useRef(new Animated.Value(1)).current;

  const showToast = () => {
    ToastAndroid.show("History cleared", ToastAndroid.SHORT);
  };

  const se1 = () => {
    navigation.goBack();
  }

  const se2 = () => {
    navigation.navigate('Incognito', { name: "Incognito" });
  }

  const se3 = () => {
    navigation.navigate('Home', { name: "Home" });
  }

  const se4 = async () => {
    try {
      await AsyncStorage.removeItem("historyKey");
      setHistoryValue([null]);
      setTimeout(() => {
        Animated.timing(
          lottieOpacity,
          {
            toValue: 0,
            duration: 10,
            useNativeDriver: true,
          }
        ).start();
        setTimeout(() => {
          Animated.timing(
            lottieOpacity,
            {
              toValue: 1,
              duration: 400,
              useNativeDriver: true,
            }
          ).start();
        }, 20);
      }, 100);
    } catch (error) {
      // error
    }
    showToast();
  }

  const se5 = () => {
    setOptionsAlertOpen(true);
  }

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeListener("keyboardDidShow", _keyboardDidShow);
      Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
    };
  }, []);

  const _keyboardDidShow = () => {
    Animated.timing(
      lottieOpacity,
      {
        toValue: 0,
        duration: 10,
        useNativeDriver: true,
      }
    ).start();
  };

  const _keyboardDidHide = () => {
    setSearchValue("");
    setTimeout(() => {
      Animated.timing(
        lottieOpacity,
        {
          toValue: 1,
          duration: 400,
          useNativeDriver: true,
        }
      ).start();
    }, 100);
  };

  function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr;
  }

  function filterByValue(array, string) {
    return array.filter(element => element.includes(string.toLowerCase()));
  }

  const getHistoryValue = async () => {
    try {
      const value = await AsyncStorage.getItem("historyKey");
      if(value !== null) {
        setHistoryValue(remove_duplicates(value.split("~")));
      }
    } catch(error) {
      // error
    }
  }

  useEffect(() => {
    navigation.addListener('focus',
    () => {
      getHistoryValue();
    }
    );
  }, []);

  const openWebsite = (url) => {
    navigation.navigate('Search', { name: `turbo/${url}` });  
  }

  const searchSubmitted = (searchString) => {
    setSearchVisible(false);
  }

  useEffect(() => {
    setSearchValue(searchValue);
    if(historyValue[0] !== null) {
      setFiltereHistoryList(filterByValue(historyValue, searchValue));
    }
    // setFiltereHistoryList(filterByValue(historyValue, searchValue));
  }, [searchValue]);

  const onSearchChangeText = async (text) => {
    setSearchValue(text);
  }

  return (
    <SafeAreaView>
    <StatusBar backgroundColor="#ffffff" barStyle={styleStatusBar} />

    <Modal
      isOpen={optionsAlertOpen} 
      onClosed={() => {setOptionsAlertOpen(false)}} 
      style={[styles.modal, styles.modal8]} 
      position={"bottom"} 
      backdropPressToClose={true} 
      swipeToClose={false}
      backdropOpacity={0.2} 
      backButtonClose={true}
      coverScreen={true} 
      animationDuration={200}
    >
      <View style={styles.optionAlertCont_MAIN}>

        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('Bookmarks', { name: "History" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              Bookmarks
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('Settings', { name: "History" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              Settings
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1}>
          <TouchableOpacity onPress={() => {
            setOptionsAlertOpen(false);
            navigation.navigate('Help', { name: "History" });
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              FAQs
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.optionAlertCont_opt_1_B}>
          <TouchableOpacity onPress={() => {
            BackHandler.exitApp();
          }}>
            <Text style={styles.optionAlertCont_optText_1}>
              Exit App
            </Text>
          </TouchableOpacity>
        </View>

        <View style={styles.optionAlertCont_opt_icon_1}>
          <TouchableOpacity style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            paddingBottom: 10,
            marginBottom: 4,
          }} onPress={() => {setOptionsAlertOpen(false)}}>
            {/* <FontAwesome style={styles.optionAlertCont_opt_icon_2} name="chevron-down"/> */}
            <Image 
              source={require("../assets/arrowDown2.png")} 
              style={{
                height: 26,
                width: 26,
              }}
            />
          </TouchableOpacity>
        </View>
        
      </View>
    </Modal>

    <View style={styles.historyMainContainer}>

      <View style={styles.history_title_1}>
        {
          searchVisible ?
          <>
          <View style={styles.history1_INPUT_C}>
            <TextInput 
              style={{
                color: "#767474FE",
                fontSize: 16,
                fontFamily: "Helvetica",
                marginLeft: 20,
                flexGrow: 1,
                marginTop: -10,
                paddingTop: -10,
                marginBottom: -10,
                paddingBottom: -10,
                maxWidth: 240,
              }}
              value={searchValue}
              onChangeText={(text) => onSearchChangeText(text)}
              autoFocus={true}
              editable={searchVisible}
              onSubmitEditing={() => {searchSubmitted(searchValue)}}
              placeholderTextColor="#CECFCFFF"
              placeholder="Search History"
            />
          </View>
          </>
          :
          <>
          <TouchableOpacity onPress={() => {navigation.goBack()}}>
          <View style={styles.history1_AA}>
            <IonicIcon name="arrow-back" style={styles.history_title_1A_icon}/>
          </View>
          </TouchableOpacity>
          <View style={styles.history1_BB}>
            <Text style={styles.history_title_1B_txt}>History</Text>
          </View>
          </>
        }
        {
          searchVisible ?
          <>
          <TouchableOpacity onPress={() => {
          setSearchVisible(!searchVisible);
          }}>
            <View style={styles.history1_CC}>
              <IonicIcon name="close" style={styles.history_title_1C_icon}/>
            </View>
          </TouchableOpacity>
          </>
          :
          <>
          <TouchableOpacity onPress={() => {
          setSearchVisible(!searchVisible);
          }}>
            <View style={styles.history1_CC}>
              <IonicIcon name="search" style={styles.history_title_1C_icon}/>
            </View>
          </TouchableOpacity>
          </>
        }
      </View>
      <LinearGradient colors={['#EDEEEEFE', '#FFFFFFFF']} style={styles.linearGradient_1}></LinearGradient>

      <View style={styles.history_style_2}>

        {
          searchVisible ?
          <>
            {
              filtereHistoryList.map((value, index) => {
                return (
                  <View style={styles.his_s22_A} key={index}>
                    <TouchableNativeFeedback
                      background={TouchableNativeFeedback.Ripple("#BBB9B9FE", rippleOverflow)}
                      onPress={() => {
                        openWebsite(value);
                      }}
                    >
                      <View style={styles.his_s22_B}>
                        <Text style={styles.his_s22_C_TXT}>{value}</Text>
                      </View>
                    </TouchableNativeFeedback>
                  </View>
                )
              })
            }
          </>
          :
          <>
            {
              historyValue[0] == null ?
              <>
              <View style={styles.lottieViewContainer}>
              <Animated.View
                style={{
                  opacity: lottieOpacity
                }}
              >
              <LottieView
                  style={styles.lottieAnimation}
                  source={require('../assets/629-empty-box.json')}
                  autoSize={true}
                  autoPlay
                  loop
                />
                <Text style={styles.lottieText}>Your browsing history appears here</Text>
                </Animated.View>
              </View>
              </>
              :
              <>
                {
                  historyValue.map((value, index) => {
                    return (
                      <View style={styles.his_s22_A} key={index}>
                        <TouchableNativeFeedback
                          background={TouchableNativeFeedback.Ripple("#BBB9B9FE", rippleOverflow)}
                          onPress={() => {
                            openWebsite(value);
                          }}
                        >
                          <View style={styles.his_s22_B}>
                            <Text style={styles.his_s22_C_TXT}>{value}</Text>
                          </View>
                        </TouchableNativeFeedback>
                      </View>
                    )
                  })
                }
              </>
            }
          </>
        }

        {/* <View style={styles.his_s22_A}>
          <TouchableNativeFeedback
            background={TouchableNativeFeedback.Ripple("#BBB9B9FE", rippleOverflow)}
            onPress={() => {
              openWebsite("https://github.com/lottie-react-native/lottie-react-native#readme");
            }}
          >
            <View style={styles.his_s22_B}>
              <Text style={styles.his_s22_C_TXT}>Hello world</Text>
            </View>
          </TouchableNativeFeedback>
        </View> */}

      </View>

      <View style={styles.history_style_3}>

        <TouchableOpacity onPress={se1} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="arrow-back"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se2} style={styles.sea_3_item}>
          <View style={{
            display: "flex",
            alignItems: "center",
          }}>
            <Image style={styles.sea3__3_icon_img} source={require("../assets/incognito.png")} />
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se3} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="home-outline"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se4} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="trash-outline"/>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={se5} style={styles.sea_3_item}>
          <View>
            <IonicIcon style={styles.sea3__3_icon} name="grid-outline"/>
          </View>
        </TouchableOpacity>

      </View>
    
    </View>
    </SafeAreaView>
  );

}
Example #29
Source File: BaseLayoutScreen.js    From geometry_3d with MIT License 4 votes vote down vote up
export default function BaseLayoutScreen(props) {
  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", () => true);
    return () =>
      BackHandler.removeEventListener("hardwareBackPress", () => true);
  }, []);
  const initShape = props.initShape;
  const params = props.params;
  THREE.suppressExpoWarnings(true);
  let savedState = null;
  if (params) {
    let currSavedState = {
      shapes: params.shapes,
      lines: params.lines,
      points: params.points,
      fileName: params.fileName,
    };
    savedState = currSavedState;
  }
  const [currPoints, setCurrPoints] = useState(null);
  const [currLines, setCurrLines] = useState(null);
  const [visible, setVisible] = useState(false);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [popUpComp, setPopUpComp] = useState(null);
  const [pointsConnect, setPointsConnect] = useState([]);

  const [signalPoints, setSignalPoints] = useState(false);
  const [signalShapes, setSignalShapes] = useState(false);
  const [signalEditPoints, setSignalEditPoints] = useState(false);

  const [action, setAction] = useState("");
  const [currShapes, setCurrShapes] = useState(null);
  const [shapesConnect, setShapesConnect] = useState([]);
  const [isFromShape, setIsFromShape] = useState(false);
  const [pointsEdit, setPointsEdit] = useState(null);

  const [showSettings, setShowSettings] = useState(false);

  const [camera, setCamera] = useState(null);

  const navigate = useNavigation();
  const getCam = (cam) => {
    setCamera(() => cam);
  };
  const getPoints = (listOfPoints) => {
    setCurrPoints(() => listOfPoints);
  };
  const getLines = (listOfLines) => {
    setCurrLines(() => listOfLines);
  };
  const getShapes = (listOfShapes) => {
    setCurrShapes(() => listOfShapes);
  };
  const connectPoints = (pointsToConnect) => {
    //setIsFromShape(() => false);
    setPointsConnect(() => pointsToConnect);
  };
  const connectShapes = (shapesToConnect) => {
    //setIsFromShape(() => true);
    setShapesConnect(() => shapesToConnect);
  };
  const editPoints = (pointsToEdit) => {
    //console.log(pointsToEdit.length);
    setPointsEdit(() => pointsToEdit);
  };
  const actions = [
    {
      text: "Add points",
      icon: require("../assets/cube.png"),
      name: "add_points",
      position: 1,
    },
    {
      text: "Remove points",
      icon: require("../assets/sphere.png"),
      name: "remove_points",
      position: 2,
    },
    {
      text: "Connect points",
      icon: require("../assets/cone.png"),
      name: "connect_points",
      position: 3,
    },
    {
      text: "Disconnect points",
      icon: require("../assets/octahedron.png"),
      name: "disconnect_points",
      position: 4,
    },
    {
      text: "Add shapes",
      icon: require("../assets/add_shape.png"),
      name: "add_shapes",
      position: 5,
    },
    {
      text: "Remove shapes",
      icon: require("../assets/more.png"),
      name: "remove_shapes",
      position: 6,
    },
    {
      text: "Settings",
      icon: require("../assets/misc_shapes.png"),
      name: "settings",
      position: 7,
    },
    {
      text: "Advanced settings",
      icon: require("../assets/connect_points.png"),
      name: "advanced_settings",
      position: 8,
    },
  ];
  const cards = {
    add_points: {
      component: (
        <EditPoints
          isAdd={true}
          currentPoints={currPoints ? currPoints : []}
          returnPoints={editPoints}
        />
      ),
      action: "add_points",
    },
    remove_points: {
      component: (
        <EditPoints
          isAdd={false}
          currentPoints={currPoints ? currPoints : []}
          returnPoints={editPoints}
        />
      ),
      action: "remove_points",
    },
    connect_points: {
      component: (
        <ControlPoints
          connect={true}
          currentPoints={currPoints ? currPoints : []}
          returnPoints={connectPoints}
        />
      ),
      action: "connect_points",
    },
    disconnect_points: {
      component: (
        <ControlPoints
          connect={false}
          currentPoints={currLines ? currLines : []}
          returnPoints={connectPoints}
        />
      ),
      action: "disconnect_points",
    },
    add_shapes: {
      component: (
        <ControlShapes
          add={true}
          currShapes={currShapes ? currShapes : []}
          returnShapes={connectShapes}
          currPoints={currPoints ? currPoints : []}
        />
      ),
      action: "add_shapes",
    },
    remove_shapes: {
      component: (
        <ControlShapes
          add={false}
          currShapes={currShapes ? currShapes : []}
          returnShapes={connectShapes}
          currPoints={[]}
        />
      ),
      action: "remove_shapes",
    },
    settings: {
      component: (
        <CameraSettings
          existingShapes={currShapes ? currShapes : []}
          camera={camera}
        />
      ),
      action: "settings",
    },
    advanced_settings: {
      component: null,
      action: "advanced_settings",
    },
  };
  const onPointsEditPopUpDone = () => {
    if (pointsEdit.length > 0) {
      setSignalEditPoints(() => !signalEditPoints);
      if (action === "add_points") {
        Toast.show({
          type: "success",
          position: "top",
          text1: `${pointsEdit.length} point(s) added`,
          text2: "Success",
          visibilityTime: 3000,
          autoHide: true,
        });
      } else if (action === "remove_points") {
        Toast.show({
          type: "success",
          position: "top",
          text1: `${pointsEdit.length} point(s) removed`,
          text2: "Success",
          visibilityTime: 3000,
          autoHide: true,
        });
      }
    } else {
      Toast.show({
        type: "error",
        position: "top",
        text1: "Not enough data",
        text2: "Please try again",
        visibilityTime: 3000,
        autoHide: true,
      });
    }
  };
  const onPointsPopUpDone = () => {
    if (pointsConnect.length >= 1 && action === "disconnect_points") {
      setSignalPoints(() => !signalPoints);
      Toast.show({
        type: "success",
        position: "top",
        text1: `${pointsConnect.length} line(s) disconnected`,
        text2: "Success",
        visibilityTime: 3000,
        autoHide: true,
      });
    } else if (pointsConnect.length <= 1) {
      Toast.show({
        type: "error",
        position: "top",
        text1: "Not enough data",
        text2: "Please try again",
        visibilityTime: 3000,
        autoHide: true,
      });
    } else {
      setSignalPoints(() => !signalPoints);
      Toast.show({
        type: "success",
        position: "top",
        text1: `${pointsConnect.length} points connected`,
        text2: "Success",
        visibilityTime: 3000,
        autoHide: true,
      });
    }
    //setPointsConnect(() => []);
  };
  const onShapesPopUpDone = () => {
    if (shapesConnect.length === 0) {
      Toast.show({
        type: "error",
        position: "top",
        text1: "Not enough data",
        text2: "Please try again",
        visibilityTime: 3000,
        autoHide: true,
      });
    } else {
      setSignalShapes(() => !signalShapes);
      Toast.show({
        type: "success",
        position: "top",
        text1: `${shapesConnect.length} shape(s) ${
          action === "add_shapes" ? "added" : "removed"
        }`,
        text2: "Success",
        visibilityTime: 3000,
        autoHide: true,
      });
    }
    //setShapesConnect(() => []);
  };
  const drawerContent = () => {
    return (
      <View style={{ flex: 1 }}>
        <View
          style={{
            width: SCREEN_WIDTH * 0.8 - 40,
            height: "100%",
            backgroundColor: "white",
          }}
        >
          <FlatList
            style={{
              marginHorizontal: 10,
              marginVertical: 5,
            }}
            keyboardShouldPersistTaps="handled"
            keyExtractor={(item, index) => `${index} side drawer`}
            showsVerticalScrollIndicator={false}
            data={actions}
            renderItem={({ index, item }) => (
              <TouchableOpacity
                key={index}
                style={{
                  alignContent: "center",
                  justifyContent: "center",
                  paddingHorizontal: 10,
                  paddingVertical: 20,
                  borderColor: "black",
                  borderWidth: 1,
                  borderRadius: 10,
                  margin: 5,
                  marginBottom: index === actions.length - 1 ? 50 : 5,
                }}
                onPress={() => {
                  const card = cards[item.name];
                  if (item.name === "settings") {
                  } else if (
                    item.name === "add_shapes" ||
                    item.name === "remove_shapes"
                  ) {
                    setIsFromShape(() => true);
                  } else {
                    setIsFromShape(() => false);
                  }
                  if (item.name === "advanced_settings") {
                    setShowSettings(() => true);
                    return;
                  }
                  setVisible(true);
                  setPointsConnect(() => []);
                  setAction(() => item.name);
                  setPopUpComp(card.component);
                }}
              >
                <Text
                  style={{
                    color: "black",
                  }}
                >
                  {item.text}
                </Text>
              </TouchableOpacity>
            )}
          />
        </View>
        <TouchableOpacity
          onPress={() => setIsMenuOpen(false)}
          style={{
            borderTopRightRadius: 20,
            borderBottomRightRadius: 20,
            justifyContent: "center",
            alignItems: "center",
            height: 40,
            width: 40,
            position: "absolute",
            right: 0,
            top: SCREEN_HEIGHT / 2 - 50,
            backgroundColor: "white",
          }}
        >
          <Ionicons name="ios-arrow-back" size={25} color="black" />
        </TouchableOpacity>
      </View>
    );
  };
  return (
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: "black",
      }}
    >
      <MenuDrawer
        open={isMenuOpen}
        drawerContent={drawerContent()}
        drawerPercentage={80}
        animationTime={100}
        overlay={true}
      >
        <TouchableOpacity
          style={{
            zIndex: 2,
            borderTopRightRadius: 20,
            borderBottomRightRadius: 20,
            justifyContent: "center",
            alignItems: "center",
            height: 40,
            width: 40,
            position: "absolute",
            left: 0,
            top: SCREEN_HEIGHT / 2 - 50,
            backgroundColor: "white",
          }}
          onPress={() => {
            setIsMenuOpen(true);
          }}
        >
          <Ionicons name="ios-arrow-forward" size={25} color="black" />
        </TouchableOpacity>
        <LayoutSetup
          getPointsCallback={getPoints}
          getLinesCallback={getLines}
          getShapesCallback={getShapes}
          getCam={getCam}
          pointsConnect={pointsConnect}
          shapesConnect={shapesConnect}
          pointsEdit={pointsEdit}
          signalPoints={signalPoints}
          signalShapes={signalShapes}
          signalEditPoints={signalEditPoints}
          action={action}
          savedState={savedState}
          initShape={initShape}
        />

        <Dialog
          visible={visible}
          dialogAnimation={
            new SlideAnimation({
              slideFrom: "bottom",
            })
          }
          width={SCREEN_WIDTH * 0.8}
          onHardwareBackPress={() => true}
          footer={
            <DialogFooter>
              <DialogButton
                text="CANCEL"
                onPress={() => {
                  setVisible(false);
                  setPopUpComp(null);
                }}
                textStyle={{
                  fontSize: 15,
                  color: "red",
                }}
              />
              <DialogButton
                text="DONE"
                onPress={() => {
                  setVisible(false);
                  if (!isFromShape) {
                    if (action === "settings") {
                    } else if (
                      (action === "remove_points" || action === "add_points") &&
                      pointsEdit
                    )
                      onPointsEditPopUpDone();
                    else if (pointsConnect) onPointsPopUpDone();
                  } else {
                    if (shapesConnect) onShapesPopUpDone();
                  }
                  setPopUpComp(null);
                }}
                textStyle={{
                  fontSize: 15,
                  color: "green",
                }}
              />
            </DialogFooter>
          }
        >
          {popUpComp}
        </Dialog>
        <TouchableOpacity
          style={styles.back}
          onPress={() =>
            navigate.navigate(
              "App",
              {},
              NavigationActions.navigate({
                routeName: params ? "Items" : "Home",
              })
            )
          }
        >
          <Ionicons name="ios-arrow-round-back" color="white" size={42} />
        </TouchableOpacity>

        <Modal visible={showSettings} animationType="slide">
          <View
            style={{
              flex: 1,
              paddingHorizontal: 10,
              paddingVertical: 10,
              backgroundColor: "white",
            }}
          >
            <TouchableOpacity
              style={styles.backModal}
              onPress={() => {
                setShowSettings(() => false);
              }}
            >
              <Ionicons name="ios-arrow-round-back" color="black" size={42} />
            </TouchableOpacity>
            <SettingModal currShapes={currShapes} currPoints={currPoints} />
          </View>
        </Modal>
      </MenuDrawer>
    </SafeAreaView>
  );
}