react-navigation#NavigationActions JavaScript Examples

The following examples show how to use react-navigation#NavigationActions. 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: ScreenTrackingMiddleware.js    From Alfredo-Mobile with MIT License 6 votes vote down vote up
screenTracking = ({ getState }) => next => (action) => {
  if (
    action.type !== NavigationActions.NAVIGATE &&
    action.type !== NavigationActions.BACK
  ) {
    return next(action)
  }

  const currentScreen = getCurrentRouteName(getState().nav)
  const result = next(action)
  const nextScreen = getCurrentRouteName(getState().nav)
  if (nextScreen !== currentScreen) {
    try {
      __DEV__ && console.tron.log(`NAVIGATING ${currentScreen} to ${nextScreen}`)
      // Example: Analytics.trackEvent('user_navigation', {currentScreen, nextScreen})
    } catch (e) {
      __DEV__ && console.tron.log(e)
    }
  }
  return result
}
Example #2
Source File: AppNavigator.js    From haven with MIT License 6 votes vote down vote up
componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', () => {
      const { nav } = this.props;
      if (
        nav.routes.length === 1 &&
        (nav.routes[0].routeName === 'Login' || nav.routes[0].routeName === 'Start')
      ) {
        return false;
      }
      // if (shouldCloseApp(nav)) return false
      let backAction = NavigationActions.back();
      if (this.navigator) {
        const { screenKey } = getCurrentRouteParamFromState(this.navigator.state.nav);
        if (screenKey) {
          backAction = NavigationActions.back({ key: screenKey });
        }
        this.navigator.dispatch(backAction);
      }
      return true;
    });

    this.subscribeBranch();

    this.createNotificationListeners();
  }
Example #3
Source File: navigation.js    From haven with MIT License 6 votes vote down vote up
navReducer = (state = initialState, action) => {
  let nextState;
  switch (action.type) {
    case actions.navigate:
      nextState = AppNavigator.router.getStateForAction(
        NavigationActions.navigate({
          routeName: action.payload,
        }),
        state,
      );
      break;
    default:
      nextState = AppNavigator.router.getStateForAction(action, state);
      break;
  }

  // Return original `state` if `nextState` is null/undefined
  return nextState || state;
}
Example #4
Source File: NavigationService.js    From iitj-canteen with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Call this function when you want to navigate to a specific route AND reset the navigation history.
 *
 * That means the user cannot go back. This is useful for example to redirect from a splashscreen to
 * the main screen: the user should not be able to go back to the splashscreen.
 *
 * @param routeName The name of the route to navigate to. Routes are defined in RootScreen using createStackNavigator()
 * @param params Route parameters.
 */
function navigateAndReset(routeName, params) {
	navigator.dispatch(
		StackActions.reset({
			index: 0,
			key: null,
			actions: [
				NavigationActions.navigate({
					routeName,
					params
				})
			]
		})
	);
}
Example #5
Source File: NavigationService.js    From iitj-canteen with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Call this function when you want to navigate to a specific route.
 *
 * @param routeName The name of the route to navigate to. Routes are defined in RootScreen using createStackNavigator()
 * @param params Route parameters.
 */
function navigate(routeName, params) {
	navigator.dispatch(
		NavigationActions.navigate({
			routeName,
			params
		})
	);
}
Example #6
Source File: ScreenTrackingMiddleware.js    From gDoctor with MIT License 6 votes vote down vote up
screenTracking = ({ getState }) => next => (action) => {
  if (
    action.type !== NavigationActions.NAVIGATE &&
    action.type !== NavigationActions.BACK
  ) {
    return next(action)
  }

  const currentScreen = getCurrentRouteName(getState().nav)
  const result = next(action)
  const nextScreen = getCurrentRouteName(getState().nav)
  if (nextScreen !== currentScreen) {
    try {
      console.tron.log(`NAVIGATING ${currentScreen} to ${nextScreen}`)
      // Example: Analytics.trackEvent('user_navigation', {currentScreen, nextScreen})
    } catch (e) {
      console.tron.log(e)
    }
  }
  return result
}
Example #7
Source File: Utilities.js    From hugin-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
/* Navigate to a route, resetting the stack, so the user cannot go back.
   We want to do this so when we go from the splash screen to the menu screen,
   the user can't return, and get stuck there. */
