react-native-paper#TextInput JavaScript Examples

The following examples show how to use react-native-paper#TextInput. 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: index.js    From puente-reactnative-collect with MIT License 6 votes vote down vote up
Feedback = () => {
  const handleEmail = async () => {
    await MailComposer.isAvailableAsync().then((mailAvailable) => {
      if (mailAvailable) {
        MailComposer.composeAsync({
          recipients: ['[email protected]'],
          subject: 'User Feedback',
          body: emailBody
        });
      }
    });
  };

  const [emailBody, setEmailBody] = useState('');

  return (
    <View style={styles.mainContainer}>
      <Headline>{I18n.t('feedback.feedback')}</Headline>
      <View style={styles.horizontalLinePrimary} />
      <Text>{I18n.t('feedback.enterFeedback')}</Text>
      <View style={styles.horizontalLinePrimary} />
      <TextInput
        multiline
        onChangeText={(text) => setEmailBody(text)}
        placeholder={I18n.t('feedback.typeFeedback')}
      />
      <View style={styles.languageContainer}>
        <Button mode="contained" onPress={() => handleEmail()}>{I18n.t('feedback.sendMail')}</Button>
      </View>
    </View>
  );
}
Example #2
Source File: index.js    From Cosmos with MIT License 6 votes vote down vote up
render() {
    const {commenting, comment, post, isBottomSheetOpen} = this.state;

    return (
      <View style={styles.commentScreen}>
        {this.renderComments()}
        <View style={styles.addComment}>
          <TextInput
            style={[Styles.fontMedium, styles.textInput]}
            mode="outlined"
            placeholder={post.comment ? 'Comment' : 'Start a discussion'}
            maxLength={300}
            value={comment}
            dense={true}
            onChangeText={(c) => this.setComment(c)}
          />
          <Button
            labelStyle={Styles.fontSmall}
            style={styles.commentBtn}
            loading={commenting}
            icon="send"
            onPress={() => this.comment()}>
            Comment
          </Button>
        </View>
        <BottomSheet
          isOpen={isBottomSheetOpen}
          closeBottomSheet={() => this.setBottomSheet(false)}
          options={[
            {text: 'Remove Comment', onPress: this.handleCommentDelete},
          ]}
        />
      </View>
    );
  }
