react-native-elements#Text TypeScript Examples
The following examples show how to use
react-native-elements#Text.
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: index.tsx From SQUID with MIT License | 6 votes |
RiskLabel = ({ qr, qrState }: { qr: SelfQR, qrState: QR_STATE, onRefreshQR: any }) => {
const color = qr
? qr.getStatusColor() : qrState === QR_STATE.NOT_VERIFIED || qrState === QR_STATE.FAILED
? COLORS.ORANGE_2 : COLORS.GRAY_2
const label = qr ? qr.getLabel() : qrState === QR_STATE.NOT_VERIFIED
? I18n.t('undetermined_risk') : qrState === QR_STATE.LOADING
? I18n.t('wait_a_moment') : qrState === QR_STATE.FAILED
? I18n.t('undetermined_risk') : ''
return (
<View style={{ backgroundColor: 'white' }} >
<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
<View>
<Text
style={{
fontFamily: FONT_BOLD,
fontSize: FONT_SIZES[700],
color,
alignSelf: 'center',
}}
>
{label}
</Text>
</View>
</View>
</View>
)
}
Example #2
Source File: ProfileScreen.tsx From magento_react_native_graphql with MIT License | 6 votes |
ProfileScreen = ({ navigation }: Props): React.ReactElement => {
const { getCustomer, data, loading, error } = useCustomer();
const { logout } = useLogout();
useEffect(() => {
getCustomer();
}, []);
const handleLogout = () => {
logout();
navigation.jumpTo(Routes.NAVIGATION_TO_HOME_SCREEN);
};
if (error?.message) {
return (
<View>
<Text>{error.message}</Text>
<Button title={translate('common.logout')} onPress={handleLogout} />
</View>
);
}
return (
<GenericTemplate loading={loading}>
<Text>
{translate('profileScreen.greeting', {
name: data?.customer?.firstName ?? translate('common.user'),
})}
</Text>
<Button title={translate('common.logout')} onPress={handleLogout} />
</GenericTemplate>
);
}
Example #3
Source File: CreateAccount.tsx From hive-keychain-mobile with MIT License | 6 votes |
CreateAccount = () => {
return (
<Background containerStyle={styles.container}>
<Text h1 style={styles.text}>
Coming Soon ...
</Text>
</Background>
);
}
Example #4
Source File: CartFooter.tsx From magento_react_native_graphql with MIT License | 6 votes |
CartFooter = ({
grandTotal,
handlePlaceOrder,
}: Props): React.ReactElement => {
const { theme } = useContext(ThemeContext);
const containerStyle = useMemo(
() => ({
backgroundColor: theme.colors?.white,
borderColor: theme.colors?.divider,
}),
[theme],
);
return (
<View style={[styles.container, containerStyle]}>
{grandTotal && (
<Text h4>{`${translate('common.total')} : ${formatPrice(
grandTotal,
)}`}</Text>
)}
<Button
containerStyle={styles.placeOrder}
title={translate('cartScreen.placeOrderButton')}
onPress={handlePlaceOrder}
/>
</View>
);
}
Example #5
Source File: ProductListItem.tsx From magento_react_native_graphql with MIT License | 6 votes |
ProductListItem = ({
item,
index,
horizontalMode = false,
onPress,
}: Props): React.ReactElement => {
const { theme } = useContext(ThemeContext);
const renderImage = () => {
const uri = `${item.smallImage.url}?width=${COLUMN_WIDTH}`;
return <Image source={{ uri }} style={styles.image} />;
};
return (
<TouchableOpacity onPress={() => onPress(index)}>
<View
style={[
styles.container,
{
borderColor: theme.colors?.divider,
backgroundColor: theme.colors?.white,
},
horizontalMode && styles.topBorder,
(horizontalMode || index % 2 !== 0) && styles.leftBorder,
]}
>
{renderImage()}
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.price}>
{formatPrice(item.priceRange.maximumPrice.finalPrice)}
</Text>
</View>
</TouchableOpacity>
);
}
Example #6
Source File: ConfigurableProductOptions.tsx From magento_react_native_graphql with MIT License | 6 votes |
ConfigurableProductOptions: React.FC<Props> = ({
options,
selectedConfigurableProductOptions,
handleSelectedConfigurableOptions,
}) => {
const renderOption = (item: ConfigurableOptionType) => (
<View key={String(item.id)} style={styles.container}>
<Text h3 h3Style={styles.label}>
{item.label}
</Text>
<ConfigurableOptionValues
values={item.values}
optionCode={item.attributeCode}
selectedIndex={selectedConfigurableProductOptions[item.attributeCode]}
handleSelectedConfigurableOptions={handleSelectedConfigurableOptions}
/>
</View>
);
return (
<>
<Divider style={styles.divider} />
{options?.map(renderOption)}
<Divider />
</>
);
}
Example #7
Source File: GenericTemplate.tsx From magento_react_native_graphql with MIT License | 6 votes |
GenericTemplate = ({
children,
footer,
scrollable = false,
loading = false,
errorMessage,
style = {},
}: Props): React.ReactElement => {
const ViewGroup = scrollable ? ScrollView : View;
const renderLoader = () =>
loading && (
<View style={styles.center}>
<Spinner />
</View>
);
const renderError = () =>
!loading &&
!!errorMessage && (
<View style={styles.center}>
<Text>{errorMessage}</Text>
</View>
);
const renderContent = () => !loading && !errorMessage && children;
return (
<>
<ViewGroup style={[styles.container, style]}>
{renderLoader()}
{renderError()}
{renderContent()}
</ViewGroup>
{!loading && footer}
</>
);
}
Example #8
Source File: ResponseSuccessOverlay.tsx From react-native-network-client with Apache License 2.0 | 5 votes |
ResponseSuccessOverlay = ({
response,
visible,
setVisible,
}: ResponseSuccessOverlayProps) => {
const hide = () => setVisible(false);
return (
<Overlay
isVisible={visible}
onBackdropPress={hide}
overlayStyle={{ marginHorizontal: 20, marginVertical: 40 }}
testID="response_success_overlay"
>
<>
<Button title="Close" onPress={hide} />
<Text h4>OK</Text>
<Text testID="response_success_overlay.success.ok.text">
{response?.ok.toString()}
</Text>
<Divider />
<Text h4>Code</Text>
<Text testID="response_success_overlay.success.code.text">
{response?.code}
</Text>
<Divider />
{Boolean(response?.redirectUrls?.length) && (
<>
<Text h4>Redirect URLs</Text>
<Text testID="response_success_overlay.success.redirect_urls.text">
{response!.redirectUrls!.join(", ")}
</Text>
<Divider />
</>
)}
<Text h4>Retries Exhausted?</Text>
<Text testID="response_success_overlay.success.retries_exhausted.text">
{response?.hasOwnProperty("retriesExhausted")
? response.retriesExhausted!.toString()
: "null"}
</Text>
<Divider />
<Text h4>Headers</Text>
<ScrollView>
<Text testID="response_success_overlay.success.headers.text">
{JSON.stringify(response?.headers, null, 2)}
</Text>
</ScrollView>
<Divider />
<Text h4>Data</Text>
<ScrollView>
<Text testID="response_success_overlay.success.data.text">
{JSON.stringify(response?.data, null, 2)}
</Text>
</ScrollView>
</>
</Overlay>
);
}
Example #9
Source File: ConfigurableOptionValues.tsx From magento_react_native_graphql with MIT License | 5 votes |
ConfigurableOptionValues = ({
values,
optionCode,
selectedIndex,
handleSelectedConfigurableOptions,
}: Props): React.ReactElement => {
const { theme } = useContext(ThemeContext);
const renderValue = (value: ConfigurableProductOptionValueType) => {
const selected = selectedIndex === value.valueIndex;
switch (value.swatchData.__typename) {
case 'ColorSwatchData': {
return (
<>
<View
style={{
width:
DIMENS.productDetailScreen.configurableOptionValueBoxSize,
height:
DIMENS.productDetailScreen.configurableOptionValueBoxSize,
backgroundColor: value.swatchData.value,
}}
/>
{selected ? (
<View style={styles.selectedColor}>
<Icon type="ionicon" name="checkmark" size={24} />
</View>
) : null}
</>
);
}
case 'TextSwatchData': {
return (
<View
style={[
styles.selectedText,
{
backgroundColor: selected
? theme.colors?.black
: theme.colors?.white,
},
]}
>
<Text
style={{
color: selected ? theme.colors?.white : theme.colors?.black,
}}
>
{value.swatchData.value}
</Text>
</View>
);
}
default: {
return null;
}
}
};
return (
<View style={styles.container}>
{values.map(value => (
<TouchableOpacity
key={String(value.valueIndex)}
onPress={() =>
handleSelectedConfigurableOptions(optionCode, value.valueIndex)
}
>
<View style={styles.valueContainer}>{renderValue(value)}</View>
</TouchableOpacity>
))}
</View>
);
}
Example #10
Source File: FeaturedProductList.tsx From magento_react_native_graphql with MIT License | 5 votes |
FeaturedProductList = ({
name,
categoryId,
}: Props): React.ReactElement => {
const { data, networkStatus, error } = useCategoryProducts({ categoryId });
const { theme } = useContext(ThemeContext);
const navigation = useNavigation();
const onProductItemClicked = (index: number) => {
if (data?.products?.items) {
navigation.navigate(Routes.NAVIGATION_TO_PRODUCT_DETAILS_SCREEN, {
name: data.products.items[index].name,
sku: data.products.items[index].sku,
});
}
};
const renderItem = ({
item,
index,
}: {
item: ProductInListType;
index: number;
}) => {
return (
<ProductListItem
item={item}
index={index}
horizontalMode
onPress={onProductItemClicked}
/>
);
};
if (error?.message) {
return (
<View>
<Text>{error.message}</Text>
</View>
);
}
if (networkStatus === NetworkStatus.loading) {
return (
<View style={styles.loadingBox(theme)}>
<Spinner />
</View>
);
}
return (
<View style={styles.container(theme)}>
{name && (
<Text h2 h2Style={styles.title}>
{name}
</Text>
)}
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={data?.products?.items ?? []}
renderItem={renderItem}
keyExtractor={item => `productListItem${item.sku}`}
/>
</View>
);
}
Example #11
Source File: CartScreen.tsx From magento_react_native_graphql with MIT License | 5 votes |
CartScreen = ({ navigation }: Props): React.ReactElement => {
const { cartData, cartLoading, cartError } = useCart();
const handleOnPress = (index: number) => console.log(index);
const handleRemoveItem = (index: number) => console.log(index);
const handlePlaceOrder = () => console.log('handle place order');
const renderEmptyList = () =>
(!cartLoading && (
<View style={styles.emptyContainer}>
<Text h4Style={styles.centerText} h4>
{translate('cartScreen.cartEmptyTitle')}
</Text>
<Text style={styles.centerText}>
{translate('cartScreen.cartEmptyMessage')}
</Text>
</View>
)) || <></>;
return (
<GenericTemplate
loading={cartLoading}
errorMessage={cartError?.message}
footer={
(cartData?.customerCart?.items?.length ?? 0) > 0 && (
<CartFooter
grandTotal={cartData?.customerCart?.prices.grandTotal}
handlePlaceOrder={handlePlaceOrder}
/>
)
}
>
<FlatList
data={cartData?.customerCart?.items ?? []}
renderItem={({ item, index }) => (
<CartListItem
item={item}
index={index}
onPress={handleOnPress}
onRemovePress={handleRemoveItem}
/>
)}
contentContainerStyle={
cartData?.customerCart?.items.length === 0 && styles.fullScreen
}
keyExtractor={item => String(item.id)}
ListEmptyComponent={renderEmptyList}
/>
</GenericTemplate>
);
}
Example #12
Source File: MediaGallery.tsx From magento_react_native_graphql with MIT License | 5 votes |
MediaGallery = ({
items,
resizeMode = 'contain',
containerStyle = {},
width = DIMENS.common.WINDOW_WIDTH,
height = DIMENS.common.WINDOW_WIDTH,
}: Props): React.ReactElement => {
const [currentPage, setCurrentPage] = useState<number>(1);
const imageDimension = useMemo(() => ({ width, height }), [width, height]);
const onMomentumScrollEnd = event => {
const contentOffset = event.nativeEvent.contentOffset.x;
const width = event.nativeEvent.layoutMeasurement.width;
const currentNumber = Math.floor(contentOffset / width) + 1;
setCurrentPage(currentNumber);
};
const renderItem = ({ item }: { item: MediaGalleryItemType }) => {
return (
<View>
<Image
source={{ uri: item.url }}
resizeMode={resizeMode}
style={imageDimension}
/>
</View>
);
};
return (
<View style={[styles.container, containerStyle]}>
<FlatList
horizontal
pagingEnabled
data={items}
keyExtractor={(item, index) => `mediaGalleryItem#${index}`}
renderItem={renderItem}
onMomentumScrollEnd={onMomentumScrollEnd}
showsHorizontalScrollIndicator={false}
/>
<Text style={styles.pagination}>{`${currentPage}/${items.length}`}</Text>
</View>
);
}
Example #13
Source File: ResponseErrorOverlay.tsx From react-native-network-client with Apache License 2.0 | 5 votes |
ResponseErrorOverlay = ({
error,
visible,
setVisible,
}: ResponseErrorOverlayProps) => {
const hide = () => setVisible(false);
return (
<Overlay
isVisible={visible}
onBackdropPress={hide}
overlayStyle={{ marginHorizontal: 20, marginVertical: 40 }}
testID="response_error_overlay"
>
<>
<Button title="Close" onPress={hide} />
<Text h2 style={{ alignSelf: "center" }}>
Error
</Text>
<Text h4>Code</Text>
<Text testID="response_error_overlay.error.code.text">
{error?.code}
</Text>
<Divider />
<Text h4>Message</Text>
<Text testID="response_error_overlay.error.message.text">
{error?.message}
</Text>
<Divider />
<Text h4>Domain</Text>
<Text testID="response_error_overlay.error.domain.text">
{error?.domain}
</Text>
<Divider />
<Text h4>User Info</Text>
<Text testID="response_error_overlay.error.user_info.text">
{JSON.stringify(error?.userInfo)}
</Text>
<Divider />
<Text h4>Native Stack</Text>
<ScrollView>
<Text testID="response_error_overlay.error.native_stack.text">
{JSON.stringify(
error?.nativeStackAndroid || error?.nativeStackIOS
)}
</Text>
</ScrollView>
</>
</Overlay>
);
}
Example #14
Source File: AddAccountByKey.tsx From hive-keychain-mobile with MIT License | 5 votes |
AddAccountByKey = ({
addAccount,
navigation,
route,
}: PropsFromRedux &
(AddAccNavigationProps | AddAccFromWalletNavigationProps)) => {
const [account, setAccount] = useState('');
const [key, setKey] = useState('');
useLockedPortrait(navigation);
const onImportKeys = async () => {
try {
const keys = await validateNewAccount(account, key);
if (keys) {
const wallet = route.params ? route.params.wallet : false;
addAccount(account, keys, wallet, false);
} else {
Toast.show(translate('toast.error_add_account'), Toast.LONG);
}
} catch (e) {
Toast.show((e as any).message || e, Toast.LONG);
}
};
const {height} = useWindowDimensions();
return (
<Background>
<>
<StatusBar backgroundColor="black" />
<View style={styles.container}>
<Separator height={height / 7.5} />
<TitleLogo />
<Separator height={height / 15} />
<Text style={styles.text}>{translate('addAccountByKey.text')}</Text>
<Separator height={height / 15} />
<CustomInput
placeholder={translate('common.username').toUpperCase()}
leftIcon={<UserLogo />}
autoCapitalize="none"
value={account}
onChangeText={setAccount}
/>
<Separator height={height / 15} />
<CustomInput
placeholder={translate('common.privateKey').toUpperCase()}
autoCapitalize="characters"
leftIcon={<KeyLogo />}
rightIcon={
<TouchableOpacity
onPress={() => {
(navigation as AddAccFromWalletNavigation).navigate(
'ScanQRScreen',
{wallet: true},
);
}}>
<QRLogo />
</TouchableOpacity>
}
value={key}
onChangeText={setKey}
/>
<Separator height={height / 7.5} />
<Button
title={translate('common.import').toUpperCase()}
onPress={onImportKeys}
/>
</View>
</>
</Background>
);
}
Example #15
Source File: index.tsx From SQUID with MIT License | 5 votes |
MainApp = () => {
const inset = useSafeArea()
const { qrData, qrState, error, refreshQR } = useSelfQR()
const appVersion = DeviceInfo.getVersion();
const [location, setLocation] = useState('')
const getBeacon = async () => {
//TEST
// let lc = 'ห้าง Tesco lotus สาขาอโศก ตรงข้ามห้างดัง ตรงรถไฟฟ้ามหานครอมรรัตน'
// AsyncStorage.setItem('beacon-location', lc);
let beacon = await AsyncStorage.getItem('beacon-location');
if (beacon) {
setLocation(beacon)
}
}
useEffect(() => {
pushNotification.requestPermissions()
getBeacon()
}, [])
return (
<View
style={[styles.container, { paddingTop: inset.top, paddingBottom: 12 }]}
>
<StatusBar
barStyle={qrData?.getTagColor() ? 'light-content' : 'dark-content'}
backgroundColor={qrData?.getTagColor() ? COLORS.BLACK_1 : COLORS.PRIMARY_LIGHT}
/>
<QRBackground qr={qrData} />
<QRAvatar qr={qrData} qrState={qrState} />
<QRTagLabel qr={qrData} />
<Beancon location={location} />
<QRHeader qr={qrData} qrState={qrState} onRefreshQR={refreshQR} />
<QRSection qr={qrData} qrState={qrState} onRefreshQR={refreshQR} />
<QRFooter />
<Text
style={{
position: 'absolute',
bottom: 0,
right: 0,
paddingRight: 5,
fontFamily: FONT_FAMILY,
fontSize: FONT_SIZES[500] * 0.85,
textAlign: 'right',
color: '#0FA7DC'
}}
>
V {appVersion}
</Text>
</View>
)
}
Example #16
Source File: SearchScreen.tsx From magento_react_native_graphql with MIT License | 4 votes |
SearchScreen = ({ navigation }: Props): React.ReactElement => {
const {
searchText,
handleChange,
networkStatus,
called,
loadMore,
data: { products: { items: products = [] } = {} } = {},
} = useSearch();
const { theme } = useContext(ThemeContext);
const loadingProps = useMemo(() => ({ color: theme.colors?.primary }), [
theme,
]);
const handleBackPress = () => navigation.pop();
const onProductItemClicked = (index: number) => {
navigation.navigate(Routes.NAVIGATION_TO_PRODUCT_DETAILS_SCREEN, {
name: products[index].name,
sku: products[index].sku,
});
};
const renderItem = ({
item,
index,
}: {
item: ProductInListType;
index: number;
}) => {
return (
<ProductListItem
item={item}
index={index}
onPress={onProductItemClicked}
/>
);
};
// FIXME: Don't show when previous search result was empty, and user is typing
// create a separate state
const renderEmptyComponent = () =>
(searchText.length >= LIMITS.searchTextMinLength &&
products.length === 0 &&
called &&
networkStatus !== NetworkStatus.loading && (
<View style={styles.center}>
<Text>
{translate('searchScreen.noProductsFound', { searchText })}
</Text>
</View>
)) || <></>;
const renderFooterComponent = () =>
(networkStatus === NetworkStatus.fetchMore && (
<View style={styles.footerContainer}>
<Spinner />
</View>
)) || <></>;
return (
<GenericTemplate>
<SearchBar
placeholder={translate('searchScreen.searchBarHint')}
onChangeText={handleChange}
value={searchText}
showLoading={networkStatus === NetworkStatus.loading}
searchIcon={{
name: 'arrow-back',
onPress: handleBackPress,
}}
loadingProps={loadingProps}
containerStyle={styles.searchBarContainer}
/>
<FlatList
numColumns={2}
data={products}
renderItem={renderItem}
keyExtractor={item => `productListItem${item.sku}`}
ListEmptyComponent={renderEmptyComponent}
ListFooterComponent={renderFooterComponent}
onEndReached={loadMore}
/>
</GenericTemplate>
);
}
Example #17
Source File: ProductDetailsScreen.tsx From magento_react_native_graphql with MIT License | 4 votes |
ProductDetailsScreen = ({
navigation,
route: {
params: { sku },
},
}: Props): React.ReactElement => {
const {
error,
loading,
priceRange,
mediaGallery,
productDetails,
selectedConfigurableProductOptions,
handleSelectedConfigurableOptions,
} = useProductDetails({
sku,
});
const {
cartCount,
isLoggedIn,
addProductsToCart,
addToCartLoading,
} = useCart();
const { theme } = useContext(ThemeContext);
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<CustomHeaderButtons>
<CustomHeaderItem
title={translate('common.cart')}
iconName="shopping-cart"
onPress={() =>
navigation.navigate(Routes.NAVIGATION_TO_CART_SCREEN)
}
/>
{cartCount !== '' && (
<Badge
value={cartCount}
status="error"
textStyle={styles.badgeText}
containerStyle={styles.badge}
/>
)}
</CustomHeaderButtons>
),
});
}, [navigation, cartCount]);
const handleAddToCart = () => {
if (!isLoggedIn) {
showLoginPrompt(
translate('productDetailsScreen.guestUserPromptMessage'),
navigation,
);
return;
}
if (
productDetails?.type === ProductTypeEnum.SIMPLE ||
productDetails?.type === ProductTypeEnum.GROUPED
) {
addProductsToCart({
quantity: 1,
sku: productDetails.sku,
});
} else {
showMessage({
message: translate('common.attention'),
description: translate('productDetailsScreen.productTypeNotSupported'),
type: 'warning',
});
}
};
const renderPrice = (): React.ReactNode => {
if (productDetails && priceRange) {
return (
<Text h2 style={styles.price}>
{formatPrice(priceRange.maximumPrice.finalPrice)}
</Text>
);
}
return null;
};
const renderOptions = (): React.ReactNode => {
if (productDetails?.type === ProductTypeEnum.CONFIGURED) {
return (
<ConfigurableProductOptions
options={productDetails?.configurableOptions}
selectedConfigurableProductOptions={
selectedConfigurableProductOptions
}
handleSelectedConfigurableOptions={handleSelectedConfigurableOptions}
/>
);
}
return null;
};
const renderDiscription = (): React.ReactNode => {
if (productDetails) {
return (
<HTML
source={{ html: productDetails.description.html }}
contentWidth={Dimensions.get('window').width}
containerStyle={styles.description}
baseFontStyle={{ color: theme.colors?.black }}
/>
);
}
return null;
};
return (
<GenericTemplate
scrollable
loading={loading}
errorMessage={error?.message}
footer={
<Button
loading={addToCartLoading}
containerStyle={styles.noBorderRadius}
buttonStyle={styles.noBorderRadius}
title={translate('productDetailsScreen.addToCart')}
onPress={handleAddToCart}
/>
}
>
<View>
<MediaGallery items={mediaGallery} />
<Text h1 style={styles.name}>
{productDetails?.name}
</Text>
{renderPrice()}
{renderOptions()}
{renderDiscription()}
</View>
</GenericTemplate>
);
}
Example #18
Source File: WebSocketClientScreen.tsx From react-native-network-client with Apache License 2.0 | 4 votes |
export default function WebSocketClientScreen({
route,
}: WebSocketClientScreenProps) {
const {
item: { client },
} = route.params;
const [connected, setConnected] = useState(false);
const [message, setMessage] = useState(
JSON.stringify({
seq: 1,
action: "user_typing",
data: { channel_id: "4dtzmswn93f68fkd97eeafm6xc" },
})
);
const [event, setEvent] = useState<string>("");
useEffect(() => {
client.onOpen((event: WebSocketEvent) => {
setConnected(true);
parseAndSetEvent(event);
});
client.onClose((event: WebSocketEvent) => {
setConnected(false);
parseAndSetEvent(event);
});
client.onError((event: WebSocketEvent) => {
parseAndSetEvent(event);
});
client.onMessage((event: WebSocketEvent) => {
parseAndSetEvent(event);
});
}, []);
const parseAndSetEvent = (event: WebSocketEvent) => {
setEvent(JSON.stringify(event, null, 2));
};
const send = () => {
client.send(message);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<Input
label="Message"
multiline={true}
numberOfLines={10}
placeholder={JSON.stringify({
action: "",
seq: 2,
data: { channel_id: "" },
})}
onChangeText={setMessage}
testID="websocket_client.message.input"
value={message}
/>
<Button
title="Send"
onPress={send}
style={{ padding: 10 }}
disabled={!Boolean(message) || !connected}
/>
<Button
title={connected ? "Disconnect" : "Connect"}
onPress={connected ? client.close : client.open}
style={{ padding: 10 }}
/>
<Input
placeholder="Received"
disabled={true}
style={{ fontWeight: "bold", fontSize: 17, opacity: 1 }}
containerStyle={{ height: 50 }}
inputContainerStyle={{
borderColor: "rgba(255,255,255,0)",
}}
/>
<ScrollView style={{ marginHorizontal: 20 }}>
<Text testID="websocket_client.event.text">{event}</Text>
</ScrollView>
</SafeAreaView>
);
}
Example #19
Source File: P12Inputs.tsx From react-native-network-client with Apache License 2.0 | 4 votes |
P12Inputs = (props: P12InputsProps) => {
const [url, setUrl] = useState("");
const hasPhotoLibraryPermissions = async () => {
const permission =
Platform.OS === "ios"
? PERMISSIONS.IOS.PHOTO_LIBRARY
: PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE;
let result = await check(permission);
if (result === RESULTS.GRANTED || result === RESULTS.LIMITED) {
return true;
} else if (
result !== RESULTS.BLOCKED &&
result !== RESULTS.UNAVAILABLE
) {
await request(permission);
hasPhotoLibraryPermissions();
}
console.log(result);
return false;
};
const pickCertificate = async () => {
const hasPermission = await hasPhotoLibraryPermissions();
if (hasPermission) {
try {
const result = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
if (result.fileCopyUri) {
props.onSelectP12(result.fileCopyUri);
}
} catch (err) {
if (DocumentPicker.isCancel(err as Error)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
}
};
const downloadCertificate = async () => {
const file: File = await downloadToNativeFile(url, clientCertP12);
props.onSelectP12(`${file.uri}`);
};
const clearP12Configuration = () => {
props.onSelectP12("");
props.onPasswordChange(undefined);
};
const buttons = [
{ title: "Select", onPress: pickCertificate },
{ title: "Download", onPress: downloadCertificate },
];
const onButtonPress = (index: number) => buttons[index].onPress();
const rightIcon = (
<View style={{ width: 250 }}>
{Boolean(props.path) ? (
<View style={{ flexDirection: "column", height: 50 }}>
<View style={{ flexDirection: "row" }}>
<View style={{ flex: 1 }}>
<Text
numberOfLines={2}
ellipsizeMode="middle"
testID="p12_inputs.path.text"
>
{props.path}
</Text>
</View>
<Button
type="clear"
icon={<Icon name="cancel" size={24} />}
onPress={clearP12Configuration}
/>
</View>
<Input
placeholder="password"
value={props.password}
onChangeText={props.onPasswordChange}
autoCapitalize="none"
testID="p12_inputs.password.input"
/>
</View>
) : (
<Input
placeholder="Download URL"
onChangeText={setUrl}
autoCapitalize="none"
testID="p12_inputs.download_url.input"
/>
)}
</View>
);
return (
<>
<Input
placeholder={props.title}
disabled={true}
style={{
fontWeight: "bold",
fontSize: 17,
opacity: 1,
}}
inputContainerStyle={{
borderColor: "rgba(255,255,255,0)",
}}
rightIcon={rightIcon}
labelStyle={{ flex: 12, flexWrap: "wrap" }}
/>
{Boolean(!props.path) ? (
<View
style={{
flex: 1,
alignItems: "flex-end",
marginTop: -30,
paddingRight: 4,
paddingBottom: 10,
}}
>
<ButtonGroup
containerStyle={{ width: 200 }}
buttons={buttons.map((button) => button.title)}
onPress={onButtonPress}
/>
</View>
) : (
<View style={{ height: 20 }} />
)}
</>
);
}
Example #20
Source File: index.tsx From hive-keychain-mobile with MIT License | 4 votes |
PinCode = ({
children,
signup = false,
title,
confirm,
submit,
navigation,
}: Props) => {
interface PinItem {
refNumber: number;
number?: number;
helper?: string;
back?: boolean;
}
const config: PinItem[][] = [
[
{refNumber: 1, number: 1},
{refNumber: 2, number: 2, helper: 'A B C'},
{refNumber: 3, number: 3, helper: 'D E F'},
],
[
{refNumber: 4, number: 4, helper: 'G H I'},
{refNumber: 5, number: 5, helper: 'J K L'},
{refNumber: 6, number: 6, helper: 'M N O'},
],
[
{refNumber: 7, number: 7, helper: 'P Q R S'},
{refNumber: 8, number: 8, helper: 'T U V'},
{refNumber: 9, number: 9, helper: 'W X Y Z'},
],
[{refNumber: 10}, {refNumber: 11, number: 0}, {refNumber: 12, back: true}],
];
const [code, setCode] = useState<string[]>([]);
const [confirmCode, setConfirmCode] = useState<string[]>([]);
const [step, setStep] = useState(0);
const [visible, setVisible] = useState(false);
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
setStep(0);
setCode([]);
setConfirmCode([]);
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
useEffect(() => {
if (code.length === 6) {
if (signup) {
setStep(1);
} else {
submit(code.join(''), (unsafeBiometrics) => {
if (unsafeBiometrics) {
setVisible(true);
}
setCode([]);
});
}
}
if (confirmCode.length === 6) {
if (
!(
confirmCode.length === code.length &&
confirmCode.every((value, index) => value === code[index])
)
) {
Toast.show(translate('toast.noMatch'));
setStep(0);
setCode([]);
setConfirmCode([]);
} else {
submit(code.join(''));
}
}
}, [code, confirmCode, signup, submit]);
const onPressElement = (number: number | undefined, back?: boolean) => {
if (step === 0) {
if ((number || number === 0) && code.length !== 6) {
setCode([...code, number + '']);
}
if (back) {
setCode(code.slice(0, -1));
}
} else {
if ((number || number === 0) && confirmCode.length !== 6) {
setConfirmCode([...confirmCode, number + '']);
}
if (back) {
setConfirmCode(confirmCode.slice(0, -1));
}
}
};
let h4;
if (!signup || step === 0) {
h4 = title;
} else {
h4 = confirm;
}
return (
<View style={styles.bgd}>
<Separator />
{children}
<Separator />
<Text h4 style={styles.sub}>
{h4}
</Text>
<Separator height={30} />
<PinCompletionIndicator code={step === 0 ? code : confirmCode} />
<Separator height={50} />
<View style={styles.container}>
{config.map((row, i) => (
<View key={i.toString()} style={styles.row}>
{row.map((elt, j: number) => (
<PinElement
key={j.toString()}
onPressElement={onPressElement}
{...elt}
/>
))}
</View>
))}
</View>
{false && (
<CustomModal
bottomHalf={true}
outsideClick={() => {
setVisible(false);
}}>
<Text style={styles.h4}>
{translate('components.pinCode.unsupportedBiometrics.title')}
</Text>
<Separator />
<Text>
{translate('components.pinCode.unsupportedBiometrics.text1')}
</Text>
<Separator />
<Text>
{translate('components.pinCode.unsupportedBiometrics.text2')}
</Text>
<Separator height={50} />
<EllipticButton
title={translate('components.pinCode.unsupportedBiometrics.button')}
onPress={() => {
IntentLauncher.startActivity({
action: 'android.settings.SECURITY_SETTINGS',
});
setVisible(false);
}}
/>
</CustomModal>
)}
</View>
);
}
Example #21
Source File: index.tsx From SQUID with MIT License | 4 votes |
MainApp = () => {
const inset = useSafeArea()
const { qrData, qrState, refreshQR } = useSelfQR()
const { beaconLocationName, enable, disable, isServiceEnabled } = useContactTracer()
const appVersion = DeviceInfo.getVersion();
const [location, setLocation] = useState('')
const popupRef = useRef<NotificationPopup | any>()
const smallDevice = Dimensions.get('window').height < 600
useEffect(() => {
setLocation(beaconLocationName.name)
if (location && popupRef && popupRef.current) {
popupRef.current.show({
slideOutTime: 20 * 1000
})
}
}, [beaconLocationName])
useEffect(() => {
pushNotification.requestPermissions()
}, [])
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#F9F9F9'}}>
<View
style={[styles.container, { paddingTop: inset.top, paddingBottom: inset.bottom }]}
>
<StatusBar
barStyle={qrData?.getTagColor() ? 'light-content' : 'dark-content'}
backgroundColor={qrData?.getTagColor() ? COLORS.BLACK_1 : COLORS.PRIMARY_LIGHT}
/>
<View style={styles.containerTop}>
<View style={styles.containerHeader}>
<TouchableOpacity style={styles.circularButton} onPress={refreshQR}>
<FontAwesome name="refresh" color={COLORS.GRAY_4} size={24} style={{ marginLeft: 10 }} />
</TouchableOpacity>
<Text style={styles.textHeader}>
{qrData && (`${qrData.getCreatedDate().format(I18n.t('fully_date'))}`)}
</Text>
<TouchableOpacity onPress={() => {
isServiceEnabled ? disable() : enable()
}}>
<FontAwesome
name="bluetooth-b"
color={COLORS.GRAY_4}
size={24}
style={{ marginRight: 10 }}
/>
{isServiceEnabled ? (
<View style={{
width: 10,
height: 10,
backgroundColor: COLORS.GREEN,
position: 'absolute',
borderRadius: 50,
borderTopWidth: Math.floor((4 / 100) * 24),
right: Math.floor((8 / 100) * 50)
}} />
) : void 0}
</TouchableOpacity>
</View>
<View style={styles.containerCard}>
<View style={styles.card}>
<View style={styles.cardHeader}>
<View style={{ flex: 1, padding: 10 }}>
<AvatarProfile qr={qrData} qrState={qrState} />
</View>
<View style={{ flex: 2, alignContent: 'flex-start' }}>
<RiskLabel qr={qrData} qrState={qrState} onRefreshQR={refreshQR} />
</View>
</View>
<View style={{ flex: 3 }}>
<QRImage qr={qrData} qrState={qrState} onRefreshQR={refreshQR} />
</View>
<View style={styles.cardFooter}>
<Image
source={require('./logo-pin-morchana.png')}
style={{
height: smallDevice ? 20 : 30,
width: (smallDevice ? 20 : 30) * (260 / 140),
}}
resizeMode="contain"
/>
<Text style={styles.textVersion}>
แอปพลิเคชันหมอชนะ <Text style={{ color: '#0FA7DC', fontSize: FONT_SIZES[600] * 0.85, fontFamily: FONT_FAMILY }}>V{appVersion}</Text>
</Text>
</View>
</View>
</View>
</View>
<NotificationPopup
ref={popupRef}
renderPopupContent={props => (
<BeaconFoundPopupContent {...props} result={location} />
)}
/>
</View>
</SafeAreaView>
)
}