about summary refs log tree commit diff
path: root/src/view/com/util/images/AutoSizedImage.tsx
blob: 0443c7be4795f27e0824b094e705aa30ba0a59e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React from 'react'
import {StyleProp, StyleSheet, TouchableOpacity, ViewStyle} from 'react-native'
import Image, {OnLoadEvent} from 'view/com/util/images/Image'
import {clamp} from 'lib/numbers'

export const DELAY_PRESS_IN = 500
const MIN_ASPECT_RATIO = 0.33 // 1/3
const MAX_ASPECT_RATIO = 5 // 5/1

export function AutoSizedImage({
  uri,
  onPress,
  onLongPress,
  onPressIn,
  style,
  children = null,
}: {
  uri: string
  onPress?: () => void
  onLongPress?: () => void
  onPressIn?: () => void
  style?: StyleProp<ViewStyle>
  children?: React.ReactNode
}) {
  const [aspectRatio, setAspectRatio] = React.useState<number>(1)
  const onLoad = (e: OnLoadEvent) => {
    setAspectRatio(
      clamp(
        e.nativeEvent.width / e.nativeEvent.height,
        MIN_ASPECT_RATIO,
        MAX_ASPECT_RATIO,
      ),
    )
  }
  return (
    <TouchableOpacity
      onPress={onPress}
      onLongPress={onLongPress}
      onPressIn={onPressIn}
      delayPressIn={DELAY_PRESS_IN}
      style={[styles.container, style]}>
      <Image
        style={[styles.image, {aspectRatio}]}
        source={{uri}}
        onLoad={onLoad}
      />
      {children}
    </TouchableOpacity>
  )
}

const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
  },
  image: {
    width: '100%',
  },
})