native-base#Header JavaScript Examples

The following examples show how to use native-base#Header. 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: HeaderView.js    From inventory-management-rn with MIT License 6 votes vote down vote up
HeaderView = ({ navigation,title }) => {
  return (
    <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row' }} androidStatusBarColor="#247095" >
      <Left>
        <TouchableOpacity onPress={() => navigation.toggleDrawer()}>
          <Icon name="menu" color="white" size={35} />
        </TouchableOpacity>
      </Left>
      <Body>
        <Text style={{fontSize: 21, color: '#fff'}}>{title}</Text>
      </Body>
      <Right>
        <TouchableOpacity onPress={() => navigation.replace('ProfilePage')}>
          <Icon name="user" color="white" size={35} />
        </TouchableOpacity>
      </Right>
    </Header>
  );
}
Example #2
Source File: DrawerScreen2.js    From inventory-management-rn with MIT License 6 votes vote down vote up
MyHeader = ({ navigation }) => {
  return (
    <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row' }}>
      <Left>
        <TouchableOpacity onPress={() => navigation.openDrawer()}>
          <Icon name="menu" color="white" size={35} />
        </TouchableOpacity>
      </Left>
      <Body>
        <Text style={{ fontSize: 21, color: '#fff' }}>Drawer</Text>
      </Body>
      <Right>
        <TouchableOpacity onPress={() => { }}>
          <Icon name="user" color="white" size={35} />
        </TouchableOpacity>
      </Right>
    </Header>
  );
}
Example #3
Source File: BLElist.js    From BLEServiceDiscovery with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return (
      <Container>
        <Header />
        <FlatList
          data={this.props.BLEList}
                renderItem={({ item }) => 
                <>
                <TouchableHighlight
                    onPress={() => this.handleClick(item)}
                    style={item.isConnectable ? styles.rowFront : styles.rowBack}
                    underlayColor={'#AAA'}
                >
                    <View>
                        <Text>
                            {this.connectableString(item)}
                        </Text>
                    </View>
                </TouchableHighlight>
                </>
                }
                keyExtractor={item => item.id.toString()}
                ListEmptyComponent={DataActivityIndicator}
            />
        

        <Footer>
          <BLE></BLE>
        </Footer>
      </Container>
    );
  }
Example #4
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
CatalogScreenHeader = ({ collection, navigation }) => {
  const savedRecords = useSelector(savedRecordsSelector).length;
  return (
    <Header style={styles.header}>
      <Left>
        {/* }<TouchableOpacity onPress={() => navigation.goBack()}> */}
        <TouchableOpacity onPress={() => navigation.navigate('CollectionsList')}>
          <Entypo name="chevron-thin-left" size={20} color={Colors.headerIcon} />
        </TouchableOpacity>
      </Left>
      <View style={styles.headerTitleContainer}>
        <HeaderCountIcon count={savedRecords} outline />
        <Title style={styles.collectionLabel}>{collection?.label}</Title>
      </View>
      <Right>

        <CatalogModal collectionId={collection.id} />
      </Right>
    </Header>
  );
}
Example #5
Source File: CollectionsIndexHeader.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
CollectionsIndexHeader = ({
  showNewCollectionButton,
  collectionsCounter,
  navigation,
  updateIsAddingNewCollectionAction,
}) => {
  const [collectionsDialogText, setCollectionsDialogText] = useState(null);
  const totalCollectionsCount = collectionsCounter.customCount + collectionsCounter.preBuiltCount;

  const handleNewCollectionPress = () => {
    updateIsAddingNewCollectionAction(true);
    navigation.navigate('CollectionInput');
  };

  return (
    <>
      <StatusBar backgroundColor={Colors.primary} barStyle="dark-content" />
      <Header style={styles.header}>
        <Left />
        <View style={styles.headerTitleContainer}>
          {totalCollectionsCount > 0 && <HeaderCountIcon count={totalCollectionsCount} />}
          <Title style={styles.headerText}>Collections</Title>
        </View>
        <Right>
          {showNewCollectionButton
            && <AddCollectionInputButton onPress={handleNewCollectionPress} />}

        </Right>
      </Header>
      {collectionsDialogText && (
        <CollectionsDialog
          collectionsDialogText={collectionsDialogText}
          setCollectionsDialogText={setCollectionsDialogText}
        />
      )}
    </>
  );
}
Example #6
Source File: ProfileScreen.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
ProfileScreen = () => (
  <SafeAreaView style={styles.root}>
    <StatusBar backgroundColor={Colors.primary} barStyle="dark-content" />
    <Header style={styles.header}>
      <Body>
        <Title style={styles.headerText}>Profile</Title>
      </Body>
    </Header>
    <UserInfo />
    <ScrollView style={styles.scrollContainer}>
      <Demographics />
      <Data />
    </ScrollView>
    <View style={styles.logoutContainer}>
      <Logout>
        <TouchableOpacity style={styles.logout}>
          <Text style={styles.logoutText}>
            Logout
          </Text>
        </TouchableOpacity>
      </Logout>
    </View>
  </SafeAreaView>
)
Example #7
Source File: SummaryScreen.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
SummaryScreen = () => (
  <SafeAreaView style={styles.root}>
    <StatusBar backgroundColor={Colors.primary} barStyle="dark-content" />
    <Header style={styles.header}>
      <Body>
        <Title style={styles.headerText}>Summary</Title>
      </Body>
    </Header>
    <Tab.Navigator
      initialRouteName="Records"
      style={styles.tabs}
      tabBarOptions={{
        labelStyle: styles.tabText,
        indicatorStyle: {
          backgroundColor: Colors.primary,
        },
      }}
    >
      <Tab.Screen
        name="Records"
        component={RecordsSummary}
      />
      <Tab.Screen
        name="Providers"
        component={ProvidersSummary}
      />
    </Tab.Navigator>
  </SafeAreaView>
)
Example #8
Source File: SettingsScreen.js    From pandoa with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return (
      <Container>
        <Header>
          <Body>
            <Title>Settings</Title>
          </Body>
        </Header>
        <Content>
          <List>
            <ListItem
              first
              onPress={() => this.props.navigation.navigate("Billing")}
            >
              <Text>Notifications</Text>
            </ListItem>
            <ListItem>
              <Text>User Settings</Text>
            </ListItem>
            <ListItem>
              <Text>Billing</Text>
            </ListItem>
            <ListItem onPress={this.logout}>
              <Text style={styles.logout}>Logout</Text>
            </ListItem>
          </List>
        </Content>
      </Container>
    );
  }