export function navigateWithDisabledBack(route, routeParams) {
    return StackActions.reset({
        index: 0,
        actions: [
            NavigationActions.navigate({
                routeName: route,
                params: routeParams,
            }),
        ]
    });
}
Example #8
Source File: storeModerators.js    From haven with MIT License 6 votes vote down vote up
render() {
    return (
      <View style={screenWrapper.wrapper}>
        <Header
          left={<NavBackButton />}
          onLeft={() => {
            this.props.navigation.dispatch(NavigationActions.back());
          }}
          title="Manage Moderators"
        />
        <StoreModeratorsList />
      </View>
    );
  }
Example #9
Source File: NavigationService.js    From mern-stack with MIT License 5 votes vote down vote up
navigate = (routeName, params) => {
  _navigator.dispatch(NavigationActions.navigate({ routeName, params }));
}
Example #10
Source File: shippingAddress.js    From haven with MIT License 5 votes vote down vote up
render() {
    const { routeName } = this.props.navigation.state;
    const {
      shippingAddresses, selected, shippingOptions,
    } = this.state;
    return (
      <View style={screenWrapper.wrapper}>
        <Header
          left={<NavBackButton />}
          onLeft={() => {
            this.props.navigation.dispatch(NavigationActions.back());
          }}
          title="Shipping"
          right={<LinkText text="Done" color={linkTextColor} />}
          onRight={() => {
            this.toNextScreen();
          }}
        />
        <ScrollView>
          <Text>{isEmpty(shippingOptions)}</Text>
          <InputGroup title="Ship To">
            {isEmpty(shippingAddresses) ? (
              <Text style={styles.noShipping}>No shipping address</Text>
            ) : (
              <RadioGroup
                alignTop
                options={shippingAddresses}
                selected={selected}
                onChange={this.handleAddressIndexChange}
                renderItem={this.renderShippingAddress}
                showSeparator
              />
            )}
            <TouchableWithoutFeedback onPress={this.onNewAddress}>
              <View>
                <Text style={styles.newAddress}>+ Add new address</Text>
              </View>
            </TouchableWithoutFeedback>
          </InputGroup>
          {routeName === 'CheckoutShippingAddress' && this.renderShippingOptions()}
        </ScrollView>
        <OBActionSheet
          ref={this.setActionSheet}
          onPress={this.handleChange}
          options={['Edit', 'Delete', 'Cancel']}
          cancelButtonIndex={2}
          destructiveButtonIndex={1}
        />
      </View>
    );
  }
Example #11
Source File: shippingAddress.js    From haven with MIT License 5 votes vote down vote up
toNextScreen() {
    this.props.navigation.dispatch(NavigationActions.back());
  }
