From 4966b2152eb213bac34cbcb0ff01c246b7746f5c Mon Sep 17 00:00:00 2001 From: Paul Frazee Date: Wed, 14 Dec 2022 15:35:15 -0600 Subject: Add post embeds (images and external links) --- src/view/com/util/images/AutoSizedImage.tsx | 112 ++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 src/view/com/util/images/AutoSizedImage.tsx (limited to 'src/view/com/util/images/AutoSizedImage.tsx') diff --git a/src/view/com/util/images/AutoSizedImage.tsx b/src/view/com/util/images/AutoSizedImage.tsx new file mode 100644 index 000000000..fedc94321 --- /dev/null +++ b/src/view/com/util/images/AutoSizedImage.tsx @@ -0,0 +1,112 @@ +import React, {useState, useEffect, useMemo} from 'react' +import { + Image, + ImageStyle, + LayoutChangeEvent, + StyleProp, + StyleSheet, + Text, + TouchableWithoutFeedback, + View, +} from 'react-native' +import {ImageLightbox} from '../../../../state/models/shell-ui' +import {useStores} from '../../../../state' +import {colors} from '../../../lib/styles' + +const MAX_HEIGHT = 300 + +interface Dim { + width: number + height: number +} + +export function AutoSizedImage({ + uri, + fullSizeUri, + style, +}: { + uri: string + fullSizeUri?: string + style: StyleProp +}) { + const store = useStores() + const [error, setError] = useState() + const [imgInfo, setImgInfo] = useState() + const [containerInfo, setContainerInfo] = useState() + const calculatedStyle = useMemo(() => { + if (imgInfo && containerInfo) { + // imgInfo.height / imgInfo.width = x / containerInfo.width + // x = imgInfo.height / imgInfo.width * containerInfo.width + return { + height: Math.min( + MAX_HEIGHT, + (imgInfo.height / imgInfo.width) * containerInfo.width, + ), + } + } + return undefined + }, [imgInfo, containerInfo]) + + useEffect(() => { + Image.getSize( + uri, + (width: number, height: number) => { + setImgInfo({width, height}) + }, + (error: any) => { + setError(String(error)) + }, + ) + }, [uri]) + + const onLayout = (evt: LayoutChangeEvent) => { + setContainerInfo({ + width: evt.nativeEvent.layout.width, + height: evt.nativeEvent.layout.height, + }) + } + + const onPressImage = () => { + if (fullSizeUri) { + store.shell.openLightbox(new ImageLightbox(fullSizeUri)) + } + } + + return ( + + + {error ? ( + + {error} + + ) : calculatedStyle ? ( + + + + ) : ( + + )} + + + ) +} + +const styles = StyleSheet.create({ + placeholder: { + width: '100%', + aspectRatio: 1, + backgroundColor: colors.gray1, + }, + errorContainer: { + backgroundColor: colors.red1, + paddingHorizontal: 8, + paddingVertical: 4, + }, + container: { + borderRadius: 8, + overflow: 'hidden', + }, + error: { + color: colors.red5, + }, +}) -- cgit 1.4.1