Example #3
Source File: index.js    From puente-reactnative-collect with MIT License 6 votes vote down vote up
export default function FormInput({
  label, formikProps, formikKey, ...rest
}) {
  return (
    <View style={{ marginHorizontal: 15, marginVertical: 0 }}>
      <TextInput
        label={label}
        onChangeText={formikProps.handleChange(formikKey)}
        onBlur={formikProps.handleBlur(formikKey)}
        {...rest}
        mode="outlined"
        theme={{ colors: { placeholder: theme.colors.primary }, text: 'black' }}
      />
      <Text style={{ color: 'red' }}>
        {formikProps.touched[formikKey] && formikProps.errors[formikKey]}
      </Text>
    </View>
  );
}
Example #4
Source File: Dropdown.js    From Legacy with Mozilla Public License 2.0 5 votes vote down vote up
export function Dropdown({
  onValueChange,
  selectedValue,
  style,
  testID,
  enabled,
  mode,
  itemStyle,
  children,
  ...rest
}) {
  const [open, setOpen] = React.useState(false);
  const [size, onLayout] = useComponentSize();
  return (
    <Menu
      visible={open}
      onDismiss={() => setOpen(false)}
      anchor={
        <TextInput
          style={style}
          right={
            <TextInput.Icon onPress={() => setOpen(true)} name="chevron-down" />
          }
          mode={mode}
          value={
            [].concat(children).find((i) => i.props.value === selectedValue)
              ?.props.label ?? selectedValue
          }
          disabled={enabled === false}
          editable={false}
          onLayout={onLayout}
          render={({ style, value, onLayout }) => (
            <TouchableWithoutFeedback
              onPress={enabled === false ? undefined : () => setOpen(true)}
            >
              <View
                style={{ paddingLeft: 14, display: "flex", flexDirection: "row", alignSelf: "stretch", flex: 1, alignItems: "center" }}
                onLayout={onLayout}
              >
                <Text style={{fontSize:16}}>{value}</Text>
              </View>
            </TouchableWithoutFeedback>
          )}
          {...rest}
        />
      }
      style={{
        marginTop: size?.height,
        width: size?.width,
      }}
    >
      <ScrollView style={{ maxHeight: 400 }}>
        {[].concat(children).map((item) => (
          <Menu.Item
            style={itemStyle}
            disabled={item.props.value === selectedValue}
            onPress={() => {
              onValueChange(item.props.value);
              setOpen(false);
            }}
            title={item.props.label}
          />
        ))}
      </ScrollView>
    </Menu>
  );
}
Example #5
Source File: RtdTextWriter.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function RtdTextWriter(props, ref) {
  const inputRef = React.useRef();
  const [value, setValue] = React.useState(props.value || '');

  if (ref) {
    ref.current = {
      getValue: () => value,
    };
  }

  const writeNdef = async () => {
    inputRef.current && inputRef.current.blur();

    if (!value) {
      return;
    }

    await NfcProxy.writeNdef({type: 'TEXT', value});
  };

  return (
    <View>
      <TextInput
        ref={inputRef}
        mode="outlined"
        label="Text"
        multiline={true}
        value={value}
        autoCapitalize={false}
        onChangeText={setValue}
        style={{marginBottom: 10}}
        autoFocus={true}
      />

      <Button mode="contained" labelStyle={{fontSize: 20}} onPress={writeNdef}>
        WRITE
      </Button>
    </View>
  );
}
Example #6
Source File: TextField.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
TextField = ({
  theme,
  field: {
    value,
    name,
  },
  form,
  placeholder,
  multiline = false,
  keyboardType = 'default',
  onSubmitEditing,
  disabled,
  hideError,
  autoCompleteType = 'off',
}) => {
  const styling = styles(theme)
  const { t } = useTranslation()

  const onFocus = () => {
    form.setFieldTouched(name, true)
  }
  const onBlur = (event) => {
    form.handleBlur(name)(event)
    // form.setFieldTouched(name, false)
  }
  const onChangeText = (event) => {
    form.handleChange(name)(event)
  }

  return (
    <View style={styling.root}>
      <TextInput
        style={styling.input}
        name={name}
        onChangeText={onChangeText}
        onBlur={onBlur}
        onFocus={onFocus}
        value={value}
        placeholder={placeholder}
        placeholderTextColor={theme.colors.placeholder}
        autoCapitalize="none"
        multiline={multiline}
        keyboardType={keyboardType}
        onSubmitEditing={onSubmitEditing}
        mode="outlined"
        dense={true}
        label={placeholder}
        disabled={disabled}
        autoCompleteType={autoCompleteType}
      />

      {!hideError ?
        <ErrorMessage name={name} render={msg => <Text style={styling.error}>{msg}</Text>} />
        : null}
    </View>
  )
}
Example #7
Source File: ColumnsList.jsx    From react-native-big-list with Apache License 2.0 5 votes vote down vote up
export default function SectionList() {
  const [numberColumns, setNumberColumns] = useState(3);
  const renderItem = ({ item }) => {
    return (
      <List.Item
        title={item.title}
        description={item.description}
        style={styles.container}
        left={(props) => <List.Icon {...props} icon="account" />}
      />
    );
  };
  const renderEmpty = () => <List.Item title="No items" />;
  const renderHeader = () => (
    <View>
      <TextInput
        label="Number of columns (max 10)"
        value={String(numberColumns)}
        type="numeric"
        keyboardType="numeric"
        onChangeText={(value) => {
          const num = parseInt(value, 10) || "";
          setNumberColumns(num);
        }}
      />
    </View>
  );
  const renderFooter = () => (
    <Block>
      <Subheading>No more items available...</Subheading>
    </Block>
  );
  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView style={styles.container}>
        <View style={styles.compare}>
          <BigList
            style={styles.container}
            data={data}
            numColumns={Math.min(
              Math.max(parseInt(numberColumns, 10) || 1, 1),
              10,
            )}
            // Item
            itemHeight={90}
            renderItem={renderItem}
            renderEmpty={renderEmpty}
            // Header
            headerHeight={90}
            renderHeader={renderHeader}
            // Footer
            footerHeight={100}
            renderFooter={renderFooter}
          />
        </View>
        <StatusBar style="auto" />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
Example #8
Source File: RtdUriShortcutWriter.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function RtdUriShortcutWriter(props, ref) {
  const scheme = props.scheme;
  const [value, setValue] = React.useState(props.value?.value || '');
  const inputRef = React.useRef();

  if (ref) {
    ref.current = {
      getValue: () => ({value, scheme}),
    };
  }

  const writeNdef = async () => {
    inputRef.current && inputRef.current.blur();

    if (!value) {
      return;
    }

    const url = scheme + value;
    await NfcProxy.writeNdef({type: 'URI', value: url});
  };

  return (
    <View>
      <View style={{flexDirection: 'row', marginBottom: 10}}>
        <Button mode="outlined" disabled>
          {scheme}
        </Button>

        <View style={{flex: 1}} />
      </View>

      <TextInput
        ref={inputRef}
        mode="outlined"
        label={InputLabel[scheme]}
        multiline={true}
        value={value}
        autoCapitalize={false}
        onChangeText={setValue}
        style={{marginBottom: 20}}
      />

      <Button mode="contained" labelStyle={{fontSize: 20}} onPress={writeNdef}>
        WRITE
      </Button>
    </View>
  );
}
Example #9
Source File: RtdUriWriter.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function RtdUriWriter(props, ref) {
  const [value, setValue] = React.useState(props.value?.value || '');
  const [prefix, setPrefix] = React.useState(props.value?.prefix || 'https://');
  const [showMenu, setShowMenu] = React.useState(false);
  const inputRef = React.useRef();

  if (ref) {
    ref.current = {
      getValue: () => ({value, prefix}),
    };
  }

  const writeNdef = async () => {
    inputRef.current && inputRef.current.blur();

    if (!value) {
      return;
    }

    let url = value;
    if (prefix !== '---') {
      url = prefix + value;
    }

    await NfcProxy.writeNdef({type: 'URI', value: url});
  };

  return (
    <View>
      <View style={{flexDirection: 'row', marginBottom: 10}}>
        <Menu
          visible={showMenu}
          onDismiss={() => setShowMenu(false)}
          anchor={
            <Button mode="outlined" onPress={() => setShowMenu(true)}>
              {prefix}
            </Button>
          }>
          {['https://', 'http://', '---'].map((type) => (
            <Menu.Item
              key={type}
              onPress={() => {
                setPrefix(type);
                setShowMenu(false);
              }}
              title={type}
            />
          ))}
        </Menu>
        <View style={{flex: 1}} />
      </View>

      <TextInput
        ref={inputRef}
        mode="outlined"
        label="URI"
        multiline={true}
        value={value}
        autoCapitalize={false}
        onChangeText={setValue}
        style={{marginBottom: 20}}
      />

      <Button mode="contained" labelStyle={{fontSize: 20}} onPress={writeNdef}>
        WRITE
      </Button>
    </View>
  );
}
Example #10
Source File: SaveRecordModal.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function SaveRecordModal(props) {
  const {visible, onClose, title, onPersistRecord} = props;
  const [name, setName] = React.useState('');

  React.useEffect(() => {
    if (!visible) {
      setName('');
    }
  }, [visible]);

  return (
    <Modal visible={visible} animationType="slide">
      <Appbar.Header>
        <Appbar.Action
          icon={() => <Icon name="close" size={24} />}
          onPress={onClose}
        />
        <Appbar.Content title={title || 'SAVE RECORD'} />
      </Appbar.Header>
      <View style={[styles.wrapper, {padding: 15, backgroundColor: 'white'}]}>
        <TextInput
          value={name}
          onChangeText={setName}
          label="Name"
          mode="outlined"
          autoFocus={true}
          style={{marginBottom: 10}}
        />
        <Button
          mode="contained"
          onPress={() => {
            if (name) {
              onPersistRecord(name);
            }
          }}>
          SAVE
        </Button>
      </View>
    </Modal>
  );
}
Example #11
Source File: VCardWriter.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function VCardWriter(props, ref) {
  const [name, setName] = React.useState(props.value?.name || '');
  const [org, setOrg] = React.useState(props.value?.org || '');
  const [tel, setTel] = React.useState(props.value?.tel || '');
  const [email, setEmail] = React.useState(props.value?.email || '');

  if (ref) {
    ref.current = {
      getValue: () => ({name, org, tel, email}),
    };
  }

  const writeNdef = async () => {
    if (!name || (!tel && !email)) {
      Alert.alert(
        'Invalid Input',
        'Must provide "Name" and either "Tel" or "Email"',
      );
      return;
    }

    await NfcProxy.writeNdef({
      type: 'VCARD',
      value: {name, org, tel, email},
    });
  };

  return (
    <View>
      <TextInput
        mode="outlined"
        label="Name"
        value={name}
        onChangeText={setName}
        style={{marginBottom: 10}}
      />

      <TextInput
        mode="outlined"
        label="Org"
        value={org}
        onChangeText={setOrg}
        style={{marginBottom: 10}}
      />

      <TextInput
        mode="outlined"
        label="Tel"
        value={tel}
        onChangeText={setTel}
        style={{marginBottom: 10}}
      />

      <TextInput
        mode="outlined"
        label="Email"
        value={email}
        onChangeText={setEmail}
        style={{marginBottom: 20}}
      />

      <Button mode="contained" labelStyle={{fontSize: 20}} onPress={writeNdef}>
        WRITE
      </Button>
    </View>
  );
}
Example #12
Source File: WifiSimpleWriter.js    From react-native-nfc-rewriter with MIT License 5 votes vote down vote up
function WifiSimpleWriter(props, ref) {
  const [ssid, setSsid] = React.useState(props.value?.ssid || '');
  const [networkKey, setNetworkKey] = React.useState(
    props.value?.networkKey || '',
  );

  if (ref) {
    ref.current = {
      getValue: () => ({ssid, networkKey}),
    };
  }

  const writeNdef = async () => {
    if (!ssid || !networkKey) {
      return;
    }

    await NfcProxy.writeNdef({
      type: 'WIFI_SIMPLE',
      value: {ssid, networkKey},
    });
  };

  return (
    <View>
      <TextInput
        mode="outlined"
        label="SSID"
        value={ssid}
        onChangeText={setSsid}
        style={{marginBottom: 10}}
      />

      <TextInput
        mode="outlined"
        label="Network Key"
        value={networkKey}
        onChangeText={setNetworkKey}
        style={{marginBottom: 20}}
      />

      <Button mode="contained" labelStyle={{fontSize: 20}} onPress={writeNdef}>
        WRITE
      </Button>
    </View>
  );
}
Example #13
Source File: index.js    From puente-reactnative-collect with MIT License 5 votes vote down vote up
PeopleModal = ({
  people,
  handleInputChange, handleAddClick, handleRemoveClick,
  toggleModal, stylesPaper, stylesDefault
}) => (
  <>
    <Appbar.Header style={{ backgroundColor: theme.colors.accent }}>
      <Appbar.Action icon="chevron-down" onPress={toggleModal} />
      <Appbar.Content title="People Manager" subtitle="" titleStyle={{ fontSize: 20, fontWeight: 'bold' }} />
    </Appbar.Header>
    {people.map((x, i) => (
      <ScrollView
        key={`${x}_${i}`} //eslint-disable-line
        style={{ margin: 20 }}
      >
        <KeyboardAvoidingView>
          <TextInput
            label={I18n.t('peopleModal.fname')}
            placeholder={I18n.t('peopleModal.enterFname')}
            onChangeText={(text) => handleInputChange(text, i, 'firstName')}
            mode="outlined"
            theme={stylesPaper}
            style={stylesDefault.label}
          />
          <TextInput
            label={I18n.t('peopleModal.lname')}
            placeholder={I18n.t('peopleModal.enterLname')}
            onChangeText={(text) => handleInputChange(text, i, 'lastName')}
            mode="outlined"
            theme={stylesPaper}
            style={stylesDefault.label}
          />
          <TextInput
            label={I18n.t('peopleModal.relationship')}
            onChangeText={(text) => handleInputChange(text, i, 'relationship')}
            mode="outlined"
            theme={stylesPaper}
            style={stylesDefault.label}
          />
          <View>
            {people.length !== 1 && (
              <PaperButton
                buttonText={I18n.t('peopleModal.remove')}
                onPressEvent={() => handleRemoveClick(i)}
              />
            )}
            {people.length - 1 === i && (
              <PaperButton
                buttonText={I18n.t('peopleModal.add')}
                onPressEvent={handleAddClick}
              />
            )}
          </View>
        </KeyboardAvoidingView>
      </ScrollView>
    ))}
  </>
)
Example #14
Source File: index.js    From puente-reactnative-collect with MIT License 5 votes vote down vote up
AutoFillMS = (props) => {
  const [fields, setFields] = useState([]);
  const [query, setQuery] = useState('');
  const [values, setValues] = useState(null);
  const [selectedValues, setSelectedValues] = useState([]);

  useEffect(() => {
    const { parameter } = props;
    async function fetchAutofill() {
      return getData('autofill_information');
    }
    fetchAutofill().then((data) => {
      const result = data[parameter];
      setFields(result.sort());
      setValues(result.length > 0);
    });
  }, []);

  const findField = () => {
    if (query === '') {
      return [];
    }
    const regex = new RegExp(`${query.trim()}`, 'i');
    return fields.filter((field) => field.search(regex) >= 0);
  };

  const fieldz = findField(query);
  const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();
  const {
    label, translatedLabel, formikProps, formikKey, scrollViewScroll, setScrollViewScroll
  } = props;

  const placeholder = I18n.t(label);

  return (
    <View style={styles.container}>
      <View style={styles.chipRow}>
        {selectedValues.map((item) => (
          <TouchableOpacity
            key={item}
            style={styles.chip}
            onPress={() => {
              const arr = selectedValues.filter((itm) => itm !== item);
              setSelectedValues(arr);
              formikProps.setFieldValue(formikKey, arr);
            }}
          >
            <Chip key={item}>
              {item}
            </Chip>
          </TouchableOpacity>
        ))}
      </View>
      {!values && (
        <TextInput
          label={translatedLabel.length > 40 ? '' : translatedLabel}
          onChangeText={formikProps.handleChange(formikKey)}
          onBlur={formikProps.handleBlur(formikKey)}
          mode="outlined"
          theme={stylesPaper}
          style={stylesDefault.label}
        />
      )}
      {values && Platform.OS === 'ios' && (
        <View>
          <Autocomplete
            autoCapitalize="none"
            autoCorrect={false}
            containerStyle={styles.autocompleteContainer}
            inputContainerStyle={styles.textInputContainer}
            data={fieldz.length === 1 && comp(query, fieldz[0]) ? [] : fieldz}
            defaultValue={query}
            onChangeText={(text) => {
              setQuery(text);
            }}
            placeholder={placeholder}
            placeholderTextColor="black"
            listStyle={styles.listContainer}
            keyExtractor={() => uuid.v4()}
            onStartShouldSetResponderCapture={() => {
              setScrollViewScroll(false);
              if (fieldz.length === 0
                    && scrollViewScroll === false) {
                setScrollViewScroll(true);
              }
            }}
            renderItem={({ item }) => (
              <TouchableOpacity
                key={`${item}`}
                onPress={() => {
                  setQuery(item);
                  selectedValues.push(item);
                  setSelectedValues([...new Set(selectedValues)]);
                  formikProps.setFieldValue(formikKey, selectedValues);
                  setQuery('');
                }}
              >
                <Text style={styles.itemText} key={item}>
                  {item}
                </Text>
              </TouchableOpacity>
            )}
          />
        </View>
      )}
      {values && Platform.OS === 'android' && (
        <View>
          <Autocomplete
            autoCapitalize="none"
            autoCorrect={false}
            containerStyle={styles.autocompleteContainer}
            inputContainerStyle={styles.textInputContainer}
            data={fieldz.length === 1 && comp(query, fieldz[0]) ? [] : fieldz}
            defaultValue={query}
            onChangeText={(text) => {
              setQuery(text);
            }}
            placeholder={placeholder}
            placeholderTextColor="black"
            listStyle={styles.listContainer}
            keyExtractor={() => uuid.v4()}
            renderItem={({ item }) => (
              <TouchableOpacity
                key={`${item}`}
                onPress={() => {
                  setQuery(item);
                  selectedValues.push(item);
                  setSelectedValues([...new Set(selectedValues)]);
                  formikProps.setFieldValue(formikKey, selectedValues);
                  setQuery('');
                }}
              >
                <Text style={styles.itemText} key={item}>
                  {item}
                </Text>
              </TouchableOpacity>
            )}
          />
        </View>
      )}
    </View>
  );
}
Example #15
Source File: index.js    From Cosmos with MIT License 5 votes vote down vote up
render() {
    const {enrolledBy, btnLoading, isBottomSheetOpen} = this.state;

    return (
      <View style={styles.boxScreenContainer}>
        <View style={styles.authorContainer}>
          <Headline style={Styles.fontMedium}>
            Author: {this.state.auth[0]}
          </Headline>
        </View>
        <View style={styles.addPartConatiner}>
          <Text style={Styles.fontSmall}>Add Participant</Text>
          <TextInput
            style={[Styles.fontMedium, styles.textInput]}
            mode="outlined"
            placeholder="Email"
            maxLength={50}
            value={this.state.email}
            dense={true}
            onChangeText={(email) => this.setAddParticipant(email)}
          />
          <Button
            labelStyle={Styles.fontSmall}
            loading={btnLoading}
            icon="plus"
            onPress={() => this.handleAddUser()}>
            Add Member
          </Button>
        </View>
        <FlatList
          ListHeaderComponent={() => {
            return (
              <Text style={Styles.fontSmall}>
                Enrolled Users: {enrolledBy.length}
              </Text>
            );
          }}
          ListHeaderComponentStyle={{margin: 10}}
          ListEmptyComponent={() => {
            return <ActivityIndicator />;
          }}
          data={enrolledBy}
          keyExtractor={(item) => item.uid}
          renderItem={({item, index}) => {
            return (
              <Card
                style={styles.card}
                onPress={() => this.handleOptions(index)}>
                <Card.Content>
                  <Subheading style={Styles.fontMedium}>{item.name}</Subheading>
                </Card.Content>
              </Card>
            );
          }}
          ItemSeparatorComponent={() => <Divider style={styles.Divider} />}
        />
        <BottomSheet
          isOpen={isBottomSheetOpen}
          closeBottomSheet={() => this.setBottomSheet(false)}
          options={[{text: 'Remove User', onPress: this.handleRemoveUser}]}
        />
      </View>
    );
  }
Example #16
Source File: index.js    From Cosmos with MIT License 5 votes vote down vote up
render() {
    const {state} = this.context;
    const {enrolledBoxes, newBoxName, btnLoading} = this.state;
    return (
      <View style={styles.listCircleContainer}>
        <Text style={[Styles.fontSmall, styles.helpText]}>
          Boxes are your personal Friend/Family/Work groups where you share
          relevant posts which interest a perticular group. You can either join
          an existing group or create a new group.
        </Text>
        <View style={styles.addPartConatiner}>
          <Text style={Styles.fontSmall}>Create New Box</Text>
          <TextInput
            style={[Styles.fontMedium, styles.textInput]}
            mode="outlined"
            placeholder="Box Name"
            maxLength={30}
            dense={true}
            value={newBoxName}
            onChangeText={(nb) => this.setNewBoxName(nb)}
          />
          <Button
            labelStyle={Styles.fontSmall}
            loading={btnLoading}
            icon="plus"
            onPress={() => this.handleCreateBox()}>
            Create Box
          </Button>
        </View>
        <Divider />
        <FlatList
          ListHeaderComponent={() => {
            return <Text style={Styles.fontSmall}>Enrolled Boxes</Text>;
          }}
          ListHeaderComponentStyle={{margin: 10}}
          ListEmptyComponent={() => {
            return (
              <View style={styles.emptyComponentContainer}>
                <Planet
                  size={width / 2.5}
                  mood={newBoxName.length !== 0 ? 'lovestruck' : 'blissful'}
                  color="#FCCB7E"
                />
                <Headline style={[Styles.fontMedium, styles.noBoxesYet]}>
                  Here you create new Boxes and see what boxes you are enrolled
                  in. To switch boxes you just tap on them from the given list.
                  To get started create a New Box, don't forget to give it
                  exciting name.
                </Headline>
              </View>
            );
          }}
          data={enrolledBoxes}
          keyExtractor={(item) => item}
          renderItem={({item}) => {
            return (
              <Card
                onPress={() => this.handleSelectBox(item)}
                style={styles.card}>
                <Card.Content style={styles.cardContent}>
                  <Subheading styles={Styles.fontMedium}>{item}</Subheading>
                  {state.box === item ? (
                    <Icons
                      name="check"
                      size={20}
                      color={DarkTheme.colors.primary}
                    />
                  ) : null}
                </Card.Content>
              </Card>
            );
          }}
          ItemSeparatorComponent={() => <Divider style={styles.Divider} />}
        />
      </View>
    );
  }
Example #17
Source File: index.js    From Cosmos with MIT License 5 votes vote down vote up
render() {
    const {username, user, loggingOut, updating: updating} = this.state;

    return (
      <View style={styles.settingContainer}>
        <ScrollView>
          <Image
            source={{uri: auth().currentUser.photoURL}}
            style={styles.userImage}
          />
          <View style={styles.inputChangeContainer}>
            <Text style={Styles.fontSmall}>Username</Text>
            <TextInput
              mode="outlined"
              placeholder="Username"
              maxLength={40}
              value={username}
              dense={true}
              style={[Styles.fontMedium, styles.inAppTextInput]}
              onChangeText={(newUsername) => this.setUsername(newUsername)}
              onKeyPress={() => this.checkForChange()}
            />
          </View>
          <View style={styles.inputChangeContainer}>
            <Text style={Styles.fontSmall}>Email</Text>
            <TextInput
              mode="outlined"
              disabled={true}
              placeholder="Email"
              value={user.email}
              dense={true}
              style={[Styles.fontMedium, styles.inAppTextInput]}
              editable={false}
            />
          </View>
          <View style={styles.btnWrapper}>
            <Button
              labelStyle={Styles.fontSmall}
              loading={updating}
              mode="contained"
              icon="update"
              onPress={this.onSubmit}
              disabled={this.state.isUpdateDisabled}>
              Update
            </Button>
            <Button
              labelStyle={Styles.fontSmall}
              loading={loggingOut}
              icon="logout"
              mode="contained"
              onPress={this.onSignOut}>
              Log Out
            </Button>
          </View>
        </ScrollView>
      </View>
    );
  }
Example #18
Source File: Universal.js    From Legacy with Mozilla Public License 2.0 5 votes vote down vote up
function Report({qr}) {
  var [reportMenu, setReportMenu] = React.useState(false);
  var [reportOption, setReportOption] = React.useState("invalid_secret_code");
  var [reportMessage, setReportMessage] = React.useState("");
  function report(data) {
    setRunReport({qr,data});
  }
  var [runReport, setRunReport] = React.useState(false);
  var { status: reportStatus } = useAPIRequest(runReport ? {
    endpoint: 'user/universal/report/v1',
    data: {
      report: JSON.stringify(runReport, null, 2)
    },
    cuppazee: true
  } : null, true)
  return <>
    <Button onPress={() => setReportMenu(true)} icon="alert">Report as broken</Button>
    <Portal>
        <Dialog visible={reportMenu} onDismiss={()=>setReportMenu(false)}>
          {runReport ? (reportStatus === "loading" ? <Dialog.Title>Reporting...</Dialog.Title> : <>
            <Dialog.Title>{!reportStatus ? "Munzee Reported" : "An error occurred"}</Dialog.Title>
            <Dialog.Actions>
              <Button onPress={()=>{setReportMenu(false);setRunReport(false)}}>Close</Button>
            </Dialog.Actions>
          </>) : <>
            <Dialog.Title>Report Munzee</Dialog.Title>
            <Dialog.Content>
              <RadioButton.Group onValueChange={value => setReportOption(value)} value={reportOption}>
                <RadioButton.Item label="Invalid Secret Code" value="invalid_secret_code" />
                <RadioButton.Item label="Unable to Scan" value="unable_to_scan" />
                <RadioButton.Item label="Other" value="other" />
                {reportOption === "other" && <TextInput label="Report Message" mode="outlined" value={reportMessage} onChangeText={(msg)=>setReportMessage(msg)} />}
              </RadioButton.Group>
              </Dialog.Content>
            <Dialog.Actions>
              <Button onPress={()=>setReportMenu(false)}>Cancel</Button>
              <Button onPress={()=>report(reportOption==="other"?reportMessage:reportOption)}>Report</Button>
            </Dialog.Actions>
          </>}
        </Dialog>
    </Portal>
  </>
}
Example #19
Source File: Create.js    From Get-Placed-App with MIT License 5 votes vote down vote up
export default function Create() {
    const [title, setTitle] = useState("")
    const [body, setbody] = useState("")

    const createTwoButtonAlert = () =>
        Alert.alert(
            "Alert",
            "Add Blog through our website",
            [
                {
                    text: "Cancel",
                    onPress: () => console.log("Cancel Pressed"),
                    style: "cancel"
                },
                { text: "OK", onPress: () => Linking.openURL('http://getplaced.pythonanywhere.com/Add_Blog_Post/') }
            ]
        );

    return (
        <View>
            <TextInput style={styles.inputStyle}
                label="Title"
                value={title}
                mode="outlined"
                onChangeText={text => setTitle(text)}
                outlineColor="#002223"
            />
            <TextInput style={{ marginTop: 10, padding: 8, }}
                label="Body"
                value={body}
                mode="outlined"
                onChangeText={text => setbody(text)}
            />
            <Button style={{ marginTop: 30, width: 180, marginLeft: 100, }}
                icon="pencil"
                mode="contained"
                color="#002223"
                onPress={createTwoButtonAlert}
            >Post Blog</Button>
        </View>
    )
}
Example #20
Source File: index.js    From react-native-nfc-rewriter with MIT License 4 votes vote down vote up
function SettingsScreen(props) {
  const [nfcStatus, setNfcStatus] = React.useState(null);
  const [feedback, setFeedback] = React.useState('');
  const [keyboardPadding, setKeyboardPadding] = React.useState(0);
  const scrollViewRef = React.useRef();
  const scrollPosRef = React.useRef(0);

  React.useEffect(() => {
    function onNfcStateChanged(evt = {}) {
      const {state} = evt;
      setNfcStatus(state === 'on');
    }

    async function checkNfcState() {
      setNfcStatus(await NfcManager.isEnabled());
      NfcManager.setEventListener(NfcEvents.StateChanged, onNfcStateChanged);
    }

    if (Platform.OS === 'android') {
      checkNfcState();
    }

    return () => {
      if (Platform.OS === 'android') {
        NfcManager.setEventListener(NfcEvents.StateChanged, null);
      }
    };
  }, []);

  React.useEffect(() => {
    async function onKbShow() {
      const estimatedKbHeight = Dimensions.get('window').width;
      setKeyboardPadding(estimatedKbHeight);
      setTimeout(() => {
        scrollViewRef.current.scrollTo({
          y: scrollPosRef.current + estimatedKbHeight,
        });
      }, 200);
    }

    function onKbHide() {
      setKeyboardPadding(0);
    }

    if (Platform.OS === 'ios') {
      Keyboard.addListener('keyboardWillShow', onKbShow);
      Keyboard.addListener('keyboardWillHide', onKbHide);
    }

    return () => {
      if (Platform.OS === 'ios') {
        Keyboard.removeListener('keyboardWillShow', onKbShow);
        Keyboard.removeListener('keyboardWillHide', onKbHide);
      }
    };
  }, []);

  return (
    <ScrollView
      style={[styles.wrapper]}
      ref={scrollViewRef}
      onScroll={({nativeEvent}) => {
        scrollPosRef.current = nativeEvent.contentOffset.y;
      }}
      keyboardShouldPersistTaps="handled">
      <View style={styles.topBanner}>
        <Text style={{lineHeight: 16}}>{generalText}</Text>
      </View>
      <List.Section>
        {Platform.OS === 'android' && (
          <>
            <List.Item
              title="NFC Status"
              description={
                nfcStatus === null ? '---' : nfcStatus ? 'ON' : 'OFF'
              }
            />
            <List.Item
              title="NFC Settings"
              description="Jump to System NFC Settings"
              onPress={() => {
                NfcManager.goToNfcSetting();
              }}
            />
          </>
        )}
        <List.Item title="Version" description={version} />
        <List.Item
          title="Repository"
          description="https://github.com/revtel/react-native-nfc-rewriter"
          onPress={() => {
            Linking.openURL(
              'https://github.com/revtel/react-native-nfc-rewriter',
            );
          }}
        />
        <List.Subheader>Creators</List.Subheader>
        <List.Item
          title="Revteltech 忻旅科技"
          left={() => (
            <Image
              source={require('../../../images/revicon_512.png')}
              style={styles.maintainerIcon}
              resizeMode="contain"
            />
          )}
          description="https://www.revtel.tech/en"
          onPress={() => {
            Linking.openURL('https://www.revtel.tech/en');
          }}
        />
        <List.Item
          title="Washow 萬象創造"
          left={() => (
            <Image
              source={require('../../../images/washow_icon.png')}
              style={styles.maintainerIcon}
              resizeMode="contain"
            />
          )}
          description="http://www.washow.cc"
          onPress={() => {
            Linking.openURL('http://www.washow.cc');
          }}
        />
      </List.Section>

      <View style={{padding: 12}}>
        <Text style={{textAlign: 'center', fontSize: 16}}>Your Feedback</Text>
        <TextInput
          style={{marginTop: 8}}
          value={feedback}
          onChangeText={setFeedback}
        />
        <Button
          mode="contained"
          style={{marginTop: 8}}
          onPress={() => {
            if (feedback) {
              captureException(new Error('Feedback'), {
                section: 'feedback',
                extra: {feedback},
              });
              Alert.alert('Thanks for your feedback');
            }
            setFeedback('');
          }}>
          SEND
        </Button>
      </View>

      {keyboardPadding > 0 && <View style={{height: keyboardPadding}} />}
    </ScrollView>
  );
}
Example #21
Source File: index.js    From Cosmos with MIT License 4 votes vote down vote up
render() {
    const {image, imageCaption, isLoading} = this.state;
    const {state} = this.context;

    if (state.box.length === 0) {
      return (
        <View style={styles.addContainer}>
          <Backpack size={width / 2.5} mood="sad" color="#FFD882" />
          <Headline style={[Styles.fontMedium, styles.imgText]}>
            Oops looks like you haven't created a group yet. Please go back to
            the Home screen and take Sun's help to create one first
          </Headline>
        </View>
      );
    }

    if (isLoading) {
      return (
        <View style={styles.addContainer}>
          <BoxLoading />
        </View>
      );
    }

    if (image !== null) {
      return (
        <View style={styles.addContainer}>
          <AppHeader
            iconLeft="x"
            onPressLeft={() => {
              Alert.alert(
                'Discard Post',
                'Do you want to discard your post, all changes will be lost?',
                [
                  {
                    text: 'Discard',
                    onPress: () =>
                      this.setState({
                        isLoading: false,
                        fileBlog: null,
                        image: null,
                        imageCaption: '',
                      }),
                  },
                  {
                    text: 'Cancel',
                    onPress: () => {},
                  },
                ],
                {cancelable: true},
              );
            }}
            iconRight="send"
            onPressRight={this.onPostUpload}
          />
          <ScrollView showsVerticalScrollIndicator={false}>
            <View>
              <Image style={styles.loadedImage} source={image} />
              <View style={styles.captionContainer}>
                <TextInput
                  value={imageCaption}
                  style={styles.textInputCaption}
                  onChangeText={(caption) => this.setImageCaption(caption)}
                  placeholder="Write a caption"
                  placeholderTextColor="white"
                  autoCapitalize="sentences"
                  autoFocus={true}
                  maxLength={300}
                  multiline={true}
                  numberOfLines={6}
                  textAlignVertical="top"
                  defaultValue="No Caption"
                />
              </View>
            </View>
          </ScrollView>
        </View>
      );
    }

    return (
      <View style={styles.addContainer}>
        <Backpack size={width / 2.5} mood="excited" color="#FFD882" />
        <Headline style={[Styles.fontMedium, styles.imgText]}>
          Lets see what you got in your bag of pics, or I can help you get a
          shot if you need help with that
        </Headline>
        <View style={styles.optionsContainer}>
          <TouchableOpacity
            style={styles.optionContainer}
            onPress={() => {
              if (state.box === '') {
                return ToastAndroid.showWithGravity(
                  'No Box selected!',
                  ToastAndroid.SHORT,
                  ToastAndroid.CENTER,
                );
              }
              this.openImagePicker();
            }}>
            <Icon size={width * 0.06} name="plus" color="white" />
            <Text style={Styles.fontMedium}>Open Bag</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.optionContainer}
            onPress={() => {
              if (state.box === '') {
                return ToastAndroid.showWithGravity(
                  'No Box selected!',
                  ToastAndroid.SHORT,
                  ToastAndroid.CENTER,
                );
              }
              this.openImageCamera();
            }}>
            <Icon size={width * 0.06} name="camera" color="white" />
            <Text style={Styles.fontMedium}>Start Camera</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
Example #22
Source File: RequestTokenForm.js    From mern-stack with MIT License 4 votes vote down vote up
render() {
    const {
      clearErrorMessage,
      errorMessage,
      isProcessing,
      navigation,
      title,
      theme: { colors },
    } = this.props;
    return (
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : null}
        style={styles.container}
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="on-drag"
        >
          <IconButton
            icon="chevron-left"
            color={colors.primary}
            size={30}
            accessibilityLabel="Back to sign in"
            onPress={() => navigation.goBack()}
          />
          <Logo />
          <Spacer>
            <Title style={{ alignSelf: 'center', color: colors.primary }}>
              {title}
            </Title>
          </Spacer>
          <Spacer>
            <TextInput
              label="Email"
              mode="outlined"
              dense
              value={this.state.email}
              autoCapitalize="none"
              autoCorrect={false}
              keyboardType="email-address"
              onChangeText={(email) => this.setState({ email })}
              onSubmitEditing={this.onSubmit}
              onFocus={clearErrorMessage}
              disabled={isProcessing || !!this.state.message}
            />
          </Spacer>
          <Spacer vertical={16}>
            <Button
              mode="contained"
              accessibilityLabel="Submit"
              onPress={this.onSubmit}
              loading={isProcessing}
              disabled={isProcessing || !!this.state.message}
            >
              Submit
            </Button>
          </Spacer>
        </ScrollView>
        <Snackbar
          visible={errorMessage}
          onDismiss={clearErrorMessage}
          action={{
            label: 'Dismiss',
            accessibilityLabel: 'Dismiss',
            onPress: () => {},
          }}
        >
          {errorMessage}
        </Snackbar>
        <Snackbar
          visible={this.state.message}
          onDismiss={() => navigation.goBack()}
          action={{
            label: 'Go Back',
            accessibilityLabel: 'Go Back',
            onPress: () => {},
          }}
        >
          {this.state.message}
        </Snackbar>
      </KeyboardAvoidingView>
    );
  }
Example #23
Source File: SignInScreen.js    From mern-stack with MIT License 4 votes vote down vote up
render() {
    const {
      clearErrorMessage,
      errorMessage,
      isProcessing,
      theme: { colors },
      type,
      unloadAuthScreen,
    } = this.props;
    return (
      <SafeAreaView forceInset={{ top: 'always' }} style={styles.container}>
        <NavigationEvents onWillBlur={unloadAuthScreen} />
        <StatusBar barStyle="dark-content" />
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : null}
          style={styles.container}
        >
          <ScrollView
            keyboardShouldPersistTaps="handled"
            keyboardDismissMode="on-drag"
          >
            <Logo />
            <Spacer>
              <Title style={{ alignSelf: 'center', color: colors.primary }}>
                Sign In
              </Title>
            </Spacer>
            <Spacer>
              <TextInput
                label="Email"
                mode="outlined"
                dense
                value={this.state.email}
                autoCapitalize="none"
                autoCorrect={false}
                keyboardType="email-address"
                onChangeText={(email) => this.setState({ email })}
                onSubmitEditing={this.onEmailSignIn}
                onFocus={clearErrorMessage}
                disabled={isProcessing}
              />
              <Spacer />
              <TextInput
                label="Password"
                mode="outlined"
                dense
                secureTextEntry
                value={this.state.password}
                autoCapitalize="none"
                autoCorrect={false}
                onChangeText={(password) => this.setState({ password })}
                onSubmitEditing={this.onEmailSignIn}
                onFocus={clearErrorMessage}
                disabled={isProcessing}
              />
              <View style={styles.navLinks}>
                <NavLink
                  text="Forgot password?"
                  routeName="RequestPasswordReset"
                  disabled={isProcessing}
                />
                <NavLink
                  text="Register instead!"
                  routeName="SignUp"
                  disabled={isProcessing}
                />
              </View>
            </Spacer>
            <Spacer vertical={4}>
              <Button
                mode="contained"
                accessibilityLabel="Sign In"
                onPress={this.onEmailSignIn}
                loading={isProcessing && type === 'email'}
                disabled={isProcessing}
              >
                Sign In
              </Button>
            </Spacer>
            <Spacer vertical={12}>
              <Text style={{ alignSelf: 'center' }}>Or Sign In With</Text>
            </Spacer>
            <Spacer>
              <OAuthButtons />
            </Spacer>
            {errorMessage === 'Email is not verified' && (
              <NavLink
                text="Have not received verification email?"
                routeName="RequestVerificationEmail"
                disabled={isProcessing}
              />
            )}
          </ScrollView>
          <Snackbar
            visible={errorMessage}
            onDismiss={clearErrorMessage}
            action={{
              label: 'Dismiss',
              accessibilityLabel: 'Dismiss',
              onPress: () => {},
            }}
          >
            {errorMessage}
          </Snackbar>
        </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
Example #24
Source File: SignUpScreen.js    From mern-stack with MIT License 4 votes vote down vote up
render() {
    const {
      clearErrorMessage,
      errorMessage,
      isProcessing,
      theme: { colors },
      type,
      unloadAuthScreen,
    } = this.props;
    return (
      <SafeAreaView forceInset={{ top: 'always' }} style={styles.container}>
        <NavigationEvents onWillBlur={unloadAuthScreen} />
        <StatusBar barStyle="dark-content" />
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : null}
          style={styles.container}
        >
          <ScrollView
            keyboardShouldPersistTaps="handled"
            keyboardDismissMode="on-drag"
          >
            <Logo />
            <Spacer>
              <Title style={{ alignSelf: 'center', color: colors.primary }}>
                Sign Up
              </Title>
            </Spacer>
            <Spacer>
              <TextInput
                label="Username"
                mode="outlined"
                dense
                value={this.state.username}
                autoCapitalize="none"
                autoCorrect={false}
                onChangeText={(username) => this.setState({ username })}
                onSubmitEditing={this.onEmailRegister}
                onFocus={clearErrorMessage}
                disabled={isProcessing}
              />
              <Spacer />
              <TextInput
                label="Email"
                mode="outlined"
                dense
                value={this.state.email}
                autoCapitalize="none"
                autoCorrect={false}
                keyboardType="email-address"
                onChangeText={(email) => this.setState({ email })}
                onSubmitEditing={this.onEmailRegister}
                onFocus={clearErrorMessage}
                disabled={isProcessing}
              />
              <Spacer />
              <View style={styles.fullName}>
                <TextInput
                  label="First Name"
                  mode="outlined"
                  style={styles.name}
                  dense
                  value={this.state.firstName}
                  autoCorrect={false}
                  onChangeText={(firstName) => this.setState({ firstName })}
                  onSubmitEditing={this.onEmailRegister}
                  onFocus={clearErrorMessage}
                  disabled={isProcessing}
                />
                <TextInput
                  label="Last Name"
                  mode="outlined"
                  style={styles.name}
                  dense
                  value={this.state.lastName}
                  autoCorrect={false}
                  onChangeText={(lastName) => this.setState({ lastName })}
                  onSubmitEditing={this.onEmailRegister}
                  onFocus={clearErrorMessage}
                  disabled={isProcessing}
                />
              </View>
              <Spacer />
              <TextInput
                label="Password"
                mode="outlined"
                dense
                secureTextEntry
                value={this.state.password}
                autoCapitalize="none"
                autoCorrect={false}
                onChangeText={(password) => this.setState({ password })}
                onSubmitEditing={this.onEmailRegister}
                onFocus={clearErrorMessage}
                disabled={isProcessing}
              />
              <View style={styles.navLinks}>
                <NavLink text="Sign in instead!" routeName="SignIn" />
              </View>
            </Spacer>
            <Spacer vertical={4}>
              <Button
                mode="contained"
                accessibilityLabel="Sign In"
                onPress={this.onEmailRegister}
                loading={isProcessing && type === 'email'}
                disabled={isProcessing}
              >
                Sign Up
              </Button>
            </Spacer>
            <Spacer vertical={12}>
              <Text style={{ alignSelf: 'center' }}>Or Sign Up With</Text>
            </Spacer>
            <Spacer>
              <OAuthButtons />
            </Spacer>
          </ScrollView>
          <Snackbar
            visible={errorMessage}
            onDismiss={clearErrorMessage}
            action={{
              label: 'Dismiss',
              accessibilityLabel: 'Dismiss',
              onPress: () => {},
            }}
          >
            {errorMessage}
          </Snackbar>
        </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
Example #25
Source File: Home.jsx    From react-native-big-list with Apache License 2.0 4 votes vote down vote up
Home = () => {
  const {
    colors: { background, surface },
  } = useTheme();
  const [openSelector, setOpenSelector] = useState(false);
  const [selected, setSelected] = useState("standard");
  const [insetBottom, setInsetBottom] = useState(0);
  const insets = useSafeAreaInsets();
  const options = [
    { label: "Standard List", value: "standard" },
    { label: "Columns List", value: "columns" },
    { label: "Sections List", value: "sections" },
    { label: "Multiselect List", value: "multiselect" },
    { label: "Compare List", value: "compare" },
  ];
  const selectedOption = options.find((item) => item.value === selected);
  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: background,
          paddingBottom: insetBottom + insets.bottom + 64,
        },
      ]}
    >
      <Appbar.Header style={[styles.header, { height: 75 }]}>
        <Appbar.Content title="BigList Example" subtitle="10.000 items" />
      </Appbar.Header>
      <TouchableOpacity
        style={[
          styles.containerBottom,
          { backgroundColor: surface, bottom: insets.bottom },
        ]}
        onPress={() => setOpenSelector(!openSelector)}
        onLayout={(event) => {
          setInsetBottom(event.height || 0);
        }}
      >
        <TextInput
          label="View mode"
          editable={false}
          onTouchStart={() => setOpenSelector(true)}
          value={selectedOption.label}
          right={
            <TextInput.Icon
              name="chevron-down"
              onPress={() => setOpenSelector(!openSelector)}
            />
          }
        />
      </TouchableOpacity>
      {selected === "standard" ? (
        <List />
      ) : selected === "columns" ? (
        <ColumnsList />
      ) : selected === "sections" ? (
        <SectionList />
      ) : selected === "multiselect" ? (
        <MultiSelectList />
      ) : selected === "compare" ? (
        <CompareList />
      ) : null}

      {openSelector && (
        <View
          style={[
            StyleSheet.absoluteFill,
            { flex: 1, backgroundColor: surface },
          ]}
        >
          <Appbar.Header style={[styles.header, { height: 75 }]}>
            <Appbar.Content
              title="View mode"
              subtitle="Select the list view mode example..."
            />
          </Appbar.Header>
          <SelectList
            data={options}
            value={selected}
            onSelect={(value) => {
              setSelected(value);
              setOpenSelector(false);
            }}
          />
        </View>
      )}
    </View>
  );
}
Example #26
Source File: astrologuers-question.screen.js    From astrale with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param route
 * @param navigation
 * @returns {*}
 * @constructor
 */
