react-native#KeyboardAvoidingView TypeScript Examples

The following examples show how to use react-native#KeyboardAvoidingView. 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: JoinScreen.tsx    From lets-fork-native with MIT License 6 votes vote down vote up
JoinScreen = React.memo((props: Props): React.ReactElement => {
  const { navigation, ws } = props
  const [value, setValue] = React.useState('')
  const headerHeight = useHeaderHeight()

  // joins an existing party
  const handleJoin = (): void => {
    if (value) {
      ws.send(JSON.stringify({ type: 'join', payload: { party_id: value } }))
      navigation.navigate('Party')
      Keyboard.dismiss()
    }
  }

  return (
    <KeyboardAvoidingView
      behavior="height"
      style={{
        ...styles.container,
        height: height - headerHeight,
      }}
    >
      <Text style={styles.text}>Please enter the party code</Text>
      <Input value={value} handleChange={setValue} keyboardType="phone-pad" />
      <Button size="sm" color="purple" onPress={(): void => handleJoin()}>
        JOIN
      </Button>
    </KeyboardAvoidingView>
  )
})
Example #2
Source File: App.tsx    From react-native-credit-card-form-ui with MIT License 6 votes vote down vote up
export default function App() {
  const creditCardRef = React.useRef() as any;

  const handleSubmit = React.useCallback(() => {
    if (creditCardRef.current) {
      const { error, data } = creditCardRef.current.submit();
      console.log('ERROR: ', error);
      console.log('CARD DATA: ', data);
    }
  }, []);

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={20}
      style={styles.container}
    >
      <CreditCard ref={creditCardRef} onValidStateChange={console.log} />
      <Button title="Submit" onPress={handleSubmit} />
    </KeyboardAvoidingView>
  );
}
Example #3
Source File: signIn.tsx    From companion-kit with MIT License 6 votes vote down vote up
renderContent() {
        const model = SignInViewModel.Instance;
        const { inProgress, error } = model;
        const { keyboard } = this.props.context;
        const containerPadding = Layout.window.height - this._contentHeight + 20;
        const containerHeight = keyboard?.isOpened ? keyboard?.screenY : '100%';
        const scaleDownTitle = this.layout.isSmallDevice || this.layout.window.width < 365;

        return (
            <KeyboardAvoidingView behavior={isAndroid ? 'padding' : null}>
                <MasloPage
                    inProgress={inProgress || AppController.Instance.loading}
                    onBack={this.goBack}
                    style={[this.baseStyles.page, { justifyContent: 'flex-start', position: 'relative' }]}
                >
                    <Container style={[
                        keyboard?.isOpened ? this.baseStyles.flexCenterBottom : this.baseStyles.flexStart,
                        { height: containerHeight, paddingTop: containerPadding },
                    ]}>
                        <View style={[this.baseStyles.textBlock, styles.textBlock, keyboard?.isOpened ? { position: 'absolute', top: containerPadding } : null]}>
                            <Text style={[scaleDownTitle ? this.textStyles.h3 : this.textStyles.h1, styles.title]}>{`What's your email?\nI need it to find your account.`}</Text>
                        </View>
                        <TextInput
                            onSubmit={this.submit}
                            model={model.email}
                            placeholder="[email protected]"
                            forceError={error}
                            autoFocus={this.allowInputAutoFocus}
                            autoCompleteType="email"
                            keyboardType="email-address"
                            textContentType="emailAddress"
                            autoCapitalize="none"
                            styleWrap={{ marginBottom: isAndroid ? 100 : 40 }}
                        />
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #4
Source File: quill-toolbar.tsx    From react-native-cn-quill with MIT License 6 votes vote down vote up
render() {
    const { container = 'avoiding-view' } = this.props;
    if (container === 'avoiding-view')
      return (
        <KeyboardAvoidingView
          onTouchStart={(e) => e.stopPropagation()}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          {this.renderToolbar()}
        </KeyboardAvoidingView>
      );
    else if (container === false) return this.renderToolbar();
    else {
      const ContainerComponent = container;
      return <ContainerComponent>{this.renderToolbar()}</ContainerComponent>;
    }
  }
Example #5
Source File: emailSettings.tsx    From companion-kit with MIT License 6 votes vote down vote up
renderContent() {

        return (
            <KeyboardAvoidingView behavior="padding" style={{ height: '100%' }}>
                <MasloPage>
                    <Container>
                        <BackArrow onPress={() => this.trigger(ScenarioTriggers.Back)} />
                        <Text style={{...TextStyles.h1, fontFamily: mainFontThin }}>Email</Text>
                    </Container>
                    <View style={{ flex: 1 }}>
                        <TextInput
                            onSubmit={this.model.submit}
                            model={this.model.email}
                            placeholder="Your New Email"
                            forceError={this.model.error}
                            autoCompleteType="email"
                            keyboardType="email-address"
                            textContentType="emailAddress"
                            autoCapitalize="none"
                            label="New Email"
                            styleWrap={styles.inputWrap}
                            styleInput={[this.baseStyles.cardTitle, styles.input]}
                            // styleError={styles.errorMsg}
                            styleLabel={styles.inputLabel}
                        />
                    </View>
                    <Container>
                        <Button
                            withBorder
                            isTransparent
                            title="Save"
                            onPress={this.onSave}
                        />
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #6
Source File: CustomModal.tsx    From hive-keychain-mobile with MIT License 6 votes vote down vote up
render() {
    let modalHeight = this.props.bottomHalf ? this.height / 2 : this.height;
    const styles = StyleSheetFactory.getSheet({
      modalHeight: modalHeight,
      height: this.height,
      width: this.width,
    });
    return (
      <KeyboardAvoidingView
        style={styles.fullHeight}
        behavior={Platform.OS === 'ios' ? 'padding' : null}>
        <View style={styles.mainContainer}>
          <TouchableWithoutFeedback
            style={{height: '100%'}}
            onPress={() => {
              this.props.outsideClick();
            }}></TouchableWithoutFeedback>
          <View style={styles.modalWrapper}>
            <View style={styles.modalContainer}>
              <LinearGradient
                start={{x: 0, y: 0}}
                end={{x: 0, y: 1}}
                colors={['white', '#B9C9D6']}
                style={styles.gradient}>
                {this.props.children}
              </LinearGradient>
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    );
  }
Example #7
Source File: BaseDataSharingView.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
BaseDataSharingView = ({children, showBackButton = true}: BaseDataSharingViewProps) => {
  const navigation = useNavigation();
  const i18n = useI18n();
  const close = useCallback(() => navigation.navigate('Home'), [navigation]);
  const {data} = useContext(FormContext);

  // Note: we can now make back buttons in this flow!
  // const back = useCallback(() => navigation.goBack(), [navigation]);

  const wrapperStyle = data.modalVisible ? styles.overlay : styles.invisible;

  return (
    <KeyboardAvoidingView style={styles.flex} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
      <Box backgroundColor="overlayBackground" flex={1}>
        <SafeAreaView style={styles.flex}>
          <Box style={wrapperStyle} />
          <Box marginBottom="s">
            <Toolbar
              navText={i18n.translate('DataUpload.Close')}
              onIconClicked={close}
              showBackButton={showBackButton}
            />
          </Box>
          <ScrollView style={styles.flex} keyboardShouldPersistTaps="handled">
            {children}
          </ScrollView>
        </SafeAreaView>
      </Box>
    </KeyboardAvoidingView>
  );
}
Example #8
Source File: SignUp.tsx    From online-groceries-app with MIT License 5 votes vote down vote up
SignUp = ({navigation}: SignUpProps) => {
  const behavior = Platform.OS === 'ios' ? 'padding' : undefined;

  const goToSignIn = () => {
    navigation.pop();
  };

  const goToHome = () => {
    navigation.navigate(Tabs.name);
  };

  return (
    <SignScaffold>
      <Image style={styles.logo} source={logo} />
      <View style={styles.form}>
        <View>
          <Text style={styles.headerTitle}>Sign up</Text>
          <Text style={styles.headerSubtitle}>
            Enter your credentials to continue
          </Text>
        </View>
        <KeyboardAvoidingView behavior={behavior}>
          <Input label="Username" />
          <View style={{marginTop: heightScreen * 0.011}} />
          <Input label="Email" />
          <View style={{marginTop: heightScreen * 0.011}} />
          <Input label="Password" />
        </KeyboardAvoidingView>

        <View style={styles.termsBox}>
          <Text style={styles.infoText}>
            By continuing you agree to our{' '}
            <Text style={[styles.infoText, styles.greenInfoText]}>
              Terms of Service
            </Text>{' '}
            and{' '}
            <Text style={[styles.infoText, styles.greenInfoText]}>
              Privacy Policy
            </Text>
            .
          </Text>
        </View>
        <Button
          onPress={goToHome}
          bgColour="#53B175"
          txtColour="#FFF"
          text="Sign up"
        />
        <View style={styles.footer}>
          <Text style={styles.infoText}>Already have an account?</Text>
          <TouchableOpacity onPress={goToSignIn}>
            <Text style={[styles.infoText, styles.greenInfoText]}>Sign in</Text>
          </TouchableOpacity>
        </View>
      </View>
    </SignScaffold>
  );
}
Example #9
Source File: index.tsx    From ecoleta with MIT License 5 votes vote down vote up
Home = () => {

  const [uf, setUf] = useState('');
  const [city, setCity] = useState('');

  const navigation = useNavigation();

  function handleNavigateToPoints() {
    navigation.navigate('Points', {
      uf,
      city
    });
  }
  
  return (
    <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
      <ImageBackground 
        source={require('../../assets/home-background.png')} 
        style={styles.container}
        imageStyle={{ width: 274, height: 368 }}
        >
        <View style={styles.main}>
          <Image source={require('../../assets/logo.png')} />
          <View>
            <Text style={styles.title}>Seu maketplace de coleta de resíduos.</Text>
            <Text style={styles.description}>Ajudamos pessoas a encontrarem pontos de coleta de forma eficiente.</Text>
          </View>
        </View>

        <View style={styles.footer}>
          <TextInput 
            style={styles.input}
            placeholder="Digite a UF"
            value={uf}
            maxLength={2}
            autoCapitalize="characters"
            autoCorrect={false}
            onChangeText={setUf}
            />

          <TextInput 
            style={styles.input}
            placeholder="Digite a Cidade"
            value={city}
            autoCorrect={false}
            onChangeText={setCity}
          />

          <RectButton style={styles.button} onPress={handleNavigateToPoints}>
            <View style={styles.buttonIcon}>
              <Text>
                <Icon name="arrow-right" color="#FFF" size={24} />
              </Text>
            </View>
            <Text style={styles.buttonText}>
              Entrar
            </Text>
          </RectButton>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
}
Example #10
Source File: index.tsx    From ecoleta with MIT License 5 votes vote down vote up
Home = () => {
  const navigation = useNavigation();

  const [uf, setUf] = useState('');
  const [city, setCity] = useState('');

  function handleNavigateToPoints() {
    navigation.navigate('Points', {
      uf,
      city,
    });
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, marginBottom: 25 }}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ImageBackground
        style={styles.container}
        source={require('../../assets/home-background.png')}
        imageStyle={{ width: 274, height: 368 }}
      >
        <View style={styles.main}>
          <Image source={require('../../assets/logo.png')} />

          <View>
            <Text style={styles.title}>
              Seu marketplace de coleta de resíduos
            </Text>
            <Text style={styles.description}>
              Ajudamos pessoas a encontrarem pontos de coleta de forma
              eficiente.
            </Text>
          </View>
        </View>

        <View style={styles.footer}>
          <TextInput
            style={styles.input}
            placeholder="Digite a UF"
            value={uf}
            onChangeText={setUf}
            maxLength={2}
            autoCorrect={false}
            autoCapitalize="characters"
          />

          <TextInput
            style={styles.input}
            placeholder="Digite a cidade"
            value={city}
            onChangeText={setCity}
            autoCorrect={false}
          />

          <RectButton style={styles.button} onPress={handleNavigateToPoints}>
            <View style={styles.buttonIcon}>
              <Feather name="arrow-right" color="#fff" size={24} />
            </View>
            <Text style={styles.buttonText}>Entrar</Text>
          </RectButton>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
}
Example #11
Source File: index.tsx    From nlw-01-omnistack with MIT License 5 votes vote down vote up
Home = () => {
  const [uf, setUf] = useState('');
  const [city, setCity] = useState('');

  const navigation = useNavigation();

  function handleNavigateToPoints() {
    navigation.navigate('Points', {
      uf,
      city,
    });
  }

  return (
    <KeyboardAvoidingView 
      style={{ flex: 1 }} 
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ImageBackground 
        source={require('../../assets/home-background.png')} 
        style={styles.container}
        imageStyle={{ width: 274, height: 368 }}
      >
        <View style={styles.main}>
          <Image source={require('../../assets/logo.png')} />
          <View>
            <Text style={styles.title}>Seu marketplace de coleta de resíduos</Text>
            <Text style={styles.description}>Ajudamos pessoas a encontrarem pontos de coleta de forma eficiente.</Text>
          </View>
        </View>
        
        <View style={styles.footer}>
          <TextInput
            style={styles.input}
            placeholder="Digite a UF"
            value={uf}
            maxLength={2}
            autoCapitalize="characters"
            autoCorrect={false}
            onChangeText={setUf}
          />

          <TextInput
            style={styles.input}
            placeholder="Digite a cidade"
            value={city}
            autoCorrect={false}
            onChangeText={setCity}
          />

          <RectButton style={styles.button} onPress={handleNavigateToPoints}>
            <View style={styles.buttonIcon}>
              <Text>
                <Icon name="arrow-right" color="#FFF" size={24} />
              </Text>
            </View>
            <Text style={styles.buttonText}>
              Entrar
            </Text>
          </RectButton>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
}
Example #12
Source File: FirstLayout.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
FirstLayout = (props: FirstLayoutProps) => {
  const {header, content, actions, more, theme, belowCard} = props;
  return (
    <>
      <StatusBar
        barStyle="dark-content"
        backgroundColor={theme.palette.statusBar}
      />
      <SafeAreaView
        style={[styles.safeArea, {backgroundColor: theme.palette.background}]}>
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : undefined}
          style={styles.root}>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            contentContainerStyle={styles.scrollView}
            keyboardShouldPersistTaps="handled">
            <View
              style={[styles.rootView, {marginHorizontal: theme.spacing * 2}]}>
              <View style={styles.main}>
                <Image
                  source={require('images/orangehrm-logo-full.png')}
                  style={styles.logo}
                />
                <Card fullWidth style={{marginBottom: theme.spacing * 4}}>
                  <CardHeader
                    style={{
                      padding: theme.spacing * 4,
                      paddingVertical: theme.spacing * 4,
                      backgroundColor: theme.palette.secondary,
                    }}>
                    <Text
                      style={{
                        color: theme.typography.secondaryColor,
                        fontSize: theme.typography.headerFontSize,
                      }}>
                      {header}
                    </Text>
                  </CardHeader>
                  <CardContent style={{padding: theme.spacing * 4}}>
                    {content}
                  </CardContent>
                  <CardActions>
                    <View
                      style={[
                        styles.cardActions,
                        {
                          paddingHorizontal: theme.spacing * 4,
                          paddingBottom: theme.spacing * 2,
                        },
                      ]}>
                      {actions}
                    </View>
                  </CardActions>
                </Card>
                {belowCard === undefined ? null : <View>{belowCard}</View>}
              </View>
              {more === undefined ? null : <View>{more}</View>}
              <View>
                <Footer />
              </View>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </>
  );
}
Example #13
Source File: SnackDialog.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
SnackDialog = (props: React.PropsWithChildren<SnackDialogProps>) => {
  const {
    theme,
    children,
    isVisible,
    closeSnackMessage,
    viewProps,
    ...dialogProps
  } = props;

  return (
    <Dialog
      isVisible={isVisible}
      hideModalContentWhileAnimating
      onBackButtonPress={closeSnackMessage}
      onSwipeComplete={closeSnackMessage}
      swipeDirection={['left', 'right', 'down']}
      coverScreen={false}
      hasBackdrop={false}
      //https://github.com/react-native-community/react-native-modal/issues/163
      useNativeDriver={false}
      swipeThreshold={50}
      // avoidKeyboard
      {...dialogProps}
      style={[styles.dialog, dialogProps.style]}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
        <SafeAreaView>
          <View
            {...viewProps}
            style={[
              {
                backgroundColor: theme.palette.background,
                borderRadius: theme.borderRadius,
              },
              viewProps?.style,
            ]}>
            {children}
          </View>
        </SafeAreaView>
      </KeyboardAvoidingView>
    </Dialog>
  );
}
Example #14
Source File: index.tsx    From nlw-ecoleta with MIT License 5 votes vote down vote up
Home = () => {
  const [uf, setUf] = useState('');
  const [city, setCity] = useState('');
  const navigation = useNavigation();

  function handleNavigateToPoints() {
    navigation.navigate('Points', { uf, city });
  }
    return (
    <KeyboardAvoidingView style={{ flex: 1}} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
    <ImageBackground 
        source={require('../../assets/home-background.png')} 
        style={styles.container}
        imageStyle={{ width: 274, height: 368 }}
    >
        <View style={styles.main}>
            <Image source={require('../../assets/logo.png')} />
            <View>
              <Text style={styles.title}>Seu marketplace de coleta de resíduos</Text>
              <Text style={styles.description}>Ajudamos pessoas a encontrarem pontos de coleta de forma eficiente</Text>
            </View>
        </View>

        <View style={styles.footer}>

        <TextInput 
        style={styles.input} 
        placeholder="Digite a UF"
        value={uf}
        maxLength={2}
        autoCapitalize="characters"
        autoCorrect={false}
        onChangeText={setUf}
        />

        <TextInput 
        style={styles.input} 
        placeholder="Digite a cidade"
        value={city}
        autoCorrect={false}
        onChangeText={setCity}
        />

          <RectButton style={styles.button} onPress={handleNavigateToPoints}>
            <View style={styles.buttonIcon}>
              <Text> 
                <Icon name='arrow-right' color='#FFF' size={24} />
              </Text>
            </View>
            <Text style={styles.buttonText}> Entrar </Text>
          </RectButton>
        </View>
    </ImageBackground>
    </KeyboardAvoidingView>
    );
}
Example #15
Source File: App.tsx    From rn-credit-card with MIT License 5 votes vote down vote up
App: React.FC = () => {
  let [fontsLoaded] = useFonts({
    RobotoMono_400Regular,
    RobotoMono_700Bold,
  })
  const formMethods = useForm<FormModel>({
    // to trigger the validation on the blur event
    mode: 'onBlur',
    defaultValues: {
      holderName: '',
      cardNumber: '',
      expiration: '',
      cvv: '',
    },
  })
  const { handleSubmit, formState } = formMethods

  function onSubmit(model: FormModel) {
    Alert.alert('Success: ' + JSON.stringify(model, null, 2))
  }

  if (!fontsLoaded) {
    return <AppLoading />
  }

  return (
    <FormProvider {...formMethods}>
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.avoider}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          <CreditCardForm
            LottieView={LottieView}
            horizontalStart
            overrides={{
              labelText: {
                marginTop: 16,
              },
            }}
          />
        </KeyboardAvoidingView>
        {formState.isValid && (
          <Button
            style={styles.button}
            title={'CONFIRM PAYMENT'}
            onPress={handleSubmit(onSubmit)}
          />
        )}
      </SafeAreaView>
    </FormProvider>
  )
}
Example #16
Source File: SignIn.tsx    From online-groceries-app with MIT License 5 votes vote down vote up
Signin = ({navigation}: SignInProps) => {
  const behavior = Platform.OS === 'ios' ? 'padding' : undefined;

  const goToSignUp = () => {
    navigation.navigate(SignUp.name);
  };

  const goToHome = () => {
    navigation.navigate(Tabs.name);
  };

  return (
    <SignScaffold>
      <Image style={styles.logo} source={logo} />
      <View style={styles.form}>
        <View>
          <Text style={styles.headerTitle}>Sign in</Text>
          <Text style={styles.headerSubtitle}>
            Enter your emails and password
          </Text>
        </View>
        <KeyboardAvoidingView behavior={behavior}>
          <Input label="Email" />
          <View style={{marginTop: heightScreen * 0.011}} />
          <Input label="Password" />
        </KeyboardAvoidingView>

        <TouchableOpacity style={styles.forgotButtonBox}>
          <Text style={styles.infoText}>Forgot your password?</Text>
        </TouchableOpacity>
        <Button
          onPress={goToHome}
          bgColour="#53B175"
          txtColour="#FFF"
          text="Sign in"
        />
        <View style={styles.footer}>
          <Text style={styles.infoText}>Don’t have an account?</Text>
          <TouchableOpacity onPress={goToSignUp}>
            <Text style={[styles.infoText, styles.greenInfoText]}>Sign up</Text>
          </TouchableOpacity>
        </View>
      </View>
    </SignScaffold>
  );
}
Example #17
Source File: index.tsx    From NLW-1.0 with MIT License 5 votes vote down vote up
Home: React.FC = () => {
  const [uf, setUf] = useState("");
  const [city, setCity] = useState("");

  const navigation = useNavigation();

  function handleNavigateToPoints() {
    navigation.navigate("Points", {
      uf,
      city,
    });
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === "ios" ? "padding" : undefined}
    >
      <ImageBackground
        source={require("../../assets/home-background.png")}
        style={styles.container}
        imageStyle={{
          width: 274,
          height: 368,
        }}
      >
        <View style={styles.main}>
          <Image source={require("../../assets/logo.png")} />
          <View>
            <Text style={styles.title}>
              Seu marketplace de coleta de resíduos
            </Text>
            <Text style={styles.description}>
              Ajudamos pessoas a encontrarem pontos de coleta de forma
              eficiente.
            </Text>
          </View>
        </View>
        <View style={styles.footer}>
          <TextInput
            style={styles.input}
            value={uf}
            onChangeText={setUf}
            maxLength={2}
            autoCapitalize="characters"
            autoCorrect={false}
            placeholder="Digite a UF"
          />
          <TextInput
            style={styles.input}
            placeholder="Digite a cidade"
            value={city}
            autoCorrect={false}
            onChangeText={setCity}
          />
          <RectButton
            style={styles.button}
            onPress={() => handleNavigateToPoints()}
          >
            <View style={styles.buttonIcon}>
              <Icon name="arrow-right" color="#fff" size={24} />
            </View>
            <Text style={styles.buttonText}>Entrar</Text>
          </RectButton>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
}
Example #18
Source File: Login.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
render() {
    return (
      <KeyboardAvoidingView style={styles.container} behavior='padding'>
          <View style={styles.header}>
            <Text style={styles.header_title}><%=project.name%></Text>
            <Text style={styles.header_subTitle}>Sign in to your account</Text>
          </View>
          <View style={styles.form}>
            {this.badCredentialsError && (
              <Text style={styles.form_globalError}>
                Login failed. Unknown login or bad password.
              </Text>
            )}
            {this.serverError && (
              <Text style={styles.form_globalError}>Server error</Text>
            )}
            <TextInput style={[
                styles.form_input,
                this.badCredentialsError && styles.form_input__invalid
              ]}
              value={this.login}
              placeholder="Login"
              placeholderTextColor={colors.placeholders}
              onChangeText={this.onLoginChange}
              onSubmitEditing={this.onSubmit}
            />
            <TextInput style={[
                styles.form_input,
                this.badCredentialsError && styles.form_input__invalid
              ]}
              value={this.password}
              placeholder="Password"
              placeholderTextColor={colors.placeholders}
              secureTextEntry={true}
              onChangeText={this.onPasswordChange}
              onSubmitEditing={this.onSubmit}
            />
            <PrimaryButton onPress={this.onSubmit}
                           loading={this.loading}
                           style={styles.form_submitButton}
                           disabled={!this.isSubmitEnabled()}
            >
              Log in
            </PrimaryButton>
          </View>
      </KeyboardAvoidingView>
    );
  }
Example #19
Source File: passwordBase.tsx    From companion-kit with MIT License 5 votes vote down vote up
renderContent() {
        const { keyboard } = this.props.context;
        const containerPadding = Layout.window.height - this._contentHeight + 20;
        const containerHeight = keyboard?.isOpened ? keyboard?.screenY : '100%';
        const scaleDownTitle = this.layout.isSmallDevice || this.layout.window.width < 365;

        const inputMargin = () => {
            if (this.useOptions) {
                return 32;
            }
            if (isAndroid) {
                return 100;
            } else {
                return 40;
            }
        };

        return (
            <KeyboardAvoidingView behavior={isAndroid ? 'padding' : null}>
                <MasloPage
                    onClose={this.onClose}
                    onBack={this.onGoBack}
                    inProgress={this.inProgress}
                    style={[this.baseStyles.page, { justifyContent: 'flex-start', position: 'relative' }]}
                >
                    <Container style={[
                        keyboard?.isOpened ? this.baseStyles.flexCenterBottom : this.baseStyles.flexStart,
                        { height: containerHeight, paddingTop: containerPadding },
                    ]}>
                        <View style={[this.baseStyles.textBlock, styles.textBlock, keyboard?.isOpened ? { position: 'absolute', top: containerPadding } : null]}>
                            <Text style={[scaleDownTitle ? this.textStyles.h3 : this.textStyles.h1, styles.title]}>{this.title}</Text>
                        </View>
                        <TextInput
                            onSubmit={this.submit}
                            model={this.viewModel.password}
                            forceError={this.viewModel.error}
                            autoFocus={this.allowInputAutoFocus}
                            autoCompleteType="password"
                            keyboardType="default"
                            textContentType="newPassword"
                            placeholder="Password"
                            autoCapitalize="none"
                            secureTextEntry
                            styleWrap={{ marginBottom: inputMargin() }}
                        />
                        {this.useOptions && (
                            <View style={[styles.buttons, { marginBottom: isAndroid ? 76 : 16 }]}>
                                {
                                    process.appFeatures.USE_MAGIC_LINK && (
                                        <>
                                            <TouchableOpacity style={styles.linkWrap} onPress={this.useMagicLink}>
                                                <Text style={[TextStyles.p4, styles.link]}>Use Magic Link</Text>
                                            </TouchableOpacity>
                                            <View style={styles.separator} />
                                        </>
                                    )
                                }

                                { this.useOptions !== 'magicLink' ? (
                                    <TouchableOpacity style={styles.linkWrap} onPress={this.forgotPassword}>
                                        <Text style={[TextStyles.p4, styles.link]}>Forgot Password?</Text>
                                    </TouchableOpacity>
                                ) : null}
                            </View>
                        )}
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #20
Source File: verificationCode.tsx    From companion-kit with MIT License 5 votes vote down vote up
renderContent() {
        const { inProgress, error } = this.viewModel;
        const { keyboard } = this.props.context;
        const containerPadding = Layout.window.height - this._contentHeight + 20;
        const containerHeight = keyboard?.isOpened ? keyboard?.screenY : '100%';
        const scaleDownTitle = this.layout.isSmallDevice || this.layout.window.width < 365;

        return (
            <KeyboardAvoidingView behavior={isAndroid ? 'padding' : null}>
                <MasloPage
                    inProgress={inProgress || AppController.Instance.loading}
                    onBack={this.goBack}
                    style={[this.baseStyles.page, { justifyContent: 'flex-start', position: 'relative' }]}
                >
                    <Container style={[
                        keyboard?.isOpened ? this.baseStyles.flexCenterBottom : this.baseStyles.flexStart,
                        { height: containerHeight, paddingTop: containerPadding },
                    ]}>
                        <View style={[this.baseStyles.textBlock, styles.textBlock, keyboard?.isOpened ? { position: 'absolute', top: containerPadding } : null]}>
                            <Text style={[scaleDownTitle ? this.textStyles.h3 : this.textStyles.h1, styles.title]}>{`Please enter 6-digit code`}</Text>
                            <Text style={[Layout.isSmallDevice ? this.textStyles.p2 : this.textStyles.p1, styles.desc]}>{`I’ve sent it to ${this.viewModel.email.value}`}</Text>
                        </View>
                        <View style={styles.otpBoxesContainer}>
                            {this.viewModel.verificationCodeValue.map((item, index) => (
                                <View style={[styles.otpBox, index === 2 ? styles.centerBox : null]} key={index}>
                                    <TextInput
                                        value={this.viewModel.verificationCodeValue[index]}
                                        ref={ref => this.viewModel.inputRefArray[index] = ref}
                                        // maxLength={1}
                                        keyboardType="numeric"
                                        onChangeText={value => this.onChangeVerificationCodeText(value, index)}
                                        onKeyPress={({ nativeEvent }) => this.onVerificationCodeKeyPress(nativeEvent, index)}
                                        style={{ height: '100%', textAlign: 'center', fontSize: 20 }}
                                        autoFocus={index === 0 ? true : false} />

                                </View>
                            ))}
                        </View>
                        {this.viewModel.errorMsg && <Text style={[TextStyles.labelMedium, styles.errorText]}>{this.viewModel.errorMsg}</Text>}
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #21
Source File: confirmAccount.tsx    From companion-kit with MIT License 5 votes vote down vote up
renderContent() {
        const { keyboard } = this.props.context;
        const containerPadding = 20 + Layout.window.height - this._contentHeight;
        const containerHeight =  keyboard?.isOpened ? keyboard?.screenY : '100%';
        const scaleDownTitle = this.layout.isSmallDevice || this.layout.window.width < 365;

        const step = this.currentStep;
        const inputVM = step.model();

        return (
            <KeyboardAvoidingView behavior={Platform.OS === 'android' ? 'padding' : null} enabled>
                <MasloPage
                    onBack={this.state.stepIndex > 0 ? this.onBack : null}
                    onClose={this.close}
                    style={[this.baseStyles.page, { justifyContent: 'flex-start' }]}
                >
                    <AnimatedContainer
                        animation="fadeIn"
                        duration={500}
                        delay={420}
                        style={[
                            this.baseStyles.container,
                            this.baseStyles.flexStart,
                            { justifyContent: keyboard?.isOpened ? 'space-between' : null, paddingTop: containerPadding, height: containerHeight },
                        ]}
                    >
                        <View style={this.baseStyles.textBlock}>
                            <Text style={[scaleDownTitle ? this.textStyles.h3 : this.textStyles.h1, styles.title]}>
                                {step.request}
                            </Text>
                        </View>
                        <TextInput
                            onSubmit={this.submit}
                            model={inputVM}
                            placeholder={inputVM.name}
                            autoFocus
                            styleWrap={styles.inputWrap}
                            keyboardType={step.keyboardType}
                            textContentType={step.textContentType}
                        />
                    </AnimatedContainer>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #22
Source File: noInvitation.tsx    From companion-kit with MIT License 5 votes vote down vote up
renderContent() {
        const model = NoInvitationViewModel.Instance;
        const { inProgress, error } = model;
        const { keyboard } = this.props.context;
        const containerPadding = Layout.window.height - this._contentHeight + 20;
        const containerHeight = keyboard?.isOpened ? keyboard?.screenY : '100%';
        const scaleDownTitle = this.layout.isSmallDevice || this.layout.window.width < 365;

        return (
            <KeyboardAvoidingView behavior={isAndroid ? 'padding' : null}>
                <MasloPage
                    inProgress={inProgress || AppController.Instance.loading}
                    onBack={this.goBack}
                    style={[this.baseStyles.page, { justifyContent: 'flex-start', position: 'relative' }]}
                >
                    <Container style={[
                        keyboard?.isOpened ? this.baseStyles.flexCenterBottom : this.baseStyles.flexStart,
                        { height: containerHeight, paddingTop: containerPadding },
                    ]}>
                        <View style={[this.baseStyles.textBlock, styles.textBlock, keyboard?.isOpened ? { position: 'absolute', top: containerPadding } : null]}>
                            <Text style={[scaleDownTitle ? this.textStyles.h3 : this.textStyles.h1, styles.title]}>{`I'm sorry, I am working with only invitation at the moment.`}</Text>
                            <Text style={[Layout.isSmallDevice ? this.textStyles.p2 : this.textStyles.p1, styles.desc]}>Please give me your email address, and I can contact you in the future when we open up the companion to general users.</Text>
                        </View>
                        <TextInput
                            onSubmit={this.submit}
                            model={model.email}
                            placeholder="[email protected]"
                            forceError={error}
                            autoFocus={this.allowInputAutoFocus}
                            autoCompleteType="email"
                            keyboardType="email-address"
                            textContentType="emailAddress"
                            autoCapitalize="none"
                            styleWrap={{ marginBottom: isAndroid ? 100 : 40 }}
                        />
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #23
Source File: index.tsx    From GoBarber with MIT License 4 votes vote down vote up
SignIn: React.FC = () => {
  const { signIn } = useAuth();
  const navigation = useNavigation();
  const passwordInputRef = useRef<TextInput>(null);
  const formRef = useRef<FormHandles>(null);

  const handleSignIn = useCallback(
    async (data: SignInFormData) => {
      try {
        formRef.current?.setErrors({});
        const schema = Yup.object().shape({
          email: Yup.string()
            .email('Digite email válido')
            .required('Email obrigatório'),
          password: Yup.string().required('Senha obrigatória'),
        });

        await schema.validate(data, {
          abortEarly: false,
        });

        await signIn({
          email: data.email,
          password: data.password,
        });
      } catch (err) {
        if (err instanceof Yup.ValidationError) {
          const errors = getValidationErrors(err);

          formRef.current?.setErrors(errors);

          return;
        }

        Alert.alert('Erro na autenticação', 'Ocorreu um erro ao fazer login');
      }
    },
    [signIn],
  );

  return (
    <>
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{ flex: 1 }}
        >
          <Container>
            <Image source={logoImg} />
            <View>
              <Title>Faça seu logon</Title>
            </View>
            <Form ref={formRef} onSubmit={handleSignIn}>
              <Input
                autoCorrect={false}
                autoCapitalize="none"
                keyboardType="email-address"
                name="email"
                icon="mail"
                placeholder="E-mail"
                returnKeyType="next"
                onSubmitEditing={() => {
                  passwordInputRef.current?.focus();
                }}
              />
              <Input
                ref={passwordInputRef}
                secureTextEntry
                name="password"
                icon="lock"
                placeholder="Senha"
                returnKeyType="send"
                onSubmitEditing={() => formRef.current?.submitForm()}
              />

              <Button onPress={() => formRef.current?.submitForm()}>
                Entrar
              </Button>
            </Form>
            <ForgotPassword>
              <ForgotPasswordText>Esqueci minha senha</ForgotPasswordText>
            </ForgotPassword>
          </Container>
        </ScrollView>
      </KeyboardAvoidingView>

      <CreateAccountButton
        onPress={() => {
          navigation.navigate('SignUp');
        }}
      >
        <Icon name="log-in" size={20} color="#ff9000" />
        <CreateAccountButtonText>Criar uma conta</CreateAccountButtonText>
      </CreateAccountButton>
    </>
  );
}
Example #24
Source File: TimePickerModal.tsx    From react-native-paper-dates with MIT License 4 votes vote down vote up
export function TimePickerModal({
  visible,
  onDismiss,
  onConfirm,
  hours,
  minutes,
  label = 'Select time',
  uppercase = true,
  cancelLabel = 'Cancel',
  confirmLabel = 'Ok',
  animationType = 'none',
  locale,
}: {
  locale?: undefined | string
  label?: string
  uppercase?: boolean
  cancelLabel?: string
  confirmLabel?: string
  hours?: number | undefined
  minutes?: number | undefined
  visible: boolean | undefined
  onDismiss: () => any
  onConfirm: (hoursAndMinutes: { hours: number; minutes: number }) => any
  animationType?: 'slide' | 'fade' | 'none'
}) {
  const theme = useTheme()

  const [inputType, setInputType] = React.useState<PossibleInputTypes>(
    inputTypes.picker
  )
  const [focused, setFocused] = React.useState<PossibleClockTypes>(
    clockTypes.hours
  )
  const [localHours, setLocalHours] = React.useState<number>(getHours(hours))
  const [localMinutes, setLocalMinutes] = React.useState<number>(
    getMinutes(minutes)
  )

  React.useEffect(() => {
    setLocalHours(getHours(hours))
  }, [setLocalHours, hours])

  React.useEffect(() => {
    setLocalMinutes(getMinutes(minutes))
  }, [setLocalMinutes, minutes])

  const onFocusInput = React.useCallback(
    (type: PossibleClockTypes) => setFocused(type),
    []
  )
  const onChange = React.useCallback(
    (params: {
      focused?: PossibleClockTypes | undefined
      hours: number
      minutes: number
    }) => {
      if (params.focused) {
        setFocused(params.focused)
      }

      setLocalHours(params.hours)
      setLocalMinutes(params.minutes)
    },
    [setFocused, setLocalHours, setLocalMinutes]
  )
  return (
    <Modal
      animationType={animationType}
      transparent={true}
      visible={visible}
      onRequestClose={onDismiss}
      presentationStyle="overFullScreen"
      supportedOrientations={supportedOrientations}
      //@ts-ignore
      statusBarTranslucent={true}
    >
      <>
        <TouchableWithoutFeedback onPress={onDismiss}>
          <View
            style={[
              StyleSheet.absoluteFill,
              styles.modalBackground,
              { backgroundColor: theme.colors.backdrop },
            ]}
          />
        </TouchableWithoutFeedback>

        <View
          style={[StyleSheet.absoluteFill, styles.modalRoot]}
          pointerEvents="box-none"
        >
          <KeyboardAvoidingView
            style={styles.keyboardView}
            behavior={'padding'}
          >
            <Animated.View
              style={[
                styles.modalContent,
                {
                  backgroundColor: theme.dark
                    ? overlay(10, theme.colors.surface)
                    : theme.colors.surface,
                  borderRadius: theme.roundness,
                },
              ]}
            >
              <View style={styles.labelContainer}>
                <Text style={[styles.label, { color: theme.colors.text }]}>
                  {uppercase ? label.toUpperCase() : label}
                </Text>
              </View>
              <View style={styles.timePickerContainer}>
                <TimePicker
                  locale={locale}
                  inputType={inputType}
                  focused={focused}
                  hours={localHours}
                  minutes={localMinutes}
                  onChange={onChange}
                  onFocusInput={onFocusInput}
                />
              </View>
              <View style={styles.bottom}>
                <IconButton
                  icon={inputTypeIcons[reverseInputTypes[inputType]]}
                  onPress={() => setInputType(reverseInputTypes[inputType])}
                  size={24}
                  style={styles.inputTypeToggle}
                  accessibilityLabel="toggle keyboard"
                />
                <View style={styles.fill} />
                <Button onPress={onDismiss} uppercase={uppercase}>
                  {cancelLabel}
                </Button>
                <Button
                  onPress={() =>
                    onConfirm({ hours: localHours, minutes: localMinutes })
                  }
                  uppercase={uppercase}
                >
                  {confirmLabel}
                </Button>
              </View>
            </Animated.View>
          </KeyboardAvoidingView>
        </View>
      </>
    </Modal>
  )
}
Example #25
Source File: index.tsx    From gobarber-mobile with MIT License 4 votes vote down vote up
Profile: React.FC = () => {
  const { user, updateUser } = useAuth();
  const theme = useTheme();

  const formRef = useRef<FormHandles>(null);
  const emailInputRef = useRef<TextInput>(null);
  const passwordInputRef = useRef<TextInput>(null);
  const oldPasswordInputRef = useRef<TextInput>(null);
  const confirmPasswordInputRef = useRef<TextInput>(null);

  const navigation = useNavigation();

  const handleGoBack = useCallback(() => {
    navigation.goBack();
  }, [navigation]);

  const handleUpdateAvatar = useCallback(() => {
    ImagePicker.showImagePicker(
      {
        title: 'Selecione um avatar',
        cancelButtonTitle: 'Cancelar',
        takePhotoButtonTitle: 'Usar câmera',
        chooseFromLibraryButtonTitle: 'Escolher da galeria',
      },
      responseImage => {
        if (responseImage.didCancel) {
          return;
        }

        if (responseImage.error) {
          Alert.alert('Erro ao atualizar seu avatar.');
          return;
        }

        const data = new FormData();

        data.append('avatar', {
          type: 'image/jpeg',
          name: `${user.id}.jpg`,
          uri: responseImage.uri,
        });

        api.patch('/users/avatar', data).then(response => {
          updateUser(response.data);
        });
      },
    );
  }, [user.id, updateUser]);

  const handleSubmit = useCallback(
    async (data: ProfileFormData) => {
      try {
        formRef.current?.setErrors({});

        const schema = Yup.object().shape({
          name: Yup.string().required('Nome é obrigatório'),
          email: Yup.string()
            .required('E-mail é obrigatório')
            .email('Digite um e-mail válido'),
          old_password: Yup.string(),
          password: Yup.string().when('old_password', {
            is: val => !!val.length,
            then: Yup.string()
              .min(6, 'No mínimo 6 dígitos')
              .required('Campo obrigatório'),
            otherwise: Yup.string(),
          }),
          password_confirmation: Yup.string()
            .when('old_password', {
              is: val => !!val.length,
              then: Yup.string().required('Campo obrigatório'),
              otherwise: Yup.string(),
            })
            .oneOf([Yup.ref('password'), null], 'Confirmação incorreta'),
        });

        await schema.validate(data, { abortEarly: false });

        const {
          name,
          email,
          old_password,
          password,
          password_confirmation,
        } = data;

        const formData = {
          name,
          email,
          ...(old_password
            ? {
                old_password,
                password,
                password_confirmation,
              }
            : {}),
        };

        const response = await api.put('/profile', formData);

        updateUser(response.data);

        Alert.alert('Perfil atualizado com sucesso!');
        navigation.goBack();
      } catch (err) {
        if (err instanceof Yup.ValidationError) {
          const errors = getValidationErrors(err);

          formRef.current?.setErrors(errors);
          return;
        }

        Alert.alert(
          'Erro na atualização do perfil',
          'Ocorreu um error ao atualizar seu perfil, tente novamente.',
        );
      }
    },
    [navigation, updateUser],
  );

  return (
    <>
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        enabled
      >
        <ScrollView keyboardShouldPersistTaps="handled">
          <Container>
            <BackButton onPress={handleGoBack}>
              <Icon name="chevron-left" size={24} color={theme.colors.gray} />
            </BackButton>

            <UserAvatarButton onPress={handleUpdateAvatar}>
              <UserAvatar
                source={{
                  uri:
                    user.avatar_url ||
                    'https://api.adorable.io/avatars/186/[email protected]',
                }}
              />
            </UserAvatarButton>

            <View>
              <Title>Meu Perfil</Title>
            </View>

            <Form
              initialData={{ name: user.name, email: user.email }}
              ref={formRef}
              onSubmit={handleSubmit}
            >
              <Input
                autoCapitalize="words"
                name="name"
                icon="user"
                placeholder="Nome"
                returnKeyType="next"
                onSubmitEditing={() => {
                  emailInputRef.current?.focus();
                }}
              />

              <Input
                ref={emailInputRef}
                keyboardType="email-address"
                autoCorrect={false}
                autoCapitalize="none"
                name="email"
                icon="mail"
                placeholder="E-mail"
                returnKeyType="next"
                onSubmitEditing={() => oldPasswordInputRef.current?.focus()}
              />

              <Input
                ref={oldPasswordInputRef}
                secureTextEntry
                name="old_password"
                icon="lock"
                placeholder="Senha atual"
                textContentType="newPassword"
                returnKeyType="next"
                containerStyle={{ marginTop: 16 }}
                onSubmitEditing={() => passwordInputRef.current?.focus()}
              />
              <Input
                ref={passwordInputRef}
                secureTextEntry
                name="password"
                icon="lock"
                placeholder="Nova senha"
                textContentType="newPassword"
                returnKeyType="next"
                onSubmitEditing={() => confirmPasswordInputRef.current?.focus()}
              />
              <Input
                ref={confirmPasswordInputRef}
                secureTextEntry
                name="password_confirmation"
                icon="lock"
                placeholder="Confirmar senha"
                textContentType="newPassword"
                returnKeyType="send"
                onSubmitEditing={() => formRef.current?.submitForm()}
              />

              <Button onPress={() => formRef.current?.submitForm()}>
                Confirmar mudanças
              </Button>
            </Form>
          </Container>
        </ScrollView>
      </KeyboardAvoidingView>
    </>
  );
}
Example #26
Source File: index.tsx    From gobarber-mobile with MIT License 4 votes vote down vote up
SignIn: React.FC = () => {
  const formRef = useRef<FormHandles>(null);
  const passwordInputRef = useRef<TextInput>(null);
  const navigation = useNavigation();
  const { signIn } = useAuth();

  const handleSignIn = useCallback(
    async (data: SignInFormData) => {
      try {
        formRef.current?.setErrors({});

        const schema = Yup.object().shape({
          email: Yup.string()
            .required('E-mail é obrigatório')
            .email('Digite um e-mail válido'),
          password: Yup.string().required('Senha é obrigatória'),
        });

        await schema.validate(data, { abortEarly: false });

        await signIn({
          email: data.email,
          password: data.password,
        });
      } catch (err) {
        if (err instanceof Yup.ValidationError) {
          const errors = getValidationErrors(err);

          formRef.current?.setErrors(errors);
          return;
        }

        Alert.alert(
          'Erro na autenticação',
          'Ocorreu um error ao fazer login, cheque as credenciais.',
        );
      }
    },
    [signIn],
  );

  return (
    <>
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        enabled
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{ flex: 1 }}
        >
          <Container>
            <Image source={logoImg} />

            <View>
              <Title>Faça seu logon</Title>
            </View>

            <Form onSubmit={handleSignIn} ref={formRef}>
              <Input
                autoCorrect={false}
                autoCapitalize="none"
                keyboardType="email-address"
                name="email"
                icon="mail"
                placeholder="E-mail"
                returnKeyType="next"
                onSubmitEditing={() => {
                  passwordInputRef.current?.focus();
                }}
              />

              <Input
                ref={passwordInputRef}
                name="password"
                icon="lock"
                placeholder="Senha"
                secureTextEntry
                returnKeyType="send"
                onSubmitEditing={() => formRef.current?.submitForm()}
              />

              <Button onPress={() => formRef.current?.submitForm()}>
                Entrar
              </Button>
            </Form>

            <ForgotPassword>
              <ForgotPasswordText>Esqueci minha senha</ForgotPasswordText>
            </ForgotPassword>
          </Container>
        </ScrollView>
      </KeyboardAvoidingView>

      <CreateAccountButton onPress={() => navigation.navigate('SignUp')}>
        <Icon name="log-in" size={20} />
        <CreateAccountButtonText>Criar uma conta</CreateAccountButtonText>
      </CreateAccountButton>
    </>
  );
}
Example #27
Source File: index.tsx    From gobarber-mobile with MIT License 4 votes vote down vote up
SignUp: React.FC = () => {
  const formRef = useRef<FormHandles>(null);
  const emailInputRef = useRef<TextInput>(null);
  const passwordInputRef = useRef<TextInput>(null);

  const navigation = useNavigation();

  const handleSignUp = useCallback(
    async (data: SignUpFormData) => {
      try {
        formRef.current?.setErrors({});

        const schema = Yup.object().shape({
          name: Yup.string().required('Nome é obrigatório'),
          email: Yup.string()
            .required('E-mail é obrigatório')
            .email('Digite um e-mail válido'),
          password: Yup.string().min(6, 'No mínimo 6 dígitos'),
        });

        await schema.validate(data, { abortEarly: false });

        await api.post('/users', data);

        Alert.alert(
          'Cadastro realizado com sucesso!',
          'Você ja pode fazer login na aplicação.',
        );
        navigation.goBack();
      } catch (err) {
        if (err instanceof Yup.ValidationError) {
          const errors = getValidationErrors(err);

          formRef.current?.setErrors(errors);
          return;
        }

        Alert.alert(
          'Erro na cadastro',
          'Ocorreu um error ao fazer cadastro, tente novamente.',
        );
      }
    },
    [navigation],
  );

  return (
    <>
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        enabled
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{ flex: 1 }}
        >
          <Container>
            <Image source={logoImg} />

            <View>
              <Title>Crie sua conta</Title>
            </View>

            <Form ref={formRef} onSubmit={handleSignUp}>
              <Input
                autoCapitalize="words"
                name="name"
                icon="user"
                placeholder="Nome"
                returnKeyType="next"
                onSubmitEditing={() => {
                  emailInputRef.current?.focus();
                }}
              />

              <Input
                ref={emailInputRef}
                keyboardType="email-address"
                autoCorrect={false}
                autoCapitalize="none"
                name="email"
                icon="mail"
                placeholder="E-mail"
                returnKeyType="next"
                onSubmitEditing={() => passwordInputRef.current?.focus()}
              />

              <Input
                ref={passwordInputRef}
                secureTextEntry
                name="password"
                icon="lock"
                placeholder="Senha"
                textContentType="newPassword"
                returnKeyType="send"
                onSubmitEditing={() => formRef.current?.submitForm()}
              />

              <Button onPress={() => formRef.current?.submitForm()}>
                Cadastrar
              </Button>
            </Form>
          </Container>
        </ScrollView>
      </KeyboardAvoidingView>

      <BackToSign onPress={() => navigation.goBack()}>
        <Icon name="arrow-left" size={20} />
        <BackToSignText>Voltar para logon</BackToSignText>
      </BackToSign>
    </>
  );
}
Example #28
Source File: recordTextCheckIn.tsx    From companion-kit with MIT License 4 votes vote down vote up
renderContent() {
        const { isEditable, textRecord } = this.textRecordVM;
        const { keyboard } = this.props.context;

        const editableContentPadding = this.layout.window.height - this._contentHeight;
        const editableContentHeight = keyboard?.isOpened ? keyboard?.screenY - editableContentPadding : '100%';

        return (
            <KeyboardAvoidingView behavior={android ? 'padding' : null} style={{ height: '100%' }}>
                <MasloPage
                    withDots
                    dotLength={3}
                    activeDot={2}
                    onClose={this.onClose}
                    style={!isEditable ? this.baseStyles.page : { justifyContent: 'flex-start', paddingTop: editableContentPadding }}
                >
                    <Container style={[
                        this.baseStyles.container,
                        this.baseStyles.flexBetween,
                        isEditable ? styles.content : null,
                        { height: !isEditable ? this._contentHeight : editableContentHeight },
                        ]}>
                        {!isEditable ? (
                            <View style={[this.baseStyles.textBlock, styles.textBlock]}>
                                <Text style={[
                                    this.textStyles.h1,
                                    this.baseStyles.textCenter,
                                    { fontSize: this._questionFontSize(this.textStyles.h1.fontSize, 23), lineHeight: this._questionFontSize(this.textStyles.h1.lineHeight, 27) }]}
                                >
                                    {this.viewModel.question}
                                </Text>
                            </View>
                        ) : (
                            <Text style={[
                                this.textStyles.h3, styles.editingTitle,
                                { fontSize: this._questionFontSize(this.textStyles.h3.fontSize, !this.layout.isSmallDevice ? 20 : 18), lineHeight: this._questionFontSize(this.textStyles.h3.lineHeight, !this.layout.isSmallDevice ? 23 : 21)}]}
                            >
                                {this.viewModel.question}
                            </Text>
                        )}
                        <View style={[this.baseStyles.flexStart, isEditable ? styles.inputWrap : styles.inputWrapNotEditable]}>
                            {!isEditable ?
                                <>
                                    <TouchableOpacity onPress={this._onEditPress} style={styles.editBtn} activeOpacity={0.6}>
                                        <View style={styles.editBtnWrap}>
                                            <Images.editIcon width={18} height={18}/>
                                            <Text style={[this.textStyles.labelMedium, styles.editBtnLabel]}>Edit your text</Text>
                                        </View>
                                    </TouchableOpacity>
                                    <Text numberOfLines={3} style={[this.textStyles.p1, styles.notEditableText]}>
                                        {this.textRecordVM.textRecord.value}
                                    </Text>
                                </>
                                :
                                <>
                                    <TextInput
                                        autoFocus
                                        styleInput={[this.textStyles.p3, styles.input]}
                                        placeholder="Start typing your answer here. "
                                        model={textRecord}
                                        multiline
                                        styleError={styles.error}
                                        returnKeyType="none"
                                        skipBlurOnSubmit
                                    />
                                    <Button
                                        title="Done"
                                        onPress={this._onSubmit}
                                        style={styles.saveButton}
                                    />
                                </>
                            }
                        </View>
                        {!isEditable &&
                            <ButtonBlock
                                okTitle="save"
                                cancelTitle="delete"
                                onOk={this.tryToSubmit}
                                onCancel={this.delete}
                            />
                        }
                    </Container>
                </MasloPage>
            </KeyboardAvoidingView>
        );
    }
Example #29
Source File: Navigator.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 4 votes vote down vote up
Navigator = (props: NavigatorProps) => {
  const {
    storageLoaded,
    instanceUrl,
    loggedInUsername,
    myInfoSuccess,
    isCalledMyInfo,
    initialRoute,
    myInfo,
    enabledModules,
    myInfoFailed,
  } = props;
  const dimensions = useWindowDimensions();
  const [isSubscribed, setIsSubscribed] = useState(false);
  const {changeCurrentRoute} = useGlobals();
  const {isApiCompatible} = useApiDetails();

  const onRouteChange = () => {
    const currentRoute = getNavigation()?.getCurrentRoute()?.name;
    if (currentRoute) {
      changeCurrentRoute(currentRoute);
    }
  };

  useEffect(() => {
    if (
      instanceUrl !== null &&
      loggedInUsername !== null &&
      !myInfoSuccess &&
      !isCalledMyInfo
    ) {
      props.fetchMyInfo();
    }

    if (getNavigation() !== null && !isSubscribed) {
      getNavigation()?.addListener('state', onRouteChange);
      setIsSubscribed(true);
    }
    /* eslint-disable react-hooks/exhaustive-deps */
  }, [
    instanceUrl,
    loggedInUsername,
    myInfoSuccess,
    isCalledMyInfo,
    isSubscribed,
  ]);
  /* eslint-enable react-hooks/exhaustive-deps */

  useEffect(() => {
    return () => {
      getNavigation()?.removeListener('state', onRouteChange);
    };
    /* eslint-disable react-hooks/exhaustive-deps */
  }, []);
  /* eslint-enable react-hooks/exhaustive-deps */

  let view = null;
  if (storageLoaded.loaded) {
    if (instanceUrl !== null && loggedInUsername !== null) {
      const isLargeScreen = isLargeScreenByWidth(dimensions.width);
      if (myInfoSuccess || myInfoFailed) {
        view = (
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            style={styles.root}>
            <Drawer.Navigator
              initialRouteName={initialRoute}
              openByDefault={false}
              drawerType={isLargeScreen ? 'permanent' : 'front'}
              drawerStyle={
                isLargeScreen ? {width: DEFAULT_FIXED_DRAWER_WIDTH} : undefined
              }
              drawerContent={(drawerContentProps: any) => (
                <DrawerContent {...drawerContentProps} />
              )}>
              {myInfoFailed === true ? (
                <Drawer.Screen
                  name={NO_EMPLOYEE_INFO}
                  component={NoEmployeeInfo}
                />
              ) : (
                <>
                  {enabledModules !== undefined &&
                  enabledModules.modules.leave &&
                  enabledModules.meta.leave.isLeavePeriodDefined ? (
                    <>
                      <Drawer.Screen
                        name={APPLY_LEAVE}
                        component={ApplyLeave}
                        options={{drawerLabel: 'Apply Leave'}}
                        initialParams={{subheader: SUBHEADER_LEAVE}}
                      />
                      <Drawer.Screen
                        name={MY_LEAVE_ENTITLEMENT_AND_USAGE}
                        component={MyLeaveUsage}
                        options={{drawerLabel: 'My Leave Usage'}}
                        initialParams={{subheader: SUBHEADER_LEAVE}}
                      />
                      {myInfo?.user.userRole === USER_ROLE_ADMIN ||
                      myInfo?.user.isSupervisor === true ? (
                        <>
                          <Drawer.Screen
                            name={LEAVE_LIST}
                            component={LeaveList}
                            options={{drawerLabel: 'Leave List'}}
                            initialParams={{subheader: SUBHEADER_LEAVE}}
                          />
                          <Drawer.Screen
                            name={ASSIGN_LEAVE}
                            component={AssignLeave}
                            options={{drawerLabel: 'Assign Leave'}}
                            initialParams={{subheader: SUBHEADER_LEAVE}}
                          />
                        </>
                      ) : null}
                    </>
                  ) : null}

                  {isApiCompatible(ORANGEHRM_API_1$2$0) &&
                  enabledModules !== undefined &&
                  enabledModules.modules.time &&
                  enabledModules.meta.time.isTimesheetPeriodDefined ? (
                    <>
                      <Drawer.Screen
                        name={PUNCH}
                        component={Punch}
                        options={{drawerLabel: 'Punch In/Out'}}
                        initialParams={{subheader: SUBHEADER_TIME}}
                      />
                      <Drawer.Screen
                        name={ATTENDANCE_SUMMARY}
                        component={AttendanceSummary}
                        options={{drawerLabel: 'My Attendance'}}
                        initialParams={{subheader: SUBHEADER_TIME}}
                      />
                      {myInfo?.user.userRole === USER_ROLE_ADMIN ||
                      myInfo?.user.isSupervisor === true ? (
                        <Drawer.Screen
                          name={ATTENDANCE_LIST}
                          component={AttendanceList}
                          options={{drawerLabel: 'Employee Attendance'}}
                          initialParams={{subheader: SUBHEADER_TIME}}
                        />
                      ) : null}
                    </>
                  ) : null}

                  {/* fallback info page */}
                  <Drawer.Screen
                    name={FULL_SCREEN_INFO}
                    component={FullScreenInfo}
                  />
                </>
              )}
            </Drawer.Navigator>
          </KeyboardAvoidingView>
        );
      } else {
        view = <Overlay modalProps={{visible: true}} />;
      }
    } else {
      let initialRouteName = LOGIN;
      if (instanceUrl === null) {
        initialRouteName = SELECT_INSTANCE;
      }

      view = (
        <Stack.Navigator
          headerMode={'none'}
          initialRouteName={initialRouteName}>
          <Stack.Screen name={SELECT_INSTANCE} component={SelectInstance} />
          <Stack.Screen name={LOGIN} component={Login} />
          <Stack.Screen
            name={SELECT_INSTANCE_HELP}
            component={SelectInstanceHelp}
          />
        </Stack.Navigator>
      );
    }
  } else {
    view = <Overlay modalProps={{visible: true}} />;
  }

  return <NavigationContainer ref={navigationRef}>{view}</NavigationContainer>;
}