@expo/vector-icons#MaterialCommunityIcons JavaScript Examples

The following examples show how to use @expo/vector-icons#MaterialCommunityIcons. 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: Stats.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
function SyncButton ({group, game_id}) {
  const [pressed,setPressed] = React.useState(false);
  const theme = useSelector(i=>i.themes[i.theme]);
  const data = useAPIRequest(pressed?{
    cuppazee: true,
    endpoint: "clan/shadow/generate/v2",
    data: {
      game_id,
      group
    }
  }:null);
  if(pressed && !data) {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", minHeight: 64 }}>
      <ActivityIndicator size="large" color={theme.page_content.fg} />
    </View>
  }
  if(pressed) {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", minHeight: 64}}>
      <MaterialCommunityIcons name="check-bold" size={32} color={theme.page_content.fg} />
    </View>
  }
  return <View style={{padding: 4}}>
    <Button color={(theme.clan_header||theme.navigation).bg} mode="contained" onPress={()=>setPressed(true)}>
      Sync Shadow Players in {group}
    </Button>
  </View>
}
Example #2
Source File: close.js    From astrale with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param navigation
 * @param style {object}
 * @param position {string}
 * @returns {*}
 * @constructor
 */
function Close({ style, position }) {
  const navigation = useNavigation();
  const { colors } = useTheme();
  const innerPosition = position === 'left' ? { left: 20 } : { right: 20 };
  return PlatformUtils.isAndroid ? (
    <MaterialCommunityIcons
      onPress={() => navigation.goBack()}
      style={[styles.container, innerPosition]}
      name="close"
      color={colors.text}
      size={30}
    />
  ) : (
    <View style={styles.iosBarContainer}>
      <View
        style={[
          styles.iosBarContent,
          {
            backgroundColor: colors.text + '3D',
          },
        ]}
      />
    </View>
  );
}
Example #3
Source File: Icon.js    From Done-With-It with MIT License 6 votes vote down vote up
function Icon({
	name,
	size = 40,
	backgroundColor = "#000",
	iconColor = "#fff",
}) {
	return (
		<View
			style={{
				width: size,
				height: size,
				borderRadius: size / 2,
				backgroundColor,
				justifyContent: "center",
				alignItems: "center",
			}}
		>
			<MaterialCommunityIcons
				name={name}
				color={iconColor}
				size={size * 0.5}
			/>
		</View>
	);
}
Example #4
Source File: OBComplete.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
OBComplete = ({ handleOnboardingState }) => (
  <View style={styles.root}>
    <View style={styles.thankYouContainer}>
      <Text style={styles.thankYouText}>You are all set </Text>
      <Text style={styles.thankYouText}>for the evaluation!</Text>
    </View>
    <TouchableOpacity onPress={() => handleOnboardingState(true)}>
      <View style={styles.logoContainer}>
        <LogoBasic height={hp('18%')} width={hp('18%')} />
      </View>
      <View style={styles.tapToStartContainer}>
        <MaterialCommunityIcons name="chevron-double-up" size={60} color={Colors.logoBlue} />
        <Text style={[styles.body, styles.tapToStartText]}>Tap to Start</Text>
      </View>
    </TouchableOpacity>
  </View>
)
Example #5
Source File: Auth.js    From Legacy with Mozilla Public License 2.0 5 votes vote down vote up
export default function AuthScreen({route}) {
  var { t } = useTranslation();
  var theme = useSelector(i => i.themes[i.theme]);
  var [status, setStatus] = React.useState(0);
  const navigation = useNavigation();
  const discovery = {
    authorizationEndpoint: 'https://api.munzee.com/oauth',
    tokenEndpoint: 'https://api.munzee.com/oauth/login',
  };
  const data = useAPIRequest({
    endpoint: 'competition/join/v1',
    cuppazee: true,
    data: {
      username: route.params.username
    }
  })
  const config = data?.team === "pear" ? config_pear : config_pine;

  const [request, response, promptAsync] = AuthSession.useAuthRequest(
    {
      clientId: config.client_id,
      scopes: ['read'],
      redirectUri: config.redirect_uri,
      state: JSON.stringify({
        redirect: Oconfig.redirect_uri,
        platform: Platform.OS
      })
    },
    discovery
  );

  React.useEffect(() => {
    if (response) {
      (async function () {
        if (!response.params || !response.params.teaken) return setStatus("invalid_response");
        if(response.params.status) {
          setStatus(`success_${response.params.status}`);
        } else {
          setStatus("success");
        }
      })()
    }
  }, [response]);
  if (status === "loading") {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.page_content.bg }}>
      <ActivityIndicator size="large" color={theme.page_content.fg} />
    </View>
  }
  if (status === "success" || status === "success_reopt" || status === "success_already") {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.page_content.bg }}>
      {status !== "success_already" && <>
        <Image source={data?.team === "pine" ? require('assets/pine.png') : require('assets/pear.png')} style={{ height: 128, width: 128, borderRadius: 8, marginBottom: 16 }} />
        <Text allowFontScaling={false} style={{ fontSize: 16, fontWeight: "bold", textAlign: "center", color: theme.page_content.fg }}>{response.params.username} {status === "success" ? "has joined" : "is in"} Team {data?.team.toUpperCase() || '???¿??'}</Text>
      </>}
      <Button mode="contained" onPress={()=>navigation.replace('CompetitionHome')}>Return to Competition Dashboard</Button>
    </View>
  }
  return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.page_content.bg }}>
    {!!status && <>
      {statusIcons[status]==="loading"?<ActivityIndicator size="large" color={theme.page_content.fg} />:<MaterialCommunityIcons name={statusIcons[status]} color={theme.page.fg} size={48} />}
      <Text allowFontScaling={false} style={{ fontSize: 16, fontWeight: "bold", textAlign: "center", color: theme.page_content.fg }}>{statusMessages[status]}</Text>
    </>}
    <Text allowFontScaling={false} style={{ color: theme.page_content.fg, fontSize: 24 }}>Opt-in to Competition</Text>
    <Text allowFontScaling={false} style={{ color: theme.page_content.fg, fontSize: 16 }}>{t('auth:tap')}</Text>
    <IconButton
      disabled={!data || (status && status !== "invalid_response")}
      size={32}
      onPress={() => {
        setStatus("waiting_for_login");
        promptAsync({
          useProxy: Oconfig.useProxy,
          redirectUri: config.redirect_uri
        });
      }}
      color={theme.page_content.fg}
      icon="login-variant"
    />
  </View>
}
Example #6
Source File: styles.js    From atendimento-e-agilidade-medica-AAMed with MIT License 5 votes vote down vote up
IconEye = styled(MaterialCommunityIcons)`
  font-size: 25px;
  color: #00000066;
`
Example #7
Source File: AnimationEditor.js    From UltimateApp with MIT License 5 votes vote down vote up
render() {
    const bigScreen = Dimensions.get('window').height > 600 ? { alignItems: 'center' } : undefined;

    return (
      <View
        ref={(ref) => {
          this.marker = ref;
        }}
        onLayout={this.onLayout}
      >
        <Animation
          editable
          animation={this.state.animation}
          currentStep={this.currentStep}
          onMoveStart={this.onMoveStart}
          onElementMoveEnd={this.onElementMoveEnd}
          onDimensionSet={this.setAnimationDimension}
          onCutMove={this.cutMove}
          widthRatio={this.wRatio}
          heightRatio={this.hRatio}
          dTop={this.state.dTop}
          dLeft={this.state.dLeft}
          onStepAdded={this.addStep}
          onStepRemoved={this.removeStep}
          currentStepAV={this.state.currentStepAV}
        />

        <View style={styles.actionsArea}>
          <View style={[styles.container, bigScreen]}>
            {this.state.isElementMoving ? (
              <View style={[styles.deletionArea]}>
                <MaterialCommunityIcons name="trash-can" color={theme.COLOR_PRIMARY} size={22} />
              </View>
            ) : (
              <View style={styles.draggableArea}>
                <BackgroundPicker
                  onBackgroundChange={this.onBackgroundChange}
                  selectedBackground={this.state.animation.background}
                />
                <View style={styles.draggableElements}>
                  {['offense', 'defense', 'disc', 'triangle'].map((type) => (
                    <DraggableDisplayedElement
                      type={type}
                      draggableBaseWidth={this.state.draggableBaseWidth}
                      onMoveEnd={this.addElementToAnimation}
                      number={this.state.labels[type]}
                      key={type}
                    />
                  ))}
                </View>
              </View>
            )}
          </View>
        </View>
      </View>
    );
  }
