about summary refs log tree commit diff
path: root/src/view/com/lightbox/ImageViewing/index.tsx
blob: 7d3f80b494a0e3678e190750b4f54d67ce6473f9 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
 * Copyright (c) JOB TODAY S.A. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
// Original code copied and simplified from the link below as the codebase is currently not maintained:
// https://github.com/jobtoday/react-native-image-viewing

import React, {
  ComponentType,
  createRef,
  useCallback,
  useRef,
  useMemo,
  useState,
} from 'react'
import {
  Animated,
  Dimensions,
  NativeSyntheticEvent,
  NativeScrollEvent,
  StyleSheet,
  View,
  VirtualizedList,
  ModalProps,
  Platform,
} from 'react-native'

import ImageItem from './components/ImageItem/ImageItem'
import ImageDefaultHeader from './components/ImageDefaultHeader'

import {ImageSource} from './@types'
import {ScrollView, GestureType} from 'react-native-gesture-handler'
import {Edge, SafeAreaView} from 'react-native-safe-area-context'

type Props = {
  images: ImageSource[]
  initialImageIndex: number
  visible: boolean
  onRequestClose: () => void
  presentationStyle?: ModalProps['presentationStyle']
  animationType?: ModalProps['animationType']
  backgroundColor?: string
  HeaderComponent?: ComponentType<{imageIndex: number}>
  FooterComponent?: ComponentType<{imageIndex: number}>
}

const DEFAULT_BG_COLOR = '#000'
const SCREEN = Dimensions.get('screen')
const SCREEN_WIDTH = SCREEN.width
const INITIAL_POSITION = {x: 0, y: 0}
const ANIMATION_CONFIG = {
  duration: 200,
  useNativeDriver: true,
}

function ImageViewing({
  images,
  initialImageIndex,
  visible,
  onRequestClose,
  backgroundColor = DEFAULT_BG_COLOR,
  HeaderComponent,
  FooterComponent,
}: Props) {
  const imageList = useRef<VirtualizedList<ImageSource>>(null)
  const [isScaled, setIsScaled] = useState(false)
  const [isDragging, setIsDragging] = useState(false)
  const [imageIndex, setImageIndex] = useState(initialImageIndex)
  const [headerTranslate] = useState(
    () => new Animated.ValueXY(INITIAL_POSITION),
  )
  const [footerTranslate] = useState(
    () => new Animated.ValueXY(INITIAL_POSITION),
  )

  const toggleBarsVisible = (isVisible: boolean) => {
    if (isVisible) {
      Animated.parallel([
        Animated.timing(headerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
        Animated.timing(footerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
      ]).start()
    } else {
      Animated.parallel([
        Animated.timing(headerTranslate.y, {
          ...ANIMATION_CONFIG,
          toValue: -300,
        }),
        Animated.timing(footerTranslate.y, {
          ...ANIMATION_CONFIG,
          toValue: 300,
        }),
      ]).start()
    }
  }

  const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const {
      nativeEvent: {
        contentOffset: {x: scrollX},
      },
    } = event

    if (SCREEN.width) {
      const nextIndex = Math.round(scrollX / SCREEN.width)
      setImageIndex(nextIndex < 0 ? 0 : nextIndex)
    }
  }

  const onZoom = (nextIsScaled: boolean) => {
    toggleBarsVisible(!nextIsScaled)
    setIsScaled(false)
  }

  const edges = useMemo(() => {
    if (Platform.OS === 'android') {
      return ['top', 'bottom', 'left', 'right'] satisfies Edge[]
    }
    return ['left', 'right'] satisfies Edge[] // iOS, so no top/bottom safe area
  }, [])

  const onLayout = useCallback(() => {
    if (initialImageIndex) {
      imageList.current?.scrollToIndex({
        index: initialImageIndex,
        animated: false,
      })
    }
  }, [imageList, initialImageIndex])

  // This is a hack.
  // RNGH doesn't have an easy way to express that pinch of individual items
  // should "steal" all pinches from the scroll view. So we're keeping a ref
  // to all pinch gestures so that we may give them to <ScrollView waitFor={...}>.
  const [pinchGestureRefs] = useState(new Map())
  for (let imageSrc of images) {
    if (!pinchGestureRefs.get(imageSrc)) {
      pinchGestureRefs.set(imageSrc, createRef<GestureType | undefined>())
    }
  }

  if (!visible) {
    return null
  }

  const headerTransform = headerTranslate.getTranslateTransform()
  const footerTransform = footerTranslate.getTranslateTransform()
  return (
    <SafeAreaView
      style={styles.screen}
      onLayout={onLayout}
      edges={edges}
      aria-modal
      accessibilityViewIsModal>
      <View style={[styles.container, {backgroundColor}]}>
        <Animated.View style={[styles.header, {transform: headerTransform}]}>
          {typeof HeaderComponent !== 'undefined' ? (
            React.createElement(HeaderComponent, {
              imageIndex,
            })
          ) : (
            <ImageDefaultHeader onRequestClose={onRequestClose} />
          )}
        </Animated.View>
        <VirtualizedList
          ref={imageList}
          data={images}
          horizontal
          pagingEnabled
          scrollEnabled={!isScaled || isDragging}
          showsHorizontalScrollIndicator={false}
          showsVerticalScrollIndicator={false}
          getItem={(_, index) => images[index]}
          getItemCount={() => images.length}
          getItemLayout={(_, index) => ({
            length: SCREEN_WIDTH,
            offset: SCREEN_WIDTH * index,
            index,
          })}
          renderItem={({item: imageSrc}) => (
            <ImageItem
              onZoom={onZoom}
              imageSrc={imageSrc}
              onRequestClose={onRequestClose}
              pinchGestureRef={pinchGestureRefs.get(imageSrc)}
              isScrollViewBeingDragged={isDragging}
            />
          )}
          renderScrollComponent={props => (
            <ScrollView
              {...props}
              waitFor={Array.from(pinchGestureRefs.values())}
            />
          )}
          onScrollBeginDrag={() => {
            setIsDragging(true)
          }}
          onScrollEndDrag={() => {
            setIsDragging(false)
          }}
          onMomentumScrollEnd={e => {
            setIsScaled(false)
            onScroll(e)
          }}
          keyExtractor={imageSrc => imageSrc.uri}
        />
        {typeof FooterComponent !== 'undefined' && (
          <Animated.View style={[styles.footer, {transform: footerTransform}]}>
            {React.createElement(FooterComponent, {
              imageIndex,
            })}
          </Animated.View>
        )}
      </View>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  screen: {
    position: 'absolute',
  },
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  header: {
    position: 'absolute',
    width: '100%',
    zIndex: 1,
    top: 0,
    pointerEvents: 'box-none',
  },
  footer: {
    position: 'absolute',
    width: '100%',
    zIndex: 1,
    bottom: 0,
  },
})

const EnhancedImageViewing = (props: Props) => (
  <ImageViewing key={props.initialImageIndex} {...props} />
)

export default EnhancedImageViewing