Example #9
Source File: index.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
DetailsPanel = ({
  navigation, collection, savedRecordsGroupedByType, savedRecords,
}) => {
  const { detailsPanelSortingState: sortingState } = collection;
  const { RECORD_TYPE, RECORD_DATE, TIME_SAVED } = sortFields;
  const hasSavedRecords = Object.entries(savedRecords).length > 0;
  const hasMultipleSavedRecords = Object.entries(savedRecords).length > 1;
  const savedItemsCount = useSelector(savedRecordsSelector).length;

  const handlePressNoteIcon = () => {
    navigation.navigate('Notes');
  };

  const displayAccordion = () => {
    switch (sortingState.activeSortField) {
      case RECORD_TYPE:
        return (
          <SubTypeAccordionsContainer
            data={savedRecordsGroupedByType}
            fromDetailsPanel
          />
        );
      case RECORD_DATE:
        return (
          <DateAccordionsContainer
            fromDetailsPanel
          />
        );
      case TIME_SAVED:
        return (
          <TimeSavedAccordionsContainer
            fromDetailsPanel
          />
        );
      default:
        console.warn('No activeSortField in DetailsPanel'); // eslint-disable-line no-console
        return null;
    }
  };

  return (
    <SafeAreaView style={styles.root}>
      <Header style={styles.header}>
        <Left>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Entypo name="chevron-thin-left" size={20} color={Colors.headerIcon} />
          </TouchableOpacity>
        </Left>
        <View style={styles.headerTitleContainer}>
          {savedItemsCount > 0 && <HeaderCountIcon count={savedItemsCount} outline />}
          <Title style={styles.headerText}>{collection?.label}</Title>
        </View>
        <Right>
          <TouchableOpacity onPress={handlePressNoteIcon}>
            <FontAwesome name="sticky-note-o" size={20} color={Colors.headerIcon} />
          </TouchableOpacity>
        </Right>
      </Header>
      {!hasSavedRecords && (
        <View style={styles.zeroStateContainer}>
          <Text style={styles.zeroStateText}>No Records in Collection.</Text>
        </View>
      )}
      {hasSavedRecords && (
        <>
          <SortingHeader
            sortingState={sortingState}
            hasMultipleSavedRecords={hasMultipleSavedRecords}
          />
          <ScrollView>
            {displayAccordion()}
          </ScrollView>
        </>
      )}
    </SafeAreaView>
  );
}
Example #10
Source File: LoginScreen.js    From inventory-management-rn with MIT License 4 votes vote down vote up
LoginScreen = ({ navigation }) => {

  const [email, setUserEmail] = useState('');
  const [password, setUserPassword] = useState('');

  const login = () => {

    // fetching the token by providing email and password
    fetch('http://chouhanaryan.pythonanywhere.com/auth/token/login/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        'email': email,
        'password': password
      })
    })
      .then((res) => res.json())
      .then(async (data) => {
        const token = data.auth_token;
        if (token) {
          console.log('token is: ' + token);

          // storing token in async storage
          try {
            await AsyncStorage.setItem('auth_key', token);
          } catch (error) {
            console.log('Token not saved in async storage properly');
            console.log(error);
          }

          // using the token just received to check the info of the current logged in user
          fetch('http://chouhanaryan.pythonanywhere.com/auth/users/me/', {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Token ${token}`
            }
          })
          .then((res) => res.json())
          .then(async (data) => {

            // storing is_staff boolean in async storage
            try {
              await AsyncStorage.setItem('is_staff', data.is_staff.toString());
            } catch (error) {
              console.log('is_staff not saved in async storage properly');
              console.log(error)
            }
            navigation.replace('Drawer');
          })
          .catch((err) => {
            console.log(err)
          })
        } else {
          Alert.alert('Invalid email or password', 'Please enter correct credentials')
        }
      })
      .catch((err) => console.log(err))
  }


  return (
    <Container style={{ backgroundColor: '#F3F9FB' }}>
      <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row', alignItems: 'center' }} androidStatusBarColor="#247095">
        <Text style={{ color: '#fff', fontSize: 24 }}>Login</Text>
        
      </Header>
      <Content>
        <Body>

          <Image
            style={{
              width: 274,
              height: 207,
              marginVertical: 40,
              marginRight: 10,
            }}
            source={require('../Images/Illustration.png')}
          />

          <Item floatingLabel style={styles.inputBox}>

            <Label style={styles.label}>Email ID</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}

              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>

          <Item floatingLabel style={styles.inputBox}>

            <Label style={styles.label}>Password</Label>
            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserPassword(value);
              }}
              name="password"
              autoCapitalize="none"
              secureTextEntry
            />
          </Item>

          {/* <TouchableOpacity
            rounded
            style={styles.loginButton}
            onPress={() => {
              Login(email, password);
            }}>
            <Text style={styles.buttonText}>Login</Text>
          </TouchableOpacity> */}

          <TouchableOpacity
            rounded
            style={styles.loginButton}
            onPress={() => {
              login()
            }}>
            <Text style={styles.buttonText}>Login</Text>
          </TouchableOpacity>



          <View style={{ flexDirection: 'row' }}>
            <Text style={styles.newUser}>New user ? </Text>
            <TouchableOpacity onPress={() => {
              navigation.navigate('RegisterScreen');
            }}   ><Text style={{
              fontSize: 18,
              textDecorationLine: 'underline',
              color: '#9ca2ad',
              // borderBottomWidth:1,
              // borderBottomColor: 'black',

              marginTop: 25,
              marginBottom: 10,
              marginBottom: 10,
            }}>Register </Text></TouchableOpacity>
          </View>
        </Body>
      </Content>
    </Container>
  );
}
Example #11
Source File: ProfilePage.js    From inventory-management-rn with MIT License 4 votes vote down vote up
ProfilePage = ({ navigation }) => {

    const [editMode, toggleEditMode] = useState(false)

    const [firstName, updateFirstName] = useState('John')
    const [lastName, updateLastName] = useState('Doe')
    const [email, updateEmail] = useState('[email protected]')
    const [gender, updateGender] = useState('M')
    const [age, updateAge] = useState('20')
    const [isStaff, updateIsStaff] = useState(false)

    const [isReady, setReady] = useState(false);

    
    useEffect(() => {
        getCurrentUserInfo();
    }, []);     //called only when component mounted 

    const getCurrentUserInfo = async () => {

        try {
            const tokenValidity = await isTokenValid(navigation)
            console.log('token valid? ',tokenValidity)
            if (tokenValidity){
                const auth_key = await AsyncStorage.getItem('auth_key');

                const res = await fetch('http://chouhanaryan.pythonanywhere.com/auth/users/me/', {
                    method: 'GET',
                    headers: {
                        Authorization: `Token ${auth_key}`,
                    },
                })
    
                const data = await res.json()
                console.log(data)
                const firstName = data.first_name
                const lastName = data.last_name
                const age = data.age.toString()
                const email = data.email
                const gender = data.gender === 'F' ? 'Female' : 'Male'
                const isStaff = data.is_staff
    
                //set user details to state
                updateAge(age)
                updateEmail(email)
                updateFirstName(firstName)
                updateLastName(lastName)
                updateGender(gender)
                updateIsStaff(isStaff)
    
                if (res.status === 200) {
                    setReady(true);
                }
            } else {
                logout(navigation)
            }

        } catch (err) {
            console.log('error' , err)
        }
    }

    const onSavePressed = async () => {

        // validation
        if (firstName === "" || lastName === "" || age === "") {
            if (firstName === "")
                Alert.alert('please enter firstName')
            else if (lastName === "")
                Alert.alert('please enter lastName')
            else if (age === "")
                Alert.alert('please enter age')
        }
        else {
            try {
                let formData = new FormData()
                formData.append('email', email)
                formData.append('first_name', firstName)
                formData.append('last_name', lastName)
                formData.append('age', age)
                // console.log(formData)

                const auth_key = await AsyncStorage.getItem('auth_key');

                const res = await fetch('http://chouhanaryan.pythonanywhere.com/auth/user_update/', {
                    method: 'POST',
                    headers: {
                        Authorization: `Token ${auth_key}`,
                    },
                    body: formData,
                })
                console.log(res)
                console.log(res.status)
                const resJson = await res.json()
                console.log(resJson)
                if (res.status === 200) {
                    Alert.alert('details updated')
                } else {
                    Alert.alert('Error in updating details')
                }
                toggleEditMode(!editMode)
            } catch (err) {
                console.log(err)
            }
        }
    }

    return (
        <ScrollView style={{ flex: 1 }}>
            <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row' }} androidStatusBarColor="#247096">
                <Left>
                    <TouchableOpacity onPress={() => { navigation.navigate('Drawer') }}>
                        <Icon name="home" color="white" size={35} />
                    </TouchableOpacity>
                </Left>
                <Body>
                    <Text style={{ fontSize: 21, color: '#fff' }}>Profile</Text>
                </Body>

            </Header>

            {/* container */}

            {!isReady &&
                <Body style={{ justifyContent: 'center' }}>
                    <ActivityIndicator size="large" color="#000" />
                </Body>
            }

            {
                isReady &&
                <View >
                    <View style={{ alignItems:'center',marginTop: 20, }}>
                        {/* <Text style={styles.profileTitle}>  </Text> */}

                        {!editMode && <TouchableOpacity style={styles.editButton} onPress={() => toggleEditMode(!editMode)}>
                            <Icon name="edit" color="#4796BD" size={25} />
                            <Text style={styles.editText}> Edit </Text>
                        </TouchableOpacity>}


                    </View>

                    <View style={{ alignItems: 'center' }}>
                        <View floatingLabel style={styles.inputBox}>
                            <Label style={styles.label}>First Name</Label>
                            <Input
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={firstName}
                                disabled={editMode ? false : true}
                                onChangeText={val => updateFirstName(val.trim())}
                            />
                        </View>

                        <View floatingLabel style={styles.inputBox}>
                            <Label style={styles.label}>Last Name</Label>
                            <Input
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={lastName}
                                disabled={editMode ? false : true}
                                onChangeText={val => updateLastName(val.trim())}
                            />
                        </View>

                        <View style={styles.inputBox}>
                            <Label style={styles.label}>Email</Label>
                            <Input
                                style={styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={email}
                                disabled={true}
                            />
                        </View>


                        <View style={styles.inputBox}>
                            <Label style={styles.label}>Gender</Label>

                            <Input
                                style={styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={gender}
                                disabled={true}
                            />
                        </View>

                        <View style={styles.inputBox}>

                            <Label style={styles.label}>Age</Label>
                            <Input
                                keyboardType="numeric"
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                onChangeText={val => updateAge(val.trim())}
                                value={age}
                                disabled={editMode ? false : true}
                            />
                        </View>


                        <View style={styles.inputBox}>

                            <Label style={styles.label}>is staff?</Label>
                            <Text style={styles.inputAreaViewMode}> {isStaff ? "true" : "false"}</Text>
                        </View>



                        {/* {
                            editMode &&
                            <View style={styles.inputBox}>

                                <Label style={styles.label}> is staff? </Label>
                                <View style={styles.radioGroup}>
                                    <Text style={styles.isStaffText}> true </Text>
                                    <Radio selected={isStaff} />

                                    <Text style={styles.isStaffText}> false </Text>
                                    <Radio selected={!isStaff} />
                                </View>
                            </View>
                        } */}

                        {/* end of userinput */}

                    </View>
                    {/* end of form */}
                    {
                        editMode &&
                        <TouchableOpacity style={styles.saveButton} onPress={() => onSavePressed()}>
                            {/* <Icon name="edit" color="#4796BD" size={25} /> */}
                            <Text style={styles.editText}> Save </Text>
                        </TouchableOpacity>
                    }


                    <TouchableOpacity
                        style={styles.logoutButton}
                        onPress={() => {
                            logout(navigation)
                        }}>
                        <Text style={styles.logoutText}>Logout</Text>
                    </TouchableOpacity>

                </View>}
        </ScrollView>
    );
}
Example #12
Source File: RegisterScreen.js    From inventory-management-rn with MIT License 4 votes vote down vote up
RegisterScreen = ({navigation}) => {
  return (
    <Container style={{backgroundColor: '#F3F9FB'}}>
       <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row', alignItems: 'center' }} androidStatusBarColor="#247095">
        <Text style={{ color: '#fff', fontSize: 20 }}>Register</Text>
      </Header>
      <Content>
        <Body>
          <Text style={styles.heading}>Register</Text>
          <Text
            style={{
              alignSelf: 'flex-start',
              fontSize: 25,
              color: '#122E40',
              marginLeft: 28,
              marginTop: 25,
              marginBottom: 10,
            }}>
            Account
          </Text>

          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Full Name</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}
              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>
          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Email-id</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}
              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>

          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Password</Label>
            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserPassword(value);
              }}
              name="password"
              secureTextEntry
            />
          </Item>
          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Confirm Password</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}
              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>
          <Text
            style={{
              alignSelf: 'flex-start',
              fontSize: 25,
              color: '#122E40',

              marginLeft: 28,

              marginTop: 25,
              marginBottom: 10,
              marginBottom: 10,
            }}>
            Shop Details
          </Text>
          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Name</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}
              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>

          <Item floatingLabel style={styles.inputBox}>
            <Label style={styles.label}>Address</Label>

            <Input
              style={styles.inputArea}
              blurOnSubmit={true}
              onChangeText={value => {
                setUserEmail(value);
              }}
              keyboardType="email-address"
              autoCapitalize="none"
            />
          </Item>
          <TouchableOpacity
            rounded
            style={styles.loginButton}
            onPress={() => {
              navigation.navigate('LoginScreen');
            }}>
            <Text style={styles.buttonText}>Register</Text>
          </TouchableOpacity>
        </Body>
      </Content>
    </Container>
  );
}
Example #13
Source File: ChatListScreen.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
ChatListScreen = (props) => {

    const loggedUser = useSelector(state => state.auth.user);
    const chatList = useSelector(state => state.chat.chatList);
    const allChats = useSelector(state => state.chat.allChats);
    let allUsers = useSelector(state => state.users.allUsers);

    // remove logged user from the list
    allUsers = allUsers.filter(item => item._id !== loggedUser._id);


    const [isLoading, setIsLoading] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [data, setData] = useState(chatList);


    const dispatch = useDispatch();

    const loadChatList = useCallback(async () => {
        setIsRefreshing(true);
        try {
            const result = await dispatch(chatActions.fetchChatList());
            await dispatch(chatActions.fetchChats());
            setData(result);
        } catch (err) {
            console.log(err)
        }
        setIsRefreshing(false);
    }, [dispatch, setIsLoading])

    const loadChats = useCallback(async () => {
        try {
            await dispatch(chatActions.fetchChats());
        } catch (err) {
            console.log(err)
        }
    }, [dispatch, setIsLoading])


    // useEffect(() => {
    //     const unsubscribe = props.navigation.addListener('focus', e => {
    //         setSearchText('');
    //         loadChatList();
    //     });
    //     return () => {
    //         unsubscribe();
    //     };
    // }, [])

    useEffect(() => {
        setIsLoading(true);
        loadChats()
        .then(() => {
            setIsLoading(false);
        });
        setIsLoading(false)
    }, [dispatch, loadChats])

    const handleSearchTextChange = (text) => {
        setSearchText(text);
        if(text !== ''){
            let filteredData = []
            let currData = allUsers;

            filteredData = currData.filter(item => {
                const lc = item.name.toLowerCase();
                text = text.toLowerCase();
                return lc.includes(text);
            });
            setData(filteredData);
        } else {
            setData(chatList);
        }
    }   


    if (isLoading) {
        return (
            <View style={styles.centered} >
                <ActivityIndicator size='large' color={Colors.primary} />
            </View>
        );
    }

    return (
        <Container>
            <Header style={{ backgroundColor: Colors.brightBlue }} searchBar rounded>
                <Item>
                    <Icon name="ios-search" />
                    <Input
                        value={searchText}
                        onChangeText={(text) => handleSearchTextChange(text)}
                        placeholder="Search" 
                    />
                    <Icon name="ios-people" />
                </Item>
            </Header>
            { data.length === 0 && (
                <View style={styles.centered}>
                    <Text>No chats !</Text>
                    <Text>Either your search does not match any user's name</Text>
                    <Text>or you have no chats.</Text>
                    <Text>Please refresh if you have new chats.</Text>
                </View>
            ) }
            <FlatList
                data={data}
                refreshing={isRefreshing}
                onRefresh={loadChatList}
                keyExtractor={(item) => item._id}
                renderItem={(user) => (
                    <ChatListItem user={user.item} />
                )}
            />
        </Container>
    );
}
Example #14
Source File: FindPeopleScreen.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
FindPeopleScreen = (props) => {

    const findPeopleUsers = useSelector(state => state.users.findPeople);

    const [isLoading, setIsLoading] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [error, setError] = useState();
    const [searchText, setSearchText] = useState('');
    const [data, setData] = useState([]);

    const dispatch = useDispatch();


    const loadFindPeople = useCallback(async () => {
        setError(null);
        setIsRefreshing(true);
        try {
            const result = await dispatch(usersActions.fetchFindPeopleUsers());
            let verifiedUsers =  result.filter(e => VerifiedUser.verifiedUsersId.includes(e._id));
            let otherUsers = result.filter(e => !VerifiedUser.verifiedUsersId.includes(e._id));
            let updatedResult = [...verifiedUsers, ...otherUsers];
            setData(updatedResult);
        } catch (err) {
            setError(err.message);
        }
        setIsRefreshing(false);
    }, [dispatch, setIsLoading, setError])

    
    useEffect(() => {
        setIsLoading(true);
        loadFindPeople()
        .then(() => {
            setIsLoading(false);
        });
    }, [dispatch, loadFindPeople])


    // useEffect(() => {
    //     const unsubscribe = props.navigation.addListener('focus', e => {
    //         setSearchText('');
    //         setData(findPeopleUsers);
    //     });
    //     return () => {
    //         unsubscribe();
    //     };
    // }, [])


    const handleSearchTextChange = (text) => {
        setSearchText(text);
        if(text !== ''){
            let filteredData = []
            let currData = findPeopleUsers;

            filteredData = currData.filter(item => {
                const lc = item.name.toLowerCase();
                const lcEmail = item.email.toLowerCase();
                text = text.toLowerCase();
                return lc.includes(text) || lcEmail.includes(text);
            });
            setData(filteredData);
        } else {
            setData(findPeopleUsers);
        }
    }


    const followHandlerForData = (id) => {
        //follow handler to remove item from search data i.e. data state
        let searchData = data;
        searchData = searchData.filter(i => i._id !== id);
        setData(searchData);
    }



    if(error){
        return (
            <View style={styles.centered} >
                <Text>An error occured.</Text>
                <Button onPress={loadFindPeople} color={Colors.primary} >
                    <Text>Try again</Text>
                </Button>
            </View>
        );
    }


    if(isLoading){
        return (
            <View style={styles.centered} >
                <ActivityIndicator size='large' color={Colors.primary} />
            </View>
        );
    }

    return (
        <Container style={{ backgroundColor: '#fff' }} >
            <Header style={{ backgroundColor: Colors.brightBlue }} searchBar rounded>
                <Item>
                    <Icon name="ios-search" />
                    <Input
                        value={searchText}
                        onChangeText={(text) => handleSearchTextChange(text)}
                        placeholder={`Search by name or email...`}
                    />
                    <Text>{data.length}</Text>
                    <Icon name="ios-people"  />
                </Item>
            </Header>
            { data.length === 0 && (
                <View style={styles.centered}>
                    <Text style={{ fontSize: 18, margin: 10 }} >No users found.</Text>
                    <Text>Either you are already following the user</Text>
                    <Text>or no user exists with that name.</Text>
                </View>
            ) }
            <FlatList
                style={styles.list}
                refreshing={isRefreshing}
                onRefresh={loadFindPeople}
                contentContainerStyle={styles.listContainer}
                data={data}
                horizontal={false}
                numColumns={2}
                keyExtractor={(item) => {
                    return item._id;
                }}
                renderItem={({ item }) => (
                    <UserList item={item} followHandler={followHandlerForData} />
                )} 
            />
        </Container>
    );
}
Example #15
Source File: CollectionInputScreen.js    From discovery-mobile-ui with MIT License 4 votes vote down vote up
CollectionInputScreen = ({
  collection,
  createCollectionAction,
  selectCollectionAction,
  editCollectionDetailsAction,
  creatingCollection,
  collectionsLabels,
  collections,
  renameCollectionAction,
}) => {
  const navigation = useNavigation();
  const [title, onChangeTitle] = useState(creatingCollection ? DEFAULT_COLLECTION_NAME : collection.label); // eslint-disable-line max-len
  const [purpose, onChangePurpose] = useState(creatingCollection ? '' : collection?.purpose);
  const [current, currentSelection] = useState(creatingCollection ? false : collection?.current);
  const [urgent, urgentSelection] = useState(creatingCollection ? false : collection?.urgent);
  const [newCollectionID, setCollectionID] = useState('');
  const [isAddingCollection, setIsAddingCollection] = useState(false);
  const [collectionsDialogText, setCollectionsDialogText] = useState(null);
  const [open, setOpen] = useState(false);
  const [hasTextValue, setHasTextValue] = useState(false);
  const [sameName, setSameName] = useState(false);
  const [moveToCatalog, setMoveToCatalog] = useState(false);

  const itemsList = [

  ];
  const itemNames = [];
  const collectionNames = [];
  if (Object.keys(collections).length > 0) {
    Object.keys(collections).forEach((key) => {
      if (collections[key] != null) {
        collectionNames.push(collections[key].label);
        for (let j = 0; j < collections[key].tags.length; j += 1) {
          if (!itemNames.includes(collections[key].tags[j])) {
            itemNames.push(collections[key].tags[j]);
          }
        }
      }
    });
  }
  for (let i = 0; i < itemNames.length; i += 1) {
    itemsList.push({ label: itemNames[i], value: itemNames[i] });
  }
  const [items, setItems] = useState(itemsList);
  const [value, setValue] = useState(creatingCollection ? [] : collection.tags);

  const discardInputAlert = () => {
    Alert.alert(
      'Discard Edits',
      'Are you sure you want to discard edits to this collection?',
      [
        {
          text: 'Cancel',
          onPress: () => {},
          style: 'cancel',
        },
        {
          text: 'Discard',
          onPress: () => handleCloseInput(),
          style: 'destructive',
        },
      ],
    );
  };

  const handleCloseInput = ({ alert }) => {
    if (alert) {
      discardInputAlert();
    }
  };

  const handleSave = () => {
    if (creatingCollection) {
      if (!collectionNames.includes(title)) {
        if (hasTextValue) {
          if (hasInputErrors({ text: title, isRename: false, label: title })) {
            return;
          }
          createCollectionAction(title);
          setIsAddingCollection(true);
        }
      }
    } else {
      if (hasInputErrors({ text: title, isRename: true, label: title })) {
        return;
      }
      renameCollectionAction(newCollectionID, title);

      editCollectionDetailsAction(purpose, value, (current || urgent), urgent);
    }
  };
  const saveCollection = () => {
    handleSave();
    navigation.navigate('CollectionsList');
  };
  const saveAndContinue = () => {
    if (creatingCollection) {
      if (!collectionNames.includes(title)) {
        if (hasTextValue) {
          if (hasInputErrors({ text: title, isRename: false, label: title })) {
            return;
          }
          createCollectionAction(title);
          setIsAddingCollection(true);
        }
      }
    } else {
      if (hasInputErrors({ text: title, isRename: true, label: title })) {
        return;
      }
      renameCollectionAction(newCollectionID, title);

      editCollectionDetailsAction(purpose, value, (current || urgent), urgent);
    }
    setMoveToCatalog(true);
    //
  };
  const discardChanges = () => {
    setCollectionsDialogText(CollectionsDialogText[COLLECTIONS_DIALOG_ACTIONS.DISCARD]);
  };

  const discardChangesCreate = () => {
    setCollectionsDialogText(CollectionsDialogText[COLLECTIONS_DIALOG_ACTIONS.DISCARD_CREATE]);
  };
    // selectCollectionAction(title);

  // console.log(collection)
  // collection.label = title
  // collection.tags = tags

  useEffect(() => {
    if (Object.keys(collections).length > 0) {
      setCollectionID(Object.keys(collections)[Object.keys(collections).length - 1]);

      if (isAddingCollection) {
        selectCollectionAction(Object.keys(collections)[Object.keys(collections).length - 1]);
        editCollectionDetailsAction(purpose, value, (current || urgent), urgent);
        setIsAddingCollection(false);
      }
    }
    if (moveToCatalog) {
      navigation.navigate('Catalog');
    }

    // if (useState(collections )!== collections) {
    // }
  }, [collections, isAddingCollection, moveToCatalog]);

  useEffect(() => {
    setSameName(false);
    if (title.length > 0) {
      setHasTextValue(true);
    }
    if (creatingCollection) {
      for (let i = 0; i < collectionNames.length; i += 1) {
        if (collectionNames[i].toLowerCase() === title.toLowerCase()) {
          setHasTextValue(false);
          setSameName(true);
        }
      }
    }
  }, [title]);

  const saveButtonTextStyle = hasTextValue ? styles.saveButtonText : styles.disabledSaveButtonText;

  // PLACEHOLDERS
  const placeholderTitle = creatingCollection ? '' : collection.label;

  const isUniqueName = ({ text, isRename, label }) => {
    // if action is rename, new label can be same as old label
    if (isRename && (text.toLowerCase() === label.toLowerCase())) {
      return true;
    }
    return !((collectionsLabels).includes(text.toLowerCase()));
  };
  const hasMinLength = (text) => text.length > 0;

  const hasInputErrors = ({ text, isRename, label }) => {
    if (!hasMinLength(text)) {
      return true;
    }
    if (!isUniqueName({ text, isRename, label })) {
      return true;
    }
    return false;
  };
  const reduceInputs = () => {
    Keyboard.dismiss();
    setOpen(false);
  };

  return (

    <SafeAreaView style={styles.root}>

      <Header style={styles.header}>
        <Left>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Entypo name="chevron-thin-left" size={20} color="black" />
          </TouchableOpacity>
        </Left>
        <TouchableWithoutFeedback onPress={reduceInputs}>
          <View style={styles.headerTitleContainer}>
            <Title style={styles.headerText}><Text>{title}</Text></Title>
          </View>
        </TouchableWithoutFeedback>
        <Right>
          <TouchableWithoutFeedback style={styles.empty_toucable} onPress={reduceInputs}>
            <View style={styles.headerTitleContainer}>

              <Text style={styles.header_empty_text}> </Text>

            </View>

          </TouchableWithoutFeedback>
        </Right>
      </Header>

      <View style={styles.inputField}>

        <KeyboardAvoidingView behavior="padding">
          <TouchableWithoutFeedback onPress={reduceInputs}>

            <View style={styles.textInputDiv}>
              <Text variant="title" style={styles.formHeader}>Title</Text>
            </View>
          </TouchableWithoutFeedback>

          <View style={styles.titleTextInputContainer}>
            <TextInput
              style={styles.textInput}
              onChangeText={onChangeTitle}
              placeholder={placeholderTitle}
              value={title}
              onTouchStart={() => setOpen(false)}
              multiline={false}
              autoFocus
            />
          </View>

          <View style={styles.titleFooter}>
            {sameName
            && (
            <View style={styles.sameNameAlertContainer}>
              <Text style={{ color: Colors.destructive }}>Collection name must be unique</Text>
            </View>
            )}
          </View>

        </KeyboardAvoidingView>

        <KeyboardAvoidingView behavior="padding">

          <TouchableWithoutFeedback onPress={reduceInputs}>

            <View style={styles.textInputDiv}>

              <TouchableOpacity style={styles.textInputHeader} disabled>
                <Text variant="title" style={styles.formHeader}>Purpose</Text>
              </TouchableOpacity>
            </View>
          </TouchableWithoutFeedback>

          <View style={styles.purposeTextInputContainer}>
            <TextInput
              style={styles.textInput}
              onChangeText={onChangePurpose}
              placeholder="add purpose"
              onSubmitEditing={Keyboard.dismiss}
              value={purpose}
              onTouchStart={() => setOpen(false)}
              multiline={false}
              autoFocus
            />
          </View>
        </KeyboardAvoidingView>

        <View style={styles.tagTextHeader}>
          <TouchableWithoutFeedback disabled onPress={reduceInputs}>
            <Text variant="title" style={styles.formHeader}>Collection Tags</Text>
          </TouchableWithoutFeedback>
        </View>

        <View style={{ zIndex: 100, backgroundColor: '#fff' }}>
          <Picker
            multiple
            min={0}
            max={5}
            open={open}
            value={value}
            setOpen={setOpen}
            setValue={setValue}
            items={items}
            setItems={setItems}
            searchable
            placeholder="add new or existing tags "
          />
        </View>
        <View style={styles.switchTextHeader}>
          <TouchableWithoutFeedback disabled onPress={reduceInputs}>

            <Text variant="title" style={styles.formHeader}>Priority</Text>
          </TouchableWithoutFeedback>

        </View>

        <View style={styles.switchRow}>
          <View style={styles.currentTextField}>

            <Feather name="watch" size={18} color={Colors.currentCollectionColor} />

            <Text style={styles.switchText}>Current</Text>
          </View>

          <Switch
            trackColor={{
              false: Colors.mediumgrey,
              true: Platform.OS === 'ios' ? Colors.primary : Colors.primaryLight,
            }}
            thumbColor={(Platform.OS === 'ios') ? 'white' : Colors[(current ? 'primary' : 'primaryLight')]}
            onValueChange={() => currentSelection(!current)}
            value={current || urgent}
            disabled={urgent}
          />
          <View style={styles.leftRightPadding}>
            <Feather name="alert-triangle" size={18} color={Colors.destructive} />

            <Text variant="title" style={styles.switchText}>Urgent</Text>
          </View>

          <Switch
            trackColor={{
              false: Colors.mediumgrey,
              true: Platform.OS === 'ios' ? Colors.primary : Colors.primaryLight,
            }}
            thumbColor={(Platform.OS === 'ios') ? 'white' : Colors[(urgent ? 'primary' : 'primaryLight')]}
            onValueChange={() => urgentSelection(!urgent)}
            value={urgent}
          />
        </View>
      </View>

      <KeyboardAvoidingView style={styles.textRow}>
        <TouchableOpacity
          style={styles.saveButton}
          onPress={() => {
            if (creatingCollection) {
              discardChangesCreate();
            } else {
              discardChanges();
            }
          }}
        >
          <BaseText variant="title" style={styles.discardButtonText}>Discard</BaseText>
        </TouchableOpacity>

        {collectionsDialogText && (
        <CollectionsDialog
          collectionsDialogText={collectionsDialogText}
          setCollectionsDialogText={setCollectionsDialogText}
        />
        )}
        <View style={styles.saveCol}>
          <TouchableOpacity
            style={styles.saveButton}
            onPress={saveCollection}
            disabled={!hasTextValue}
          >
            <BaseText variant="title" style={saveButtonTextStyle}>Save</BaseText>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.saveButton}
            onPress={saveAndContinue}
            disabled={!hasTextValue}
          >
            <BaseText variant="title" style={saveButtonTextStyle}>Save and Continue</BaseText>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>

    </SafeAreaView>
  );
}
Example #16
Source File: NotesScreen.js    From discovery-mobile-ui with MIT License 4 votes vote down vote up
NotesScreen = ({
  resource,
  createRecordNoteAction,
  editRecordNoteAction,
  collection,
  createCollectionNoteAction,
  editCollectionNoteAction,
}) => {
  const navigation = useNavigation();
  const route = useRoute();
  const editingNote = route?.params?.editingNote;
  const [text, onChangeText] = useState('');
  const [editNoteId, setEditNoteId] = useState(null);
  const [showNoteInput, setShowNoteInput] = useState(false);
  const isResourceNotes = !!resource;

  const closeInput = () => {
    onChangeText('');
    setEditNoteId(null);
    setShowNoteInput(false);
  };

  const discardInputAlert = () => {
    Alert.alert(
      'Discard Edits',
      'Are you sure you want to discard edits to this note?',
      [
        {
          text: 'Cancel',
          onPress: () => {},
          style: 'cancel',
        },
        {
          text: 'Discard',
          onPress: () => closeInput(),
          style: 'destructive',
        },
      ],
    );
  };

  const handleCloseInput = ({ alert }) => {
    if (alert) {
      discardInputAlert();
    } else {
      closeInput();
    }
  };

  const handleSave = () => {
    if (isResourceNotes) {
      if (editNoteId) {
        editRecordNoteAction(resource.id, text, editNoteId);
      } else {
        createRecordNoteAction(resource.id, text);
      }
    } else if (editNoteId) {
      editCollectionNoteAction(editNoteId, text);
    } else {
      createCollectionNoteAction(text);
    }
    closeInput();
  };

  const handleCreateNote = () => {
    setShowNoteInput(true);
  };

  const handleEditNote = (noteId, noteText) => {
    setEditNoteId(noteId);
    onChangeText(noteText);
    setShowNoteInput(true);
  };

  useEffect(() => {
    if (editingNote) {
      handleEditNote(editingNote.id, editingNote.text);
    } else {
      handleCreateNote();
    }
  }, []);

  const hasTextValue = text.length > 0;
  const saveButtonTextStyle = hasTextValue ? styles.saveButtonText : styles.disabledSaveButtonText;
  const noteCount = isResourceNotes
    ? collection.records[resource.id]?.notes && Object.keys(collection.records[resource?.id]?.notes).length // eslint-disable-line max-len
    : Object.keys(collection.notes).length;

  return (
    <SafeAreaView style={styles.root}>
      <Header style={styles.header}>
        <Left>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Entypo name="chevron-thin-left" size={20} color="black" />
          </TouchableOpacity>
        </Left>
        <View style={styles.headerTitleContainer}>
          {noteCount > 0 && <HeaderCountIcon count={noteCount} outline />}
          <Title style={styles.headerText}><Text>Notes</Text></Title>
        </View>
        <Right>
          {!showNoteInput && (
            <TouchableOpacity onPress={handleCreateNote} disabled={showNoteInput}>
              <Feather name="plus-square" size={24} color="black" />
            </TouchableOpacity>
          )}
        </Right>
      </Header>
      <ScrollView>
        {isResourceNotes && (
          <View style={styles.resourceCardContainer}>
            <ResourceCard
              resourceId={resource.id}
              resource={resource}
              handleEditNote={handleEditNote}
              editNoteId={editNoteId}
              fromNotesScreen
            />
          </View>
        )}
        {!isResourceNotes && (
          <>
            <View style={styles.collectionHeaderContainer}>
              <View style={styles.collectionLabelContainer}>
                <Text>{collection.label}</Text>
              </View>
            </View>
            <CollectionNotes
              editNoteId={editNoteId}
              handleEditNote={handleEditNote}
              fromNotesScreen
            />
          </>
        )}
      </ScrollView>
      {showNoteInput && (
      <KeyboardAvoidingView behavior="padding">
        <View style={styles.noteEditingActions}>
          <TouchableOpacity onPress={() => handleCloseInput({ alert: true })}>
            <Ionicons name="ios-close-outline" size={24} color="black" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.saveButton} onPress={handleSave} disabled={!hasTextValue}>
            <BaseText variant="title" style={saveButtonTextStyle}>Save</BaseText>
          </TouchableOpacity>
        </View>
        <View style={styles.textInputContainer}>
          <TextInput
            style={styles.textInput}
            onChangeText={onChangeText}
            multiline
            value={text}
            autoFocus
          />
        </View>
      </KeyboardAvoidingView>
      )}
    </SafeAreaView>
  );
}