Example #8
Source File: ImageInput.js    From Done-With-It with MIT License 5 votes vote down vote up
function ImageInput({ imageUri, onChangeImage }) {
	useEffect(() => {
		requestPermission();
	}, []);

	const requestPermission = async () => {
		const {
			granted,
		} = await ImagePicker.requestCameraRollPermissionsAsync();
		if (!granted) {
			alert("You need to enable permission to access the library");
		}
	};

	const handlePress = () => {
		if (!imageUri) {
			selectImage();
		} else {
			Alert.alert(
				"Delete",
				"Are you sure you want to delete this image?",
				[
					{ text: "Yes", onPress: () => onChangeImage(null) },
					{ text: "No" },
				]
			);
		}
	};

	const selectImage = async () => {
		try {
			const result = await ImagePicker.launchImageLibraryAsync({
				mediaTypes: ImagePicker.MediaTypeOptions.Images,
				quality: 0.5,
			});
			if (!result.cancelled) onChangeImage(result.uri);
		} catch (error) {
			console.log("Error reading an image", error);
		}
	};

	return (
		<TouchableWithoutFeedback onPress={handlePress}>
			<View style={styles.container}>
				{!imageUri && (
					<MaterialCommunityIcons
						color={colors.medium}
						name="camera"
						size={40}
					/>
				)}
				{imageUri && (
					<Image source={{ uri: imageUri }} style={styles.image} />
				)}
			</View>
		</TouchableWithoutFeedback>
	);
}
Example #9
Source File: Comment.js    From SocialApp-React-Native with MIT License 5 votes vote down vote up
Comment = (props) => {

    const { comment, deleteCommentHandler, userId } = props;
    const [imageUri, setImageUri] = useState('')


    const onImageErrorHandler = () => {
        setImageUri(ENV.defaultImageUri)
    }

    const deleteComment = () => {
        deleteCommentHandler(comment);
    }

    return (
        <View style={styles.container}>
            <TouchableOpacity onPress={() => { }}>
                <Image 
                    style={styles.image} 
                    source={{ uri: imageUri || `${ENV.apiUrl}/user/photo/${comment.postedBy._id}?${new Date(comment.postedBy.updated)}` }} 
                    onError={onImageErrorHandler}
                />
            </TouchableOpacity>
            <View style={styles.content}>
                <View style={styles.contentHeader}>
                    <Text style={styles.name}>
                        {comment.postedBy.name + " "}
                        {
                            VerifiedUser.verifiedUsersId.includes(comment.postedBy._id) && <Octicons name="verified" size={16} color={Colors.brightBlue} />
                        }
                    </Text>
                    <Text style={styles.time}>
                        {timeDifference(new Date(), new Date(comment.created))}
                    </Text>
                </View>
                <View style={{ display: 'flex', flexDirection: 'row' }} >
                    <Text rkType='primary3 mediumLine'>{comment.text}</Text>
                    { comment.postedBy._id === userId && (
                        <TouchableOpacity 
                            style={{ position: 'absolute', right: 0 }}
                            onPress={deleteComment}
                        >
                            <MaterialCommunityIcons 
                                name="delete"
                                size={20}
                                color='red'
                            />
                        </TouchableOpacity>
                    ) }
                </View>
            </View>
        </View>
    );
}
Example #10
Source File: App.js    From pandoa with GNU General Public License v3.0 5 votes vote down vote up
//import getTheme from "native-base/dist/src/theme/components";
//import material from "native-base/dist/src/theme/variables/material";

