@expo/vector-icons#AntDesign JavaScript Examples

The following examples show how to use @expo/vector-icons#AntDesign. 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: OBSectionBodyTemplate.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
OBSectionBodyTemplate = ({
  title, subTitle, subTitle2, showSuccess, children,
}) => (
  <View style={styles.root}>
    <View style={styles.titleContainer}>
      <View style={styles.logoContainer}>
        <LogoBasic height={hp('5%')} width={hp('5%')} />
      </View>
      <Text style={styles.titleText}>{title}</Text>
    </View>
    <View style={styles.subTitlesContainer}>
      <View style={styles.subTitleContainer}>
        {showSuccess && (
        <AntDesign
          name="checkcircle"
          style={styles.successIcon}
          size={24}
          color={Colors.logoBlue}
        />
        )}
        <Text style={styles.subTitleText}>
          {subTitle}
        </Text>
      </View>
      {subTitle2 && (
        <View style={styles.subTitle2Container}>
          <Text style={styles.subTitle2Text}>
            {subTitle2}
          </Text>
        </View>
      )}
    </View>
    {children}
  </View>
)
Example #2
Source File: BotaoExibeNoticias.js    From aglomerou with GNU General Public License v3.0 6 votes vote down vote up
export default function BotaoExibeNoticias() {
  const [modalLinksNoticias, setModalLinksNoticias] = useState(false);
  const notificar = () => setModalLinksNoticias(true);

  const closeModal = () => setModalLinksNoticias(false);

  return (
    <>
      <View style={styles.container}>
        <TouchableOpacity onPress={notificar} style={styles.button}>
          <View>
            <Text style={styles.texth}>Mantenha-se informado!</Text>
            <Text style={styles.textd}>
              Acesse as notícias sobre a COVID-19.
            </Text>
          </View>
          <View style={styles.rightIcon}>
            <AntDesign name="right" size={30} color="#326002" />
          </View>
        </TouchableOpacity>
      </View>
      <ModalLinksNoticias
        modalVisible={modalLinksNoticias}
        closeModal={closeModal}
      />
    </>
  );
}
Example #3
Source File: BotaoNotificar.js    From aglomerou with GNU General Public License v3.0 6 votes vote down vote up
export default function BotaoNotificar() {
  const [modalFromModificao, setModalFromNotificacao] = useState(false);
  const notificar = () => {
    setModalFromNotificacao(true);
  };

  const closeModal = () => {
    setModalFromNotificacao(false);
  };

  return (
    <>
      <View style={styles.container}>
        <TouchableOpacity onPress={notificar} style={styles.button}>
          <View>
            <Text style={styles.texth}>Ajude no combate ao Coronavírus.</Text>
            <Text style={styles.textd}>Notifique aglomeração!</Text>
          </View>
          <View style={styles.rightIcon}>
            <AntDesign name="right" size={30} color="#326002" />
          </View>
        </TouchableOpacity>
      </View>
      <ModalFormNotificao
        modalVisible={modalFromModificao}
        closeModal={closeModal}
      />
    </>
  );
}
Example #4
Source File: CardCover.js    From juken with MIT License 5 votes vote down vote up
CardCover = ({ getClearInterpolation }) => {

  const coverOpacity = getClearInterpolation('x', [1, 0, 1]);
  const iconSmileOpacity = getClearInterpolation('x', [0, 0, 1]);
  const iconFrownOpacity = getClearInterpolation('x', [1, 0, 0]);
  const colorScheme = useColorScheme();
  const coverBackground = getClearInterpolation('x', [
    colorScheme === "light" ? theme.color.incorrect : theme.color_dark.incorrect,
    colorScheme === "light" ? theme.bg.card : theme.bg_dark.card,
    colorScheme === "light" ? theme.color.correct : theme.color_dark.correct
  ]);

  return (
    <Animated.View
      pointerEvents="none"
      style={[
        styles.wrapper,
        {
          backgroundColor: coverBackground,
          opacity: coverOpacity,
        },
      ]}
    >
      
      {/* smile icon */}
      <Animated.View
        style={[
          styles.icon,
          styles.iconSmile,
          { opacity: iconSmileOpacity }
        ]}
      >
        <AntDesign
          name="smileo"
          size={iconSize}
          color={theme.palette.white}
        />
      </Animated.View>
      
      {/* frown icon */}
      <Animated.View
        style={[
          styles.icon,
          styles.iconFrown,
          { opacity: iconFrownOpacity }
        ]}
      >
        <AntDesign
          name="frowno"
          size={iconSize}
          color={theme.palette.white}
        />
      </Animated.View>
    </Animated.View>
  )
}
Example #5
Source File: YourNameScreen.js    From ovuli with MIT License 5 votes vote down vote up
YourNameScreen = () => {
  const [name, setName] = React.useState(null);
  const navigation = useNavigation();

  const saveName = async () => {
    // Saving the Name in Asyncstorage
    try {
      await AsyncStorage.setItem('Name', name);
    } catch (e) {
      console.log(e);
    }
    if (name) {
      console.log(name);
      // Navigating to the next screen
      navigation.navigate('DoYouKnow');
    } else {
      alert('Please enter your Name to Proceed');
    }
  };

  return (
    <KeyboardAwareScrollView
      style={{ flex: 1 }}
      enableOnAndroid={true}
      enableAutoAutomaticScroll={true}
      keyboardOpeningTime={0}
    >
      <ScrollView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}
      >
        <View style={styles.container}>
          <Image source={top} style={styles.top} />
          <View style={{ flexDirection: 'row', marginTop: 200 }}>
            <Text
              style={[styles.nameText, { fontFamily: 'PT-Sans', fontSize: 30, fontWeight: 'bold' }]}
            ></Text>
            <Text style={styles.nameText}>{i18n.t('how_can_we_call_you')}</Text>
          </View>

          <TextInput
            style={styles.inputContainer}
            underlineColorAndroid="transparent"
            autoCapitalize="none"
            placeholder={i18n.t('please_enter_your_name')}
            onChangeText={text => setName(text)}
            value={name}
          />
          <Image source={bottom} style={styles.bottom} />
          <TouchableOpacity style={styles.button} onPress={saveName}>
            <Text style={styles.buttonText}>{i18n.t('continue')}</Text>
            <AntDesign
              style={{ alignSelf: 'center', color: '#F55963', top: 2, left: -4 }}
              name="arrowright"
              size={18}
            />
          </TouchableOpacity>
        </View>
      </ScrollView>
    </KeyboardAwareScrollView>
  );
}
Example #6
Source File: ThirdLastPeriodScreen.js    From ovuli with MIT License 5 votes vote down vote up
ThirdLastPeriodScreen = () => {
  const [selectedDate, setSelectedDate] = React.useState(null);
  const navigation = useNavigation();

  const saveLastPeriod = () => {
    try {
      AsyncStorage.setItem('thirdLastPeriod', selectedDate.toISOString());
    } catch (error) {
      console.log(error);
    }

    navigation.navigate('Dashboard');
  };

  return (
    <View style={styles.container}>
      <StatusBar hidden />
      <Image style={styles.topImage} source={TopImage} />
      <View
        style={{
          flexDirection: 'row',
          marginTop: 20,
          marginBottom: 20,
          width: Dimensions.get('window').width - 70,
          marginLeft: 20,
        }}
      >
        <Text
          style={[styles.nameText, { fontFamily: 'PT-Sans', fontSize: 30, fontWeight: 'bold' }]}
        ></Text>
        <Text style={{ fontSize: 25, fontFamily: 'PT-Sans', marginTop: 8 }}>
          {i18n.t('when_was_your_third_last_period')}
        </Text>
      </View>

      <View style={styles.calenderContainer}>
        <CalendarPicker
          onDateChange={date => setSelectedDate(date)}
          startFromMonday={true}
          previousTitle=""
          nextTitle=""
          headingLevel={0}
          weekdays={CALENDAR_WEEK_DAYS}
          dayOfWeekStyles={styles.dayOfWeekStyles}
          selectedDayStyle={styles.selectedDate}
          selectedDayTextColor="#fff"
        />
      </View>
      <TouchableOpacity style={styles.button} onPress={saveLastPeriod}>
        <View style={styles.buttonTextContainer}>
          <Text style={styles.buttonText}>{i18n.t('finish')}</Text>
          <AntDesign style={styles.arrowIcon} name="arrowright" size={18} />
        </View>
      </TouchableOpacity>
    </View>
  );
}
Example #7
Source File: SecondLastPeriodScreen.js    From ovuli with MIT License 5 votes vote down vote up
SecondLastPeriodScreen = () => {
  const [selectedDate, setSelectedDate] = React.useState(null);
  const navigation = useNavigation();

  const saveLastPeriod = () => {
    try {
      AsyncStorage.setItem('secondLastPeriod', selectedDate.toISOString());
    } catch (error) {
      console.log(error);
    }

    navigation.navigate('ThirdLastPeriod');
  };

  return (
    <View style={styles.container}>
      <StatusBar hidden />
      <Image style={styles.topImage} source={TopImage} />
      <View
        style={{
          flexDirection: 'row',
          marginTop: 20,
          marginBottom: 20,
          width: Dimensions.get('window').width - 50,
          marginLeft: 10,
        }}
      >
        <Text
          style={[styles.nameText, { fontFamily: 'PT-Sans', fontSize: 30, fontWeight: 'bold' }]}
        ></Text>
        <Text style={{ fontSize: 25, fontFamily: 'PT-Sans', marginTop: 8 }}>
          {i18n.t('when_was_your_second_last_period')}
        </Text>
      </View>
      <View style={styles.calenderContainer}>
        <CalendarPicker
          onDateChange={date => setSelectedDate(date)}
          startFromMonday={true}
          previousTitle=""
          nextTitle=""
          headingLevel={0}
          weekdays={CALENDAR_WEEK_DAYS}
          dayOfWeekStyles={styles.dayOfWeekStyles}
          selectedDayStyle={styles.selectedDate}
          selectedDayTextColor="#fff"
        />
      </View>
      <TouchableOpacity style={styles.button} onPress={saveLastPeriod}>
        <View style={styles.buttonTextContainer}>
          <Text style={styles.buttonText}>{i18n.t('continue')}</Text>
          <AntDesign style={styles.arrowIcon} name="arrowright" size={18} />
        </View>
      </TouchableOpacity>
    </View>
  );
}
Example #8
Source File: LastPeriodScreen.js    From ovuli with MIT License 5 votes vote down vote up
LastPeriodScreen = () => {
  const [selectedDate, setSelectedDate] = React.useState(null);
  const navigation = useNavigation();
  const route = useRoute();
  const saveLastPeriod = () => {
    try {
      AsyncStorage.setItem('lastPeriod', selectedDate.toISOString());
    } catch (error) {
      console.log(error);
    }

    if (route.params.prevScreen == 'DoYouKnow') {
      navigation.navigate('SecondLastPeriod');
    }
    if (route.params.prevScreen == 'AverageCycle') {
      navigation.navigate('Dashboard');
    }
  };

  return (
    <View style={styles.container}>
      <StatusBar hidden />
      <Image style={styles.topImage} source={TopImage} />
      <View style={{ padding: 20, alignSelf: 'flex-start' }}>
        <Text style={styles.nameText}>{i18n.t('when_was_your_last_period')}</Text>
      </View>

      <View style={styles.calenderContainer}>
        <CalendarPicker
          onDateChange={date => setSelectedDate(date)}
          startFromMonday={true}
          previousTitle=""
          nextTitle=""
          headingLevel={0}
          weekdays={CALENDAR_WEEK_DAYS}
          dayOfWeekStyles={styles.dayOfWeekStyles}
          selectedDayStyle={styles.selectedDate}
          selectedDayTextColor="#fff"
        />
      </View>
      <TouchableOpacity style={styles.button} onPress={saveLastPeriod}>
        <View style={styles.buttonTextContainer}>
          <Text style={styles.buttonText}>{i18n.t('continue')}</Text>
          <AntDesign style={styles.arrowIcon} name="arrowright" size={18} />
        </View>
      </TouchableOpacity>
    </View>
  );
}
Example #9
Source File: LanguageScreen.js    From ovuli with MIT License 5 votes vote down vote up
LanguageScreen = () => {
  const [selectedLanguageIndex, setSelectedLanguageIndex] = React.useState(
    languages.indexOf('English'),
  );
  const navigation = useNavigation();
  const saveUserLanguage = async () => {
    try {
      let selectedLanguage = languages[selectedLanguageIndex];
      await AsyncStorage.setItem('userLanguage', selectedLanguage);
      i18n.locale = selectedLanguage;

      navigation.navigate('Name');
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <Image source={top} style={styles.top} />
      <View style={styles.cycleText}>
        <Text
          style={[{ fontFamily: 'PT-Sans', fontSize: 30, fontWeight: 'bold', alignSelf: 'center' }]}
        ></Text>
        <Text style={{ fontFamily: 'PT-Sans', fontSize: 25, marginTop: 8, alignSelf: 'center' }}>
          {i18n.t('please_select_your_language')}
        </Text>
      </View>
      <Text
        style={{ fontFamily: 'PT-Sans', fontSize: 25, alignSelf: 'center', marginBottom: 25 }}
      ></Text>
      <View style={styles.wheelPicker}>
        <SmoothPicker
          initialScrollToIndex={2}
          // ref={ref => (this.refList = ref)}
          keyExtractor={(_, index) => index.toString()}
          showsVerticalScrollIndicator={false}
          // bounces={true}
          offsetSelection={50}
          magnet={true}
          scrollAnimation={true}
          data={languages}
          onSelected={({ index }) => setSelectedLanguageIndex(index)}
          renderItem={({ item, index }) => (
            <Bubble selected={index === selectedLanguageIndex}>{item}</Bubble>
          )}
        />
      </View>
      <Image source={bottom} style={styles.bottom} />
      <TouchableOpacity style={styles.button} onPress={saveUserLanguage}>
        <Text style={styles.buttonText}>{i18n.t('continue')}</Text>
        <AntDesign
          style={{ alignSelf: 'center', color: '#F55963', top: 2, left: -4 }}
          name="arrowright"
          size={18}
        />
      </TouchableOpacity>
    </View>
  );
}
Example #10
Source File: AvgCycleScreen.js    From ovuli with MIT License 5 votes vote down vote up
AvgCycle = () => {
  const navigation = useNavigation();
  const [userAverageCycle, setUserAverageCycle] = React.useState(0);

  const saveAvgPeriod = async () => {
    try {
      await AsyncStorage.setItem('AvgPeriod', JSON.stringify(userAverageCycle));
    } catch (error) {
      console.log(error);
    }

    navigation.navigate('LastPeriod', { prevScreen: 'AverageCycle' });
  };

  return (
    <View style={{ backgroundColor: '#fff', flex: 1 }}>
      <Image source={top} style={styles.top} />
      <View style={[{ flexDirection: 'row' }, styles.cycleText]}>
        <Text
          style={[{ fontFamily: 'PT-Sans', fontSize: 30, fontWeight: 'bold', alignSelf: 'center' }]}
        ></Text>
        <Text style={{ fontSize: 25, fontFamily: 'PT-Sans', marginTop: 8 }}>
          {i18n.t('how_long_is_your_cycle')}
        </Text>
      </View>
      <View style={styles.wrapperHorizontal}>
        <StatusBar hidden />
        <SmoothPicker
          initialScrollToIndex={userAverageCycle + 1}
          ref={ref => (this.refList = ref)}
          keyExtractor={(_, index) => index.toString()}
          horizontal={true}
          showsHorizontalScrollIndicator={false}
          bounces={true}
          data={Array.from({ length: 40 }, (_, i) => 1 + i)}
          onSelected={({ index }) => setUserAverageCycle(index)}
          renderItem={({ item, index }) => (
            <Bubble horizontal selected={++index === userAverageCycle + 1}>
              {item}
            </Bubble>
          )}
        />
      </View>
      <TouchableOpacity style={styles.button} onPress={saveAvgPeriod}>
        <Text style={styles.buttonText}>{i18n.t('continue')}</Text>
        <AntDesign
          style={{ alignSelf: 'center', color: '#F55963', top: 2, left: -4 }}
          name="arrowright"
          size={18}
        />
      </TouchableOpacity>
    </View>
  );
}
Example #11
Source File: Modal.js    From juken with MIT License 5 votes vote down vote up
ModalComp = ({
  visible,
  children,
  close,
  contentStyle,
  closeAnimation,
}) => {

  if (!closeAnimation && !visible) return null;

  const colorScheme = useColorScheme();

  const topBar = (
    <TopBar
      rightOnPress={close}
      right={(
        <AntDesign
          name="close"
          color={colorScheme === "light" ? "black": "white"}
          size={22}
        />
      )}
    />
  )

  if (device('web')) {
    return !visible ? null : (
      <Modal
        transparent
        style={[styles.webModalStyle, colorScheme === 'light' ? null : styles.webModalStyle_dark]}
      >
        <View style={[styles.wrapper, colorScheme === 'light' ? null : styles.wrapper_dark]}>
          <ScrollView style={{minHeight: '100%'}}>
            <Page center style={{minHeight: '100vh'}}>

              {/** heading */}
              <View style={[styles.heading, colorScheme === 'light' ? null : styles.heading_dark]}>
                {topBar}
              </View>

              {/** contents */}
              <View style={[styles.contents, colorScheme === 'light' ? null : styles.contents_dark, contentStyle]}>
                {children}
              </View>
            </Page>
          </ScrollView>
        </View>
      </Modal>
    );
  }

  return (
    <RNModal
      isVisible={visible}
      onBackButtonPress={close}
      onBackdropPress={close}
      useNativeDriver={false}
      hideModalContentWhileAnimating={true}
      propagateSwipe
      animationInTiming={DURATION}
      animationOutTiming={DURATION}
      backdropTransitionInTiming={DURATION}
      backdropTransitionOutTiming={0}

    >
      <View style={[styles.wrapper, colorScheme === 'light' ? null : styles.wrapper_dark]}>

        {/** heading */}
        <View style={[styles.heading, colorScheme === 'light' ? null : styles.heading_dark]}>
          {topBar}
        </View>

        {/** contents */}
        <ScrollView style={[ styles.contents, colorScheme === 'light' ? null : styles.contents_dark, contentStyle ]}>
          {children}
        </ScrollView>
      </View>
    </RNModal>
  )
}
Example #12
Source File: Routes.js    From timetable with MIT License 5 votes vote down vote up
BottomTab = () => {
  const Tab = createBottomTabNavigator()
  const { t } = useTranslation()
  const { theme } = useContext(ThemeContext)

  return (
    <Tab.Navigator
      initialRouteName='Stations'
      tabBarOptions={{
        activeTintColor: theme.bottomTabNavActive,
        inactiveTintColor: theme.bottomTabNavInactive,
        style: { backgroundColor: theme.bottomTabNavBackground }
      }}
    >
      <Tab.Screen
        name='Favorites'
        component={Favorites}
        options={{
          title: t('routes.favorites'),
          tabBarIcon: ({ color, size }) => (
            <AntDesign name='staro' color={color} size={size} />
          )
        }}
      />
      <Tab.Screen
        name='Stations'
        component={Stations}
        options={{
          title: t('routes.stations'),
          tabBarIcon: ({ color, size }) => (
            <Entypo name='location' color={color} size={size} />
          )
        }}
      />
      <Tab.Screen
        name='Lines'
        component={Lines}
        options={{
          title: t('routes.lines'),
          tabBarIcon: ({ color, size }) => (
            <Entypo name='dots-three-horizontal' color={color} size={size} />
          )
        }}
      />
      <Tab.Screen
        name='About'
        component={About}
        options={{
          title: t('routes.about'),
          tabBarIcon: ({ color, size }) => (
            <Entypo name='info' color={color} size={size} />
          )
        }}
      />
    </Tab.Navigator>
  )
}
Example #13
Source File: Card.js    From juken with MIT License 5 votes vote down vote up
DirectionRightIcon = () => (
  <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
    <AntDesign name="smileo" size={18} color={theme.color.correct} />
    <AntDesign name="caretright" size={10} color={theme.color.correct} />
  </View>
)
Example #14
Source File: Card.js    From juken with MIT License 5 votes vote down vote up
DirectionLeftIcon = () => (
  <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
    <AntDesign name="caretleft" size={10} color={theme.color.incorrect} />
    <AntDesign name="frowno" size={18} color={theme.color.incorrect} />
  </View>
)
Example #15
Source File: index.native.js    From polaris with Apache License 2.0 5 votes vote down vote up
Right = ({ toggleDrawer }) => (
  <TouchableOpacity onPress={toggleDrawer}>
    <AntDesign name="bars" color="white" size={28} />
  </TouchableOpacity>
)
Example #16
Source File: index.native.js    From polaris with Apache License 2.0 5 votes vote down vote up
Left = ({ isHome, goBack }) =>
  isHome ? (
    <Text> </Text>
  ) : (
    <TouchableOpacity onPress={goBack}>
      <AntDesign name="arrowleft" color="white" size={28} />
    </TouchableOpacity>
  )
Example #17
Source File: Login.js    From juken with MIT License 4 votes vote down vote up
Login = ({ startDemo }) => {
  const [ token, setToken ] = useState('');
  const failed = useRef(null);
  const empty = useRef(null);
  const { showActionSheetWithOptions } = useActionSheet();
  const colorScheme = useColorScheme();

  const login = useStoreActions(actions => actions.session.login);
  const loginLoading = useStoreState(state => state.loadings.login);

  return (
    <>
    <TouchableWithoutFeedback
      onPress={() => {
        if (device('mobile')) Keyboard.dismiss();
      }}
    >

      <View style={[styles.page, colorScheme === 'light' ? null : styles.page_dark]}>

        {/* toasts */}
        <Toast ref={failed} type={TYPES.ERROR} />
        <Toast ref={empty} type={TYPES.WARNING} />

        {/* page */}
        <Page style={[styles.page, colorScheme === 'light' ? null : styles.page_dark]}>
          <KeyboardAvoidingView
            style={styles.container}
            behavior={device('ios') ? 'padding' : 'height'}
          >
            <View style={styles.imageWrapper}>
              <Image source={require('./logo.png')} style={styles.imageIcon} />
              <Image source={require('./wa2.png')} style={styles.imageText} />
            </View>

            <TextInput
              placeholder="WaniKani Personal Access Token"
              value={token}
              onChangeText={text => setToken(text)}
            />

            {/* login button */}
            <Button
              style={{ marginTop: 8 }}
              textStyle={{ color: colorScheme === "light" ? theme.palette.black: theme.palette_dark.lightGray }}
              text={loginLoading ? 'Logging in...' : 'Login'}
              iconRight={
                loginLoading
                  ? <ActivityIndicator size={24} color={colorScheme === "light" ? theme.palette.black: theme.palette_dark.lightGray} />
                  : <AntDesign name="arrowright" size={24} color={theme.palette.black} />
              }
              disabled={loginLoading}
              onPress={() => {
                if (device('mobile')) Keyboard.dismiss();
                if (!token) {
                  empty.current.show('Please enter your API token');
                  return;
                }
                if (token === '1111') {
                  startDemo();
                  return;
                }
                login({
                  token,
                  onFail: () => failed.current.show('Invalid token')
                });
              }}
            />

            {/* more button */}
            {device('mobile') && (
              <Button
                textStyle={{ color: theme.palette.white }}
                text="More"
                style={{ marginTop: 12, backgroundColor: 'transparent' }}
                onPress={() => {
                  showActionSheetWithOptions({
                    options: [
                      'Cancel',
                      'Feedback',
                      'Report Issues',
                      'Source Code',
                      device('ios') ? null : 'Demo',
                    ].filter(Boolean),
                  }, async buttonIndex => {
                    if (buttonIndex === 1) {
                      await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
                    } else if (buttonIndex === 2) {
                      await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
                    } else if (buttonIndex === 3) {
                      await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
                    } else if (buttonIndex === 4) {
                      startDemo()
                    }
                  })
                }}
              />
            )}

            {/** do not show this part for iOS */}
            {device('web') && (
              <>
                <View style={styles.or}>
                  <Text style={styles.orText}>-or-</Text>
                </View>

                {/* demo button */}
                <Button
                  text="Demo"
                  iconLeft={<MaterialCommunityIcons name="test-tube" size={24} color={theme.palette.black} />}
                  onPress={() => startDemo()}
                />

                {/* feedback button */}
                <Button
                  style={{ marginTop: 8 }}
                  text="Feedback & Bug Report"
                  iconLeft={<MaterialIcons name="email" size={24} color={theme.palette.black} />}
                  onPress={async () => {
                    await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
                  }}
                />

                {/* source code button */}
                <Button
                  style={{
                    marginTop: 8,
                    backgroundColor: theme.color.githubBlack
                  }}
                  textStyle={{
                    color: theme.color.githubWhite
                  }}
                  text="Source Code"
                  iconLeft={<AntDesign name="github" size={24} color={theme.color.githubWhite} />}
                  onPress={async () => {
                    await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
                  }}
                />
              </>
            )}

          </KeyboardAvoidingView>
        </Page>
      </View>
    </TouchableWithoutFeedback>
    </>
  )
}
Example #18
Source File: Message.js    From juken with MIT License 4 votes vote down vote up
Message = ({
  icon,
  iconStyle,
  style,
  title,
  description,
  component,
  loading,
  error,
  errorMessage,
  center,
  ctas = [],
}) => (

  <Page
    style={[
      styles.page,
      error && styles.coverError,
      style,
    ]}
  >
    
    {/** loading indicator */}
    {loading && (
      <ActivityIndicator
        size="large"
        color={theme.palette.white}
      />
    )}

    {/** error icon */}
    {error && (
      <AntDesign
        name="frowno"
        size={52}
        color={theme.palette.white}
      />
    )}

    {/** custom icon */}
    {icon && typeof icon === 'string' && <Text style={[styles.iconStyle, iconStyle]}>{icon}</Text>}
    {icon && typeof icon !== 'string' && <View style={[styles.iconStyle, iconStyle]}>{icon}</View>}

    {/** page title */}
    {title && (
      <Text
        style={[
          styles.text,
          styles.width,
          styles.title,
        ]}
      >
        {title}
      </Text>
    )}
    
    {/** page description */}
    {description && (
      <Text
        style={[
          styles.text,
          styles.width,
          styles.description,
          center && styles.center,
        ]}
      >
        {description}
      </Text>
    )}
    
    {/** print error message */}
    {errorMessage && (
      <ScrollView style={[ styles.width, styles.error ]}>
        <Text textBreakStrategy="simple" style={styles.errorText}>
          {errorMessage}
        </Text>
      </ScrollView>
    )}

    {/** render any component for description */}
    {!!component && (
      <View style={[ styles.text, styles.width]}>
        {component}
      </View>
    )}

    {/** render cta's */}
    {ctas.length > 0 && ctas.filter(Boolean).map(cta => (
      <Button
        key={cta.id}
        style={[ styles.width, cta.style ]}
        text={cta.text}
        textStyle={cta.textStyle}
        onPress={cta.onPress}
        color={cta.color}
        iconRight={cta.iconRight}
      />
    ))}
    
  </Page>
)
Example #19
Source File: Review.js    From juken with MIT License 4 votes vote down vote up
Review = ({ demo = false, stopDemo } = {}) => {
  const [ srsStages, setSrsStages ] = useState({});
  const [ menuOpen, setMenuOpen ] = useState(false);

  // only ask unfinished reviews
  const [ wrapUpMode, setWrapUpMode ] = useState(false);

  const logout = useStoreActions(actions => actions.session.logout);
  const submitReview = useStoreActions(actions => actions.reviews.submitReview);
  const retrySubmission = useStoreActions(actions => actions.reviews.retrySubmission);
  const ignoreSubmissionErrors = useStoreActions(actions => actions.reviews.ignoreSubmissionErrors);
  const submissionQueue = useStoreState(state => state.reviews.submissionQueue);
  const submissionErrors = useStoreState(state => state.reviews.submissionErrors);
  const userSettings = useStoreState(state => state.session.userSettings);

  // Allow answering without revealing
  const skipMode = _.get(userSettings, SKIP_MODE);
  
  // Tap anywhere on the card to reveal
  const quickMode = _.get(userSettings, QUICK_MODE);
  
  const colorScheme = useColorScheme();
  const iconcolor = colorScheme === 'light' ? "black":"white";

  useScrollLock();
  useLeaveWarning();

  // load reviews
  const {
    loadReviews,
    loadingReviews,
    reviews,
    subjects,
  } = useLoadReviews(demo);

  // manage review session
  const {
    queue,
    submitAnswer,
    subjectsDict,
    totalCards,
    totalReviews,
    stats,
    unfinishedReviews,
  } = useReviewSession(
    reviews,
    subjects,
  );

  // TODO: refactor
  const queueFiltered = useMemo(() => (
    // wrap up mode filter
    queue.filter(i => wrapUpMode
      ? !_.isNil(_.get(unfinishedReviews, i.review.id))
      : true
    )
  ), [
    queue,
    wrapUpMode,
  ])

  // are all queue items asked
  const isQueueClear = !loadingReviews && queueFiltered.length === 0;

  return (
    <>

    {/** subject details modal 
      <SubjectDetailsModal
        visible={true}
        close={() => {}}
      />
    */}

    {/** display srs stages toasts */}
    <SrsStages stages={srsStages} />

    {loadingReviews && (
      <Overlay>
        <Message loading />
      </Overlay>
    )}

    <Page
      style={[
        styles.page,
        colorScheme === 'light' ? null: styles.page_dark,
        isQueueClear && (colorScheme === 'light' && isQueueClear ? styles.pageNoReviews : styles.pageNoReviews_dark)
      ]}
    >

      <View style={styles.deckWrapper}>

        {/** top bar */}
        <ReviewTopBar
          demo={demo}
          logout={logout}
          stopDemo={stopDemo}
          submissionQueue={submissionQueue}
          submissionErrors={submissionErrors}
          ignoreSubmissionErrors={ignoreSubmissionErrors}
          retrySubmission={retrySubmission}
          isQueueClear={isQueueClear}
          setMenuOpen={setMenuOpen}
        />

        {/** menu */}
        <ReviewMenu
          menuOpen={menuOpen}
          setMenuOpen={setMenuOpen}
          demo={demo}
          logout={logout}
          stopDemo={stopDemo}
          loadReviews={loadReviews}
          wrapUpMode={wrapUpMode}
          setWrapUpMode={setWrapUpMode}
        />

        {/* render deck */}
        {queueFiltered.length > 0 && (
          <Deck
            style={styles.deck}
            cards={queueFiltered}
            allowSkipping={skipMode}
            dismissCard={direction => {
              submitAnswer(
                // item that was submitted: the top item
                // of the processed queue list
                queueFiltered[0],
                // right direction means correct answer
                direction === 'right',
                // callback for when the submit answer causes
                // the review to be completed
                res => {

                  const {
                    review,
                    incorrectMeanings,
                    incorrectReadings,
                  } = res;

                  // review was correct when there are
                  // no incorrect readings or meanings
                  const isCorrect = (
                    !incorrectMeanings &&
                    !incorrectReadings
                  );

                  // increase srs stage if the answer was correct
                  if (isCorrect) {
                    const currentStage = _.get(review, 'data.srs_stage');
                    setSrsStages({ current: currentStage, next: currentStage + 1 })
                  }

                  // submit review
                  submitReview({
                    demo,
                    subjectId: _.get(review, 'data.subject_id'),
                    reviewId: review.id,
                    incorrectMeanings,
                    incorrectReadings,
                  });
                }
              );
            }}
            renderCard={(item, props) => {

              // empty cards
              if (!item) return <Card empty />

              const { id, review, reviewType } = item;
              const subjectId = _.get(review, 'data.subject_id');
              const subject = _.get(subjectsDict, subjectId);
              const subjectType = _.get(subject, 'object');
              const meaningMnemonic = _.get(subject, 'data.meaning_mnemonic');
              const readingMnemonic = _.get(subject, 'data.reading_mnemonic');
              const {
                question,
                questionComponent,
                answer,
              } = extractSubject(subject, reviewType);

              return (
                <Card
                  key={`${id}_${reviewType}`}
                  deckProps={props}
                  subjectType={subjectType}
                  reviewType={reviewType}
                  reviewQuestion={question}
                  reviewQuestionComponent={questionComponent}
                  reviewAnswer={answer}
                  meaningMnemonic={meaningMnemonic}
                  readingMnemonic={readingMnemonic}
                  quickMode={quickMode}
                />
              )
            }}
          />
        )}

        {/* no reviews notice */}
        {isQueueClear && (
          <View style={styles.noReviewsContainer}>
            <AntDesign name="smileo" size={32} color={theme.palette.white} />
            {!wrapUpMode && <Text style={styles.noReviewsText}>Review queue clear!</Text>}
            {wrapUpMode && <Text style={styles.noReviewsText}>Wrap-up queue clear!</Text>}
            {wrapUpMode && (
              <Text style={styles.noReviewsDesc}>
                You can now end your review session
              </Text>
            )}

          </View>
        )}

        {/* stats */}
        {totalReviews > 0 && (
          <View style={[ styles.box, colorScheme === "light" ? null :styles.box_dark, styles.bars ]}>

            {/* review bar */}
            <View style={styles.barWrapper}>
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, styles.barTextLabel, { marginRight: 8 } ]}>Reviews</Text>
              <Bar
                style={[styles.bar, colorScheme === "light" ? null : styles.bar_dark]}
                values={[ _.get(stats, 'reviews.incorrectPercent', 0), _.get(stats, 'reviews.correctPercent', 0) ]}
                colors={colorScheme === "light" ? [ theme.palette.red, theme.palette.green] : [ theme.palette_dark.red, theme.palette_dark.green]}
              />
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, { marginLeft: 8 } ]}>{_.get(stats, 'reviews.completed')}</Text>
              {_.get(stats, 'reviews.unfinished') > 0 && (
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, styles.barTextOpac, { fontSize: 8, marginTop: -12 } ]}>{_.get(stats, 'reviews.unfinished')}</Text>
              )}
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, styles.barTextOpac, { marginLeft: 4, marginRight: 4 } ]}>of</Text>
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark ]}>{totalReviews}</Text>
            </View>

            {/* card bar */}
            <View style={[ styles.barWrapper, { marginTop: 4 } ]}>
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, styles.barTextLabel, { marginRight: 8 } ]}>Cards</Text>
              <Bar
                style={[styles.bar,colorScheme === "light" ? null : styles.bar_dark]}
                values={[ _.get(stats, 'cards.incorrectPercent', 0), _.get(stats, 'cards.correctPercent', 0) ]}
                colors={colorScheme === "light" ? [ theme.palette.red, theme.palette.green] : [ theme.palette_dark.red, theme.palette_dark.green]}
              />
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, { marginLeft: 8 } ]}>{_.get(stats, 'cards.completed')}</Text>
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark, styles.barTextOpac, { marginLeft: 4, marginRight: 4 } ]}>of</Text>
              <Text style={[ styles.barText, colorScheme === "light" ? null : styles.barTextDark ]}>{totalCards}</Text>
            </View>

          </View>
        )}

        {/* controls */}
        {isQueueClear && (
          <>
            <View style={{ height: 6 }} />
            {wrapUpMode && (
              <Button
                text="Disable Wrap-up Mode"
                style={{ marginTop: 8 }}
                iconLeft={<SimpleLineIcons name="clock" size={18} color={iconcolor} />}
                onPress={() => setWrapUpMode(false)}
              />
            )}
            {!wrapUpMode && (
              <Button
                text="Refresh"
                style={{ marginTop: 8 }}
                iconLeft={<SimpleLineIcons name="refresh" size={18} color={iconcolor} />}
                onPress={() => loadReviews()}
              />
            )}
            <Button
              text="Logout"
              style={{ marginTop: 8, backgroundColor: 'transparent' }}
              textStyle={{ color: theme.palette.white }}
              onPress={() => {
                if (demo) stopDemo()
                else logout();
              }}
            />
          </>
        )}
      </View>
    </Page>
  </>
)}
Example #20
Source File: ReviewTopBar.js    From juken with MIT License 4 votes vote down vote up
ReviewTopBar = ({
  submissionQueue,
  submissionErrors,
  ignoreSubmissionErrors,
  retrySubmission,
  isQueueClear,
  setMenuOpen,
}) => {
  
  const isInternetReachable = useNetworkListener();
  const { showActionSheetWithOptions } = useActionSheet();

  const uploadSuccess = submissionQueue.length === 0;
  const uploadFail = submissionErrors.length > 0;
  const uploadQueue = submissionQueue.length;
  const uploadErrors = submissionErrors.length;

  let badgeColor = uploadFail
    ? theme.palette.red
    : 'rgba(0, 0, 0, .1)';
  
  let badgeIcon = null;
  if (uploadSuccess) badgeIcon = <AntDesign name="check" size={10} color="white" />;
  if (uploadQueue > 0) badgeIcon = <AntDesign name="arrowup" size={10} color="white" />;

  let badgeText = null;
  if (uploadQueue > 0) badgeText = uploadQueue;
  if (uploadFail) badgeText = uploadErrors;

  return (
    <>

      {/** top bar */}
      <TopBar
        style={styles.wrapper}
        centerText={isQueueClear ? '' : 'Reviews'}
        left={<Entypo name="menu" size={20} color="white" />}
        leftOnPress={() => setMenuOpen(true)}
        right={
          <>
            {!isInternetReachable && (
              <Badge
                style={{ marginRight: 6, backgroundColor: theme.palette.red }}
                icon={<Feather name="wifi-off" size={10} color="white" />}
              />
            )}
            <Badge
              style={{ backgroundColor: badgeColor }}
              text={badgeText}
              icon={badgeIcon}
            />
          </>
        }
        rightOnPress={!uploadFail ? null : () => {
          showActionSheetWithOptions({
              options: [
                'Cancel',
                'Retry',
                'Ignore',
              ],
              destructiveButtonIndex: 2,
              title: `Failed to submit ${uploadErrors} review${uploadErrors === 1 ? '' : 's'}`,
              message: (
                'You can retry submission after making sure your device ' +
                'has an active internet connection. If you submitted the reviews ' +
                'from another application, please use the Ignore button to dismiss ' +
                'the errors.'
              ),
            }, buttonIndex => {
              if (buttonIndex === 1) {
                retrySubmission();
              } else if (buttonIndex === 2) {
                dialog({
                  webTitle: 'Unless you submitted your reviews elsewhere, your unsubmitted reviews will be lost. Are you sure ?',
                  mobileTitle: 'Are you sure ?',
                  mobileMessage: 'Unless you submitted your reviews elsewhere, your unsubmitted reviews will be lost.',
                  onConfirm: ignoreSubmissionErrors
                });
              }
            })
        }}
      />
    </>
  )
}
Example #21
Source File: main.js    From Reminder-App with MIT License 4 votes vote down vote up
function main() {
  const { init_data, snooze } = useContext(ReminderContext);
  const { init_data_Birthday } = useContext(BirthdayContext);
  const { state, init_data_Settings } = useContext(SettingsContext);
  var currentTheme = state.Theme ? lighttheme : darktheme;
  const { colors } = currentTheme;
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(
      async (response) => {
        if (response.actionIdentifier === "snooze") {
          if (
            response.notification.request.content.categoryIdentifier ==
            "reminder"
          ) {
            snooze({
              text: response.notification.request.content.body,
              val: response.notification.request.identifier,
              snoozetime: 30,
            });
          }
        }
        await Notifications.dismissNotificationAsync(
          response.notification.request.identifier
        );
      }
    );
    return () => subscription.remove();
  }, []);

  useEffect(() => {
    init_data();
    init_data_Birthday();
    init_data_Settings();
    setTimeout(() => {
      setLoading(false);
    }, 500);
  }, []);

  if (loading) {
    return (
      <View
        style={{ flex: 1, justifyContent: "center", alignContent: "center" }}
      >
        <ActivityIndicator color="#7f2ee1" animating={true} size={40} />
      </View>
    );
  } else
    return (
      <PaperProvider theme={currentTheme}>
        <NavigationContainer>
          <Tab.Navigator
            sceneContainerStyle={{ backgroundColor: colors.background }}
            tabBarOptions={{
              showLabel: false,
              activeBackgroundColor: colors.tab,
              inactiveBackgroundColor: colors.tab,
              activeTintColor: colors.accent,
              inactiveTintColor: colors.primary,
            }}
          >
            <Tab.Screen
              name="Reminder"
              component={Reminder_Screen}
              options={{
                tabBarIcon: ({ size, color }) => (
                  <AntDesign name="clockcircleo" size={size} color={color} />
                ),
              }}
            />
            <Tab.Screen
              name="Birthday"
              component={Birthday_Screen}
              options={{
                tabBarIcon: ({ size, color }) => (
                  <AntDesign name="gift" size={size} color={color} />
                ),
              }}
            />
            <Tab.Screen
              name="Settings"
              component={Settings_Screen}
              options={{
                tabBarIcon: ({ size, color }) => (
                  <AntDesign name="setting" size={size} color={color} />
                ),
              }}
            />
          </Tab.Navigator>
        </NavigationContainer>
      </PaperProvider>
    );
}
Example #22
Source File: DoYouKnow.js    From ovuli with MIT License 4 votes vote down vote up
DoYouKnow = () => {
  const navigation = useNavigation();

  const countYes = () => {
    navigation.navigate('AverageCycle');
  };
  const countNo = () => {
    navigation.navigate('LastPeriod', { prevScreen: 'DoYouKnow' });
  };

  return (
    <View style={styles.container}>
      <Image source={top} style={styles.top} />
      <View style={{ flexDirection: 'row' }}>
        <Text style={styles.nameText}>{i18n.t('do_you_know_your_cycle_length')}</Text>
      </View>

      <TouchableOpacity
        style={{
          borderWidth: 2,

          width: 80,

          borderRadius: 5,

          top: Dimensions.get('window').height - 230,
          borderColor: '#F55963',
          position: 'absolute',

          flex: 1,
          alignContent: 'center',
          justifyContent: 'center',
          flexDirection: 'row',
          left: 80,
          backgroundColor: '#F55963',
        }}
        onPress={countYes}
      >
        <Text
          style={
            (styles.condText,
            [
              {
                fontSize: 20,
                textAlign: 'center',
                padding: 5,

                color: '#F55963',

                color: 'white',
              },
            ])
          }
        >
          {i18n.t('yes')}
        </Text>
        <AntDesign style={{ alignSelf: 'center', color: '#F55963' }} size={18} />
      </TouchableOpacity>

      <TouchableOpacity
        style={
          (styles.condnobutton,
          [
            {
              borderWidth: 2,
              width: 80,
              borderRadius: 5,

              top: Dimensions.get('window').height - 230,
              borderColor: '#F55963',
              position: 'absolute',

              flex: 1,
              alignContent: 'center',
              justifyContent: 'center',
              flexDirection: 'row',
              right: 80,
              backgroundColor: '#F55963',
            },
          ])
        }
        onPress={countNo}
      >
        <Text
          style={{
            fontSize: 20,
            textAlign: 'center',
            padding: 5,

            color: '#F55963',
            color: 'white',
          }}
        >
          {i18n.t('no')}
        </Text>
        <AntDesign style={{ alignSelf: 'center', color: '#F55963' }} size={18} />
      </TouchableOpacity>
    </View>
  );
}
Example #23
Source File: Reminder_Screen.js    From Reminder-App with MIT License 4 votes vote down vote up
function My_List() {
  const { state, add_reminder, delete_reminder, edit } = useContext(Context);

  const { colors } = useTheme();
  const [showmodel, setmodel] = useState(false);
  const [selecteditem, setselecteditem] = useState(null);

  let itemRefs = new Map();

  useEffect(() => {
    state.map((item) => {
      let ti = new Date(item.Date);
      if (ti.getTime() <= Date.now()) {
        delete_reminder(item);
      }
    });
    state.sort(function (a, b) {
      var keyA = new Date(a.Date).getTime(),
        keyB = new Date(b.Date).getTime();
      if (keyA < keyB) return -1;
      if (keyA > keyB) return 1;
      return 0;
    });
  }, [state]);

  const chnage_model = (item) => {
    LayoutAnimation.configureNext(
      LayoutAnimation.create(
        200,
        LayoutAnimation.Types.linear,
        LayoutAnimation.Properties.opacity
      )
    );
    setselecteditem(item);
    setmodel(!showmodel);
  };
  const hide_model = () => {
    LayoutAnimation.configureNext(
      LayoutAnimation.create(
        200,
        LayoutAnimation.Types.linear,
        LayoutAnimation.Properties.opacity
      )
    );
    setmodel(false);
    setselecteditem(null);
  };

  function emptylist() {
    return (
      <View
        style={{
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <Text
          style={[
            styles.text,
            { fontSize: 25, textAlign: "center", color: colors.text },
          ]}
        >
          {
            "Looks like you have no reminder! \n Click on the plus icon to add one."
          }
        </Text>
      </View>
    );
  }

  function footer() {
    return (
      <View
        style={{
          height: 75,
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <TouchableOpacity
          onPress={() => {
            add_reminder();
          }}
        >
          <AntDesign name="plus" size={34} color={colors.text} />
        </TouchableOpacity>
      </View>
    );
  }
  if (showmodel) {
    return (
      <Model edit={edit} hide_model={hide_model} selecteditem={selecteditem} />
    );
  }
  function header() {
    return (
      <View style={styles.TitleContainer}>
        <Text style={[styles.text, { fontSize: 45, color: colors.text }]}>
          Reminders
        </Text>
      </View>
    );
  }
  return (
    <View style={styles.container}>
      <FlatList
        ListHeaderComponent={header}
        ListEmptyComponent={emptylist}
        style={{ flex: 0.8 }}
        keyExtractor={(item) => item.key}
        data={state}
        renderItem={({ item, index }) => (
          <Element
            index={index}
            item={item}
            itemRefs={itemRefs}
            deleteItem={(item) => {
              delete_reminder(item);
            }}
            showmodel={chnage_model}
          />
        )}
        ListFooterComponent={footer}
        // onDragEnd={({ data }) => this.setState({ data })}
        // activationDistance={10}
      />
    </View>
  );
}
Example #24
Source File: Birthday_Screen.js    From Reminder-App with MIT License 4 votes vote down vote up
function My_List() {
  const { state, add_birthday, delete_birthday, edit } = useContext(Context);
  const { colors } = useTheme();
  const [showmodel, setmodel] = useState(false);
  const [selecteditem, setselecteditem] = useState(null);

  useEffect(() => {
    state.sort(function (a, b) {
      var keyA = new Date(a.Date).getTime(),
        keyB = new Date(b.Date).getTime();
      if (keyA < keyB) return -1;
      if (keyA > keyB) return 1;
      return 0;
    });
  }, [state]);

  useEffect(() => {
    state.map((item) => {
      edit({ selecteditem: item, text: item.text, time: item.Date });
    });
  }, []);

  let itemRefs = new Map();

  const chnage_model = (item) => {
    LayoutAnimation.configureNext(
      LayoutAnimation.create(
        200,
        LayoutAnimation.Types.linear,
        LayoutAnimation.Properties.opacity
      )
    );
    setselecteditem(item);
    setmodel(!showmodel);
  };
  const hide_model = () => {
    LayoutAnimation.configureNext(
      LayoutAnimation.create(
        200,
        LayoutAnimation.Types.linear,
        LayoutAnimation.Properties.opacity
      )
    );
    setmodel(false);
    setselecteditem(null);
  };

  function emptylist() {
    return (
      <View
        style={{
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <Text
          style={[
            styles.text,
            { fontSize: 25, textAlign: "center", color: colors.text },
          ]}
        >
          {"Click on the plus icon to add Birthday Reminder."}
        </Text>
      </View>
    );
  }

  function footer() {
    return (
      <View
        style={{
          height: 75,
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <TouchableOpacity
          onPress={() => {
            add_birthday();
          }}
        >
          <AntDesign name="plus" size={34} color={colors.text} />
        </TouchableOpacity>
      </View>
    );
  }
  if (showmodel) {
    return (
      <Model edit={edit} hide_model={hide_model} selecteditem={selecteditem} />
    );
  }
  function header() {
    return (
      <View style={styles.TitleContainer}>
        <Text style={[styles.text, { fontSize: 45, color: colors.text }]}>
          Birthdays
        </Text>
      </View>
    );
  }
  return (
    <View style={styles.container}>
      <FlatList
        ListHeaderComponent={header}
        ListEmptyComponent={emptylist}
        style={{ flex: 0.8 }}
        keyExtractor={(item) => item.key}
        data={state}
        renderItem={({ item, index }) => (
          <Element
            index={index}
            item={item}
            itemRefs={itemRefs}
            deleteItem={(item) => {
              delete_birthday(item);
            }}
            showmodel={chnage_model}
          />
        )}
        ListFooterComponent={footer}
      />
    </View>
  );
}
Example #25
Source File: model.js    From Reminder-App with MIT License 4 votes vote down vote up
export default function ({ selecteditem, hide_model, edit }) {
  const [text, settext] = useState(selecteditem.text);
  const [time, settime] = useState(new Date(selecteditem.Date));
  const [mode, setMode] = useState("date");
  const [show, setShow] = useState(false);
  const { colors } = useTheme();
  const [visible, setVisible] = useState(false);

  const onToggleSnackBar = () => setVisible(!visible);

  const onDismissSnackBar = () => setVisible(false);
  if (show) {
    return (
      <DateTimePicker
        minimumDate={new Date(Date.now())}
        value={time}
        mode={mode}
        display="default"
        onChange={(event, date) => {
          if (event.type == "dismissed") {
            setShow(false);
            return;
          }
          let tep = new Date(Date.now());

          if (tep.getTime() / 1000 - date.getTime() / 1000 > 1) {
            setShow(false);
            onToggleSnackBar();
            return;
          }
          settime(date);
          setShow(false);
        }}
        style={{ width: 320, backgroundColor: "gray" }} //add this
      />
    );
  }
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
      }}
    >
      <TouchableOpacity
        onPress={() => hide_model()}
        style={{
          alignSelf: "flex-end",
          marginHorizontal: 10,
          marginBottom: 10,
        }}
      >
        <AntDesign name="closecircleo" size={30} color={colors.text} />
      </TouchableOpacity>
      <View style={[styles.model, { backgroundColor: colors.tab }]}>
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            flex: 1,
          }}
        >
          <View
            style={{
              flex: 1,
              marginTop: 7,
              marginHorizontal: 3,
            }}
          >
            <TextInput
              maxLength={100}
              multiline
              numberOfLines={2}
              selectTextOnFocus={text == "Tap to edit"}
              onChangeText={(text) => settext(text)}
              value={text}
              style={[styles.text, { color: colors.text }]}
            />
            <Text
              style={[
                styles.text,
                { fontSize: 14, marginTop: 15, color: colors.text },
              ]}
            >
              {`${moment(time).format("hh:mm a")}, ${
                moment(time).format("Do ") + moment(time).format("MMM YYYY")
              }`}
            </Text>
          </View>
          <View style={[styles.sep]} />
          <View style={{ flexDirection: "column" }}>
            <Text
              style={[
                styles.text,
                { fontSize: 10, alignSelf: "center", color: colors.text },
              ]}
            >
              Tap to change
            </Text>
            <TouchableOpacity
              style={styles.button}
              onPress={() => {
                setMode("date");
                setShow(true);
              }}
            >
              <Text style={[styles.text, { fontSize: 16, color: colors.text }]}>
                Date
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.button}
              onPress={() => {
                setMode("time");
                setShow(true);
              }}
            >
              <Text style={[styles.text, { fontSize: 16, color: colors.text }]}>
                Time
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
      <TouchableOpacity
        onPress={() => {
          edit({ text, selecteditem, time: moment(time) });
          hide_model();
        }}
        style={styles.button}
      >
        <Text style={[styles.text, { fontSize: 18, color: colors.text }]}>
          Save
        </Text>
      </TouchableOpacity>
      <Snackbar
        visible={visible}
        onDismiss={onDismissSnackBar}
        action={{
          label: "OK",
          onPress: () => {
            onToggleSnackBar();
          },
        }}
      >
        Invaild Date or Time
      </Snackbar>
    </View>
  );
}
Example #26
Source File: birthdaymodel.js    From Reminder-App with MIT License 4 votes vote down vote up
export default function ({ selecteditem, hide_model, edit }) {
  const [text, settext] = useState(selecteditem.text);
  const [time, settime] = useState(new Date(selecteditem.Date));
  const [show, setShow] = useState(false);
  const { colors } = useTheme();

  if (show) {
    return (
      <DateTimePicker
        maximumDate={new Date(Date.now())}
        value={time}
        mode={"date"}
        display="default"
        onChange={(event, date) => {
          if (event.type == "dismissed") {
            setShow(false);
            return;
          }
          settime(date);
          setShow(false);
        }}
        style={{ width: 320, backgroundColor: "gray" }} //add this
      />
    );
  }
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
      }}
    >
      <TouchableOpacity
        onPress={() => hide_model()}
        style={{
          alignSelf: "flex-end",
          marginHorizontal: 10,
          marginBottom: 10,
        }}
      >
        <AntDesign name="closecircleo" size={30} color={colors.text} />
      </TouchableOpacity>
      <View style={[styles.model, { backgroundColor: colors.tab }]}>
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            flex: 1,
          }}
        >
          <View
            style={{
              flex: 1,
              marginTop: 7,
              marginHorizontal: 3,
            }}
          >
            <TextInput
              maxLength={100}
              multiline
              numberOfLines={2}
              onChangeText={(text) => settext(text)}
              selectTextOnFocus={text == "Tap to change the name"}
              value={text}
              style={[styles.text, { color: colors.text }]}
            />
            <Text
              style={[
                styles.text,
                { fontSize: 14, marginTop: 15, color: colors.text },
              ]}
            >
              {` ${
                moment(time).format("Do ") + moment(time).format("MMMM YYYY")
              }`}
            </Text>
          </View>
          <View style={[styles.sep]} />
          <View style={{ flexDirection: "column" }}>
            <Text
              style={[
                styles.text,
                { fontSize: 10, alignSelf: "center", color: colors.text },
              ]}
            >
              Tap to change
            </Text>
            <TouchableOpacity
              style={styles.button}
              onPress={() => {
                setShow(true);
              }}
            >
              <Text style={[styles.text, { fontSize: 16, color: colors.text }]}>
                Date
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
      <TouchableOpacity
        onPress={() => {
          edit({ text, selecteditem, time: moment(time) });
          hide_model();
        }}
        style={styles.button}
      >
        <Text style={[styles.text, { fontSize: 18, color: colors.text }]}>
          Save
        </Text>
      </TouchableOpacity>
    </View>
  );
}
Example #27
Source File: Timetable.js    From timetable with MIT License 4 votes vote down vote up
Timetable = ({ route }) => {
  const { t, i18n } = useTranslation()
  const { theme } = useTheme()
  // netInfo helps to check network connection status. Timeout 15s
  const netInfo = useNetInfo({ reachabilityRequestTimeout: 15 * 1000 })

  // station ID which you get from Stations screen
  const { stationTimetableId, metadata } = route.params
  const metainfo = { station: stationTimetableId, info: metadata }

  /**
   * Arrival bus list!
   * Used to get latest info.
   * API request sample.
   * https://xxxxxxx:xxxx/xxxxxxxxxxxx/?station=${stationTimetableId}
   **/

  const endPoint =
    i18n.language == 'en'
      ? `${process.env.API_TIMETABLE_EN + stationTimetableId}`
      : `${process.env.API_TIMETABLE_GE + stationTimetableId}`

  // Local Time string object
  const [localTime, setLocalTime] = useState('')

  // Stream of data
  const fetcher = (...args) => fetch(...args).then(res => res.json())

  const { data, error } = useSWR(endPoint, fetcher, {
    refreshInterval: 1000 * 10
  })

  // Bouncing animation
  const focus = new Animated.Value(0)

  Animated.loop(
    Animated.timing(focus, {
      toValue: 10,
      duration: 4000,
      easing: Easing.bounce,
      useNativeDriver: true
    })
  ).start()

  useEffect(() => {
    // Server related warning
    if (error) {
      Alert.alert(t('timetable.error'), t('timetable.server_err'), [
        { text: t('timetable.cancel') }
      ])
    }

    const interval = setInterval(() => {
      setLocalTime(
        new Date().toLocaleTimeString('en-US', { hour12: false }, 'ka-KA')
      )
    }, 1000)

    // clean up
    return () => {
      clearInterval(interval), focus.stopAnimation()
    }
  }, [])

  /**
   * Saves station ID and metainfo to local storage!
   * Checks if ID exist in storage and displays pop up warning.
   **/

  const saveFavoriteHandler = async () => {
    try {
      const result = await AsyncStorage.getItem('TestFavorite')

      if (result == null) {
        const createArray = [metainfo]

        AsyncStorage.setItem('TestFavorite', JSON.stringify(createArray))
      } else if (result !== null) {
        const array = await JSON.parse(result)
        let onAlert = false

        array.forEach(value => {
          if (value.station == stationTimetableId) {
            onAlert = true
            Alert.alert('', t('timetable.favorite'), [
              { text: t('timetable.cancel') }
            ])
          }
        })

        if (onAlert == false) {
          array.push(metainfo)
          AsyncStorage.setItem('TestFavorite', JSON.stringify(array))
        }
      }
    } catch (err) {
      Alert.alert('', err, [{ text: t('timetable.cancel') }])
    }
  }

  /**
   * Displays Local Time!
   * Shows night time if it's between 12:00AM - 6:00AM.
   * Shows delay if timetable is empty between 7:00AM - 11:00PM,
   * also for displaying delay we check network status.
   **/

  const DisplayTime = () => {
    if (parseInt(localTime) >= 7 && parseInt(localTime) <= 22) {
      return (
        <View style={styles.localTime}>
          <Text style={{ color: theme.text }}>{localTime} (GMT+4)</Text>
          <Text style={{ color: theme.text }}>{t('timetable.localTime')}</Text>
          <Text style={{ color: theme.text }}>
            {t('timetable.localTimeDelay')}
          </Text>
        </View>
      )
    } else if (
      (parseInt(localTime) >= 0 && parseInt(localTime) <= 6) ||
      parseInt(localTime) == 23
    ) {
      return (
        <View style={styles.localTime}>
          <Text style={{ color: theme.text }}>{localTime} (GMT+4)</Text>
          <Text style={{ color: theme.text }}>{t('timetable.localTime')}</Text>
          <Text style={{ color: theme.text }}>
            {t('timetable.localTimeNight')}
          </Text>
        </View>
      )
    }
  }

  // FlatList Item
  const Item = ({ title, time, bus, nowText, minText }) => {
    // Apply animation if time is below two minutes and display 'Now' instead of time.
    // Time is number it can be between 0-100: represents minutes.

    const willBeIn = () => {
      if (time <= 2 || 0) {
        return (
          <Animated.View style={{ opacity: focus }}>
            <Text style={{ color: theme.text }}>{nowText}</Text>
          </Animated.View>
        )
      } else {
        return (
          <Text style={{ color: theme.text }}>
            {time} {minText}
          </Text>
        )
      }
    }

    return (
      <View style={[styles.listItemView, { borderColor: theme.border }]}>
        <Text style={{ color: theme.text }}>{bus}</Text>
        <Text style={[styles.title, { color: theme.text }]}>{title}</Text>
        {willBeIn()}
      </View>
    )
  }

  return (
    <View style={styles.container}>
      <Text style={[styles.info, { color: theme.text }]}>
        {t('timetable.station')} {stationTimetableId}
      </Text>

      <AntDesign
        name='staro'
        color='white'
        size={30}
        style={styles.favoriteIcon}
        onPress={saveFavoriteHandler}
      />

      <View style={styles.listHeader}>
        <Text style={{ color: theme.text }}>{t('timetable.bus')}</Text>
        <Text style={{ color: theme.text }}>{t('timetable.direction')}</Text>
        <Text style={{ color: theme.text }}>{t('timetable.time')}</Text>
      </View>

      {!data ? null : (
        <FlatList
          data={data.ArrivalTime}
          renderItem={({ item }) => (
            <Item
              title={item.DestinationStopName}
              time={item.ArrivalTime}
              bus={item.RouteNumber}
              minText={t('timetable.minText')}
              nowText={t('timetable.nowText')}
            />
          )}
          keyExtractor={item => item.RouteNumber}
        />
      )}

      {!data
        ? null
        : netInfo.isConnected && data.ArrivalTime.length === 0 && DisplayTime()}
    </View>
  )
}
Example #28
Source File: Favorites.js    From timetable with MIT License 4 votes vote down vote up
Favorites = () => {
  const navigation = useNavigation()
  const { t } = useTranslation()
  const { theme } = useTheme()

  const [list, setList] = useState([])
  const [refreshing, setRefreshing] = useState(false)

  // used for removing [square brackets] in array of an objects.
  const myRegex = args => args.replace(/(?!^)[\[\]](?!$)/g, '')

  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', async () => {
      const result = await AsyncStorage.getItem('TestFavorite')

      if (result == null) return
      else {
        setList(JSON.parse(myRegex(result)))
      }
    })

    // Cleanup
    return unsubscribe
  }, [navigation])

  const onRefreshHandler = async () => {
    setRefreshing(true)

    const result = await AsyncStorage.getItem('TestFavorite')
    setList(JSON.parse(myRegex(result)))

    setRefreshing(false)
  }

  // FlatList Item
  const Item = ({ station, info }) => {
    const [modalVisible, setModalVisible] = useState(false)

    const onDeleteHandler = async () => {
      const result = await AsyncStorage.getItem('TestFavorite')
      if (result !== null) {
        const array = await JSON.parse(result)
        const deleteItem = await array.filter(item => item.station !== station)
        AsyncStorage.setItem('TestFavorite', JSON.stringify(deleteItem))
      }
      setModalVisible(!modalVisible)
    }

    return (
      <TouchableHighlight
        style={styles.touchableHighlight}
        onPress={() => {
          navigation.navigate('Timetable', { stationTimetableId: station })
        }}
        onLongPress={() => setModalVisible(true)}
        activeOpacity={0.1}
        underlayColor={'transparent'}
      >
        <View style={styles.item}>
          <View
            style={[styles.separator, { borderBottomColor: theme.border }]}
          />

          <Text style={{ color: theme.text }}>{info}</Text>

          <Modal
            animationType='slide'
            transparent={true}
            visible={modalVisible}
            onRequestClose={() => setModalVisible(!modalVisible)}
          >
            <View
              style={[
                styles.modalView,
                {
                  backgroundColor: theme.backgroundColor,
                  shadowColor: theme.shadow
                }
              ]}
            >
              <Text style={[styles.modalText, { color: theme.text }]}>
                {t('favorites.modal')}
              </Text>

              <Text style={[styles.modalStation, { color: theme.text }]}>
                {info}
              </Text>

              <View style={styles.modalButtons}>
                <Button
                  onPress={onDeleteHandler}
                  text={t('favorites.modalButtonYes')}
                  buttonColor={theme.buttonColor}
                  textColor='red'
                  margin={25}
                  paddingVertical={4}
                  fontSize={15}
                />

                <Button
                  onPress={() => setModalVisible(!modalVisible)}
                  text={t('favorites.modalButtonNo')}
                  buttonColor={theme.buttonColor}
                  textColor={theme.buttonText}
                  margin={25}
                  paddingVertical={4}
                  fontSize={15}
                />
              </View>
            </View>
          </Modal>
        </View>
      </TouchableHighlight>
    )
  }

  return (
    <View style={styles.container}>
      {list.length > 0 ? (
        <FlatList
          data={list}
          renderItem={({ item }) => (
            <Item info={item.info} station={item.station} />
          )}
          keyExtractor={item => item.station}
          onRefresh={onRefreshHandler}
          refreshing={refreshing}
        />
      ) : (
        <View style={styles.emptyList}>
          <AntDesign name='staro' color='white' size={45} />
          <Text style={{ color: theme.text }}>{t('favorites.empty')}</Text>
        </View>
      )}
    </View>
  )
}