react-native#Keyboard JavaScript Examples
The following examples show how to use
react-native#Keyboard.
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: useKeyboardHeight.js From react-native-select-dropdown with MIT License | 6 votes |
useKeyboardHeight = () => {
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardDidShow', e => {
setKeyboardHeight(e.endCoordinates.height);
});
const hideSubscription = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardHeight(0);
});
return () => {
showSubscription.remove();
hideSubscription.remove();
};
}, [setKeyboardHeight]);
return keyboardHeight;
}
Example #2
Source File: index.js From bluezone-app with GNU General Public License v3.0 | 6 votes |
componentDidMount() {
this.ref.focus();
this.keyboardWillShowSub = Keyboard.addListener(
'keyboardDidShow',
this.keyboardDidShow,
);
this.keyboardWillHideSub = Keyboard.addListener(
'keyboardDidHide',
this.keyboardDidHide,
);
}
Example #3
Source File: useKeyboardStatus.js From react-native-country-codes-picker with MIT License | 6 votes |
useKeyboardStatus = () => {
const [isOpen, setIsOpen] = useState(false);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const keyboardHideListener = useRef(null);
const keyboardShowListener = useRef(null);
const onKeyboardShow = e => {
setKeyboardHeight(e.endCoordinates.height);
setIsOpen(true);
}
const onKeyboardHide = () => {
setKeyboardHeight(0);
setIsOpen(false);
}
useEffect(() => {
keyboardShowListener.current = Keyboard.addListener('keyboardDidShow', onKeyboardShow);
keyboardHideListener.current = Keyboard.addListener('keyboardDidHide', onKeyboardHide);
return () => {
keyboardShowListener.current.remove();
keyboardHideListener.current.remove();
};
},[]);
return {
isOpen: isOpen,
keyboardHeight: keyboardHeight,
keyboardPlatform: Platform.OS
};
}
Example #4
Source File: ChatDetail.js From haven with MIT License | 6 votes |
render() {
const { loading } = this.props;
if (!loading && _.isEmpty(this.state.messages)) {
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
{this.renderMainContent()}
</TouchableWithoutFeedback>
);
} else {
return this.renderMainContent();
}
}
Example #5
Source File: PasswordInput.js From RRWallet with MIT License | 6 votes |
componentDidMount() {
Keyboard.addListener("keyboardDidHide", this._handleKeyboardDidHide);
AppState.addEventListener("change", this._handleAppStateChange);
setTimeout(() => {
this.textinput && this.textinput.focus();
}, 600);
autorun(() => {
if (this.inputCode.length == 6) {
console.log("completion", this.inputCode);
if (this.props.onCompletion && this.completionCode != this.inputCode) {
this.completionCode = this.inputCode;
this.props.onCompletion(this.inputCode);
}
}
});
}
Example #6
Source File: NPS.js From monsuivipsy with Apache License 2.0 | 6 votes |
render() {
const { visible, page } = this.state;
return (
<Modal visible={visible} animationType="slide" presentationStyle="formSheet" onDismiss={this.onClose}>
<View style={styles.container}>
<KeyboardAvoidingView
style={styles.keyboardAvoidingView}
behavior={Platform.select({ ios: "padding", android: null })}
>
<View style={styles.backContainer}>
<TouchableOpacity onPress={this.onClose}>
<Text style={styles.backText}>{getCaption("back")}</Text>
</TouchableOpacity>
</View>
<ScrollView
style={styles.scrollView}
keyboardDismissMode="on-drag"
onScrollBeginDrag={Keyboard.dismiss}
>
{page === 1 && this.renderFirstPage()}
{page === 2 && this.renderSecondPage()}
</ScrollView>
</KeyboardAvoidingView>
</View>
</Modal>
);
}
Example #7
Source File: AmountInput.js From actual with MIT License | 6 votes |
componentDidMount() {
Keyboard.addListener('keyboardDidHide', e => {
this.setState({ showMath: false, currentOp: null });
});
const clearOperation = () => this.setState({ currentOp: null });
const reset = ({ isNegative }) => {
this.setState({ isNegative, currentOp: null });
};
this.props.emitter.on('clear-operation', clearOperation);
this.props.emitter.on('set-negative', this.setNegative);
this.props.emitter.on('reset', reset);
this.cleanup = () => {
this.props.emitter.off('clear-operation', clearOperation);
this.props.emitter.off('set-negative', this.setNegative);
this.props.emitter.off('reset', reset);
};
}
Example #8
Source File: hooks.js From rakning-c19-app with MIT License | 6 votes |
export function useKeyboard(config) {
const { useWillShow = false, useWillHide = false } = config;
const [visible, setVisible] = useState(false);
const showEvent = useWillShow ? 'keyboardWillShow' : 'keyboardDidShow';
const hideEvent = useWillHide ? 'keyboardWillHide' : 'keyboardDidHide';
function dismiss() {
Keyboard.dismiss();
setVisible(false);
}
useEffect(() => {
function onKeyboardShow() {
setVisible(true);
}
function onKeyboardHide() {
setVisible(false);
}
Keyboard.addListener(showEvent, onKeyboardShow);
Keyboard.addListener(hideEvent, onKeyboardHide);
return () => {
Keyboard.removeListener(showEvent, onKeyboardShow);
Keyboard.removeListener(hideEvent, onKeyboardHide);
};
}, [useWillShow, useWillHide]);
return [visible, dismiss];
}
Example #9
Source File: index.js From cometchat-pro-react-native-ui-kit with MIT License | 6 votes |
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
this.checkRestrictions();
}
Example #10
Source File: index.js From puente-reactnative-collect with MIT License | 6 votes |
Assets = ({
selectedAsset, setSelectedAsset, surveyingOrganization, scrollViewScroll, setScrollViewScroll
}) => {
const [page, setPage] = useState('assetCore');
const switchAssetPage = (pageIndex, asset) => {
setPage(pageIndex);
setSelectedAsset(asset);
};
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<View>
{selectedAsset && (
<NewAssets
setSelectedAsset={setSelectedAsset}
selectedAsset={selectedAsset}
surveyingOrganization={surveyingOrganization}
assetPageIndex={page}
scrollViewScroll={scrollViewScroll}
setScrollViewScroll={setScrollViewScroll}
setPage={setPage}
/>
)}
{selectedAsset === null && (
<ViewAssets
organization={surveyingOrganization}
switchAssetPage={switchAssetPage}
/>
)}
</View>
</TouchableWithoutFeedback>
);
}
Example #11
Source File: use-keyboard.js From astrale with GNU General Public License v3.0 | 6 votes |
useKeyboard = () => {
const [isKeyboardVisible, setKeyboardVisible] = React.useState(false);
React.useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true);
}
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false);
}
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return isKeyboardVisible;
}
Example #12
Source File: ContactSellerForm.js From Done-With-It with MIT License | 6 votes |
function ContactSellerForm({ listing }) {
const handleSubmit = async ({ message }, { resetForm }) => {
Keyboard.dismiss();
const result = await messagesApi.send(message, listing.id);
if (!result.ok) {
console.log("Error", result);
return Alert.alert(
"Error",
"Could not send the message to the seller."
);
}
resetForm();
Notifications.presentLocalNotificationAsync({
title: "Awesome!",
body: "Your message was sent to the seller.",
});
};
return (
<Form
initialValues={{ message: "" }}
onSubmit={handleSubmit}
validationSchema={validationSchema}
>
<FormField
maxLength={255}
multiline
name="message"
numberOfLines={3}
placeholder="Message..."
/>
<SubmitButton title="Contact Seller" />
</Form>
);
}
Example #13
Source File: Feedback.js From timetable with MIT License | 5 votes |
Feedback = () => {
const navigation = useNavigation()
const { t } = useTranslation()
const { theme } = useTheme()
const sendEmailHandler = ({ name, email, message }) => {
const data = JSON.stringify({ name, email, message }).replace(/[{}'']/g, '')
fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + process.env.API_SEND_GRID_KEY
},
body: JSON.stringify({
personalizations: [
{
to: [
{
email: process.env.SEND_GRID_EMAIL_TO
}
],
subject: 'Bus Timetable Feedback'
}
],
from: {
email: process.env.SEND_GRID_EMAIL_FROM
},
content: [
{
type: 'text/plain',
value: data
}
]
})
})
.then(() => {
Alert.alert('', t('feedback.onSuccessfulSubmit'), [
{
text: t('feedback.cancel'),
onPress: () => navigation.navigate('About')
}
])
})
.catch(() => {
Alert.alert(t('feedback.error'), t('feedback.onSubmitError'), [
{ text: t('feedback.cancel') }
])
})
}
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={styles.container}>
<Text style={[styles.info, { color: theme.text }]}>
{t('feedback.info')}
</Text>
<ScrollView style={styles.form}>
<Form
onSubmitHandler={sendEmailHandler}
namePlaceholder={t('feedback.namePlaceholder')}
emailPlaceholder={t('feedback.emailPlaceholder')}
messagePlaceholder={t('feedback.messagePlaceholder')}
submitTitle={t('feedback.submitTitle')}
schemaRequiredName={t('feedback.schemaRequiredName')}
schemaRequiredEmail={t('feedback.schemaRequiredEmail')}
schemaRequiredMessage={t('feedback.schemaRequiredMessage')}
buttonColor={theme.buttonColor}
buttonText={theme.buttonText}
/>
</ScrollView>
</View>
</TouchableWithoutFeedback>
)
}
Example #14
Source File: Dialogs.js From filen-mobile with GNU Affero General Public License v3.0 | 5 votes |
RedeemCodeDialog = memo(({ navigation }) => {
const [darkMode, setDarkMode] = useMMKVBoolean("darkMode", storage)
const redeemCodeDialogVisible = useStore(useCallback(state => state.redeemCodeDialogVisible))
const setRedeemCodeDialogVisible = useStore(useCallback(state => state.setRedeemCodeDialogVisible))
const [value, setValue] = useState("")
const inputRef = useRef()
const [buttonsDisabled, setButtonsDisabled] = useState(false)
const [lang, setLang] = useMMKVString("lang", storage)
useEffect(() => {
setButtonsDisabled(false)
if(!redeemCodeDialogVisible){
setTimeout(() => {
setValue("")
}, 250)
}
if(redeemCodeDialogVisible){
setTimeout(() => {
inputRef.current.focus()
}, 250)
}
}, [redeemCodeDialogVisible])
return (
<Dialog.Container
visible={redeemCodeDialogVisible}
useNativeDriver={false}
onRequestClose={() => setRedeemCodeDialogVisible(false)}
onBackdropPress={() => {
if(!buttonsDisabled){
setRedeemCodeDialogVisible(false)
}
}}
>
<Dialog.Title>{i18n(lang, "redeemACode")}</Dialog.Title>
<Dialog.Input placeholder={i18n(lang, "code")} value={value} autoFocus={true} onChangeText={(val) => setValue(val)} textInputRef={inputRef} />
<Dialog.Button label={i18n(lang, "cancel")} disabled={buttonsDisabled} onPress={() => setRedeemCodeDialogVisible(false)} />
<Dialog.Button label={i18n(lang, "redeem")} disabled={buttonsDisabled} onPress={() => {
setButtonsDisabled(true)
setRedeemCodeDialogVisible(false)
Keyboard.dismiss()
useStore.setState({ fullscreenLoadingModalVisible: true })
const code = value.trim()
if(code.length == 0){
return false
}
redeemCode({ code }).then(() => {
setButtonsDisabled(false)
DeviceEventEmitter.emit("event", {
type: "reload-account-info"
})
DeviceEventEmitter.emit("event", {
type: "reload-account-usage"
})
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: i18n(lang, "codeRedeemSuccess", true, ["__CODE__"], [code]) })
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}} />
</Dialog.Container>
)
})
Example #15
Source File: ListingBasicInfo.js From haven with MIT License | 5 votes |
componentDidMount() {
this.keyboardDidShowSub = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow);
this.keyboardWillHideSub = Keyboard.addListener('keyboardDidHide', this.keyboardWillHide);
}
Example #16
Source File: PasswordInput.js From RRWallet with MIT License | 5 votes |
componentWillUnmount() {
Keyboard.removeListener("keyboardDidHide", this._handleKeyboardDidHide);
AppState.removeEventListener("change", this._handleAppStateChange);
}
Example #17
Source File: index.js From monsuivipsy with Apache License 2.0 | 5 votes |
Supported = ({ navigation }) => {
const [contribution, setContribution] = useState("");
const [npsSent, setNpsSent] = useState(false);
const [sendButton, setSendButton] = useState("Valider");
const sendNPS = async () => {
if (npsSent) {
return;
}
const { useful, reco, feedback, email } = this.state;
setSendButton("Merci !");
logEvents.logNPSSend(useful, reco);
const userId = Matomo.userId;
sendTipimail(
{
from: {
address: "[email protected]",
personalName: "Ma Tête et Moi - Application",
},
subject: "Ma Tête et Moi - NPS",
text: formatText(useful, reco, feedback, email, userId),
},
__DEV__ ? "[email protected]" : "[email protected]"
);
this.npsSent = true;
this.setState({ visible: false });
};
return (
<SafeAreaView style={styles.safe}>
<ScrollView style={styles.container} keyboardDismissMode="on-drag" onScrollBeginDrag={Keyboard.dismiss}>
<BackButton />
<View style={styles.header}>
<Text style={styles.title}>Ma Tête et Moi</Text>
<Text style={styles.title}>Nous vous écoutons :</Text>
</View>
<View style={styles.textArea}>
<TextInput
multiline={true}
numberOfLines={6}
onChangeText={setContribution}
value={contribution}
placeholder="Message..."
textAlignVertical="top"
/>
</View>
<View style={styles.buttonWrapper}>
<Button onPress={sendNPS} title={sendButton} />
</View>
</ScrollView>
</SafeAreaView>
);
}
Example #18
Source File: AndroidKeyboardAvoidingView.android.js From actual with MIT License | 5 votes |
export default function AndroidKeyboardAvoidingView({
children,
behavior = 'height',
enabled = true,
keyboardVerticalOffset = 0,
includeStatusBar,
style
}) {
let [keyboard, setKeyboard] = useState(false);
let [accessoryId, setAccessoryId] = useState(null);
useEffect(() => {
let cleanups = [
Keyboard.addListener('keyboardDidShow', e => {
setKeyboard(true);
}),
Keyboard.addListener('keyboardDidHide', e => {
setKeyboard(false);
// TODO: This is wrong. In Android, the user can hide the
// keyboard and bring it back up again all while never losing
// focus of the input. This means we'll render the accessory
// view the first time but never again. Need to figure out a
// better solution.
setAccessoryId(null);
})
];
return () => cleanups.forEach(handler => handler.remove());
}, []);
return (
<AccessoryIdContext.Provider value={setAccessoryId}>
<KeyboardAvoidingView
style={[{ flex: 1 }, style]}
behavior={behavior}
keyboardVerticalOffset={
keyboardVerticalOffset +
(includeStatusBar ? StatusBarHeight.statusBarHeight : 0)
}
enabled={enabled}
>
<>
{children}
{keyboard && accessoryId && renderAccessoryView(accessoryId)}
</>
</KeyboardAvoidingView>
</AccessoryIdContext.Provider>
);
}
Example #19
Source File: search.js From turkce-sozluk with MIT License | 5 votes |
function SearchBox({ onChangeFocus }) {
const [value, setValue] = React.useState('')
const [isFocus, setFocus] = React.useState(false)
React.useEffect(() => {
onChangeFocus(isFocus)
}, [isFocus, onChangeFocus])
const onCancel = () => {
setFocus(false)
Keyboard.dismiss()
}
const onClear = () => {
setValue('')
}
return (
<Box flexDirection="row" alignItems="center">
<Box position="relative" flex={1}>
<Input
style={{
shadowColor: '#000',
shadowOpacity: 0.1,
shadowRadius: 24,
shadowOffset: {
width: 0,
height: 4
}
}}
bg="white"
height={52}
color="textDark"
borderWidth={1}
borderColor={isFocus ? '#D1D1D1' : 'transparent'}
placeholder="Türkçe Sözlük’te Ara"
placeholderTextColor="textMedium"
pl={52}
borderRadius="normal"
value={value}
onFocus={() => setFocus(true)}
onChangeText={text => setValue(text)}
/>
{value.length > 0 && (
<Button onPress={onClear} position="absolute" right={16} top={14}>
<Close color={theme.colors.textDark} />
</Button>
)}
<Button position="absolute" left={16} top={14}>
<Search color={theme.colors.textMedium} />
</Button>
</Box>
{isFocus && (
<Button onPress={onCancel} px={15} height={52}>
<Text>Vazgeç</Text>
</Button>
)}
</Box>
)
}
Example #20
Source File: index.js From cometchat-pro-react-native-ui-kit with MIT License | 5 votes |
render() {
const userList = [...this.state.userList];
const userListWithHeaders = [];
let headerIndices = [0];
if (userList.length) {
headerIndices = [];
userList.forEach((user) => {
const chr = user.name[0].toUpperCase();
if (chr !== this.currentLetter) {
this.currentLetter = chr;
if (!this.state.textInputValue) {
headerIndices.push(userListWithHeaders.length);
userListWithHeaders.push({
value: this.currentLetter,
header: true,
});
}
userListWithHeaders.push({ value: user, header: false });
} else {
userListWithHeaders.push({ value: user, header: false });
}
});
}
return (
<CometChatContextProvider ref={(el) => (this.contextProviderRef = el)}>
<TouchableWithoutFeedback
onPress={() => {
Keyboard.dismiss();
}}>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={style.contactWrapperStyle}>
<View style={style.headerContainer}></View>
{this.listHeaderComponent()}
<FlatList
data={userListWithHeaders}
renderItem={this.renderUserView}
contentContainerStyle={{ flexGrow: 1 }}
ListEmptyComponent={this.listEmptyContainer}
ItemSeparatorComponent={this.itemSeparatorComponent}
keyExtractor={(item, index) => item.uid + '_' + index}
stickyHeaderIndices={
Platform.OS === 'android' ? null : headerIndices
}
onScroll={this.handleScroll}
onEndReached={this.endReached}
onEndReachedThreshold={0.3}
showsVerticalScrollIndicator={false}
/>
<DropDownAlert ref={(ref) => (this.dropDownAlertRef = ref)} />
</KeyboardAvoidingView>
</TouchableWithoutFeedback>
</CometChatContextProvider>
);
}
Example #21
Source File: RootContainer.Screen.js From react-native-hook-template with MIT License | 5 votes |
RootContainerScreen = () => {
const sendNetworkFail = useSelector(state => state.sendNetworkFail);
const [isKeyboardShow, setIsKeyboardShow] = useState(false);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const dispatch = useDispatch();
const clearNetworkStatus = () => dispatch(clearNetworkFail());
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
e => {
setIsKeyboardShow(true);
setKeyboardHeight(e.endCoordinates.height);
},
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setIsKeyboardShow(false);
},
);
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
}, []);
if (sendNetworkFail.err) {
switch (sendNetworkFail.err) {
case 'NETWORK_ERROR':
Toast.show('No network connection, please try again');
break;
case 'TIMEOUT_ERROR':
Toast.show('Timeout, please try again');
break;
case 'CONNECTION_ERROR':
Toast.show('DNS server not found, please try again');
break;
default:
Toast.show(sendNetworkFail.err);
break;
}
clearNetworkStatus();
}
return (
<View style={styles.mainContainer}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Drawer" headerMode={'none'}>
<Stack.Screen name="Drawer" component={DrawerNavigatorScreen} />
<Stack.Screen
name="DetailProfileScreen"
component={DetailProfileScreen}
options={{gestureEnabled: true, gestureDirection: 'horizontal'}}
/>
<Stack.Screen
name="DetailFollowerScreen"
component={DetailFollowerScreen}
options={{gestureEnabled: true, gestureDirection: 'horizontal'}}
/>
</Stack.Navigator>
</NavigationContainer>
{/*Keyboard padding*/}
{isKeyboardShow && Platform.OS === 'ios' ? (
<View style={{height: keyboardHeight}} />
) : null}
</View>
);
}
Example #22
Source File: index.js From puente-reactnative-collect with MIT License | 5 votes |
OfflineData = ({ surveyingOrganization, scrollViewScroll, setScrollViewScroll }) => {
const [inputs, setInputs] = useState({});
const [cacheSuccess, setCacheSuccess] = useState(false);
const [submittedForms, setSubmittedForms] = useState(0);
const { populateResidentDataCache, isLoading } = useContext(OfflineContext);
useEffect(() => {
setInputs(configArray);
}, [configArray]);
const repopulateAllData = async () => populateResidentDataCache().then((records) => {
setSubmittedForms(records.length);
setCacheSuccess(true);
});
return (
<View>
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<Formik
initialValues={{}}
onSubmit={async (values) => {
await cacheResidentDataMulti(values.communityname);
await getData('residentData').then((forms) => {
setSubmittedForms(Object.keys(forms).length);
setCacheSuccess(true);
});
}}
>
{(formikProps) => (
<View style={layout.formContainer}>
<PaperButton
onPressEvent={repopulateAllData}
buttonText="Populate all ID Forms"
loading={!!isLoading}
style={{ backgroundColor: 'blue' }}
/>
{inputs.length && inputs.map((result) => (
<View key={result.formikKey}>
<PaperInputPicker
data={result}
formikProps={formikProps}
surveyingOrganization={surveyingOrganization}
scrollViewScroll={scrollViewScroll}
setScrollViewScroll={setScrollViewScroll}
customForm={false}
/>
</View>
))}
<PaperButton
onPressEvent={formikProps.handleSubmit}
buttonText={_.isEmpty(formikProps.values) ? I18n.t('global.emptyForm') : I18n.t('global.submit')}
disabled={!!_.isEmpty(formikProps.values)}
icon={_.isEmpty(formikProps.values) ? 'alert-octagon' : 'plus'}
style={{ backgroundColor: _.isEmpty(formikProps.values) ? '#FFDDDD' : 'green' }}
/>
<PaperButton
onPressEvent={() => deleteData('residentData')}
buttonText="Clear Cached ID Forms"
icon="delete"
style={{ backgroundColor: 'red' }}
/>
<PopupSuccess
success={cacheSuccess}
setSuccess={setCacheSuccess}
submittedForms={submittedForms}
/>
</View>
)}
</Formik>
</TouchableWithoutFeedback>
</View>
);
}
Example #23
Source File: index.js From musicont with MIT License | 5 votes |
Index = ({ songs }) => {
const { goBack } = useNavigation();
const [audios, setAudios] = useState([]);
const [search, setSearch] = useState('');
const handleInput = (val) => {
const value = val.replace(' ', ' ');
setSearch(value);
if (value.length > 3) {
const results = songs.filter((song) => {
let regex = new RegExp(value, 'ig');
return regex.exec(song?.title) || regex.exec(song?.author);
});
setAudios(results);
} else {
setAudios([]);
}
};
return (
<>
<StatusBar style="dark" />
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<View style={styles.input}>
<Icon name="search" color="#FFF" />
<TextInput style={styles.textInput} onChangeText={handleInput} value={search} returnKeyType="search" placeholder="Search..." />
</View>
<TouchableOpacity style={styles.btn} onPress={() => goBack()}>
<Text style={styles.btnTxt}>Cancel</Text>
</TouchableOpacity>
</View>
<View style={styles.result}>
{audios.length > 0 ? (
<Section.MusicList audios={audios} />
) : (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 24, fontWeight: 'bold', color: 'rgba(0, 0, 0, .3)' }}>Search something...</Text>
</View>
)}
</View>
</SafeAreaView>
</TouchableWithoutFeedback>
</>
);
}
Example #24
Source File: index.js From stayaway-app with European Union Public License 1.2 | 5 votes |
export default function TopComponent(props){
const { scrollable, containerPadding, children, style, ...otherProps } = props;
const { name, colors } = useTheme();
const memoizedStyle = useMemo(() => styles(colors), [name]);
const [screenHeight, setScreenHeight] = useState(Scalling.height);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const onContentSizeChange = (contentWidth, contentHeight) => {
setScreenHeight(contentHeight);
};
useEffect(() => {
function onKeyboardShow(event) {
const { endCoordinates: { height }} = event;
setKeyboardHeight(height);
}
function onKeyboardHide() {
setKeyboardHeight(0);
}
Keyboard.addListener('keyboardDidShow', onKeyboardShow);
Keyboard.addListener('keyboardDidHide', onKeyboardHide);
return () => {
Keyboard.removeListener('keyboardDidShow', onKeyboardShow);
Keyboard.removeListener('keyboardDidHide', onKeyboardHide);
};
});
return (
<View
style={{
...memoizedStyle.container,
...style,
}}
{...otherProps}
>
{ scrollable && renderScrollableContent(containerPadding, children, screenHeight, keyboardHeight, onContentSizeChange, memoizedStyle)}
{ ! scrollable && renderContent(containerPadding, children, memoizedStyle)}
</View>
);
}
Example #25
Source File: Dialogs.js From filen-mobile with GNU Affero General Public License v3.0 | 4 votes |
RenameDialog = memo(({ navigation }) => {
const [darkMode, setDarkMode] = useMMKVBoolean("darkMode", storage)
const [value, setValue] = useState("")
const inputRef = useRef()
const [buttonsDisabled, setButtonsDisabled] = useState(false)
const renameDialogVisible = useStore(useCallback(state => state.renameDialogVisible))
const setRenameDialogVisible = useStore(useCallback(state => state.setRenameDialogVisible))
const currentActionSheetItem = useStore(useCallback(state => state.currentActionSheetItem))
const [lang, setLang] = useMMKVString("lang", storage)
const [ext, setExt] = useState("")
useEffect(() => {
setButtonsDisabled(false)
if(typeof currentActionSheetItem !== "undefined"){
if(currentActionSheetItem.type == "folder"){
setValue(currentActionSheetItem.name.trim())
}
else{
if(currentActionSheetItem.name.indexOf(".") !== -1){
const nameEx = currentActionSheetItem.name.split(".")
const fileExt = nameEx[nameEx.length - 1]
nameEx.pop()
setValue(nameEx.join(".").trim())
setExt(fileExt.trim())
}
else{
setValue(currentActionSheetItem.name.trim())
}
}
}
if(renameDialogVisible){
setTimeout(() => {
inputRef.current.focus()
//inputRef.current.setNativeProps({ selection: { start: value.length, end: value.length } })
}, 250)
}
}, [renameDialogVisible])
return (
<Dialog.Container
visible={renameDialogVisible}
useNativeDriver={false}
onRequestClose={() => setRenameDialogVisible(false)}
onBackdropPress={() => {
if(!buttonsDisabled){
setRenameDialogVisible(false)
}
}}
>
<Dialog.Title>{i18n(lang, "rename")}</Dialog.Title>
<Dialog.Input placeholder={i18n(lang, "newName")} value={value} selection={/*{ start: value.length, end: value.length }*/undefined} onChangeText={(val) => setValue(val)} textInputRef={inputRef} />
<Dialog.Button label={i18n(lang, "cancel")} disabled={buttonsDisabled} onPress={() => setRenameDialogVisible(false)} />
<Dialog.Button label={i18n(lang, "rename")} disabled={buttonsDisabled} onPress={() => {
if(typeof currentActionSheetItem !== "object"){
return false
}
setButtonsDisabled(true)
setRenameDialogVisible(false)
Keyboard.dismiss()
useStore.setState({ fullscreenLoadingModalVisible: true })
let name = value.trim()
const item = currentActionSheetItem
if(item.name == name){
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
return showToast({ message: i18n(lang, "invalidFolderName") })
}
if(item.type == "file"){
name = name + "." + ext
}
if(item.type == "folder"){
if(!fileAndFolderNameValidation(name)){
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
return showToast({ message: i18n(lang, "invalidFolderName") })
}
folderExists({ name, parent: item.parent }).then((res) => {
if(res.exists){
if(item.uuid !== res.existsUUID){
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
return showToast({ message: i18n(lang, "alreadyExistsInThisFolder", true, ["__NAME__"], [name]) })
}
}
renameFolder({ folder: item, name }).then(async () => {
DeviceEventEmitter.emit("event", {
type: "change-item-name",
data: {
uuid: item.uuid,
name
}
})
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
//showToast({ message: i18n(lang, "folderRenamed") })
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}
else{
if(!fileAndFolderNameValidation(name)){
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
return showToast({ message: i18n(lang, "invalidFileName") })
}
fileExists({ name, parent: item.parent }).then((res) => {
if(res.exists){
if(item.uuid !== res.existsUUID){
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
return showToast({ message: i18n(lang, "alreadyExistsInThisFolder", true, ["__NAME__"], [name]) })
}
}
renameFile({ file: item, name }).then(async () => {
DeviceEventEmitter.emit("event", {
type: "change-item-name",
data: {
uuid: item.uuid,
name
}
})
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
//showToast({ message: i18n(lang, "fileRenamed") })
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}
}} />
</Dialog.Container>
)
})
Example #26
Source File: CountryPicker.js From react-native-country-codes-picker with MIT License | 4 votes |
/**
* Country picker component
* @param {?boolean} show Hide or show component by using this props
* @param {?boolean} disableBackdrop Hide or show component by using this props
* @param {?boolean} enableModalAvoiding Is modal should avoid keyboard ? On android to work required to use with androidWindowSoftInputMode with value pan, by default android will avoid keyboard by itself
* @param {?string} androidWindowSoftInputMode Hide or show component by using this props
* @param {?string} inputPlaceholder Text to showing in input
* @param {?string} searchMessage Text to show user when no country to show
* @param {?string} lang Current selected lang by user
* @param {?string} initialState Here you should define initial dial code
* @param {?array} excludedCountries Array of countries which should be excluded from picker
* @param {Function} pickerButtonOnPress Function to receive selected country
* @param {Function} onBackdropPress Function to receive selected country
* @param {?Object} style Styles
* @param {?React.ReactNode} itemTemplate Country list template
* @param rest
*/
export default function CountryPicker({
show,
pickerButtonOnPress,
inputPlaceholder,
searchMessage,
lang = 'en',
style,
enableModalAvoiding,
androidWindowSoftInputMode,
onBackdropPress,
disableBackdrop,
excludedCountries = [],
initialState,
itemTemplate: ItemTemplate = CountryButton,
...rest
}) {
const codes = countryCodes?.map(country => {
if (excludedCountries?.find(short => country?.code === short?.toUpperCase()))
return;
return country;
});
const keyboardStatus = useKeyboardStatus();
const animationDriver = React.useRef(new Animated.Value(0)).current;
const animatedMargin = React.useRef(new Animated.Value(0)).current;
const [searchValue, setSearchValue] = React.useState(initialState || '');
const [visible, setVisible] = React.useState(show);
React.useEffect(() => {
if (show) {
openModal();
} else {
closeModal();
}
}, [show]);
React.useEffect(() => {
if (
enableModalAvoiding &&
!!(
keyboardStatus.keyboardPlatform === 'ios' ||
(keyboardStatus.keyboardPlatform === 'android' &&
androidWindowSoftInputMode === 'pan')
)
) {
if (keyboardStatus.isOpen)
Animated.timing(animatedMargin, {
toValue: keyboardStatus.keyboardHeight,
duration: 290,
easing: Easing.ease,
useNativeDriver: false,
}).start();
if (!keyboardStatus.isOpen)
Animated.timing(animatedMargin, {
toValue: 0,
duration: 290,
easing: Easing.ease,
useNativeDriver: false,
}).start();
}
}, [keyboardStatus.isOpen]);
const resultCountries = React.useMemo(() => {
if (!isNaN(searchValue))
return codes.filter((country) =>
country?.dial_code.includes(searchValue)
);
return codes.filter((country) =>
country?.name[lang || 'en'].includes(searchValue)
);
}, [searchValue]);
const modalPosition = animationDriver.interpolate({
inputRange: [0, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1],
outputRange: [height, 105, 75, 50, 30, 15, 5, 0],
extrapolate: 'clamp',
});
const modalBackdropFade = animationDriver.interpolate({
inputRange: [0, 0.5, 1],
outputRange: [0, 0.5, 1],
extrapolate: 'clamp'
});
const openModal = () => {
setVisible(true);
Animated.timing(animationDriver, {
toValue: 1,
duration: 400,
useNativeDriver: false,
}).start();
};
const closeModal = () => {
Animated.timing(animationDriver, {
toValue: 0,
duration: 400,
useNativeDriver: false,
}).start(() => setVisible(false));
};
if (!visible)
return null;
return (
<>
{!disableBackdrop && (
<Animated.View
onStartShouldSetResponder={onBackdropPress}
style={[
{
flex: 1,
opacity: modalBackdropFade,
backgroundColor: 'rgba(116,116,116,0.45)',
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'flex-end'
},
style?.backdrop
]}
/>
)}
<Animated.View
style={[
styles.modal,
style?.modal,
{
transform: [
{
translateY: modalPosition,
},
],
},
]}
>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
}}
>
<TextInput
style={[styles.searchBar, style?.textInput]}
value={searchValue}
onChangeText={(text) => setSearchValue(text)}
placeholder={inputPlaceholder || 'Search your country'}
{...rest}
/>
</View>
<View style={[styles.line, style?.line]}/>
{resultCountries.length === 0 ? (
<View style={[styles.countryMessage, style?.countryMessageContainer]}>
<Text
style={[
{
color: '#8c8c8c',
fontSize: 16,
},
style?.searchMessageText,
]}
>
{searchMessage || 'Sorry we cant find your country :('}
</Text>
</View>
) : (
<FlatList
showsVerticalScrollIndicator={false}
data={resultCountries || codes}
keyExtractor={(item, index) => item + index}
initialNumToRender={10}
maxToRenderPerBatch={10}
style={[{
height: 250
}, style?.itemsList]}
keyboardShouldPersistTaps={'handled'}
renderItem={({item, index}) => {
let itemName = item?.name[lang];
let checkName = itemName.length ? itemName : item?.name['en'];
return (
<ItemTemplate
key={index}
item={item}
style={style}
name={checkName}
onPress={() => {
Keyboard.dismiss();
typeof pickerButtonOnPress === 'function' && pickerButtonOnPress(item);
}}
/>
);
}}
{...rest}
/>
)}
<Animated.View
style={[
styles.modalInner,
style?.modalInner,
{
height: animatedMargin,
},
]}
/>
</Animated.View>
</>
);
}
Example #27
Source File: Main.js From SemanaOmnistack10 with MIT License | 4 votes |
function Main({ navigation }) {
const [devs, setDevs] = useState([]);
const [techs, setTechs] = useState('');
const [searching, setSearching] = useState(false);
const [currentRegion, setCurrentRegion] = useState(null);
const [keyboardShown, setKeyboardShown] = useState(false);
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync();
if (granted) {
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true
});
const { latitude, longitude } = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.04
});
}
}
loadInitialPosition();
Keyboard.addListener('keyboardDidShow', () => setKeyboardShown(true));
Keyboard.addListener('keyboardDidHide', () => setKeyboardShown(false));
}, []);
useEffect(() => {
subscribeToNewDevs(dev => setDevs([...devs, dev]));
}, [devs]);
function setupWebsocket() {
disconnect();
const { latitude, longitude } = currentRegion;
connect(
latitude,
longitude,
techs
);
}
async function loadDevs() {
if (searching)
return;
setSearching(true);
const { latitude, longitude } = currentRegion;
const response = await api.get('/search', { params: { latitude, longitude, techs } });
setDevs(response.data.devs);
setSearching(false);
setupWebsocket();
}
function handleRegionChange(region) {
setCurrentRegion(region);
}
if (!currentRegion)
return null;
return (
<>
<MapView
onRegionChangeComplete={handleRegionChange}
initialRegion={currentRegion}
style={styles.map}
>
{devs.map(dev => (
<Marker
key={dev._id}
coordinate={{
longitude: dev.location.coordinates[0],
latitude: dev.location.coordinates[1]
}}>
<Image style={styles.avatar} source={{ uri: dev.avatar_url }}></Image>
<Callout onPress={() => {
// Navegação
navigation.navigate('Profile', { github: dev.github });
}}>
<View style={styles.callout}>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</View>
</Callout>
</Marker>
))}
</MapView>
<View style={[styles.searchForm, (keyboardShown ? styles.searchTop : styles.searchBottom)]}>
<TextInput
style={styles.searchInput}
placeholder='Buscar devs por techs...'
placeholderTextColor='#999'
autoCapitalize='words'
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity onPress={loadDevs} disabled={searching} style={styles.searchButton}>
{!searching && <MaterialIcons name="my-location" size={20} color="#FFF" />}
{searching && <MaterialIcons name="gps-not-fixed" size={20} color="#FFF" />}
</TouchableOpacity>
</View>
</>
);
}
Example #28
Source File: ChatDetail.js From haven with MIT License | 4 votes |
componentDidMount() {
const {
fetchChatDetail,
setChatDetailLoading,
fetchChats,
profile,
isFromOrder,
peerID,
subject,
moderatorId,
buyerId,
vendorId,
isBlocked,
} = this.props;
const { inDispute } = this.state;
this.setState({ isMounted: true, recievedMessages: [] });
// Fetch current chat history
fetchChatDetail({ peerID, subject, isFromOrder });
if (!this.isSameChat()) {
// This section is for showing loading indicator.
// When user navigate back to chat list and again to the same chat detail, then no need to
// show loading indicator
setChatDetailLoading(true);
}
this.setInitialMessage([]);
// const { username, password } = this.props.appstate;
// const socketUrl = `ws://${username}:${password}@${websocketHost}/ws`;
const socketUrl = `ws://${websocketHost}/ws`;
this.ws = new global.WebSocket(socketUrl, '', { headers: serverConfig.getAuthHeader() });
this.ws.onmessage = (e) => {
if (isBlocked) {
return;
}
const data = JSON.parse(e.data);
const { message, messageTyping } = data;
if (!message) {
if ((messageTyping && messageTyping.peerId === peerID) ||
(
inDispute &&
messageTyping &&
[moderatorId, buyerId, vendorId].includes(messageTyping.peerId))
) {
// This is for showing typing indicator if the messageTyping response comes through
// websocket, then it sets the type state to true for 2 sec
if (this.state.showTypingTimerId) {
clearTimeout(this.state.showTypingTimerId);
}
const showTypingTimerId = setTimeout(() => {
this.setState({ typing: false, showTypingTimerId: -1 });
}, 2000);
this.setState({ typing: true, showTypingTimerId });
} else {
this.setState({ typing: false });
}
return;
}
// When message response is recieved, then updates the chats to update the chat badges
if (message.subject === subject && message.peerId === moderatorId) {
fetchChats();
fetchChatDetail({ peerID, subject, isFromOrder });
if (!inDispute) {
this.setState({ inDispute: true });
this.appendMessage(profile, { ...message, moderatorJoined: true });
} else {
this.appendMessage(profile, { ...message });
}
}
if (message.subject === subject && [buyerId, vendorId, peerID].includes(message.peerId)) {
// When message is for current chat then it will be added to current message list.
this.appendMessage(profile, message);
}
};
if (Platform.OS === 'ios') {
this.keyboardDidShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardDidShow);
this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
} else {
this.keyboardDidShowSub = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow);
this.keyboardWillHideSub = Keyboard.addListener('keyboardDidHide', this.keyboardWillHide);
}
}
Example #29
Source File: index.js From guardioes-app with Apache License 2.0 | 4 votes |
Login = ({ navigation }) => {
const { storeUser, setIsLoggedIn, setNeedSignIn } = useUser()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [showAlert, setShowAlert] = useState(false)
const [showProgressBar, setShowProgressBar] = useState(false)
const passwordInput = useRef()
const handleLogin = async () => {
Keyboard.dismiss()
if (email === '' || password === '') {
Alert.alert(translate('register.fieldNotBlank'))
return
}
setShowProgressBar(true)
setShowAlert(true)
const response = await authUser({ user: { email, password } })
if (response.status === 200) {
await storeUser(
response.data.user,
response.headers.authorization,
{
email,
password,
}
)
setShowAlert(false)
setTimeout(() => {
setNeedSignIn(false)
setIsLoggedIn(true)
}, 1000)
} else if (response.status === 401) {
setShowAlert(false)
Alert.alert(translate('login.errorMessages.emailPwdWrong'))
} else {
setShowAlert(false)
Alert.alert(translate('register.geralError'))
}
}
let LogoType = GDSLogoBR
if (translate('lang.code') === 'es') {
LogoType = GDSLogoES
}
return (
<>
<SafeAreaView style={{ flex: 0, backgroundColor: '#5DD39E' }} />
<GradientBackground>
<KeyboardScrollView>
<Logo source={LogoType} />
<PageTitle>{translate('login.title')}</PageTitle>
<FormSeparator>
<SnowInput
placeholder={translate('login.email')}
keyboardType='email-address'
returnKeyType='next'
maxLength={100}
onChangeText={(text) => setEmail(text)}
onSubmitEditing={() =>
passwordInput.current.focus()
}
/>
<SnowInput
placeholder={translate('login.password')}
secureTextEntry
maxLength={100}
ref={passwordInput}
onChangeText={(text) => setPassword(text)}
onSubmitEditing={() => handleLogin()}
/>
</FormSeparator>
<FormSeparator>
<Touch onPress={() => handleLogin()}>
<SnowButton>
<Label>{translate('login.loginbutton')}</Label>
</SnowButton>
</Touch>
</FormSeparator>
<TransparentButton
onPress={() => navigation.navigate('ForgetPwd')}
>
<LabelVisible>
{translate('login.forgetbutton')}
</LabelVisible>
</TransparentButton>
<ButtonBack onPress={() => navigation.goBack()}>
<Feather
name='chevron-left'
size={scale(40)}
color='#ffffff'
/>
</ButtonBack>
</KeyboardScrollView>
<CoolAlert
show={showAlert}
showProgress={showProgressBar}
title={
showProgressBar
? translate('login.awesomeAlert.accessing')
: null
}
closeOnTouchOutside={!showProgressBar}
closeOnHardwareBackPress={false}
showConfirmButton={!showProgressBar}
/>
</GradientBackground>
</>
)
}