export default function App(props) {
  const [isLoadingComplete, setLoadingComplete] = React.useState(false);
  const [initialNavigationState, setInitialNavigationState] = React.useState();
  const containerRef = React.useRef();
  const { getInitialState } = useLinking(containerRef);

  // Load any resources or data that we need prior to rendering the app
  React.useEffect(() => {
    async function loadResourcesAndDataAsync() {
      try {
        SplashScreen.preventAutoHide();
        // Load our initial navigation state
        setInitialNavigationState(await getInitialState());

        // Load fonts
        await Font.loadAsync({
          ...Ionicons.font,
          ...MaterialCommunityIcons.font,
          "space-mono": require("./assets/fonts/SpaceMono-Regular.ttf"),
          Roboto: require("native-base/Fonts/Roboto.ttf"),
          Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf")
        });
      } catch (e) {
        // We might want to provide this error information to an error reporting service
        console.warn(e);
      } finally {
        setLoadingComplete(true);
        SplashScreen.hide();
      }
    }

    loadResourcesAndDataAsync();
  }, []);

  useEffect(() => {
    const config = async () => {
      let res = await Permissions.askAsync(Permissions.LOCATION);
      if (res.status !== "granted") {
        console.log("Permission to access location was denied");
      } else {
        console.log("Permission to access location granted");
      }
    };

    config();
  }, []);

  if (!isLoadingComplete && !props.skipLoadingScreen) {
    return null;
  } else {
    return (
      <Provider store={Store().store}>
        <PersistGate loading={null} persistor={Store().persistor}>
          <StyleProvider style={getTheme(material)}>
            <View style={styles.container}>
              {/* Platform.OS === "ios" && <StatusBar barStyle="default" /> */}

              <NavigationContainer
                ref={containerRef}
                initialState={initialNavigationState}
              >
                <Stack.Navigator headerMode="none">
                  <Stack.Screen name="Root" component={BottomTabNavigator} />
                </Stack.Navigator>
              </NavigationContainer>
            </View>
          </StyleProvider>
        </PersistGate>
      </Provider>
    );
  }
}
Example #11
Source File: App.js    From Legacy with Mozilla Public License 2.0 4 votes vote down vote up
function App() {
  let [fontsLoaded] = useFonts(Platform.OS == "web" ? {
    // Coiny_400Regular,
  } : {
      Coiny_400Regular,
      Roboto_100Thin,
      Roboto_300Light,
      Roboto_400Regular,
      Roboto_500Medium,
      Roboto_700Bold,
      Roboto_900Black,
    });
  const loadingLogin = useSelector(i => i.loadingLogin || i.version < 0);
  const version = useSelector(i => i.version);
  const ref = React.useRef();
  const dispatch = useDispatch();
  const { t } = useTranslation();

  const { getInitialState } = useLinking(ref, {
    prefixes: ['https://cuppazee.app', 'cuppazee://'],
    config: {
      __primary: {
        screens: {
          ...pageScreens,
          Auth: 'auth',
        },
      }
    },
  });
  var [isReady, setIsReady] = React.useState(false);
  var [initialState, setInitialState] = React.useState();
  var theme = useSelector(i => i.themes[i.theme])

  React.useEffect(() => {
    Promise.race([
      getInitialState(),
      new Promise(resolve =>
        setTimeout(resolve, 150)
      )
    ])
      .catch(e => {
        console.error(e);
      })
      .then(state => {
        if (state !== undefined) {
          setTimeout(() => dispatch(setCurrentRoute(state?.routes?.[0]?.state?.routes?.slice?.()?.reverse?.()?.[0] ?? {})), 100);
          setInitialState(state);
        }

        setIsReady(true);
      });
  }, [getInitialState]);

  function handleStateChange(a) {
    dispatch(setCurrentRoute(a?.routes?.[0]?.state?.routes?.slice?.()?.reverse?.()?.[0] ?? {}))
  }

  if (!theme || !theme.page || !theme.page.bg) {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: 'white' }}>
      <ActivityIndicator size="large" color="orange" />
    </View>;
  }
  if (!fontsLoaded) {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.page.bg }}>
      <ActivityIndicator size="large" color={theme.page.fg} />
    </View>;
  }
  if (loadingLogin) {
    return <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: theme.page.bg }}>
      <Text allowFontScaling={false} style={{ ...font("bold"), fontSize: 20, color: theme.page.fg, marginBottom: 20 }}>{t('common:logging_in')}</Text>
      <ActivityIndicator size="large" color={theme.page.fg} />
    </View>;
  }
  if (version != Math.max(...Object.keys(changelogs).map(Number))) {
    var arr = Object.keys(changelogs).map(Number).filter(i => i > version).slice(-10).sort((a, b) => a - b);
    var logs = arr.map(i => [i, changelogs[i]])
    return <SafeAreaView style={{ backgroundColor: theme.navigation.bg, height: "100%" }}>
      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{ padding: 8, justifyContent: "center", alignItems: "center", flexGrow: 1 }}>
        {logs.map(([build, log]) => <View style={{ maxWidth: "100%" }}>
          <View style={{ alignItems: "center" }}>
            <Text allowFontScaling={false} style={{ color: theme.navigation.fg, fontSize: 32, ...font("bold") }}>{t('changelog:build_n', { n: build })}</Text>
          </View>
          {log?.map(i => <View style={{ flexDirection: "row", alignItems: "center", width: 400, maxWidth: "100%" }}>
            {i.image && <Image source={getIcon(i.image)} style={{ height: 48, width: 48 }} />}
            {i.icon && <View style={{ height: 48, width: 48, backgroundColor: theme.page_content.bg, borderRadius: 24, justifyContent: "center", alignItems: "center" }}>
              <MaterialCommunityIcons size={32} color={theme.page_content.fg} name={i.icon} />
            </View>}
            <View style={{ padding: 8, flex: 1 }}>
              <Text allowFontScaling={false} style={{ color: theme.navigation.fg, fontSize: 20, ...font("bold") }}>{i.title}</Text>
              <Text allowFontScaling={false} style={{ color: theme.navigation.fg, fontSize: 16, ...font() }}>{i.description}</Text>
            </View>
          </View>) ?? <Text allowFontScaling={false} style={{ ...font("bold"), fontSize: 20, color: theme.page.fg, marginBottom: 20 }}>{t('changelog:no_changelog')}</Text>}
          {build == Math.max(...Object.keys(changelogs).map(Number)) && <Button mode="contained" style={{ borderWidth: theme.page_content.border ? 2 : 0, borderColor: theme.page_content.border }} color={theme.page_content.bg} onPress={() => {
            dispatch(cuppazeeVersion(Math.max(...Object.keys(changelogs).map(Number))))
          }}>{logs.some(i=>i[1].some(x=>x.privacy))?t('changelog:continue_and_agree'):t('changelog:continue')}</Button>}
        </View>)}
      </ScrollView>
    </SafeAreaView>;
  }
  if (!isReady) {
    return null;
  }
  var navWidth = 400;
  return (
    <NavigationContainer independent={true} onStateChange={handleStateChange} initialState={initialState} ref={ref}>
      <StatusBar translucent={true} backgroundColor={theme.navigation.bg + 'cc'} barStyle="light-content" />
      <View style={{ flex: 1 }}>
        <DrawerNav />
        {/* <View style={{position:"absolute",bottom:-0.5*navWidth,right:-0.5*navWidth,width:navWidth,height:navWidth,borderRadius:navWidth/2,paddingBottom:navWidth/2,paddingRight:navWidth/2,backgroundColor:"white"}}><Text>Hello</Text></View> */}
      </View>
    </NavigationContainer>
  );
}
Example #12
Source File: Lines.js    From timetable with MIT License 4 votes vote down vote up
Lines = () => {
  const { i18n, t } = useTranslation()
  const navigation = useNavigation()
  const { theme } = useTheme()

  const [busArray, setBusArray] = useState([])

  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      setBusArray(i18n.language == 'en' ? EnBus.Bus : GeBus.Bus)
    })

    // Cleanup
    return unsubscribe
  }, [navigation])

  // FlatList Item
  const Item = ({ busNumber, stopA, stopB }) => {
    const [boolean, setBoolean] = useState(true)

    // Change direction
    const changeDirectionHandler = () => setBoolean(!boolean)

    // Bus Line start-end direction
    const direction = boolean ? (
      <TouchableOpacity
        onPress={() =>
          navigation.navigate('LinesMap', { busNumber, forward: 0 })
        }
      >
        <View style={styles.listItem}>
          <Text style={{ color: theme.text }}>{stopA}</Text>
          <Entypo name='arrow-long-right' color='#1f5c87' size={25} />
          <Text style={{ color: theme.text }}>{stopB}</Text>
        </View>
      </TouchableOpacity>
    ) : (
      <TouchableOpacity
        onPress={() =>
          navigation.navigate('LinesMap', { busNumber, forward: 1 })
        }
      >
        <View style={styles.listItem}>
          <Text style={{ color: theme.text }}>{stopB}</Text>
          <Entypo name='arrow-long-right' color='#1f5c87' size={25} />
          <Text style={{ color: theme.text }}>{stopA}</Text>
        </View>
      </TouchableOpacity>
    )

    return (
      <View>
        <View style={[styles.separator, { borderBottomColor: theme.border }]} />

        <View
          style={[
            styles.wrapBusIcon,
            {
              backgroundColor: theme.backgroundColor,
              borderColor: theme.border
            }
          ]}
        >
          <MaterialCommunityIcons
            name='bus'
            color='#1f5c87'
            size={15}
            style={styles.busIcon}
          />

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

        <Text style={[styles.from, { color: theme.text }]}>
          {t('lines.from')}
        </Text>

        {direction}

        <View style={styles.changeDirection}>
          <Button
            onPress={changeDirectionHandler}
            text={t('lines.change')}
            buttonColor={theme.buttonColor}
            textColor={theme.buttonText}
            margin={0}
            paddingVertical={4}
            fontSize={12}
          />
        </View>
      </View>
    )
  }

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={busArray}
        renderItem={({ item }) => (
          <Item
            busNumber={item.RouteNumber}
            stopA={item.StopA}
            stopB={item.StopB}
          />
        )}
        keyExtractor={item => item.RouteNumber}
      />
    </SafeAreaView>
  )
}
Example #13
Source File: index.js    From atendimento-e-agilidade-medica-AAMed with MIT License 4 votes vote down vote up
export default function Home() {
  const navigation = useNavigation();

  const [hospitals, setHospitals] = useState([]);
  const [user, setUser] = useState(null || '');
  const [currentRegion, setCurrentRegion] = useState(null);
  const [regionChange, setRegionChange] = useState(null);
  const [currentLocation, setCurrentLocation] = useState(null);
  const [description, setDescription] = useState('');
  const [connection, setConnection] = useState(null);
  const [isActiveButton, setIsActiveButton] = useState(false);
  const [modal, setModal] = useState(false);
  const [approved, setApproved] = useState(false);
  const [hospitalName, setHospitalName] = useState('');
  const [hospitalDest, setHospitalDest] = useState({});
  const [distance, setDistance] = useState('');
  const [duration, setDuration] = useState('');

  const [userOrigin, setUserOrigin] = useState({ latitude: 0, longitude: 0 });

  const [destination, setDestination] = useState({ latitude: 0, longitude: 0 });
  // let conn;

  useEffect(() => {
    const conn = io('http://10.0.0.53:3333', {
      query: { user_id: user._id },
    });
    setConnection(conn);
    conn.on('solicitation_response', data => {
      setHospitalDest(data);
      setHospitalName(data.hospital.name);
      data.approved ? setApproved(true) : setApproved(false);
      setDestination({
        latitude: data.hospital.location.coordinates[1],
        longitude: data.hospital.location.coordinates[0],
      });
    });

    conn.on('arrived__manually_mobile', data => {
      const { arrived_mobile } = data;
      if (arrived_mobile) {
        setDuration('');
        setDistance('');
        setDestination({ latitude: 0, longitude: 0 });
        setModal(false);
        setApproved(false);
      }
    });
    conn.on('warning', data => {
      const { not_here } = data;
      if (not_here) {
        setDuration('');
        setDistance('');
        setDestination({ latitude: 0, longitude: 0 });
        setModal(false);
        setApproved(false);
        Alert.alert(
          'Você não compareceu',
          'Você tem mais 2 oportunidades antes de ser banido'
        );
      }
    });
  }, []);

  useEffect(() => {
    function getUserLogged() {
      return new Promise((resolve, result) => {
        setTimeout(() => {
          resolve(AsyncStorage.getItem('store'));
        }, 1000);
      });
    }
    getUserLogged()
      .then(data => {
        const dataParse = JSON.parse(data);
        setUser(dataParse.auth.user);
      })
      .catch(error => console.log(error));

    watchPositionAsync(
      {
        accuracy: Accuracy.High,
        timeInterval: 10000,
        enableHighAccuracy: true,
      },
      data => {
        console.log('10s se passaram');
        setUserOrigin({
          latitude: data.coords.latitude,
          longitude: data.coords.longitude,
        });
        if (approved) {
          console.log('aprovado');
          fetch(
            'https://maps.googleapis.com/maps/api/geocode/json?address=' +
              data.coords.latitude +
              ',' +
              data.coords.longitude +
              '&key=' +
              GOOGLE_MAPS_APIKEY
          )
            .then(response => response.json())
            .then(responseJson => {
              setCurrentLocation(responseJson.results[0].formatted_address);
            });
          if (
            calculateDistance(data.coords, destination) == 0.01 ||
            calculateDistance(data.coords, destination) == 0.02
          ) {
            console.log('chegou');
            connection.emit('arrived', {
              hospital_id: hospitalDest.hospital._id,
              user,
              arrived: true,
            });
            setApproved(false);
            setDestination({ latitude: 0, longitude: 0 });
            setModal(!modal);
            setDuration(null);
            setDistance(null);
          }
        }
      }
    );
  }, []);

  // função que vai carregar a posição inicial do paciente no mapa
  useEffect(() => {
    async function loadInitialPosition() {
      const { granted } = await requestPermissionsAsync();
      if (!granted) {
        return Alert.alert('Ops', 'Você precisa habilitar a permissão');
      }
      const { coords } = await getCurrentPositionAsync({
        enableHighAccuracy: true,
      });
      const { latitude, longitude } = coords;
      setCurrentRegion({
        latitude,
        longitude,
        latitudeDelta: 0.014,
        longitudeDelta: 0.014,
      });
      setUserOrigin({
        latitude: latitude,
        longitude: longitude,
      });
      fetch(
        'https://maps.googleapis.com/maps/api/geocode/json?address=' +
          latitude +
          ',' +
          longitude +
          '&key=' +
          GOOGLE_MAPS_APIKEY
      )
        .then(response => response.json())
        .then(responseJson => {
          setCurrentLocation(responseJson.results[0].formatted_address);
        });
    }

    loadInitialPosition();
    //handlePositionUpdate();
  }, [currentRegion]);

  useEffect(() => {
    async function loadHospitals() {
      const { latitude, longitude } = currentRegion || 1;
      if (latitude && longitude) {
        try {
          const response = await api.get('search', {
            params: {
              longitude,
              latitude,
            },
          });
          setHospitals(response.data.hospitais);
        } catch (err) {
          console.debug('[ERROR: loadHospitals] => ', err);
        }
      }
    }
    loadHospitals();
  }, [currentRegion]);

  async function handleSolicitation() {
    const hospital_ids = [];

    hospitals.map(hospital => {
      hospital_ids.push(hospital._id);
    });

    if (description === '') return Alert.alert('AVISO', 'Preencha o campo.');

    connection.emit('user_solicitation', {
      hospital_ids,
      user,
      description,
      currentLocation,
    });
    Alert.alert(
      'Solicitação enviada',
      'Sua solicitação de atendimento foi enviada aos hospitais próximos à sua localização.'
    );
    Keyboard.dismiss();
    setDescription('');
    setIsActiveButton(true);
    setModal(true);
    setTimeout(() => {
      setIsActiveButton(false);
    }, 1000);
  }

  function rad(x) {
    return (x * Math.PI) / 180;
  }

  function calculateDistance(pointA, pointB) {
    let R = 6378137;
    let dLat = rad(pointB.latitude - pointA.latitude);
    let dLong = rad(pointB.longitude - pointA.longitude);
    let a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(rad(pointA.latitude)) *
        Math.cos(rad(pointB.latitude)) *
        Math.sin(dLong / 2) *
        Math.sin(dLong / 2);
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let d = (R * c) / 1000;
    return d.toFixed(2);
  }

  async function handleRegionChanged(region) {
    setRegionChange(region);
  }

  if (!currentRegion) {
    return null;
  }

  return (
    <View style={styles.container}>
      <Header flag={true} navigation={navigation} />

      <MapView
        onRegionChangeComplete={handleRegionChanged}
        initialRegion={currentRegion}
        showsUserLocation
        loadingEnabled={true}
        style={styles.mapContainer}
      >
        {approved && !!destination.latitude && !!destination.longitude && (
          <MapViewDirections
            origin={userOrigin}
            onReady={result => {
              setDistance(result.distance);
              setDuration(result.duration);
            }}
            onError={err => console.log(err)}
            destination={destination}
            apikey={GOOGLE_MAPS_APIKEY}
            strokeWidth={4}
            strokeColor={'#222'}
          />
        )}
        {hospitals.map(hospital => (
          <Marker
            key={hospital._id}
            coordinate={{
              latitude: hospital.location.coordinates[1],
              longitude: hospital.location.coordinates[0],
            }}
          >
            <MaterialCommunityIcons
              name="hospital-marker"
              size={40}
              color="#0984e3"
            />

            <Callout style={styles.calloutHospital}>
              <Text style={styles.name}>{hospital.name}</Text>
              <Text style={styles.desc}>
                <Text style={styles.tittles}>RUA:</Text>{' '}
                {hospital.address.street}
              </Text>
              <Text>
                <Text style={styles.tittles}>BAIRRO:</Text>{' '}
                {hospital.address.neighborhood}
              </Text>
              <Text>
                <Text style={styles.tittles}>CEP:</Text> {hospital.address.cep}
              </Text>
              <Text>
                <Text style={styles.tittles}>TELEFONE: </Text>
                {hospital.phone}
              </Text>
            </Callout>
          </Marker>
        ))}
      </MapView>
      {modal ? (
        <Animatable.View
          style={styles.modal}
          animation="fadeInDown"
          duration={1000}
          useNativeDriver
        >
          {!approved ? (
            <>
              <FontAwesome name="circle" size={15} color="#ff9f1a" />
              <Text>Solicitação aguardando aprovação do hospital.</Text>
            </>
          ) : (
            <>
              <FontAwesome name="circle" size={15} color="#0ec445" />
              <Text>
                Sua solicitação foi aprovada em {hospitalName}.{'\n'}
                Tempo estimado: {`${Math.round(duration)} min \n`}
                Distância: {`${Number(distance).toFixed(2)} km`}
              </Text>
            </>
          )}
        </Animatable.View>
      ) : null}
      {!approved && (
        <View style={styles.searchForm}>
          <TextInput
            style={styles.searchInput}
            placeholder="Descrição..."
            placeholderTextColor="#999"
            autoCapitalize="words"
            autoCorrect={false}
            multiline
            value={description}
            onChangeText={setDescription}
          />

          <TouchableOpacity
            onPress={handleSolicitation}
            style={
              isActiveButton
                ? [styles.loadButton, { backgroundColor: '#006bad55' }]
                : styles.loadButton
            }
            disabled={isActiveButton}
          >
            <MaterialIcons name="send" size={25} color="#fff" />
          </TouchableOpacity>
        </View>
      )}
      <View style={styles.mapDrawerOverlay} />
    </View>
  );
}
Example #14
Source File: ViewProfile.js    From salyd with GNU General Public License v3.0 4 votes vote down vote up
ViewProfile = ({ navigation }) => {

    const { user, token } = useContext(GlobalContext);
    const { _id, name, email, phone, image } = user;

    const logout = async () => {
        const token = await AsyncStorage.removeItem("token")
        const user = await AsyncStorage.removeItem("user")
        if (!token) {
            navigation.replace("Login");
        }
    }
    console.log(image)

    return (
        <React.Fragment>
            <Header navigation={navigation} isBack> View Profile </Header>
            <View style={styles.root}>
                <View style={{ alignItems: "center" }}>
                    <Image
                        style={{ width: 140, height: 140, borderRadius: 140 / 2, marginTop: 50 }}
                        source={{ uri: (image ? image : "https://sanjaymotels.com/wp-content/uploads/2019/01/testimony.png") }}
                    />

                </View>
                <View style={{ alignItems: "center", margin: 15 }}>
                    <Text style={styles.name}> {name} </Text>
                </View>

                <TouchableOpacity onPress={() => {
                    navigation.navigate('EditProfile', {
                        name, email, phone
                    })
                }}>
                    <View style={styles.cardContainer}>
                        <View style={styles.mycard}>
                            <View style={styles.cardContent}>
                                <FontAwesome name="user-circle" style={styles.icon} />
                                <Text style={styles.mytext}>Account Details</Text>
                                <Ionicons name="ios-arrow-forward" style={styles.arrow} />
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity onPress={() => {
                    navigation.navigate('RecentOrders')
                }}>
                    <View style={styles.mycard}>
                        <View style={styles.cardContent}>
                            <MaterialCommunityIcons name="food-variant" style={styles.icon} />
                            <Text style={styles.mytext}>Order History</Text>
                            <Ionicons name="ios-arrow-forward" style={styles.arrow} />
                        </View>
                    </View>
                </TouchableOpacity>


                <TouchableOpacity onPress={() => {
                    navigation.navigate('Contact')
                }}>

                    <View style={styles.mycard} onPress={() => {
                        navigation.navigate('Contact')
                    }}>
                        <View style={styles.cardContent}>
                            <Feather name="phone-call" style={styles.icon} />
                            <Text style={styles.mytext}>Contact Us</Text>
                            <Ionicons name="ios-arrow-forward" style={styles.arrow} />
                        </View>
                    </View>
                </TouchableOpacity>

                <View style={{
                    justifyContent: "center",
                    alignItems: "center"
                }}>
                    <Button onPressFunction={() => logout()}>Logout</Button>
                </View>

            </View>
        </React.Fragment>
    )
}
Example #15
Source File: AnimationBackground.js    From UltimateApp with MIT License 4 votes vote down vote up
AnimationBackground = (props) => {
  const topMargin = props.animationHeight * 0.05;
  const bottomMargin = props.animationHeight * 0.1;
  const leftRightMargin = props.animationWidth * 0.05;
  const fieldHeight = props.animationHeight - topMargin - bottomMargin;
  const fieldWidth = props.animationWidth - 2 * leftRightMargin;
  const linesWidth = Math.min(fieldHeight, fieldWidth) * 0.005;
  const zoneLineTop = topMargin + fieldHeight * 0.4;
  const threeQuarterLineTop = topMargin + fieldHeight * 0.24;

  const brickRadius = linesWidth * 10;
  const brickLeft = leftRightMargin + fieldWidth / 2 - brickRadius / 2;
  const brickZoneTop = zoneLineTop + fieldHeight * 0.4 - 2 * brickRadius;
  const brick34Top = threeQuarterLineTop + fieldHeight * 0.33 - 2 * brickRadius;

  const Brick = ({ top }) => (
    <MaterialCommunityIcons name="close" style={[styles.brick, { left: brickLeft, top }]} size={brickRadius} />
  );

  switch (props.background) {
    case AnimationBackgrounds.ENDZONE:
      return (
        <View style={{ height: props.animationHeight, width: props.animationWidth }}>
          {/* Right vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin + fieldWidth,
              },
            ]}
          />

          {/* Left vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Top horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Zone horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: zoneLineTop,
                left: leftRightMargin,
              },
            ]}
          />

          <Brick top={brickZoneTop} />
        </View>
      );
    case AnimationBackgrounds.THREE_QUARTERS_FIELD:
      return (
        <View style={{ height: props.animationHeight, width: props.animationWidth }}>
          {/* Right vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin + fieldWidth,
              },
            ]}
          />

          {/* Left vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Top horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Zone horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: threeQuarterLineTop,
                left: leftRightMargin,
              },
            ]}
          />

          <Brick top={brick34Top} />
        </View>
      );
    case AnimationBackgrounds.RECTANGLE:
      return (
        <View style={{ height: props.animationHeight, width: props.animationWidth }}>
          {/* Right vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin + fieldWidth,
              },
            ]}
          />

          {/* Left vertical bar */}
          <View
            style={[
              styles.bar,
              {
                height: fieldHeight,
                width: linesWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Top horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: topMargin,
                left: leftRightMargin,
              },
            ]}
          />

          {/* Bottom horizontal bar */}
          <View
            style={[
              styles.bar,
              {
                height: linesWidth,
                width: fieldWidth,
                top: fieldHeight + topMargin,
                left: leftRightMargin,
              },
            ]}
          />
        </View>
      );
    case AnimationBackgrounds.EMPTY:
      return null;
    default:
      return null;
  }
}
Example #16
Source File: astrologers.screen.js    From astrale with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param navigation
 * @returns {*}
 * @constructor
 */
