tooot/src/screens/Shared/Account/Header.tsx

88 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-12-18 00:00:45 +01:00
import React, { Dispatch, useEffect, useRef, useState } from 'react'
2020-11-22 00:46:23 +01:00
import { Animated, Dimensions, Image, StyleSheet } from 'react-native'
2020-12-18 00:00:45 +01:00
import { AccountAction, AccountState } from '../Account'
2020-11-22 00:46:23 +01:00
export interface Props {
2020-12-18 00:00:45 +01:00
accountState: AccountState
accountDispatch?: Dispatch<AccountAction>
account?: Mastodon.Account
2020-11-22 00:46:23 +01:00
limitHeight?: boolean
}
2020-12-18 00:00:45 +01:00
const AccountHeader: React.FC<Props> = ({
accountState,
accountDispatch,
account,
limitHeight = false
}) => {
const [imageShown, setImageShown] = useState(true)
2020-11-22 00:46:23 +01:00
useEffect(() => {
2020-12-18 00:00:45 +01:00
if (account?.header) {
if (account.header.includes('/headers/original/missing.png')) {
animateNewSize(accountState.headerRatio)
2020-11-22 00:46:23 +01:00
} else {
2020-12-18 00:00:45 +01:00
if (account.header !== account.header_static) {
setImageShown(false)
}
2020-11-22 00:46:23 +01:00
Image.getSize(
2020-12-18 00:00:45 +01:00
account.header,
2020-11-22 00:46:23 +01:00
(width, height) => {
if (!limitHeight) {
2020-12-18 00:00:45 +01:00
accountDispatch &&
accountDispatch({
type: 'headerRatio',
payload: height / width
})
}
animateNewSize(
limitHeight ? accountState.headerRatio : height / width
)
2020-11-22 00:46:23 +01:00
},
() => {
animateNewSize(accountState.headerRatio)
2020-11-22 00:46:23 +01:00
}
)
}
}
2020-12-18 00:00:45 +01:00
}, [account])
const theImage = imageShown ? (
<Image source={{ uri: account?.header }} style={styles.image} />
) : null
2020-11-22 00:46:23 +01:00
const windowWidth = Dimensions.get('window').width
const imageHeight = useRef(
new Animated.Value(windowWidth * accountState.headerRatio)
).current
2020-11-22 00:46:23 +01:00
const animateNewSize = (ratio: number) => {
Animated.timing(imageHeight, {
toValue: windowWidth * ratio,
duration: 350,
useNativeDriver: false
2020-12-18 00:00:45 +01:00
}).start(({ finished }) => {
if (finished) {
setImageShown(true)
}
})
2020-11-22 00:46:23 +01:00
}
return (
<Animated.View style={[styles.imageContainer, { height: imageHeight }]}>
2020-12-18 00:00:45 +01:00
{theImage}
2020-11-22 00:46:23 +01:00
</Animated.View>
)
}
const styles = StyleSheet.create({
imageContainer: {
backgroundColor: 'lightgray'
},
image: {
width: '100%',
height: '100%'
}
})
export default AccountHeader