|
| 1 | +import React, { useState, useEffect } from 'react' |
| 2 | +import { StyleSheet, View, Dimensions, Image as RNImage, LayoutChangeEvent } from 'react-native' |
| 3 | +import { Image } from '../components/Image' |
| 4 | +import './markdown.theme.css' // Duplicate of the React-Native styles from this file |
| 5 | +import { UniversalImageProps } from '../components/Image.types' |
| 6 | + |
| 7 | +/* --- <MarkdownImage/> --------------------------------------------------------------------------- */ |
| 8 | + |
| 9 | +export const MarkdownImage = (props: UniversalImageProps) => { |
| 10 | + // Props |
| 11 | + const { src, alt } = props |
| 12 | + |
| 13 | + // State |
| 14 | + const [imgDimensions, setImgDimensions] = useState({ width: 0, height: 0 }) |
| 15 | + const [wrapperWidth, setWrapperWidth] = useState(0) |
| 16 | + |
| 17 | + // Flags |
| 18 | + const hasWrapperWidth = !!wrapperWidth |
| 19 | + |
| 20 | + // Vars |
| 21 | + const imgRatio = imgDimensions.height / imgDimensions.width |
| 22 | + const maxWindowWidth = Dimensions.get('window').width |
| 23 | + const widthToUse = Math.min(...[imgDimensions.width, wrapperWidth, maxWindowWidth].filter(Boolean)) |
| 24 | + const heightToUse = widthToUse * imgRatio |
| 25 | + const finalDimensions = imgRatio ? { width: widthToUse, height: heightToUse } : imgDimensions |
| 26 | + |
| 27 | + // -- Handlers -- |
| 28 | + |
| 29 | + const handleWrapperLayout = (event: LayoutChangeEvent) => { |
| 30 | + if (wrapperWidth < 5) setWrapperWidth(event.nativeEvent.layout.width) |
| 31 | + } |
| 32 | + |
| 33 | + // -- Effects -- |
| 34 | + |
| 35 | + useEffect(() => { |
| 36 | + const checkImageDimensions = async () => { |
| 37 | + RNImage.getSize(src as string, (width, height) => { |
| 38 | + setImgDimensions({ width, height }) |
| 39 | + }) |
| 40 | + } |
| 41 | + if (typeof src === 'string') checkImageDimensions() |
| 42 | + }, []) |
| 43 | + |
| 44 | + // -- Render -- |
| 45 | + |
| 46 | + return ( |
| 47 | + <View |
| 48 | + style={{ |
| 49 | + ...styles.imgWrapper, |
| 50 | + ...(!hasWrapperWidth ? { minWidth: '100%' } : finalDimensions) |
| 51 | + }} |
| 52 | + onLayout={!hasWrapperWidth ? handleWrapperLayout : undefined} |
| 53 | + > |
| 54 | + <Image |
| 55 | + alt={alt} |
| 56 | + src={src} |
| 57 | + style={finalDimensions} |
| 58 | + contentFit="contain" |
| 59 | + /> |
| 60 | + </View> |
| 61 | + ) |
| 62 | +} |
| 63 | + |
| 64 | +/* --- Styles ---------------------------------------------------------------------------------- */ |
| 65 | +// -i- These styles won't work in Next.js for some reason, duplicate them in markdown.theme.css |
| 66 | + |
| 67 | +const styles = StyleSheet.create({ |
| 68 | + imgWrapper: { |
| 69 | + display: 'flex', |
| 70 | + position: 'relative', |
| 71 | + flexDirection: 'column', |
| 72 | + marginTop: 16, |
| 73 | + } |
| 74 | +}) |
0 commit comments