function AstrologersScreen({ navigation }) {
  const { colors } = useTheme();
  const [showAdvice, setShowAdvice] = React.useState(true);
  const _handleCloseAdvice = () => setShowAdvice(false);
  const astrologist_colors = {
    Western: '#0f3e6a',
    Vedic: '#3d530d',
    Hellenistic: '#735b13',
    Oriental: '#62230d',
  };
  const dummy_astrologist = [
    {
      id: 1,
      name: 'Marisa',
      school: 'Hellenistic',
      years_exp: 9,
      stars: 4,
      reviews: 125,
      photo: require('./astrologers/marisa.jpg'),
    },
    {
      id: 2,
      name: 'Carter',
      school: 'Western',
      years_exp: 21,
      stars: 5,
      reviews: 120,
      photo: require('./astrologers/carter.jpg'),
    },
    {
      id: 3,
      name: 'Samanta',
      school: 'Oriental',
      years_exp: 12,
      stars: 5,
      reviews: 321,
      photo: require('./astrologers/samanta.jpg'),
    },

    {
      id: 4,
      name: 'Bianca',
      school: 'Vedic',
      years_exp: 45,
      stars: 4,
      reviews: 69,
      photo: require('./astrologers/bianca.jpg'),
    },
    {
      id: 5,
      name: 'George',
      school: 'Western',
      years_exp: 15,
      stars: 5,
      reviews: 198,
      photo: require('./astrologers/george.jpg'),
    },
    {
      id: 6,
      name: 'Meowi',
      school: 'Oriental',
      years_exp: 1,
      stars: 5,
      reviews: 7,
      photo: require('./astrologers/meowi.jpg'),
    },
  ];

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <SpaceSky />
      <View style={{ marginBottom: 10 }}>
        <MainNav style={{ top: 0 }} />
        <View style={styles.headerContainer}>
          <ShadowHeadline>{i18n.t('Astrologers')}</ShadowHeadline>
        </View>
      </View>
      <ScrollView>
        {showAdvice && (
          <View
            style={[
              styles.adviceContainer,
              { borderColor: colors.primary + 'E6' },
            ]}
          >
            <MaterialCommunityIcons
              onPress={_handleCloseAdvice}
              name="close"
              size={20}
              style={styles.adviceClose}
              color={colors.primary + 'E6'}
            />
            <Title style={{ textAlign: 'center' }}>
              {i18n.t('How it works')}
            </Title>
            <View style={{ marginTop: 10 }}>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Avatar.Text
                  size={30}
                  label="1"
                  theme={{ colors: { primary: colors.primary + 'E6' } }}
                  labelStyle={{ fontSize: 22 }}
                />
                <Text style={{ marginLeft: 15, fontSize: 12 }}>
                  {i18n.t('Select an astrologer')}
                </Text>
              </View>
              <View
                style={[
                  styles.listDivider,
                  {
                    borderLeftColor: colors.accent + 'E6',
                  },
                ]}
              />
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Avatar.Text
                  size={30}
                  label="2"
                  theme={{ colors: { primary: colors.primary + 'E6' } }}
                  labelStyle={{ fontSize: 22 }}
                />
                <Text
                  style={{
                    marginLeft: 15,
                    fontSize: 12,
                  }}
                >
                  {i18n.t('Introduce your email and question')}
                </Text>
              </View>
              <View
                style={[
                  styles.listDivider,
                  {
                    borderLeftColor: colors.accent + 'E6',
                  },
                ]}
              />
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Avatar.Text
                  size={30}
                  label="3"
                  theme={{ colors: { primary: colors.primary + 'E6' } }}
                  labelStyle={{ fontSize: 22 }}
                />
                <Text
                  style={{
                    marginLeft: 15,
                    fontSize: 12,
                  }}
                >
                  {i18n.t('Wait ~24 hours for the response')}
                </Text>
              </View>
            </View>
          </View>
        )}
        <View style={styles.astrologistContainer}>
          {dummy_astrologist.map(
            ({ id, name, school, years_exp, stars, photo, reviews }, i) => (
              <React.Fragment key={id}>
                <TouchableRipple
                  onPress={() =>
                    navigation.navigate('Question', {
                      key: 'Profile',
                      astrologist: dummy_astrologist[i],
                    })
                  }
                  style={styles.astrologistCard}
                  underlayColor={colors.text + '33'}
                  borderless
                >
                  <>
                    <Image
                      style={styles.astrologistImage}
                      source={photo}
                      resizeMethod="resize"
                      resizeMode="cover"
                    />
                    <LinearGradient
                      colors={['transparent', 'rgba(0,0,0,0.8)']}
                      style={styles.astrologistGradient}
                    >
                      <Title theme={{ colors: { text: '#FFFFFF' } }}>
                        {name}
                      </Title>
                    </LinearGradient>
                    <Subheading
                      theme={{ colors: { text: '#FFFFFF' } }}
                      style={[
                        styles.astrologistSubheading,
                        { backgroundColor: astrologist_colors[school] },
                      ]}
                    >
                      {i18n.t(school, { word: i18n.t('Astrology') })}
                    </Subheading>
                    <View
                      style={[
                        styles.astrologistDetailsContainer,
                        { borderColor: astrologist_colors[school] },
                      ]}
                    >
                      <Text style={{ fontSize: 10 }}>
                        {years_exp} other years experience
                      </Text>
                      <View style={styles.astrologistStars}>
                        <MaterialCommunityIcons name="star" color="gold" />
                        <MaterialCommunityIcons name="star" color="gold" />
                        <MaterialCommunityIcons name="star" color="gold" />
                        <MaterialCommunityIcons name="star" color="gold" />
                        <MaterialCommunityIcons
                          name={stars === 5 ? 'star' : 'star-half'}
                          color="gold"
                        />
                        <Text style={styles.astrologistReview}>{reviews}</Text>
                      </View>
                    </View>
                  </>
                </TouchableRipple>
                {i + (1 % 2) === 0 ? (
                  <View style={{ width: '100%', height: 50 }} />
                ) : null}
              </React.Fragment>
            )
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
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: index.js    From ovuli with MIT License 4 votes vote down vote up
CalendarComponent = props => {
  const [calendarState, setCalendarDate] = React.useState(calendarDate.format('YYYY-MM-DD'));
  function onPressArrowLeft() {
    calendarDate = calendarDate.add(-1, 'month');
    updateCalendarDate();
  }
  function onPressArrowRight() {
    calendarDate = calendarDate.add(1, 'month');
    updateCalendarDate();
  }
  function onPressListView() {
    //his.setState({ horizontal: true });
  }
  function onPressGridView() {
    //this.setState({ horizontal: false });
  }
  function onDayPress(date) {
    // calendarDate = moment(date.dateString);
    // this.updateCalendarDate();
  }
  function updateCalendarDate() {
    setCalendarDate(calendarDate.format('YYYY-MM-DD'));
  }
  return (
    <View style={styles.container}>
      <Calendar
        current={calendarState}
        // dayComponent={CalendarDayComponent}
        calendarHeaderComponent={CalendarHeader}
        headerData={{
          calendarDate: calendarDate.format('MMM, YYYY'),
        }}
        style={styles.calendarStyle}
        theme={{
          textDayFontSize: 18,
        }}
        markingType={'custom'} //{"period"}
        markedDates={{
          [calendarState]: {
            customStyles: {
              container: {
                backgroundColor: '#e35052',
              },
              text: {
                color: '#eeee',
                fontWeight: 'bold',
              },
            },
          },
          '2020-04-10': {
            customStyles: {
              container: {
                backgroundColor: '#fab3a0',
              },
              text: { color: '#635e5d' },
            },
          },
          '2020-04-11': {
            customStyles: {
              container: {
                backgroundColor: '#fab3a0',
              },
              text: { color: '#635e5d' },
            },
          },
        }}
        onDayPress={onDayPress}
        onPressArrowLeft={onPressArrowLeft}
        onPressArrowRight={onPressArrowRight}
        onPressListView={onPressListView}
        onPressGridView={onPressGridView}
        horizontal={false}
        // eslint-disable-next-line react/jsx-no-duplicate-props
        onDayPress={onDayPress}
        hideExtraDays
      />
      <View style={styles.firstHorizontalLine} />
      <View style={styles.iconContainer}>
        <View style={styles.firstIconContainer}>
          <MaterialCommunityIcons name="checkbox-blank-circle" size={32} color="#fbc0b0" />
          <Text style={styles.ovulationText}>Ovulation</Text>
        </View>
        <View style={styles.secondIconContainer}>
          <MaterialCommunityIcons name="checkbox-blank-circle" size={32} color="#d2e1fc" />
          <Text style={styles.periodsText}>Periods</Text>
        </View>
      </View>

      <View
        style={{
          borderBottomColor: '#e8f1fb',
          borderBottomWidth: 3,
        }}
      />
    </View>
  );
}
Example #19
Source File: Card.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
Card = (props) => {
    const { post, userId, fromUserProfile } = props;
    const navigation = useNavigation();
    const dispatch = useDispatch();

    // const liked = post.likes.indexOf(userId) !== -1;

    const [isImageLoading, setIsImageLoading] = useState(true);
    const [imageUri, setImageUri] = useState('')
    const [showFullBody, setShowFullBody] = useState(false);
    const [imgWidth, setImgWidth] = useState();
    const [imgHeight, setImgHeight] = useState();

    const onImageErrorHandler = () => {
        setImageUri(ENV.defaultImageUri)
    }


    let TouchableComp = TouchableOpacity;
    if(Platform.OS === 'android' && Platform.Version >= 21){
        TouchableComp = TouchableNativeFeedback;
    }


    const deleteHandler = (id) => {
        Alert.alert(
            'Are you sure?', 
            'Do you really want to delete this post?',
            [
                {text: 'No', style: 'default'},
                {
                    text: 'Yes', 
                    style: 'destructive', 
                    onPress: async () => {
                        await dispatch(postActions.deletePost(id))
                        showMessage({
                            message: "Your post was successfully deleted.",
                            type: "success",
                            icon: { icon: "success", position: 'left' },
                            duration: 3000
                        });
                    }
                }
            ]
        )
    };

    const checkLike = () => {
        let match = post.likes.indexOf(userId) !== -1;
        return match;
    }

    const toggleLike = async () => {
        props.toggleLikeHandler(post._id, checkLike());
    }

    useEffect(() => {
        let imageUrl = `${ENV.apiUrl}/post/photo/${post._id}?${new Date(post.updated)}`;
        Image.getSize(imageUrl, (width, height) => {
            // calculate image width and height 
            const screenWidth = Dimensions.get('window').width
            const scaleFactor = width / screenWidth
            const imageHeight = height / scaleFactor
            setImgWidth(screenWidth);
            setImgHeight(imageHeight);
        })
    }, [])


    return (
        <TouchableComp 
            background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#b3b3b3') }
            onPress={() =>  
                fromUserProfile ? 
                {} 
                : 
                navigation.navigate('UserProfile', { userId: post.postedBy._id, name: post.postedBy.name }) }
        >
            <View style={styles.card}>
                <View style={styles.cardTitleHeader}>
                    <View style={{ display: 'flex', flex: 1, flexDirection: 'row' }} >
                        <View style={styles.timeContainer}>
                            <Image
                                style={styles.userIcon} 
                                source={{ uri: imageUri || `${ENV.apiUrl}/user/photo/${post.postedBy._id}?${new Date(post.postedBy.updated)}` }}
                                onError={onImageErrorHandler}
                            />
                            <Text 
                                style={{ fontSize: 15, alignSelf: 'center', paddingHorizontal: 10, paddingVertical: 5 }} 
                                onPress={() => navigation.navigate('UserProfile', { userId: post.postedBy._id, name: post.postedBy.name })} 
                            > 
                                {post.postedBy.name + " "}
                                {
                                    VerifiedUser.verifiedUsersId.includes(post.postedBy._id) && <Octicons name="verified" size={18} color={Colors.brightBlue} />
                                }
                            </Text>
                        </View>
                        <View style={{ position: 'absolute', right: 0, display: 'flex', flexDirection: 'row'}}>
                            <Ionicons 
                                name={ Platform.OS === 'android' ? 'md-time' : 'ios-time' }
                                size= {14}
                                style={{ marginTop: 3 }}
                            />
                            <Text> {timeDifference(new Date(), new Date(post.created))} </Text>
                        </View>
                    </View>
                </View>
                <View style={styles.cardImageContainer} >
                    <Image 
                        style={{...styles.cardImage, height: imgHeight }}
                        source={{ uri: `${ENV.apiUrl}/post/photo/${post._id}?${new Date(post.updated)}` }}
                        onLoad={() => setIsImageLoading(false)}
                    />
                    <ActivityIndicator 
                        style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 }} 
                        animating={isImageLoading} 
                        size='large' 
                        color={Colors.brightBlue} 
                    />
                </View>
                <View style={styles.cardHeader}>
                    <View>
                        <Text style={styles.title}>{post.title ? post.title : ""}</Text>
                        { post.body && post.body.length > 30 ? (
                            <View>
                                { showFullBody ? (
                                    <Text style={styles.description}> 
                                        {post.body} 
                                        <Text
                                            style={{ color: Colors.brightBlue }}
                                            onPress={() => setShowFullBody((prevState) => !prevState)} 
                                        >
                                            Read Less
                                        </Text>
                                    </Text>
                                ) : (
                                    <Text style={styles.description}> 
                                        {post.body.substring(0, 30)}
                                        <Text
                                            style={{ color: Colors.brightBlue }}
                                            onPress={() => setShowFullBody((prevState) => !prevState)} 
                                        >
                                            ...Read More
                                        </Text>
                                    </Text>
                                ) }

                            </View>
                        ) : (
                            <Text style={styles.description}> {post.body} </Text>
                        ) }
                        
                    </View>
                </View>

                <View style={styles.cardFooter}>
                    <View style={styles.socialBarContainer}>
                        <View style={styles.socialBarSection}>
                            <TouchableOpacity 
                                style={styles.socialBarButton}
                                onPress={toggleLike}
                            >
                                <Ionicons 
                                    name="md-thumbs-up"
                                    size={24}
                                    style={{ marginRight: 5 }}
                                    color={checkLike() ? 'blue' : "black"}
                                />
                                <Text style={styles.socialBarLabel}> {post.likes.length} </Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.socialBarSection}>
                            <TouchableOpacity 
                                style={styles.socialBarButton}
                                onPress={() => navigation.navigate('Comments',{ postId: post._id, userId: userId })}
                            >
                                <Ionicons 
                                    name="md-chatboxes"
                                    size={24}
                                    style={{ marginRight: 5 }}
                                />
                                <Text style={styles.socialBarLabel}> {post.comments.length} </Text>
                            </TouchableOpacity>
                        </View>
                        
                        
                    </View>
                </View>
                <TouchableOpacity 
                    onPress={() => navigation.navigate('Comments', { postId: post._id, userId: userId })}
                >
                    { post.comments.length > 0 ? (
                        <Text style={{ paddingHorizontal: 16, paddingBottom: 15, paddingTop: 5 }} >View all {post.comments.length} comments </Text>
                    ) : (
                        <Text style={{ paddingHorizontal: 16, paddingBottom: 15, paddingTop: 5 }} >Comment here </Text>
                    ) }
                </TouchableOpacity>
                { post.postedBy._id === userId && (
                    <View style={styles.postActions} >
                        <View style={styles.socialBarSection}>
                            <TouchableOpacity 
                                style={styles.socialBarButton}
                                onPress={deleteHandler.bind(this, post._id)}
                            >
                                <MaterialCommunityIcons 
                                    name="delete"
                                    size={20}
                                    style={{ marginRight: 5 }}
                                    color="red"
                                />
                                <Text style={styles.socialBarLabel}>Delete</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.socialBarSection}>
                            <TouchableOpacity 
                                style={styles.socialBarButton}
                                onPress={() => navigation.navigate('EditPost', { postId: post._id })}
                            >
                                <MaterialCommunityIcons 
                                    name="square-edit-outline"
                                    size={20}
                                    style={{ marginRight: 5 }}
                                    color={Colors.lightAccent}
                                />
                                <Text style={styles.socialBarLabel}>Edit</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                )}

            </View>
    
        </TouchableComp>
    );
}
Example #20
Source File: BottomSheetMe.js    From pandoa with GNU General Public License v3.0 4 votes vote down vote up
function BottomSheetMe(props) {
  const bottomSheetRef = useRef();
  const [trackingStatus, setTrackingStatus] = useState(false);

  const toggleSwitch = e => {
    if (e === true) {
      startLocationTracking();
      setTrackingStatus(true);
    } else {
      stopLocationTracking();
      setTrackingStatus(false);
    }
    console.log("toggleSwitch", e);
  };

  const { contentPosition, filteredWarnings, navigation } = props;

  const renderInnerDetails = () => {
    return (
      <View style={styles.panelInner}>
        <View style={styles.buttonWrapper}>
          <LargeButton>
            <View style={styles.switchTracking}>
              <View style={styles.description}>
                <Text>Enable tracking</Text>
                <Text style={styles.subText}>
                  This will record your movement every 5 min
                </Text>
              </View>
              <Switch onValueChange={toggleSwitch} value={trackingStatus} />
            </View>
          </LargeButton>
        </View>
        <View style={styles.buttonWrapper}>
          <LargeButton>
            <MaterialCommunityIcons
              name="file-import"
              size={33}
              color={commonColor.brandPrimary}
            />
            <Text>Import </Text>
          </LargeButton>
          <Share>
            <LargeButton>
              <MaterialCommunityIcons
                name="database-export"
                size={33}
                color={commonColor.brandSuccess}
              />
              <Text>Export</Text>
            </LargeButton>
          </Share>
        </View>
        <View style={styles.buttonWrapper}>
          <LargeButton>
            <View style={styles.switchTracking}>
              <View style={styles.description}>
                <Text>Remove points</Text>
                <Text style={styles.subText}>
                  Remove points from your route
                </Text>
              </View>

              <MaterialCommunityIcons
                name="chevron-right"
                size={33}
                color={commonColor.textColorLight}
              />
            </View>
          </LargeButton>
        </View>
      </View>
    );
  };
  const renderInnerHeader = () => {
    return (
      <>
        <View style={styles.headerShadow} />
        <View style={styles.headerInner}>
          <View style={styles.panelHeader}>
            <View style={styles.panelHandle} />
          </View>
          <View style={styles.panelTitleWrapper}>
            <Text style={styles.panelTitle}>My tracks</Text>
          </View>
        </View>
      </>
    );
  };

  return (
    <BottomSheet
      ref={bottomSheetRef}
      contentPosition={contentPosition}
      snapPoints={[60, 338]}
      renderContent={renderInnerDetails}
      renderHeader={renderInnerHeader}
    />
  );
}