react-native#useWindowDimensions TypeScript Examples
The following examples show how to use
react-native#useWindowDimensions.
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: Introduction.tsx From hive-keychain-mobile with MIT License | 6 votes |
Introduction = ({navigation}: IntroductionNavProp) => {
const {height, width} = useWindowDimensions();
const styles = getDimensionedStyles({height, width});
return (
<Background>
<>
<Separator height={height / 15} />
<KeychainLogo {...styles.image} />
<Separator height={height / 20} />
<GradientEllipse style={styles.gradient} dotColor="red">
<Text style={styles.text}>{translate('intro.text')}</Text>
</GradientEllipse>
<GradientEllipse style={styles.gradient} dotColor="white">
<Text style={styles.text}>{translate('intro.manage')}</Text>
</GradientEllipse>
<Separator height={height / 7.5} />
<EllipticButton
title={translate('intro.existingAccount')}
onPress={() => {
navigation.navigate('SignupScreen');
}}
/>
<Separator height={height / 20} />
<EllipticButton
title={translate('intro.createAccount')}
onPress={() => {
Linking.canOpenURL(hiveConfig.CREATE_ACCOUNT_URL).then(
(supported) => {
if (supported) {
Linking.openURL(hiveConfig.CREATE_ACCOUNT_URL);
}
},
);
}}
/>
</>
</Background>
);
}
Example #2
Source File: ForgotPIN.tsx From hive-keychain-mobile with MIT License | 6 votes |
ForgotPIN = ({forgetAccounts}: PropsFromRedux) => {
const {width, height} = useWindowDimensions();
const styles = getDimensionedStyles({width});
return (
<View>
<Text style={styles.h4}>{translate('components.forgotPIN.title')}</Text>
<Separator />
<Text>{translate('components.forgotPIN.text')}</Text>
<Separator height={height / 15} />
<EllipticButton
title={translate('components.forgotPIN.button')}
onPress={() => {
goBack();
forgetAccounts();
}}
/>
</View>
);
}
Example #3
Source File: Transfer.tsx From hive-keychain-mobile with MIT License | 6 votes |
Transfer = ({transaction, user, locale, token = false}: Props) => {
const [toggle, setToggle] = useState(false);
const username = user.name;
const {timestamp, from, to, amount, memo} = transaction;
const other = from === username ? to : from;
const direction = from === username ? '-' : '+';
const color = direction === '+' ? '#3BB26E' : '#B9122F';
const date = new Date(
token ? (timestamp as number) * 1000 : timestamp,
).toLocaleDateString([locale], {
year: '2-digit',
month: '2-digit',
day: '2-digit',
});
const styles = getDimensionedStyles({
...useWindowDimensions(),
color,
});
return (
<TouchableOpacity
style={styles.container}
onPress={() => {
setToggle(!toggle);
}}>
<View style={styles.main}>
<View style={styles.left}>
<Text>{date}</Text>
<Text style={styles.username}>{`@${other}`}</Text>
</View>
<Text style={styles.amount}>{`${direction} ${withCommas(amount)} ${
amount.split(' ')[1]
}`}</Text>
</View>
{toggle && memo && memo.length ? <Text>{memo}</Text> : null}
</TouchableOpacity>
);
}
Example #4
Source File: PercentageDisplay.tsx From hive-keychain-mobile with MIT License | 6 votes |
PercentageDisplay = ({color, percent, name, secondary}: Props) => {
const styles = getDimensionedStyles({
color,
percent,
...useWindowDimensions(),
});
return (
<View style={styles.container}>
<View style={styles.textWrapper}>
<Text style={styles.name}>{name.toUpperCase()}</Text>
<Text style={styles.percent}>{`${percent.toFixed(0)} %`}</Text>
<Text style={styles.secondary}>{secondary}</Text>
</View>
<View style={styles.greyBar}>
<View style={styles.filler} />
</View>
</View>
);
}
Example #5
Source File: SavingsBalance.tsx From hive-keychain-mobile with MIT License | 6 votes |
SavingsBalance = ({currency, account, setMax}: Props) => {
let value: number = null;
if (currency === 'HIVE') {
value = parseFloat(account.savings_balance + '');
} else value = parseFloat(account.savings_hbd_balance + '');
const styles = getDimensionedStyles({
...useWindowDimensions(),
});
return (
<TouchableOpacity
style={styles.container}
onPress={() => {
setMax(value.toFixed(3) + '');
}}>
<View style={styles.main}>
<View style={styles.left}>
<View style={styles.logo}>
<Savings />
</View>
<Text style={styles.name}>
{translate('common.balance').toUpperCase()}
</Text>
</View>
<Text style={styles.amount}>
{formatBalance(value)}
<Text style={styles.currency}>{` ${currency}`}</Text>
</Text>
</View>
</TouchableOpacity>
);
}
Example #6
Source File: UserPicker.tsx From hive-keychain-mobile with MIT License | 6 votes |
UserPicker = ({username, accounts, onAccountSelected}: Props) => {
const {width, height} = useWindowDimensions();
const styles = getDimensionedStyles({width, height});
if (!username) {
return null;
}
return (
<View style={styles.container}>
<UserProfilePicture style={styles.image} username={username} />
<View style={styles.subContainer}>
<CustomPicker
list={accounts}
onSelected={onAccountSelected}
selectedValue={username}
prefix="@"
style={styles.picker}
prompt={translate('components.picker.prompt_user')}
/>
</View>
</View>
);
}
Example #7
Source File: index.tsx From hive-keychain-mobile with MIT License | 6 votes |
NewTab = ({
history,
favorites,
updateTabUrl,
homeRef,
accounts,
}: Props) => {
const styles = getStyles(useWindowDimensions().width);
return (
<View style={styles.container} ref={homeRef} collapsable={false}>
<View style={styles.titleContainer}>
<KeychainLogo width={45} />
<Text style={styles.title}>
KEYCHAIN <Text style={styles.home}>HOME</Text>
</Text>
</View>
<ScreenToggle
menu={[
translate('browser.home.menu.explore'),
translate('browser.home.menu.history'),
translate('browser.home.menu.favorites'),
]}
components={[
<Explore updateTabUrl={updateTabUrl} accounts={accounts} />,
<History history={history} updateTabUrl={updateTabUrl} />,
<Favorites favorites={favorites} updateTabUrl={updateTabUrl} />,
]}
toUpperCase
style={styles.sub}
/>
</View>
);
}
Example #8
Source File: DAppCard.tsx From hive-keychain-mobile with MIT License | 6 votes |
DAppCard = ({dApp, updateTabUrl}: Props) => {
const styles = getStyles(useWindowDimensions());
console.log(dApp);
return (
<TouchableOpacity
style={styles.container}
onPress={() => {
let url = dApp.url;
if (dApp.appendUsername) {
url += store.getState().activeAccount.name;
}
updateTabUrl(url);
}}>
<View style={styles.imageContainer}>
<Image style={styles.image} source={{uri: dApp.icon}} />
</View>
<Text style={styles.name}>{dApp.name}</Text>
<Text style={styles.desc}>{dApp.description}</Text>
</TouchableOpacity>
);
}
Example #9
Source File: CategoryButton.tsx From hive-keychain-mobile with MIT License | 6 votes |
CategoryButton = ({category, setCategory}: Props) => {
const styles = getStyles(useWindowDimensions());
return (
<TouchableOpacity
style={[styles.category, {backgroundColor: category.color}]}
onPress={() => {
setCategory(category.title);
}}>
<Text style={styles.text}>
{translate(`browser.home.categories.${category.title}`)}
</Text>
</TouchableOpacity>
);
}
Example #10
Source File: MarkerQR.tsx From hive-keychain-mobile with MIT License | 6 votes |
Marker = () => {
const styles = getStyles(useWindowDimensions());
return (
<View style={styles.marker}>
<View style={[styles.markerSide, styles.topLeft]}></View>
<View style={[styles.markerSide, styles.topRight]}></View>
<View style={[styles.markerSide, styles.bottomLeft]}></View>
<View style={[styles.markerSide, styles.bottomRight]}></View>
</View>
);
}
Example #11
Source File: Signup.tsx From hive-keychain-mobile with MIT License | 6 votes |
Signup = ({signUp, navigation}: Props) => {
const {width} = useWindowDimensions();
const onSubmitSignup = (pwd: string) => {
signUp(pwd);
};
return (
<Background>
<Pincode
signup
navigation={navigation}
title={translate('signup.choose')}
confirm={translate('signup.confirm')}
submit={onSubmitSignup}>
<KeychainLogo width={width * 0.25} />
</Pincode>
</Background>
);
}
Example #12
Source File: Unlock.tsx From hive-keychain-mobile with MIT License | 6 votes |
Unlock = ({unlock, navigation}: UnlockScreenProps) => {
const {width} = useWindowDimensions();
return (
<Background>
<Pincode
navigation={navigation}
title={translate('unlock.enterPIN')}
submit={unlock}>
<KeychainLogo width={width / 4} />
</Pincode>
</Background>
);
}
Example #13
Source File: App.tsx From curved-bottom-navigation-bar with MIT License | 6 votes |
export function MyTabs() {
const {width} = useWindowDimensions();
return (
<SafeAreaProvider>
<NavigationContainer>
<Tab.Navigator
tabBar={props => (
<AnimatedTabBar
tabs={tabs}
{...props}
titleShown={true}
barWidth={width - 32}
/>
)}>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen
name="NotificationScreen"
component={NotificationScreen}
/>
<Tab.Screen name="Settings" component={SettingsScreen} />
<Tab.Screen name="ProfileScreen" component={ProfileScreen} />
</Tab.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
}
Example #14
Source File: useDeviceOrientation.tsx From react-native-sdk with MIT License | 6 votes |
function useDeviceOrientation() {
const { height, width } = useWindowDimensions()
const [isPortrait, setIsPortrait] = useState<boolean>(height >= width)
useEffect(() => {
setIsPortrait(height >= width)
}, [width])
return { height, width, isPortrait }
}
Example #15
Source File: SyncComponent.tsx From solid-health with MIT License | 6 votes |
SyncComponent: FunctionComponent = () => {
const width = useWindowDimensions().width;
const status = useSyncStatus();
let progress;
if (status.maxValue == null) {
progress = 0;
} else if(status.maxValue === 0) {
progress = 1;
} else {
progress = status.value / status.maxValue;
}
return (
<View style={styles.container}>
<Text style={styles.text}>{status.description}</Text>
<ProgressBar
progress={progress}
indeterminate={status.maxValue == null}
width={width - 20}
useNativeDriver
/>
</View>
);
}
Example #16
Source File: TokenDisplay.tsx From hive-keychain-mobile with MIT License | 5 votes |
TokenDisplay = ({
name,
logo,
currency,
value,
buttons,
color,
price,
incoming,
outgoing,
amountStyle,
secondaryCurrency,
secondaryValue,
bottomLeft,
toggled,
setToggle,
}: Props) => {
const styles = getDimensionedStyles({
color,
...useWindowDimensions(),
change: price ? price.usd_24h_change! + '' : '0',
});
return (
<TouchableOpacity style={styles.container} onPress={setToggle}>
<View style={styles.main}>
<View style={styles.left}>
<View style={styles.logo}>{logo}</View>
<Text style={styles.name}>{name}</Text>
</View>
<View>
<Text style={amountStyle || styles.amount}>
{value ? formatBalance(value) : 0}
<Text style={styles.currency}>{` ${currency}`}</Text>
</Text>
{secondaryCurrency ? (
<Text style={amountStyle || styles.amount}>
{secondaryValue ? formatBalance(secondaryValue) : 0}
<Text style={styles.currency}>{` ${secondaryCurrency}`}</Text>
</Text>
) : null}
</View>
</View>
{toggled && (
<View style={[styles.row, styles.toggle]}>
{bottomLeft
? bottomLeft
: renderLeftBottom(styles, price, currency, incoming, outgoing)}
<View style={[styles.row, styles.halfLine, styles.rowReverse]}>
{buttons}
</View>
</View>
)}
</TouchableOpacity>
);
}
Example #17
Source File: Loading.tsx From hive-keychain-mobile with MIT License | 5 votes |
Loading = () => {
const {width} = useWindowDimensions();
return (
<Background containerStyle={styles.bgd}>
<KeychainLogo width={width / 2} />
</Background>
);
}
Example #18
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 #19
Source File: Cart.tsx From RNChallenge_2 with MIT License | 5 votes |
Cart = ({closeCart}: Props) => {
const insets = useSafeAreaInsets();
const [cart, setCart] = useState([]);
const {width, height} = useWindowDimensions();
useEffect(() => {
const _cart = cartItems();
setCart(_cart);
}, []);
return (
<View
style={[
styles.safeAreaView,
{
paddingTop: insets.top,
paddingBottom: insets.bottom,
},
]}>
<CartHeader onClose={() => closeCart()} />
<View style={{flex: 1}}>
<Text style={[styles.title]}>My Bag</Text>
<Animated.ScrollView
contentContainerStyle={{
paddingHorizontal: 30,
paddingTop: 10,
}}>
{cart &&
cart.map((furniture: Furniture, index: number) => (
<CartItem
deleteItem={(id) => removeItem(id)}
onQuandityChange={(id: string, quandity: number) =>
quandityChange(id, quandity)
}
item={furniture}
key={furniture.id}
index={index}
/>
))}
</Animated.ScrollView>
<View style={[styles.footer]}>
<View
style={{
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={[styles.tPrice]}>Total Price</Text>
<Text style={[styles.price]}>{totalCartValue()} $</Text>
</View>
<TouchableOpacity style={[styles.checkoutBtn]}>
<Text style={[styles.checkout]}>Checkout</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
function quandityChange(id: string, quandity: number) {
let newCartItems = cart.map((item) => {
if (item.id === id) {
item.quandity = quandity;
}
return item;
});
setCart(newCartItems);
}
function totalCartValue() {
let cartValue = 0;
cart.map((item: Furniture) => {
cartValue = cartValue + item.price * item.quandity;
});
return cartValue;
}
function removeItem(id) {
const newCart = cart.filter((cart: Furniture) => cart.id !== id);
setCart(newCart);
animate();
}
}
Example #20
Source File: ExploreDetails.tsx From RNChallenge_2 with MIT License | 5 votes |
ExploreDetailsPage = ({navigation, route}: Props) => {
const {id, index, selected} = route.params;
const [furnitureColor, setColor] = useState(colors[`furniture${index % 4}`]);
const {width, height} = useWindowDimensions();
return (
<View style={[styles.safeAreaView]}>
<SharedElement id={`explore-${selected.id}`}>
<DetailsHeader
shared={'explore'}
id={id}
images={selected.images}
headerColor={furnitureColor}
/>
</SharedElement>
<View style={[styles.content]}>
<View style={[styles.Details]}>
<View style={[styles.row]}>
<View style={[styles.nameContainer]}>
<Text style={[styles.name]} allowFontScaling={false}>
{selected.name}
</Text>
<Text
style={{
fontSize: 12,
marginTop: 5,
color: 'gray',
}}
allowFontScaling={false}>
{selected.desc}
</Text>
<View style={[styles.ratingView]}>
<Rating
type="star"
ratingCount={5}
imageSize={15}
ratingColor={'gray'}
ratingBackgroundColor={'gray'}
showRating={false}
tintColor={colors.backgroundColor}
readonly
/>
<Text style={[styles.rating]}>{selected.rating}</Text>
</View>
</View>
<Text
style={[
styles.name,
{
color: colors.segment,
},
]}
allowFontScaling={false}>
{selected.price} $
</Text>
</View>
</View>
</View>
</View>
);
}
Example #21
Source File: ExploreItem.tsx From RNChallenge_2 with MIT License | 5 votes |
ExploreItem = ({item, index, onClick}: ExploreItemProps) => {
const {width} = useWindowDimensions();
return (
<TouchableOpacity
onPress={() => onClick(item, index)}
activeOpacity={0.6}
style={[
styles.container,
{
width: width * 0.4,
height: width * 0.45,
},
]}>
<View
style={{
flex: 1,
width: width * 0.4,
height: width * 0.45,
backgroundColor: colors[`furniture${index % 4}`],
position: 'absolute',
borderRadius: 15,
}}
/>
<View
style={{
width: '100%',
justifyContent: 'flex-start',
alignItems: 'center',
}}>
<SharedElement
style={{
width: width * 0.4 - 40,
height: width * 0.3,
}}
id={`explore-image-${item.id}`}>
<Image
style={{
width: width * 0.4 - 40,
height: width * 0.3,
resizeMode: 'contain',
}}
source={item.images[0]}
/>
</SharedElement>
</View>
<View
style={{
paddingBottom: 5,
}}>
<SharedElement id={`explore-${item.name}-${item.id}`}>
<Text numberOfLines={1} style={[styles.name]}>
{item.name}
</Text>
</SharedElement>
<SharedElement id={`explore-${item.price}-${item.id}`}>
<Text style={[styles.price]}>{item.price} $</Text>
</SharedElement>
</View>
</TouchableOpacity>
);
}
Example #22
Source File: Balance.tsx From hive-keychain-mobile with MIT License | 5 votes |
Balance = ({
currency,
account,
pd,
globalProperties,
engine,
tokenBalance,
tokenLogo,
setMax,
}: Props) => {
let {color, value, logo} = getCurrencyProperties(currency, account);
let parsedValue = parseFloat(value as string);
if (pd && value) {
parsedValue =
parseFloat(value as string) -
parseFloat(account.delegated_vesting_shares as string);
parsedValue = toHP(value as string, globalProperties);
}
if (engine) {
parsedValue = +tokenBalance!;
logo = tokenLogo!;
}
const styles = getDimensionedStyles({
color,
...useWindowDimensions(),
});
return (
<TouchableOpacity
style={styles.container}
onPress={() => {
setMax(parsedValue.toFixed(3) + '');
}}>
<View style={styles.main}>
<View style={styles.left}>
<View style={styles.logo}>{logo}</View>
<Text style={styles.name}>
{(pd
? translate('common.available')
: translate('common.balance')
).toUpperCase()}
</Text>
</View>
<Text style={styles.amount}>
{formatBalance(parsedValue)}
<Text style={styles.currency}>{` ${currency}`}</Text>
</Text>
</View>
</TouchableOpacity>
);
}
Example #23
Source File: EngineTokenDisplay.tsx From hive-keychain-mobile with MIT License | 5 votes |
EngineTokenDisplay = ({
token,
tokensList,
market,
toggled,
setToggle,
}: Props) => {
const styles = getDimensionedStyles(useWindowDimensions());
const tokenInfo = tokensList.find((t) => t.symbol === token.symbol);
const tokenMarket = market.find((t) => t.symbol === token.symbol);
if (!tokenInfo) {
return null;
}
const metadata = JSON.parse(tokenInfo.metadata);
const logo = (
<Image
style={styles.icon}
source={{
uri: metadata.icon || Img.resolveAssetSource(HiveEngine).uri,
}}
/>
);
return (
<TokenDisplay
name={tokenInfo.name}
currency={token.symbol}
color="black"
amountStyle={styles.amount}
value={parseFloat(token.balance)}
toggled={toggled}
setToggle={setToggle}
price={{
usd: tokenMarket ? parseFloat(tokenMarket.lastPrice) : 0,
usd_24h_change: parseFloat(
tokenMarket ? tokenMarket.priceChangePercent : '0',
),
}}
buttons={[
<Send
key="send_token"
currency={token.symbol}
engine
tokenBalance={token.balance}
tokenLogo={logo}
/>,
<ShowHistory
key="history_token"
currency={token.symbol}
tokenBalance={token.balance}
tokenLogo={logo}
/>,
]}
logo={logo}
/>
);
}
Example #24
Source File: index.tsx From frontatish with MIT License | 5 votes |
Splash = () => {
const Colors = useColors();
const x = useWindowDimensions().width / 2 - 40;
const y = useWindowDimensions().height / 2 - 80;
const animatedLogo = useRef(new Animated.ValueXY()).current;
const opacity = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.parallel([
Animated.timing(opacity, {
toValue: 1,
duration: 3000,
useNativeDriver: true,
}),
Animated.timing(animatedLogo, {
toValue: { x: -x, y: -y },
duration: 3000,
useNativeDriver: true,
}),
]).start(() => {});
});
const logo = {
top: 0,
height: scaleDimension(80),
width: scaleDimension(80),
borderRadius: 40,
backgroundColor: Colors.primary,
};
const logoName = {
fontSize: Fonts.size.h2,
color: Colors.font_2,
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Animated.View
style={[
logo,
{
transform: [
{ translateX: animatedLogo.x },
{ translateY: animatedLogo.y },
{
scale: opacity.interpolate({
inputRange: [0, 1],
outputRange: [2, 0.7],
}),
},
],
},
]}
/>
<Animated.Text style={[logoName, { opacity }]}>BrandName</Animated.Text>
</View>
);
}
Example #25
Source File: useOrientation.ts From mobile with Apache License 2.0 | 5 votes |
useOrientation = (): OrientationReturnValue => {
const scaledSize = useWindowDimensions();
return {orientation: scaledSize.width > scaledSize.height ? 'landscape' : 'portrait', scaledSize};
}
Example #26
Source File: TutorialContent.tsx From mobile with Apache License 2.0 | 5 votes |
TutorialContent = ({item, isActive}: TutorialContentProps) => {
const [i18n] = useI18n();
const prefersReducedMotion = useReduceMotionPreference();
const {width: viewportWidth, height: viewportHeight} = useWindowDimensions();
const animationRef: React.Ref<LottieView> = useRef(null);
useEffect(() => {
// need to stop if user prefers reduced animations
if (prefersReducedMotion) {
animationRef.current?.play(animationData[item].pauseFrame, animationData[item].pauseFrame);
} else if (isActive) {
animationRef.current?.play();
} else {
animationRef.current?.reset();
}
}, [isActive, prefersReducedMotion, item]);
const autoFocusRef = useRef<any>();
useLayoutEffect(() => {
const tag = findNodeHandle(autoFocusRef.current);
if (isActive && tag) {
AccessibilityInfo.setAccessibilityFocus(tag);
}
}, [isActive]);
return (
<ScrollView style={styles.flex} contentContainerStyle={styles.center}>
<LottieView
ref={animationRef}
style={{width: viewportWidth, height: viewportHeight / 2}}
source={animationData[item].source}
imageAssetsFolder="animation/images"
loop={!prefersReducedMotion}
/>
<Box paddingHorizontal="xxl">
<Text
ref={autoFocusRef}
textAlign="center"
color="overlayBodyText"
variant="bodySubTitle"
marginBottom="m"
accessibilityRole="header"
>
{i18n.translate(`Tutorial.${item}Title`)}
</Text>
<Text variant="bodyText" textAlign="center" color="overlayBodyText">
{i18n.translate(`Tutorial.${item}`)}
</Text>
</Box>
</ScrollView>
);
}
Example #27
Source File: Tutorial.tsx From mobile with Apache License 2.0 | 5 votes |
TutorialScreen = () => {
const navigation = useNavigation();
const {width: viewportWidth} = useWindowDimensions();
const carouselRef = useRef(null);
const [currentStep, setCurrentStep] = useState(0);
const [i18n] = useI18n();
const close = useCallback(() => navigation.goBack(), [navigation]);
const isStart = currentStep === 0;
const isEnd = currentStep === tutorialData.length - 1;
const renderItem = useCallback<CarouselProps<TutorialKey>['renderItem']>(
({item, index}) => {
return (
<View style={styles.flex} accessibilityElementsHidden={index !== currentStep}>
<TutorialContent item={item} isActive={tutorialData[currentStep] === item} />
</View>
);
},
[currentStep],
);
const nextItem = useCallback(() => {
if (carouselRef.current) {
if (isEnd) {
close();
return;
}
(carouselRef.current! as CarouselStatic<TutorialKey>).snapToNext();
}
}, [close, isEnd]);
const prevItem = useCallback(() => {
if (carouselRef.current) {
(carouselRef.current! as CarouselStatic<TutorialKey>).snapToPrev();
}
}, []);
return (
<Box backgroundColor="overlayBackground" flex={1}>
<SafeAreaView style={styles.flex}>
<Toolbar
title=""
navIcon="icon-back-arrow"
navText={i18n.translate('Tutorial.Close')}
navLabel={i18n.translate('Tutorial.Close')}
onIconClicked={close}
/>
<Carousel
ref={carouselRef}
data={tutorialData}
renderItem={renderItem}
sliderWidth={viewportWidth}
itemWidth={viewportWidth}
onSnapToItem={newIndex => setCurrentStep(newIndex)}
importantForAccessibility="no"
accessible={false}
/>
<Box flexDirection="row" padding="l">
<Box flex={1}>
{!isStart && (
<Button text={i18n.translate(`Tutorial.ActionBack`)} variant="subduedText" onPress={prevItem} />
)}
</Box>
<Box flex={1} justifyContent="center">
<ProgressCircles numberOfSteps={tutorialData.length} activeStep={currentStep + 1} marginBottom="none" />
</Box>
<Box flex={1}>
<Button
text={i18n.translate(`Tutorial.Action${isEnd ? 'End' : 'Next'}`)}
variant="text"
onPress={nextItem}
/>
</Box>
</Box>
</SafeAreaView>
</Box>
);
}
Example #28
Source File: TimePicker.tsx From react-native-paper-dates with MIT License | 4 votes |
function TimePicker({
hours,
minutes,
onFocusInput,
focused,
inputType,
onChange,
locale,
}: {
locale?: undefined | string
inputType: PossibleInputTypes
focused: PossibleClockTypes
hours: number
minutes: number
onFocusInput: (type: PossibleClockTypes) => any
onChange: onChangeFunc
}) {
const [displayMode, setDisplayMode] = React.useState<'AM' | 'PM' | undefined>(
undefined
)
const dimensions = useWindowDimensions()
const isLandscape = dimensions.width > dimensions.height
// method to check whether we have 24 hours in clock or 12
const is24Hour = React.useMemo(() => {
const formatter = new Intl.DateTimeFormat(locale, {
hour: '2-digit',
minute: '2-digit',
timeZone: 'UTC',
})
const formatted = formatter.format(new Date(Date.UTC(2020, 1, 1, 23)))
return formatted.includes('23')
}, [locale])
// Initialize display Mode according the hours value
React.useEffect(() => {
if (hours >= 12) {
setDisplayMode('PM')
} else {
setDisplayMode('AM')
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onInnerChange = React.useCallback<onChangeFunc>(
(params) => {
params.hours = toHourOutputFormat(params.hours, hours, is24Hour)
onChange(params)
},
[onChange, hours, is24Hour]
)
return (
<DisplayModeContext.Provider
value={{ mode: displayMode, setMode: setDisplayMode }}
>
<View style={isLandscape ? styles.rootLandscape : styles.rootPortrait}>
<TimeInputs
inputType={inputType}
hours={hours}
minutes={minutes}
is24Hour={is24Hour}
onChange={onChange}
onFocusInput={onFocusInput}
focused={focused}
/>
{inputType === inputTypes.picker ? (
<View style={styles.clockContainer}>
<AnalogClock
hours={toHourInputFormat(hours, is24Hour)}
minutes={minutes}
focused={focused}
is24Hour={is24Hour}
onChange={onInnerChange}
/>
</View>
) : null}
</View>
</DisplayModeContext.Provider>
)
}
Example #29
Source File: DetailsPage.tsx From RNChallenge_2 with MIT License | 4 votes |
DetailsPage = ({navigation, route}: Props) => {
const {id, index, selected, shareId} = route.params;
const [furnitureColor, setColor] = useState(colors[`furniture${index % 4}`]);
const {width, height} = useWindowDimensions();
const insets = useSafeAreaInsets();
const [quandity, setQuandity] = useState(0);
const [addToBagQuandity, setBagQuandity] = useState(0);
const [showCart, setCart] = useState(false);
return (
<View
style={[
styles.safeAreaView,
{
paddingTop: insets.top,
},
]}>
<Modal
style={{
padding: 0,
margin: 0,
}}
useNativeDriver={true}
onBackButtonPress={() => setCart(false)}
onBackdropPress={() => setCart(false)}
animationOut={'slideOutDown'}
animationIn={'slideInUp'}
isVisible={showCart}>
<Cart closeCart={() => setCart(false)} />
</Modal>
<DetailsHeader
goToCart={() => setCart(true)}
quandity={addToBagQuandity}
shared={shareId}
id={id}
images={selected.images}
headerColor={furnitureColor}
/>
<ScrollView
showsVerticalScrollIndicator={false}
bounces={false}
style={{
flex: 1,
}}
contentContainerStyle={[styles.content]}>
<View style={[styles.Details]}>
<View style={[styles.row]}>
<View style={[styles.nameContainer]}>
<SharedElement id={`${shareId}-${selected.name}-${id}`}>
<Text style={[styles.name]} allowFontScaling={false}>
{selected.name}
</Text>
</SharedElement>
<Text
style={{
fontSize: 12,
marginTop: 5,
color: '#616161',
}}
allowFontScaling={false}>
{selected.desc}
</Text>
<View style={[styles.ratingView]}>
<Rating
type="star"
ratingCount={5}
imageSize={15}
ratingColor={'gray'}
ratingBackgroundColor={'gray'}
showRating={false}
tintColor={colors.backgroundColor}
readonly
/>
<Text style={[styles.rating]}>{selected.rating}</Text>
</View>
</View>
<SharedElement id={`${shareId}-${selected.price}-${id}`}>
<Text
style={[
styles.name,
{
color: colors.segment,
},
]}
allowFontScaling={false}>
{selected.price} $
</Text>
</SharedElement>
</View>
<ColorPicker
style={{marginTop: 25}}
defaultColorIndex={index % 4}
onColorSelect={(color: string) => setColor(color)}
colors={[
colors.furniture0,
colors.furniture1,
colors.furniture2,
colors.furniture3,
]}
/>
<QuantityPicker
style={{
marginTop: 25,
}}
onQuantityChange={(value: number) => setQuandity(value)}
/>
<View
style={{
width: '100%',
alignItems: 'center',
marginTop: 40,
}}>
<AddToBagButton
addToCart={() => {
if (quandity > 0) {
setBagQuandity(quandity);
}
}}
/>
</View>
<Text style={[styles.recentlyViewed]}>RECENTLY VIEWED</Text>
</View>
<ScrollView bounces horizontal showsHorizontalScrollIndicator={false}>
{recentViewed().map((item: Furniture, index: number) => (
<RecentlyViewed index={index} furniture={item} key={item.id} />
))}
</ScrollView>
</ScrollView>
</View>
);
}