function AstrologerQuestionScreen({ route, navigation }) {
  const dispatch = useGlobals()[1];
  const astrologist = route.params.astrologist;
  const setData = React.useState({
    message: null,
    email: null,
    astrologer: astrologist.name,
  })[1];
  const isDark = useIsDark();
  const isAndroid = PlatformUtils.isAndroid;
  const handleProceed = () => {
    try {
      dispatch({ type: 'toggleLoader' });
    } catch {
    } finally {
      dispatch({ type: 'toggleLoader' });
      navigation.pop();
    }
  };

  return (
    <BlurView
      style={[StyleSheet.absoluteFill, { flex: 1 }]}
      tint={isDark ? 'dark' : 'light'}
      intensity={isAndroid ? 150 : 100}
    >
      <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
        <ScrollView style={{ paddingBottom: 200 }}>
          <Close position="right" />
          <View style={{ margin: 20, alignItems: 'center' }}>
            <Headline>{astrologist.name}</Headline>
            <Subheading>
              {i18n.t(astrologist.school, { word: i18n.t('Astrology') })}
            </Subheading>
            <Image source={astrologist.photo} style={styles.image} />
          </View>
          <Divider />
          <View style={{ margin: 20 }}>
            <View style={{ height: 5 }} />
            <TextInput
              label={i18n.t('Your question')}
              multiline
              style={{ height: 150 }}
              maxLength={250}
              onChangeText={(text) =>
                setData((data) => ({ ...data, message: text }))
              }
            />
            <View style={{ height: 5 }} />
            <TextInput
              label={i18n.t('Your email')}
              keyboardType="email-address"
              onChangeText={(text) =>
                setData((data) => ({ ...data, email: text }))
              }
            />
          </View>
          <View style={{ marginHorizontal: 20, marginBottom: 20 }}>
            <Button
              onPress={handleProceed}
              mode="contained"
              style={{ borderRadius: 20 }}
              icon="send"
            >
              {i18n.t('Proceed')}
            </Button>
            <Text style={styles.advice}>
              *
              {i18n.t(
                "You'll need to see an ad before you can send the question"
              )}
            </Text>
          </View>
          <Divider />
        </ScrollView>
      </TouchableWithoutFeedback>
    </BlurView>
  );
}
Example #27
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
Password = () => {
  const [submitting, setSubmitting] = useState(false);
  const [currentState, setCurrentState] = useState('');
  const [newState, setNewState] = useState('');

  const wrongCredentials = () => {
    Alert.alert(
      I18n.t('global.error'),
      I18n.t('passwordSettings.wrongCreds'), [
        { text: 'OK' }
      ],
      { cancelable: true }
    );
  };

  const handleFailedAttempt = () => {
    Alert.alert(
      I18n.t('global.error'),
      I18n.t('passwordSettings.errorMessage'), [
        { text: 'OK' }
      ],
      { cancelable: true }
    );
  };

  const handleSucccessfullAttempt = () => {
    Alert.alert(
      I18n.t('global.success'),
      I18n.t('passwordSettings.successMessage'), [
        { text: 'OK' }
      ],
      { cancelable: true }
    );
  };

  const changePassword = async () => {
    setSubmitting(true);
    const currentUser = await getData('currentUser');

    if (currentState !== currentUser.password) {
      setSubmitting(false);
      wrongCredentials();
    } else {
      const user = await Parse.User.logIn(currentUser.username, currentUser.password);
      user.set('password', newState);

      const submitAction = () => {
        setTimeout(() => {
          setSubmitting(false);
          handleSucccessfullAttempt();
        }, 1000);
      };

      await user.save().then(async () => {
        currentUser.password = newState;
        await storeData(currentUser, 'currentUser').then(() => {
          submitAction();
        }, (error) => {
          console.log(error); //eslint-disable-line
          setSubmitting(false);
          handleFailedAttempt();
        });
      }, (error) => {
        console.log(error); //eslint-disable-line
        setSubmitting(false);
        handleFailedAttempt();
      });
    }
  };

  return (
    <View>
      <Headline>{I18n.t('passwordSettings.changePassword')}</Headline>
      <View style={styles.horizontalLinePrimary} />
      <View style={styles.lineContainer}>
        <Text style={styles.text}>{I18n.t('passwordSettings.currentPassword')}</Text>
        <TextInput mode="outlined" onChangeText={(text) => setCurrentState(text)} />
      </View>
      <View style={styles.lineContainer}>
        <Text style={styles.text}>{I18n.t('passwordSettings.newPassword')}</Text>
        <TextInput mode="outlined" onChangeText={(text) => setNewState(text)} />
      </View>
      {submitting ? (
        <ActivityIndicator
          size="large"
          color={theme.colors.primary}
        />
      ) : (
        <Button mode="contained" onPress={() => changePassword()}>{I18n.t('passwordSettings.changePassword')}</Button>
      )}
    </View>
  );
}
Example #28
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
NamePhoneEmail = () => {
  useEffect(() => {
    async function setUserInformation() {
      const currentUser = await getData('currentUser');
      setObjectId(currentUser.objectId);
      const fname = currentUser.firstname;
      const lname = currentUser.lastname;
      const phoneNumber = currentUser.phonenumber;
      const { email } = currentUser;

      setUserObject({
        firstName: fname,
        lastName: lname,
        phoneNumber,
        email
      });
    }
    setUserInformation().then(() => {
      setInputs([
        {
          label: I18n.t('namePhoneEmailSettings.userInformation.fname'),
          value: userObject.firstName,
          key: 'firstName'
        },
        {
          label: I18n.t('namePhoneEmailSettings.userInformation.lname'),
          value: userObject.lastName,
          key: 'lastName'
        },
        {
          label: I18n.t('namePhoneEmailSettings.userInformation.phoneNumber'),
          value: userObject.phoneNumber,
          key: 'phoneNumber'
        },
        {
          label: I18n.t('namePhoneEmailSettings.userInformation.email'),
          value: userObject.email,
          key: 'email'
        }
      ]);
      setUpdated(false);
    });
  }, [updated]);

  const [userObject, setUserObject] = useState({});
  const [edit, setEdit] = useState('');
  const [inputs, setInputs] = useState([]);
  const [objectId, setObjectId] = useState('');
  const [updated, setUpdated] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const updateUserObject = (key, text) => {
    const copyUserObject = userObject;
    copyUserObject[key] = text;
    setUserObject(copyUserObject);
  };

  const handleFailedAttempt = () => {
    Alert.alert(
      I18n.t('global.error'),
      I18n.t('namePhoneEmailSettings.errorMessage'), [
        { text: 'OK' }
      ],
      { cancelable: true }
    );
  };

  const handleSucccessfullAttempt = () => {
    Alert.alert(
      I18n.t('global.success'),
      I18n.t('namePhoneEmailSettings.successMessage'), [
        { text: 'OK' }
      ],
      { cancelable: true }
    );
  };

  const updateUser = async () => {
    setSubmitting(true);
    const postParams = {
      objectId,
      firstname: userObject.firstName,
      lastname: userObject.lastName,
      email: userObject.email,
      phonenumber: userObject.phoneNumber
    };
    const currentUser = await getData('currentUser');

    const user = await Parse.User.logIn(currentUser.username, currentUser.password);
    for (const key in postParams) { //eslint-disable-line
      user.set(String(key), postParams[key]);
    }

    const submitAction = () => {
      setTimeout(() => {
        setSubmitting(false);
        handleSucccessfullAttempt();
      }, 1000);
    };

    await user.save().then(async (updatedUser) => {
      await storeData(updatedUser, 'currentUser').then(() => {
        setUpdated(true);
        submitAction();
      }, (error) => {
        console.log(error); //eslint-disable-line
        setSubmitting(false);
        handleFailedAttempt();
      });
    }, (error) => {
      console.log(error); //eslint-disable-line
      setSubmitting(false);
      handleFailedAttempt();
    });
  };

  return (
    <View>
      <Headline>{I18n.t('namePhoneEmailSettings.namePhoneEmail')}</Headline>
      <View style={styles.horizontalLinePrimary} />
      {inputs.length > 0 && inputs.map((result) => (
        <View key={result.key}>
          <Text style={styles.text}>{result.label}</Text>
          <View>
            {edit !== result.key && (
              <View style={styles.textContainer}>
                <Text style={styles.text}>{userObject[result.key]}</Text>
                <Button
                  style={{ marginLeft: 'auto' }}
                  onPress={() => {
                    setEdit(result.key);
                  }}
                >
                  {I18n.t('findRecordSettings.edit')}
                </Button>
              </View>
            )}
            {edit === result.key && (
              <View style={styles.textContainer}>
                <TextInput
                  style={{ flex: 3 }}
                  placeholder={result.value}
                  mode="outlined"
                  onChangeText={(text) => updateUserObject(result.key, text)}
                />
                <View style={styles.buttonContainer}>
                  <IconButton
                    icon="check"
                    size={25}
                    color={theme.colors.primary}
                    style={styles.svg}
                    onPress={() => {
                      setEdit('');
                    }}
                  />
                  <IconButton
                    icon="window-close"
                    size={25}
                    color={theme.colors.primary}
                    style={styles.svg}
                    onPress={() => {
                      setEdit('');
                    }}
                  />
                </View>
              </View>
            )}
          </View>
          <View style={styles.horizontalLineGray} />

        </View>
      ))}
      {submitting ? (
        <ActivityIndicator
          size="large"
          color={theme.colors.primary}
        />
      ) : (
        <Button onPress={() => updateUser()}>{I18n.t('global.submit')}</Button>
      )}
    </View>
  );
}
Example #29
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
FindRecords = () => {
  useEffect(() => {
    async function setUserInformation() {
      const storedLimit = await getData('findRecordsLimit');
      const currentLimit = storedLimit === null || storedLimit === undefined ? 2000 : storedLimit;
      const residentData = await getData('residentData');
      const residentDataCount = residentData.length;

      setCurrentData({
        currentLimit,
        residentDataCount
      });
    }
    setUserInformation().then(() => {
      setInputs([
        {
          label: I18n.t('findRecordSettings.currentReccordsStored'),
          value: currentData.residentDataCount,
          key: 'residentDataCount',
          edit: false
        },
        {
          label: I18n.t('findRecordSettings.recordStorageLimit'),
          value: currentData.currentLimit,
          key: 'currentLimit',
          edit: true
        }
      ]);
      setUpdated(false);
    });
  }, [updated]);

  const handleFailedAttempt = () => {
    Alert.alert(
      I18n.t('global.error'),
      I18n.t('findRecordSettings.errorMessage'), [
        { text: I18n.t('global.ok') }
      ],
      { cancelable: true }
    );
  };

  const handleSucccessfullAttempt = () => {
    Alert.alert(
      I18n.t('global.success'),
      I18n.t('findRecordSettings.successMessage'), [
        { text: I18n.t('global.ok') }
      ],
      { cancelable: true }
    );
  };

  const updateUser = async () => {
    setSubmitting(true);

    const newLimit = currentData.currentLimit;

    const submitAction = () => {
      setTimeout(() => {
        setSubmitting(false);
        handleSucccessfullAttempt();
      }, 1000);
    };

    await storeData(newLimit, 'findRecordsLimit').then(() => {
      setUpdated(true);
      submitAction();
    }, (error) => {
      console.log(error); //eslint-disable-line
      setSubmitting(false);
      handleFailedAttempt();
    });
  };

  const updateCurrentData = (key, text) => {
    const copyUserObject = currentData;
    copyUserObject[key] = text;
    setCurrentData(copyUserObject);
  };

  const [currentData, setCurrentData] = useState({});
  const [edit, setEdit] = useState('');
  const [inputs, setInputs] = useState([]);
  const [updated, setUpdated] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  return (
    <View>
      <Headline>{I18n.t('findRecordSettings.findRecords')}</Headline>
      <View style={styles.horizontalLinePrimary} />
      {inputs.length > 0 && inputs.map((result) => (
        <View key={result.key}>
          <Text style={styles.text}>{result.label}</Text>
          <View>
            {edit !== result.key && (
              <View style={styles.textContainer}>
                <Text style={styles.text}>{currentData[result.key]}</Text>
                {result.edit === true && (
                  <Button
                    style={{ marginLeft: 'auto' }}
                    onPress={() => {
                      setEdit(result.key);
                    }}
                  >
                    {I18n.t('findRecordSettings.edit')}
                  </Button>
                )}
              </View>
            )}
            {edit === result.key && (
              <View style={styles.textContainer}>
                <TextInput
                  style={{ flex: 3 }}
                  placeholder={result.value}
                  mode="outlined"
                  onChangeText={(text) => updateCurrentData(result.key, text)}
                />
                <View style={styles.buttonContainer}>
                  <IconButton
                    icon="check"
                    size={25}
                    color={theme.colors.primary}
                    style={styles.svg}
                    onPress={() => {
                      setEdit('');
                    }}
                  />
                  <IconButton
                    icon="window-close"
                    size={25}
                    color={theme.colors.primary}
                    style={styles.svg}
                    onPress={() => {
                      setEdit('');
                    }}
                  />
                </View>
              </View>
            )}
          </View>
          <View style={styles.horizontalLineGray} />

        </View>
      ))}
      {submitting ? (
        <ActivityIndicator
          size="large"
          color={theme.colors.primary}
        />
      ) : (
        <Button onPress={() => updateUser()}>{I18n.t('global.submit')}</Button>
      )}
    </View>
  );
}