Example #12
Source File: checkout.js    From haven with MIT License 5 votes vote down vote up
render() {
    const {
      shippingAddress,
      shippingAddresses,
      shippingOption,
      balance,
      paymentMethod,
      feeLevel,
      localCurrency,
      navigation,
    } = this.props;

    const listing = navigation.getParam('listing');
    const combo = navigation.getParam('combo');

    const {
      quantity,
      selectedCoupon,
      loadingModerators,
      checkoutData,
    } = this.state;
    const { price } = checkoutData;

    return (
      <View style={screenWrapper.wrapper}>
        <Header
          left={<NavBackButton />}
          onLeft={() => {
            this.props.navigation.dispatch(NavigationActions.back());
          }}
          title="Checkout"
        />
        <CheckoutTemplate
          listing={listing}
          combo={combo}
          quantity={quantity}
          shippingAddress={shippingAddresses[shippingAddress] || {}}
          shippingOption={shippingOption}
          balance={balance}
          paymentMethod={paymentMethod}
          feeLevel={feeLevel}
          loadingModerators={loadingModerators}
          toShippingAddress={this.handleGoToShippingAddress}
          toPaymentMethod={this.handleGoToPaymentMethod}
          toAddFund={this.handleGoToAddFund}
          toModerators={this.handleGoToModerators}
          setCheckoutObject={this.handleSetCheckoutObject}
          localCurrency={localCurrency}
          selectedCoupon={selectedCoupon}
          onChangeCoupon={this.handleChangeCoupon}
        />
        <View style={styles.bottomWrapper}>
          <PayBanner
            disabled={this.isNotPayable()}
            amount={price}
            paymentMethod={paymentMethod}
            onPay={this.handleShowPanel}
          />
        </View>
        <OBSlidingPanel
          ref={this.setSlidingPanel}
        >
          <PayPanel
            amount={price}
            paymentMethod={paymentMethod}
            onInternal={this.handlePay('internal')}
            onExternal={this.handlePay('external')}
          />
        </OBSlidingPanel>
      </View>
    );
  }
Example #13
Source File: NavigationServices.js    From Alfredo-Mobile with MIT License 5 votes vote down vote up
function navigate(routeName, params) {
  _navigator.currentNavProp.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}
