aboutsummaryrefslogtreecommitdiff
path: root/src/screens/moments/CameraScreen.tsx
blob: 483bfe385af0d75d8d3b64c3e918a7c630c35b39 (plain)
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import CameraRoll from '@react-native-community/cameraroll';
import {useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import {RouteProp} from '@react-navigation/core';
import {useFocusEffect} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import React, {useRef, useCallback, useEffect, useState} from 'react';
import {Modal, StyleSheet, TouchableOpacity, View} from 'react-native';
import {CameraType, FlashMode, RNCamera} from 'react-native-camera';
import {AnimatedCircularProgress} from 'react-native-circular-progress';
import CloseIcon from '../../assets/ionicons/close-outline.svg';
import {FlashButton, FlipButton, GalleryIcon} from '../../components';
import {MAX_VIDEO_RECORDING_DURATION, TAGG_PURPLE} from '../../constants';
import {MainStackParams} from '../../routes';
import {HeaderHeight, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';
import {showGIFFailureAlert, takePicture, takeVideo} from '../../utils/camera';

type CameraScreenRouteProps = RouteProp<MainStackParams, 'CameraScreen'>;
export type CameraScreenNavigationProps = StackNavigationProp<
  MainStackParams,
  'CameraScreen'
>;
interface CameraScreenProps {
  route: CameraScreenRouteProps;
  navigation: CameraScreenNavigationProps;
}
const CameraScreen: React.FC<CameraScreenProps> = ({route, navigation}) => {
  const {screenType, selectedCategory} = route.params;
  const cameraRef = useRef<RNCamera>(null);
  const tabBarHeight = useBottomTabBarHeight();
  const [cameraType, setCameraType] = useState<keyof CameraType>('back');
  const [flashMode, setFlashMode] = useState<keyof FlashMode>('off');
  const [mostRecentPhoto, setMostRecentPhoto] = useState<string>('');
  const [isRecording, setIsRecording] = useState<boolean>(false);
  const [pictureProcessing, setPictureProcessing] = useState<boolean>(false);
  const [mounted, setMounted] = useState<boolean>(false);
  const [vidUri, setVidUri] = useState<string>();
  const [videoRecordStart, setVideoRecordStart] = useState<boolean>(false);

  useFocusEffect(
    useCallback(() => {
      navigation.dangerouslyGetParent()?.setOptions({
        tabBarVisible: false,
      });

      // reset in case we have returned to this screen
      setPictureProcessing(false);

      // reset in case this wasn't properly called
      setIsRecording(false);

      // in case the preview image gets stuck
      if (mounted) {
        cameraRef?.current?.resumePreview();
      }

      return () => setIsRecording(false);
    }, [navigation]),
  );

  /*
   *  Chooses the last picture from gallery to display as the gallery button icon
   */
  useEffect(() => {
    CameraRoll.getPhotos({first: 1})
      .then((lastPhoto) => {
        if (lastPhoto.edges.length > 0) {
          const image = lastPhoto.edges[0].node.image;
          setMostRecentPhoto(image.uri);
        }
      })
      .catch((_err) =>
        console.log('Unable to fetch preview photo for gallery'),
      );

    setMounted(true);
  }, []);

  const navigateToEditMedia = (uri: string) => {
    cameraRef?.current?.resumePreview();
    navigation.navigate('EditMedia', {
      screenType,
      media: {
        uri,
        isVideo: !(
          uri.endsWith('jpg') ||
          uri.endsWith('JPG') ||
          uri.endsWith('PNG') ||
          uri.endsWith('png') ||
          uri.endsWith('GIF') ||
          uri.endsWith('gif')
        ),
      },
      selectedCategory,
    });
  };

  const handleClose = () => {
    navigation.dangerouslyGetParent()?.setOptions({
      tabBarVisible: true,
    });
    navigation.goBack();
  };

  return (
    <View style={styles.container}>
      <Modal
        transparent={true}
        visible={isRecording && cameraType === 'front' && flashMode === 'on'}>
        <View style={styles.flashView} />
      </Modal>
      <TouchableOpacity style={styles.closeButton} onPress={handleClose}>
        <CloseIcon height={25} width={25} color={'white'} />
      </TouchableOpacity>
      <FlashButton flashMode={flashMode} setFlashMode={setFlashMode} />
      <RNCamera
        ref={cameraRef}
        style={styles.camera}
        type={cameraType}
        flashMode={
          flashMode === 'on' && isRecording && cameraType === 'back'
            ? 'torch'
            : flashMode
        }
        onDoubleTap={() => {
          if (!pictureProcessing) {
            setCameraType(cameraType === 'front' ? 'back' : 'front');
          }
        }}
        onRecordingStart={(event: {
          nativeEvent: {
            uri: string;
            videoOrientation: number;
            deviceOrientation: number;
          };
        }) => {
          console.log('start', event.nativeEvent.uri);
          setIsRecording(true);
          setVidUri(event.nativeEvent.uri);
          setVideoRecordStart(true);
        }}
        onRecordingEnd={() => {
          if (videoRecordStart && vidUri) {
            navigateToEditMedia(vidUri);
          }
          setVideoRecordStart(false);
          setIsRecording(false);
        }}
      />
      {!pictureProcessing && (
        <View style={[styles.bottomContainer, {bottom: tabBarHeight}]}>
          <FlipButton cameraType={cameraType} setCameraType={setCameraType} />
          <TouchableOpacity
            style={
              isRecording
                ? styles.captureButtonVideoContainer
                : styles.captureButtonContainer
            }
            activeOpacity={1}
            onLongPress={async () => {
              const resetAndStartCameraRecording = async () => {
                if (await cameraRef.current?.isRecording()) {
                  cameraRef.current?.stopRecording();
                }
              };

              await resetAndStartCameraRecording();
              takeVideo(cameraRef, (vid) => setVidUri(vid.uri));
            }}
            onPressOut={async () => {
              const cancelRecording = async () => {
                if (isRecording && (await cameraRef.current?.isRecording())) {
                  cameraRef.current?.stopRecording();
                } else {
                  takePicture(cameraRef, (pic) => navigateToEditMedia(pic.uri));
                }
                setIsRecording(false);
              };
              setPictureProcessing(true);
              cancelRecording();
              // tmp fix for when the animation glitches during the beginning of
              // recording causing onPressOut to not be detected.
              // setTimeout(() => {
              //   cancelRecording();
              // }, 500);
              // setTimeout(() => {
              //   cancelRecording();
              // }, 1000);
              // setTimeout(() => {
              //   cancelRecording();
              // }, 1500);
            }}
            onPress={() => {
              if (!pictureProcessing) {
                setPictureProcessing(true);
              }
              takePicture(cameraRef, (pic) => navigateToEditMedia(pic.uri));
            }}>
            <View style={styles.captureButton} />
          </TouchableOpacity>
          {isRecording && (
            <AnimatedCircularProgress
              size={95}
              width={6}
              fill={100}
              rotation={0}
              duration={(MAX_VIDEO_RECORDING_DURATION + 1) * 1000} // an extra second for UI to load
              tintColor={TAGG_PURPLE}
              style={styles.bottomContainer}
              lineCap={'round'}
            />
          )}
          <View style={styles.bottomRightContainer}>
            <GalleryIcon
              mostRecentPhotoUri={mostRecentPhoto}
              callback={(media) => {
                const filename = media.filename;
                if (
                  filename &&
                  (filename.endsWith('gif') || filename.endsWith('GIF'))
                ) {
                  showGIFFailureAlert(() => navigateToEditMedia(media.path));
                } else {
                  navigateToEditMedia(media.path);
                }
              }}
            />
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  camera: {
    flex: 1,
    justifyContent: 'space-between',
  },
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  flashView: {
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    backgroundColor: '#fff',
    opacity: 0.5,
  },
  captureButtonVideoContainer: {
    alignSelf: 'center',
    backgroundColor: 'transparent',
    borderRadius: 100,
    borderWidth: 15,
    borderColor: 'rgba(255,255,255,0.3)',
    width: 93,
    height: 93,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  captureButtonContainer: {
    alignSelf: 'center',
    backgroundColor: 'transparent',
    borderRadius: 100,
    borderWidth: 4,
    borderColor: '#fff',
    width: 93,
    height: 93,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  captureButton: {
    backgroundColor: '#fff',
    width: 68,
    height: 68,
    borderRadius: 74,
  },
  closeButton: {
    position: 'absolute',
    top: 0,
    paddingTop: HeaderHeight,
    zIndex: 1,
    marginLeft: '5%',
  },
  bottomContainer: {
    position: 'absolute',
    width: SCREEN_WIDTH,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  bottomRightContainer: {
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    width: (SCREEN_WIDTH - 100) / 2,
  },
});

export default CameraScreen;