react-native#Vibration JavaScript Examples

The following examples show how to use react-native#Vibration. 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: ReactionIcon.js    From Cosmos with MIT License 5 votes vote down vote up
ReactionIcon = ({
  style,
  iconName,
  pressAction = () => {},
  longPressAction = () => {},
  hasReacted,
}) => {
  const [fill, setFill] = useState(false);
  const iconAnimation = new Animated.Value(1);
  const iconOpacity = iconAnimation.interpolate({
    inputRange: [0.8, 1],
    outputRange: [0.2, 1],
  });

  const requireIcon = () => {
    let Icon;
    switch (iconName) {
      case 'heart':
        Icon = require('../Svg/HeartIcon/index.js').default;
        return <Icon width={IconSize} height={IconSize} fill={fill} />;
      case 'meh':
        Icon = require('../Svg/MehFaceIcons/index.js').default;
        return <Icon width={IconSize} height={IconSize} fill={fill} />;
      case 'frown':
        Icon = require('../Svg/SadFaceIcon/index.js').default;
        return <Icon width={IconSize} height={IconSize} fill={fill} />;
      case 'comment':
        Icon = require('../Svg/CommentIcon/index.js').default;
        return <Icon width={IconSize} height={IconSize} fill={fill} />;
      default:
        Icon = require('../Svg/CommentIcon/index.js').default;
        return <Icon width={IconSize} height={IconSize} fill={fill} />;
    }
  };

  useEffect(() => {
    setFill(hasReacted);
  }, [hasReacted]);

  return (
    <TouchableWithoutFeedback
      onLongPress={() => {
        Vibration.vibrate(30);
        longPressAction();
      }}
      onPress={() => {
        Vibration.vibrate(15);
        Animated.timing(iconAnimation, {
          toValue: 0.8,
          duration: 200,
          useNativeDriver: true,
        }).start(() => {
          setFill(!hasReacted);
          Animated.timing(iconAnimation, {
            toValue: 1,
            duration: 200,
            useNativeDriver: true,
          }).start(() => pressAction());
        });
      }}>
      <Animated.View
        style={[
          {...style},
          styles.reactIcons,
          {
            opacity: iconOpacity,
            transform: [{scale: iconAnimation}],
          },
        ]}>
        {requireIcon()}
      </Animated.View>
    </TouchableWithoutFeedback>
  );
}
Example #2
Source File: Scanner.js    From Legacy with Mozilla Public License 2.0 4 votes vote down vote up
export default function App() {
  var {t} = useTranslation();
  var nav = useNavigation();
  const [scanned,setScanned] = useState(false);
  const [list,setList] = useState([]);
  const [flash,setFlash] = useState(false);
  const [zoom,setZoom] = useState(0);
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  var data = useAPIRequest(list.map(i=>({
    endpoint: 'munzee/testscan',
    data: {barcode: i}
  })));
  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={{ flex: 1 }}>
      {scanned&&<View>
        <Button title={t('scanner:scan_new')} onPress={()=>setScanned(false)} />
        {list.slice().reverse().map((i,index)=>data[index]?.valid?<TouchableOpacity style={{borderBottomWidth: 1}} onPress={()=>{
            if(data[index].munzee) {
              WebBrowser.openBrowserAsync(i)
            } else {
              nav.navigate('DBType',{munzee:data[index].munzee_logo.slice(49,-4)})
            }
          }}>
          <View style={{flexDirection:"row",alignItems:"center",padding:8}}>
            <Image style={{height:48,width:48}} source={getIcon(data[index].munzee_logo)} />
            <View>
              {data[index].munzee&&<Text allowFontScaling={false} style={{color:'blue',fontSize:16,...font("bold")}}>
                {t('scanner:munzee',{name:data[index].munzee.friendly_name,username:data[index].munzee.creator_username})}
              </Text>}
              <Text allowFontScaling={false} style={{color:'blue',fontSize:data[index].munzee?12:16,...font(data[index].munzee?400:"bold")}}>
                {t('scanner:type',{type:data[index].munzee_type})}
              </Text>
            </View>
          </View>
        </TouchableOpacity>:<TouchableOpacity style={{borderBottomWidth: 1}} onPress={()=>{
            if(i?.startsWith?.('http')) {
              WebBrowser.openBrowserAsync(i)
            }
          }}>
          <Text allowFontScaling={false} style={{color:i?.startsWith?.('http')?'blue':'black',textAlign:"center",fontSize:16,...font("bold"),padding:4,paddingVertical:16}}>{i}</Text>
        </TouchableOpacity>)}
      </View>}
      {!scanned&&<Camera
        style={{ flex: 1 }}
        zoom={zoom}
        type={type}
        flashMode={flash?Camera.Constants.FlashMode.torch:Camera.Constants.FlashMode.off}
        barCodeScannerSettings={{
          barCodeTypes: [BarCodeScanner.Constants.BarCodeType.qr],
        }}
        onBarCodeScanned={(a)=>{
          try {
            Vibration.vibrate(500);
            setScanned(true);
            setList(list.concat(a?.data));
          } catch (e) {
            console.log(e);
          }
        }}
      >
        <View
          style={{
            backgroundColor: 'transparent',
            flexDirection: 'row',
            flex: 1
          }}>
          <View style={{position:"absolute",bottom:16,left:16,right:16,zIndex:1000}}>
            <View style={{flexDirection:"row",alignItems:"center"}}>
              <IconButton
                style={{backgroundColor:"white"}}
                icon={`camera-${type === Camera.Constants.Type.back?'rear':'front'}`}
                size={32}
                color="#016930"
                onPress={()=>setType(
                  type === Camera.Constants.Type.back
                    ? Camera.Constants.Type.front
                    : Camera.Constants.Type.back
                )}
              />
              <Slider
                style={{flex:1,marginHorizontal:8}}
                color="#016930"
                value={zoom}
                onValueChange={(value) => setZoom(value)} />
              <IconButton
                disabled={type === Camera.Constants.Type.front}
                style={{backgroundColor:"white"}}
                icon="flashlight"
                size={32}
                color="#016930"
                onPress={()=>setFlash(!flash)}
              />
            </View>
          </View>
          {/* <TouchableOpacity
            style={{
              flex: 0.1,
              alignSelf: 'flex-end',
              alignItems: 'center'
            }}
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back
              );
              
            }}>
            <Text allowFontScaling={false} style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
          </TouchableOpacity> */}
        </View>
      </Camera>}
    </View>
  );
}
Example #3
Source File: AuthScreen.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
AuthScreen = (props) => {

    const [isSignup, setIsSignUp] = useState(false);
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const [isLoading, setIsLoading] = useState(false);

    const [expoPushToken, setExpoPushToken] = useState('');
    const [notification, setNotification] = useState({});

    const dispatch = useDispatch();
    let token;
    let _notificationSubscription;

    const registerForPushNotificationsAsync = async () => {
        if (Constants.isDevice) {
            const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                Alert.alert(
                    'Failed !',
                    'Failed to get push token for push notification!',
                    [{ text: 'Okay' }]
                );
                return;
            }
            try{
                token = await Notifications.getExpoPushTokenAsync();
            } catch(err){
                showMessage({
                    message: `ERROR - ${err.message}`,
                    description: `${err}`,
                    type: "danger",
                    icon: { icon: "danger", position: 'left' },
                    duration: 3000
                });
            }
            console.log(token);
            setExpoPushToken(token);
        } else {
            Alert.alert(
                'Error !',
                'Must use physical device for Push Notifications',
                [{ text: 'Okay' }]
            )
        }
        if (Platform.OS === 'android') {
            Notifications.createChannelAndroidAsync('default', {
                name: 'default',
                sound: true,
                priority: 'max',
                vibrate: [0, 250, 250, 250],
            });
        }
    };

    useEffect(() => {
        registerForPushNotificationsAsync();
        console.log(expoPushToken);
        _notificationSubscription = Notifications.addListener(_handleNotification);
    }, [])
        

    const _handleNotification = notification => {
        Vibration.vibrate();
        setNotification(notification);
    };






    const validateAuthForm = () => {
        const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        const passwordRegex = /\d/
        if(isSignup && !name){
            showMessage({
                message: "Please enter a valid name.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(isSignup && name && name.length < 2){
            showMessage({
                message: "Please enter a valid name.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(!emailRegex.test(email.toLowerCase())){
            showMessage({
                message: "Please enter a valid email.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(!password || password.length === 0){
            showMessage({
                message: "Please enter your password.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(isSignup && password.length < 6){
            showMessage({
                message: "Password should be atleast 6 characters long.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;

        }
        if(isSignup && !passwordRegex.test(password)){
            showMessage({
                message: "Password should contain atleast 1 number.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        return true;
    }


    const AuthHandler = async () => {
        setIsLoading(true);
        if(validateAuthForm()){
            if(isSignup){
                try {
                    const msg = await dispatch(authActions.signup(name, email, password, expoPushToken))
                    showMessage({
                        message: "Signup Success",
                        description: 'Please Login !',
                        type: "success",
                        icon: { icon: "success", position: 'left' },
                        duration: 3000
                    });
                    setIsSignUp(false);
                    setName('');
                    setEmail('');
                    setPassword('');
                } catch (error) {
                    showMessage({
                        message: error.message,
                        type: "danger",
                        icon: { icon: "danger", position: 'left' },
                        duration: 3000
                    });
                }
                setIsLoading(false);
            } else {
                try {
                    await dispatch(authActions.signin(email, password, expoPushToken))
                    showMessage({
                        message: "Signed in success",
                        type: "success",
                        icon: { icon: "success", position: 'left' },
                        duration: 3000
                    });
                } catch (error) {
                    showMessage({
                        message: error.message,
                        type: "danger",
                        icon: { icon: "danger", position: 'left' },
                        duration: 3000
                    });
                    setIsLoading(false);
                }
            }
        }
    };

    const inputChangeHandler = (text,inputField) => {
        if(inputField === 1){
            setName(text)
        } else if(inputField === 2){
            setEmail(text)
        } else if(inputField === 3){
            setPassword(text)
        }
    }


    return (
            <View style={styles.container}>
                <Image style={styles.bgImage} source={require('../../assets/bg-auth.png')} />
                <View style={styles.titleContainer} >
                    <Text style={styles.title}>SocialApp</Text>
                </View>

                {/* { error !== null && (
                    <View style={styles.errorMsgContainer} >
                        <Image style={styles.msgIcon} source={{ uri: "https://i.imgur.com/GnyDvKN.png" }} />
                        <Text style={styles.msgText}> {error} </Text>
                    </View>
                )} */}

                { isSignup && (
                    <View style={styles.inputContainer}>
                        <TextInput style={styles.inputs}
                            placeholder="Name"
                            underlineColorAndroid='transparent'
                            value={name}
                            onChangeText={(text) => inputChangeHandler(text,1)}
                        />
                        <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/name.png' }} />
                    </View>
                ) }
                
                <View style={styles.inputContainer}>
                    <TextInput style={styles.inputs}
                        placeholder="Email"
                        keyboardType="email-address"
                        underlineColorAndroid='transparent'
                        value={email}
                        onChangeText={(text) => inputChangeHandler(text, 2) }
                    />
                    <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/email.png' }} />
                </View>

                <View style={styles.inputContainer}>
                    <TextInput style={styles.inputs}
                        placeholder="Password"
                        secureTextEntry={true}
                        underlineColorAndroid='transparent'
                        value={password}
                        onChangeText={(text) => inputChangeHandler(text, 3) }
                    />
                    <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/key.png' }} />
                </View>

                <TouchableOpacity 
                    onPress={() => props.navigation.navigate('ForgotPassword')}
                    style={styles.btnForgotPassword} 
                >
                    <Text style={styles.btnText}>Forgot your password?</Text>
                </TouchableOpacity>

                <TouchableOpacity 
                    style={[styles.buttonContainer, styles.loginButton]}
                    onPress={AuthHandler}
                >

                    { isLoading ? (
                        <ActivityIndicator size="small" color="#fff" />
                    )  :(
                        <Text style={styles.loginText}>
                            { isSignup ? "Register" : "Login" }
                        </Text>
                    ) }
                    
                </TouchableOpacity>


                <TouchableOpacity 
                    style={[styles.buttonContainer, styles.registerButton]}
                    onPress={() => {
                        setIsSignUp(prevState => !prevState);
                    }}
                >
                    <Text style={styles.btnText} >
                        { isSignup ? "Already a user ? Login" : "Don't have an account ? Register" }
                    </Text>
                </TouchableOpacity>
            </View>    
    );
}