Example #14
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>
  );
}
Example #15
Source File: LoginScreen.js    From geometry_3d with MIT License 4 votes vote down vote up
function LoginScreen(props) {
  const { navigate } = useNavigation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [visible, setVisible] = useState(false);
  const handleLogin = () => {
    setVisible(() => true);
    fb.auth
      .signInWithEmailAndPassword(email, password)
      .then(() => {
        props.reduxSetCurrentUser({
          email: email,
          password: password,
        });
        setVisible(() => false);
        //console.log(props.currentUser);
      })
      .catch((error) => {
        setErrorMessage(error.message);
        setVisible(() => false);
      });
  };
  useEffect(() => {
    LayoutAnimation.easeInEaseOut();
  });
  return visible ? (
    <LoadingScreen />
  ) : (
    <KeyboardAwareScrollView
      resetScrollToCoords={{ x: 0, y: 0 }}
      contentContainerStyle={styles.container}
      enableOnAndroid={true}
      keyboardShouldPersistTaps="handled"
      scrollEnabled={true}
      enableAutomaticScroll={Platform.OS === "ios"}
    >
      <StatusBar barStyle="light-content"></StatusBar>
      <ScrollView keyboardShouldPersistTaps={'handled'} style={{backgroundColor: 'black'}}>
        <Text style={styles.greeting}>{"Hello! \nWelcome back"}</Text>
        <View style={styles.errorMessage}>
          <Text style={styles.error}>{errorMessage}</Text>
        </View>
        <View style={styles.form}>
          <View>
            <Text style={styles.inputTitle}>Email Address</Text>
            <TextInput
              style={styles.input}
              autoCapitalize="none"
              onChangeText={(emailInput) => setEmail(() => emailInput.trim())}
              value={email}
            ></TextInput>
          </View>
          <View>
            <Text textBreakStrategy={"simple"} style={styles.inputTitle}>Password</Text>
            <TextInput
              style={styles.input}
              secureTextEntry
              autoCapitalize="none"
              onChangeText={(passwordInput) => setPassword(() => passwordInput.trim())}
              value={password}
            ></TextInput>
          </View>
          <TouchableOpacity style={styles.button} onPress={handleLogin}>
            <Text textBreakStrategy={"simple"} style={{ color: "white", fontWeight: "500" }}>Sign in</Text>
          </TouchableOpacity>
          <TouchableOpacity style={{...styles.button, marginTop: 10, backgroundColor: "#2bffea"}} onPress={() => {
            navigate("App", {}, NavigationActions.navigate({routeName: "HomeScreen"}))
          }}>
            <Text textBreakStrategy={"simple"} style={{ color: "black", fontWeight: "500" }}>Guest session</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={{ alignSelf: "center", marginTop: 32 }}
            onPress={() => navigate("Register")}
          >
            <Text textBreakStrategy={"simple"} style={{ color: "white", fontSize: 13 }}>
              First time?
              <Text textBreakStrategy={"simple"} style={{ color: "#478eff", fontWeight: "500" }}>
                {" "}
                Sign up!
              </Text>
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </KeyboardAwareScrollView>
  );
}
Example #16
Source File: SavedItemScreen.js    From geometry_3d with MIT License 4 votes vote down vote up
function SavedItemScreen(props) {
  const saveItemsHolder = [...props.saveComponents.items];
  const navigation = useNavigation();
  const [saveItems, setSaveItems] = useState(
    saveItemsHolder.map((item) => ({ ...item, showOptions: false }))
  );
  const [visible, setVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [userData, setUserData] = useState(null);
  const [newScene, setNewScene] = useState(null);
  const [chosenItem, setChosenItem] = useState(null);
  const [newName, setNewName] = useState("");
  useEffect(() => {
    if (newScene) {
      setSaveItems(() => [newScene, ...saveItems]);
      props.reduxAddSaveItem(newScene);
    }
  }, [newScene]);
  const ifExist = (fileName) => {
    for (let item of saveItems) {
      if (item.fileName === fileName) return true;
    }
    return false;
  };
  const retrieveSyncedItems = () => {
    setIsLoading(() => true);
    fb.userCollection
      .doc(fb.auth.currentUser.uid)
      .get()
      .then((doc) => {
        const data = doc.data();
        setUserData(() => {
          uid: data.uid;
        });
        for (let url of data.scenes) {
          fetch(url)
            .then((res) => {
              return res.json();
            })
            .then((data) => {
              let newItem = {
                fileName: data.fileName,
                name: data.name,
                lines: data.lines,
                shapes: data.shapes,
                points: data.points,
                isSynced: true,
                showOptions: false,
                url: url,
              };
              if (!ifExist(newItem.fileName)) {
                setNewScene(() => newItem);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        setIsLoading(() => false);
      })
      .catch((e) => {
        setIsLoading(() => false);
        console.log(e);
      });
  };

  const syncSavedItems = () => {
    setIsLoading(() => true);
    const currUser = fb.auth.currentUser;
    const storageRef = fb.storage.ref();
    let _saveItems = [];

    for (let item of saveItems) {
      if (!item.isSynced) {
        item.isSynced = true;
        _saveItems.push(item);
      }
    }
    if (_saveItems.length === 0) {
      Toast.show({
        type: "error",
        position: "top",
        text1: "All items synced",
        text2: "Try adding more items",
        visibilityTime: 3000,
        autoHide: true,
      });
      setIsLoading(() => false);
      return;
    }
    let counter = 0;
    for (let item of _saveItems) {
      const refScene = storageRef.child(
        `/${currUser.uid}/scenes/${item.fileName}.json`
      );
      let json = JSON.stringify(item);
      let fileBlob = new Blob([json], { type: "application/json" });
      refScene
        .put(fileBlob)
        .then((snapshot) => {
          snapshot.ref.getDownloadURL().then((url) => {
            item.url = url;
            fb.userCollection
              .doc(fb.auth.currentUser.uid)
              .update({ scenes: fb.FieldValue.arrayUnion(url) });
          });
          counter++;
          if (counter === _saveItems.length) {
            Toast.show({
              type: "success",
              position: "top",
              text1: "All items synced",
              text2: "Success",
              visibilityTime: 3000,
              autoHide: true,
            });
            setIsLoading(() => false);
          }
        })
        .catch((e) => {
          //console.log(e);
          counter++;
          if (counter === _saveItems.length) {
            Toast.show({
              type: "error",
              position: "top",
              text1: "Something wrong happened",
              text2: "Success",
              visibilityTime: 3000,
              autoHide: true,
            });
            setIsLoading(() => false);
          }
        });
    }
  };
  return isLoading ? (
    <View>
      <Spinner visible={true} />
    </View>
  ) : (
    <SafeAreaView style={{ marginTop: 10, marginHorizontal: 20 }}>
      {/*<AdMobBanner
                bannerSize="fullBanner"
                adUnitID={adBannerUnitID} // Test ID, Replace with your-admob-unit-id
                servePersonalizedAds={true} // true or false
                onDidFailToReceiveAdWithError={() => {
                    console.log("CANT");
                }}
                style={{
                    marginTop: -10,
                    marginHorizontal: -20
                }}
            />*/}
      <View
        style={{
          flexDirection: "row",
          marginTop: 10,
          justifyContent: "space-between",
        }}
      >
        <Text style={{ fontSize: 20 }}>Saved items</Text>
        <TouchableOpacity
          style={{
            paddingVertical: 5,
            paddingHorizontal: 10,
            borderWidth: 1,
            borderColor: saveItems.length > 0 ? "red" : "gray",
            backgroundColor: saveItems.length > 0 ? "red" : "gray",
            borderRadius: 5,
          }}
          disabled={saveItems.length <= 0}
          onPress={() => {
            if (saveItems.length > 0) setVisible(true);
          }}
        >
          <Text style={{ color: "white" }}>Clear</Text>
        </TouchableOpacity>
      </View>
      {saveItems.length === 0 && (
        <View
          style={{
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Image
            source={require("../../assets/cube.png")}
            style={{
              width: 100,
              height: 100,
              marginTop: 50,
            }}
          />
          <Text style={{ margin: 20 }}>~~ Such empty ~~</Text>
        </View>
      )}
      <FlatList
        style={{
          marginTop: 10,
          maxHeight: SCREEN_HEIGHT / 1.6,
        }}
        keyboardShouldPersistTaps={"handled"}
        showsVerticalScrollIndicator={false}
        data={saveItems}
        extraData={saveItems}
        keyExtractor={(item) => `${item.fileName}`}
        renderItem={({ index, item }) => (
          <View style={{ flexDirection: "row" }}>
            <TouchableOpacity
              style={{
                flex: 1,
                padding: 10,
                borderWidth: 1,
                borderColor: "black",
                borderRadius: 5,
                marginBottom: 10,
                marginRight: 10,
              }}
              showsVerticalScrollIndicator={false}
              keyExtractor={(item, index) => `${index} save items`}
              onPress={() => {
                navigation.navigate(
                  "Objects",
                  {},
                  NavigationActions.navigate({
                    routeName: "BaseLayoutScreen",
                    params: {
                      shapes: JSON.stringify(item.shapes),
                      lines: JSON.stringify(item.lines),
                      points: JSON.stringify(item.points),
                      fileName: item.fileName,
                    },
                  })
                );
              }}
            >
              <Text>{item.name}</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{
                padding: 10,
                borderWidth: 1,
                borderColor: "#f34aff",
                borderRadius: 5,
                marginBottom: 10,
              }}
              onPress={() => {
                setChosenItem(() => item);
                setVisible(() => true);
              }}
            >
              <Ionicons name="ios-cog" size={24} color={"#f34aff"} />
            </TouchableOpacity>
          </View>
        )}
      />
      {saveItems.length > 0 && fb.auth.currentUser && (
        <TouchableOpacity
          style={{
            paddingHorizontal: 10,
            paddingVertical: 5,
            borderRadius: 5,
            borderWidth: 1,
            borderColor: "#53ff40",
          }}
          onPress={() => {
            //props.reduxSetCanRetrieve(false);
            syncSavedItems();
          }}
        >
          <Text style={{ textAlign: "center" }}>Sync with online account</Text>
        </TouchableOpacity>
      )}
      {fb.auth.currentUser && (
        <TouchableOpacity
          style={{
            paddingHorizontal: 10,
            paddingVertical: 5,
            borderRadius: 5,
            borderWidth: 1,
            borderColor: "#34c6eb",
            marginTop: 10,
          }}
          onPress={() => {
            retrieveSyncedItems();
          }}
        >
          <Text style={{ textAlign: "center", color: "black" }}>
            Retrieve synced items
          </Text>
        </TouchableOpacity>
      )}
      <Dialog
        visible={visible}
        dialogAnimation={
          new SlideAnimation({
            slideFrom: "bottom",
          })
        }
        width={SCREEN_WIDTH * 0.8}
        onHardwareBackPress={() => true}
        footer={
          <DialogFooter>
            <DialogButton
              text={chosenItem ? "CANCEL" : "NO"}
              onPress={() => {
                setVisible(false);
                setChosenItem(() => null);
                setNewName(() => "");
              }}
              textStyle={{
                fontSize: 15,
                color: "red",
              }}
            />
            <DialogButton
              text={chosenItem ? "DONE" : "YES"}
              onPress={() => {
                setVisible(() => false);
                if (!chosenItem) {
                  props.reduxSetSaveItem([]);
                  setSaveItems(() => []);
                  clearItemFireStore();
                } else {
                  if (newName !== "") {
                    const filtered = saveItems.map((item) => {
                      if (item === chosenItem) {
                        item.name = newName;
                      }
                      return item;
                    });
                    setSaveItems(() => saveItems);
                    props.reduxSetSaveItem(filtered);
                  }
                  setChosenItem(() => null);
                  setNewName(() => "");
                }
              }}
              textStyle={{
                fontSize: 15,
                color: "green",
              }}
            />
          </DialogFooter>
        }
      >
        {chosenItem ? (
          <View
            style={{
              paddingHorizontal: 15,
              paddingVertical: 10,
            }}
          >
            <View
              style={{
                marginLeft: 5,
                flexDirection: "row",
              }}
            >
              <Text style={{ marginTop: 10 }}>Rename</Text>
              <TextInput
                style={styles.input}
                onChangeText={(text) => {
                  setNewName(() => text);
                }}
                value={newName}
              />
            </View>
            <TouchableOpacity
              style={{
                paddingVertical: 5,
                paddingHorizontal: 10,
                borderColor: "red",
                borderWidth: 1,
                borderRadius: 5,
                marginTop: 20,
              }}
              onPress={() => {
                setVisible(() => false);
                const filtered = saveItems.filter(
                  (item) => item !== chosenItem
                );
                setSaveItems(() => filtered);
                props.reduxSetSaveItem(filtered);
                if (chosenItem.url !== "") {
                  deleteItemFireStore(chosenItem.url).then(() => {
                    deleteItemStorage(chosenItem.fileName).then(() => {
                      setChosenItem(() => null);
                    });
                  });
                } else {
                  setChosenItem(() => null);
                }
              }}
            >
              <Text style={{ color: "red", textAlign: "center" }}>Delete</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <Text
            style={{ fontSize: 20, textAlign: "center", marginVertical: 20 }}
          >
            Are you sure ?
          </Text>
        )}
      </Dialog>
    </SafeAreaView>
  );
}
Example #17
Source File: orderDetails.js    From haven with MIT License 4 votes vote down vote up
render() {
    const {
      getPeerIDFromOrder, navigation, peerID, fetching,
    } = this.props;
    const orderType = navigation.getParam('orderType');
    const orderId = this.getOrderId();

    const header = (
      <Header
        left={<NavBackButton />}
        onLeft={() => {
          navigation.dispatch(NavigationActions.back());
        }}
        title={getOrderTitleFromOrderId(orderId)}
        right={<StoreMoreMenu onMore={this.handlePressMore} black size={28} />}
      />
    );

    const {
      showFundDlg,
      showDisputeDlg,
      showFulfillDlg,
      showRatingModal,
      showLearnMoreModal,
      contractType,
      memo,
      orderDetails = {},
      tab,
      copied,
      order = {},
      updating,
      showContractModal,
    } = this.state;
    if (!order) {
      return (
        <View style={screenWrapper.wrapper}>
          {header}
        </View>
      );
    }

    const moderatorId = get(orderDetails, 'contract.buyerOrder.payment.moderator');
    const isModerated = get(orderDetails, 'contract.buyerOrder.payment.method') === 'MODERATED';
    const disputeTimestamp = get(orderDetails, 'contract.dispute.timestamp');
    const vendorId = order.vendorId || peerID;
    const buyerId = order.buyerId || peerID;
    const blurComponentIOS = (
      <BlurView style={StyleSheet.absoluteFill} blurType="xlight" blurAmount={50} />
    );
    return (
      <View style={screenWrapper.wrapper}>
        <NavigationEvents onDidFocus={this.handleNavigationFocus} />
        {header}
        <Tabs
          currentTab={tab}
          tabs={this.getOrderTabs()}
          onChange={this.updateState('tab')}
          withBorder
        />
        {tab === 'details' ? (
          <ScrollView
            refreshControl={
              <RefreshControl
                refreshing={updating && fetching}
                onRefresh={this.onRefresh}
              />
            }
          >
            {!isEmpty(order) && (
              <View style={styles.brief}>
                <OrderBrief
                  orderType={orderType}
                  order={order}
                  onPress={this.handleGoToListing}
                  noBorder
                  hideTimestamp
                  shouldFetchProfile
                  showLearnMore
                  onLearnMore={this.showLearnMoreDlg}
                />
              </View>
            )}
            {!isEmpty(orderDetails) && (
              <OrderSummary
                orderId={this.getOrderId()}
                orderDetails={orderDetails}
                orderType={orderType}
                onDispute={this.disputeOrder}
                onClaim={this.claimOrder}
                onCancel={this.cancelOrder}
                onMessage={this.handleGoToChat}
                navigation={navigation}
              />
            )}
          </ScrollView>
        ) : (
          <ChatDetailTemplate
            isFromOrder
            isModerated={isModerated}
            peerID={getPeerIDFromOrder(this.getOrderId(), orderType)}
            subject={this.getOrderId()}
            orderType={orderType}
            moderatorId={moderatorId}
            vendorId={vendorId}
            buyerId={buyerId}
            inDispute={orderDetails.state === 'DISPUTED'}
            disputeTimestamp={disputeTimestamp}
          />
          )}
        {tab === 'details' && (
          <OrderFooter
            orderType={orderType}
            order={order}
            orderDetails={orderDetails}
            onOrderAction={this.onOrderAction}
          />
        )}
        <Dialog.Container visible={showFundDlg} blurComponentIOS={blurComponentIOS}>
          <Dialog.Title>Fund Order</Dialog.Title>
          <Dialog.Description>Leave Notes</Dialog.Description>
          <Dialog.Input value={memo} onChangeText={this.updateState('memo')} />
          <Dialog.Button
            label="Cancel"
            onPress={() => {
              this.setState({ showFundDlg: false, memo: '' });
            }}
          />
          <Dialog.Button label="Confirm" onPress={this.doFund} />
        </Dialog.Container>
        <FulfillModal
          isOpen={showFulfillDlg}
          orderId={this.getOrderId()}
          buyerId={buyerId}
          vendorId={this.getVendorId()}
          contractType={contractType}
          onHideFulfill={this.handleHideFulfill}
        />
        <DisputeModal
          orderType={orderType}
          isOpen={showDisputeDlg}
          orderId={this.getOrderId()}
          vendorId={this.getVendorId()}
          onHideDispute={this.handleHideDispute}
        />
        <RatingModal
          show={showRatingModal}
          orderType={orderType}
          order={order}
          hideModal={this.hideRatingModal}
          finishReview={this.doComplete}
        />
        <OBActionSheet
          ref={this.setActionSheet}
          onPress={this.handleChange}
          options={[
            orderType === 'purchases' ? 'Go to seller\'s profile' : 'Go to buyer\'s profile',
            'View listing',
            'Copy order number',
            'View contract',
            'Cancel',
          ]}
          cancelButtonIndex={4}
        />
        {copied && (
          <View style={styles.overlay}>
            <Text style={styles.overlayText}>Order number copied!</Text>
          </View>
        )}
        <OBLightModal
          animationType="slide"
          transparent
          visible={showLearnMoreModal}
          onRequestClose={this.hideLearnMoreDlg}
        >
          <Header
            modal
            left={<NavCloseButton />}
            onLeft={this.hideLearnMoreDlg}
          />
          <View style={styles.contentContainer}>
            <Text style={styles.learnMoreText}>
              Due to changes in the exchange rate, the current market price for an order may differ from the total price of the item at the time of purchase.
            </Text>
          </View>
        </OBLightModal>
        <ContractModal
          show={showContractModal}
          onClose={this.handleCloseContractModal}
          orderDetails={orderDetails}
        />
      </View>
    );
  }
Example #18
Source File: routes.js    From haven with MIT License 4 votes vote down vote up
MainTab = createBottomTabNavigator(
  {
    Shop: {
      screen: ShopTab,
      navigationOptions: {
        tabBarOnPress: ({ defaultHandler }) => {
          eventTracker.trackEvent('MainNavigationTap-Discover');
          defaultHandler();
        },
        tabBarIcon: ({ focused }) => (
          <Feather name="shopping-cart" size={23} color={focused ? '#00bf65' : '#969696'} />
        ),
      },
    },
    Feed: {
      screen: FeedTab,
      navigationOptions: {
        tabBarOnPress: ({ defaultHandler }) => {
          eventTracker.trackEvent('MainNavigationTap-Social');
          defaultHandler();
        },
        tabBarIcon: ({ focused }) => (
          <Feather name="users" size={23} color={focused ? '#00bf65' : '#969696'} />
        ),
      },
    },
    Plus: {
      screen: () => null,
      navigationOptions: {
        tabBarOnPress: ({ defaultHandler }) => {
          eventTracker.trackEvent('MainNavigationTap-Create');
          defaultHandler();
        },
        tabBarIcon: () => <PlusButton />,
      },
    },
    Chat: {
      screen: ChatsTab,
      navigationOptions: {
        tabBarOnPress: ({ defaultHandler }) => {
          eventTracker.trackEvent('MainNavigationTap-Chat');
          defaultHandler();
        },
        tabBarIcon: ({ focused }) => <ChatNavIcon focused={focused} />,
      },
    },
    Me: {
      screen: MeTab,
      navigationOptions: {
        tabBarOnPress: ({ defaultHandler }) => {
          eventTracker.trackEvent('MainNavigationTap-Me');
          defaultHandler();
        },
        tabBarIcon: ({ focused }) => <ProfilePicture focused={focused} />,
      },
    },
  },
  {
    tabBarPosition: 'bottom',
    swipeEnabled: false,
    lazy: false,
    tabBarComponent: props => (
      <BottomTabBar
        {...props}
        onTabPress={(tabInfo) => {
        if (tabInfo.route.routeName === 'Me') {
          const resetTabAction = NavigationActions.navigate({
            routeName: 'Me',
            action: StackActions.reset({
              index: 0,
              actions: [NavigationActions.navigate({ routeName: 'WalletMain' })],
            }),
          });
          props.navigation.dispatch(resetTabAction);
        } else {
          props.onTabPress(tabInfo);
        }
      }}
      />
    ),
    animationEnabled: false,
    removeClippedSubviews: true,
    tabBarOptions: {
      showLabel: false,
      activeTintColor: '#000000',
      tabStyle: {
        justifyContent: 'center',
        alignItems: 'center',
      },
    },
  },
)