aboutsummaryrefslogtreecommitdiff
path: root/src/components/notifications/Notification.tsx
blob: 3f9cc56accd7804074a936663965b164bfb3c8a4 (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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import {useNavigation} from '@react-navigation/native';
import React, {useEffect, useState} from 'react';
import {Alert, Image, StyleSheet, Text, View} from 'react-native';
import {TouchableWithoutFeedback} from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import {useDispatch, useStore} from 'react-redux';
import {BACKGROUND_GRADIENT_MAP} from '../../constants';
import {ERROR_DELETED_OBJECT} from '../../constants/strings';
import {loadImageFromURL} from '../../services';
import {
  acceptFriendRequest,
  declineFriendRequest,
  loadUserNotifications,
  updateReplyPosted,
  updateUserXFriends,
} from '../../store/actions';
import {RootState} from '../../store/rootReducer';
import {
  CommentNotificationType,
  CommentThreadType,
  MomentType,
  NotificationType,
  ScreenType,
  ThreadNotificationType,
  UserType,
} from '../../types';
import {
  fetchUserX,
  getTimeInShorthand,
  normalize,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
  userXInStore,
} from '../../utils';
import {Avatar} from '../common';
import AcceptDeclineButtons from '../common/AcceptDeclineButtons';
import {MessageButton} from '../messages';

interface NotificationProps {
  item: NotificationType;
  screenType: ScreenType;
  loggedInUser: UserType;
}

const Notification: React.FC<NotificationProps> = (props) => {
  const {
    item: {
      actor: {id, username, first_name, last_name, thumbnail_url},
      verbage,
      notification_type,
      notification_object,
      unread,
      timestamp,
    },
    screenType,
    loggedInUser,
  } = props;

  const navigation = useNavigation();
  const state: RootState = useStore().getState();
  const dispatch = useDispatch();

  const [avatar, setAvatar] = useState<string | undefined>(undefined);
  const [momentURI, setMomentURI] = useState<string | undefined>(undefined);
  const notification_title =
    notification_type === 'FRD_ACPT'
      ? `Say Hi to ${first_name}!`
      : `${first_name} ${last_name}`;

  useEffect(() => {
    (async () => {
      const response = await loadImageFromURL(thumbnail_url);
      if (response) {
        setAvatar(response);
      } else {
        setAvatar(undefined);
      }
    })();
  }, [thumbnail_url]);

  useEffect(() => {
    if (notification_object) {
      let url: string | undefined;
      let obj;
      if (
        notification_type === 'MOM_3+' ||
        notification_type === 'MOM_FRIEND' ||
        notification_type === 'MOM_TAG'
      ) {
        obj = notification_object as MomentType;
        url = obj.thumbnail_url;
      } else if (notification_type === 'CMT') {
        obj = notification_object as CommentNotificationType;
        url = obj.notification_data.thumbnail_url;
      }
      if (url) {
        setMomentURI(url);
      }
    }
  }, [id, notification_object, notification_type]);

  const onNotificationTap = async () => {
    switch (notification_type) {
      case 'INVT_ONBRD':
      case 'FRD_ACPT':
      case 'FRD_REQ':
        if (!userXInStore(state, screenType, id)) {
          await fetchUserX(
            dispatch,
            {userId: id, username: username},
            screenType,
          );
        }
        navigation.push('Profile', {
          userXId: id,
          screenType,
        });
        break;
      case 'CMT':
        //Notification object is set to null if the comment / comment_thread / moment gets deleted
        if (!notification_object) {
          Alert.alert(ERROR_DELETED_OBJECT);
          break;
        }

        /**
         * Notification object knows
         *  1 - Which comment
         *  2 - Which user
         * The comment / reply belongs to
         * STEP 1 : Populate reply / comment
         * STEP 2 : Load user data if moment does not belong to the logged in user
         * STEP 3 : Navigate to relevant moment
         */

        let comment_id: string;
        let not_object;
        let reply: CommentThreadType | undefined;
        let userXId;

        // STEP 1
        if ('parent_comment' in notification_object) {
          //This is a reply
          not_object = notification_object as ThreadNotificationType;
          comment_id = not_object.parent_comment;
          reply = {
            parent_comment: {comment_id: comment_id},
            comment_id: not_object.comment_id,
          };
        } else {
          not_object = notification_object as CommentNotificationType;
          comment_id = not_object.comment_id;
        }

        //STEP 2
        const {user, ...moment} = not_object.notification_data;
        if (user.id !== loggedInUser.userId) {
          fetchUserX(
            dispatch,
            {userId: user.id, username: user.username},
            screenType,
          );
          userXId = user.id;
        }

        const {moment_id} = moment;

        //STEP 3
        if (moment) {
          if (reply) {
            dispatch(updateReplyPosted(reply));
          }
          navigation.push('IndividualMoment', {
            moment,
            userXId,
            screenType,
          });
          setTimeout(() => {
            navigation.push('MomentCommentsScreen', {
              moment_id,
              screenType,
              comment_id,
            });
          }, 500);
        }
        break;
      case 'MOM_3+':
      case 'MOM_FRIEND':
      case 'MOM_TAG':
        const object = notification_object as MomentType;
        await fetchUserX(
          dispatch,
          {userId: id, username: username},
          screenType,
        );
        navigation.push('IndividualMoment', {
          moment: object,
          userXId: id,
          screenType,
        });
        break;
      default:
        break;
    }
  };

  const handleAcceptRequest = async () => {
    await dispatch(
      acceptFriendRequest({id, username, first_name, last_name, thumbnail_url}),
    );
    await dispatch(updateUserXFriends(id, state));
    dispatch(loadUserNotifications());
  };

  const handleDeclineFriendRequest = async () => {
    await dispatch(declineFriendRequest(id));
    dispatch(loadUserNotifications());
  };

  const isOwnProfile = id === loggedInUser.userId;
  const navigateToProfile = async () => {
    if (notification_type === 'SYSTEM_MSG') {
      return;
    }
    if (!userXInStore(state, screenType, id)) {
      await fetchUserX(dispatch, {userId: id, username: username}, screenType);
    }
    navigation.navigate('Profile', {
      userXId: isOwnProfile ? undefined : id,
      screenType,
    });
  };

  const renderContent = () => (
    <View style={styles.container}>
      <TouchableWithoutFeedback
        onPress={navigateToProfile}
        style={styles.avatarContainer}>
        <Avatar style={styles.avatar} uri={avatar} />
      </TouchableWithoutFeedback>
      {notification_type === 'SYSTEM_MSG' || notification_type === 'MOM_TAG' ? (
        // Single-line body text with timestamp
        <View style={styles.contentContainer}>
          <View style={styles.textContainerStyles}>
            {notification_type === 'SYSTEM_MSG' ? (
              <Text style={styles.actorName}>{verbage}</Text>
            ) : (
              <Text>
                <Text style={styles.actorName}>{notification_title} </Text>
                <Text style={styles.verbageStyles}>{verbage} </Text>
                <Text style={styles.timeStampStyles}>
                  {getTimeInShorthand(timestamp)}
                </Text>
              </Text>
            )}
          </View>
        </View>
      ) : (
        // Two-line title and body text with timestamp
        <View style={styles.contentContainer}>
          <TouchableWithoutFeedback onPress={navigateToProfile}>
            <Text style={styles.actorName}>{notification_title}</Text>
          </TouchableWithoutFeedback>
          <TouchableWithoutFeedback
            style={styles.textContainerStyles}
            onPress={onNotificationTap}>
            <Text>
              <Text style={styles.verbageStyles}>{verbage} </Text>
              <Text style={styles.timeStampStyles}>
                {getTimeInShorthand(timestamp)}
              </Text>
            </Text>
          </TouchableWithoutFeedback>
        </View>
      )}
      {/* Friend request accept/decline button */}
      {notification_type === 'FRD_REQ' && (
        <View style={styles.buttonsContainer}>
          <AcceptDeclineButtons
            requester={{id, username, first_name, last_name}}
            onAccept={handleAcceptRequest}
            onReject={handleDeclineFriendRequest}
          />
        </View>
      )}
      {/* Message button when user accepts friend request */}
      {notification_type === 'FRD_ACPT' && (
        <View style={styles.buttonsContainer}>
          <MessageButton
            userXId={id}
            isBlocked={false}
            friendship_status={'friends'}
            externalStyles={{
              container: {
                width: normalize(63),
                height: normalize(21),
                marginTop: '7%',
              },
              buttonTitle: {
                fontSize: normalize(11),
                lineHeight: normalize(13.13),
                letterSpacing: normalize(0.5),
                fontWeight: '700',
                textAlign: 'center',
              },
            }}
            solid
          />
        </View>
      )}
      {/* Moment Image Preview */}
      {(notification_type === 'CMT' ||
        notification_type === 'MOM_3+' ||
        notification_type === 'MOM_TAG' ||
        notification_type === 'MOM_FRIEND') &&
        notification_object && (
          <TouchableWithoutFeedback
            style={styles.moment}
            onPress={onNotificationTap}>
            <Image style={styles.imageFlex} source={{uri: momentURI}} />
          </TouchableWithoutFeedback>
        )}
    </View>
  );

  return unread ? (
    <LinearGradient colors={BACKGROUND_GRADIENT_MAP[2]} useAngle angle={90}>
      {renderContent()}
    </LinearGradient>
  ) : (
    renderContent()
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    height: Math.round(SCREEN_HEIGHT / 10),
    width: SCREEN_WIDTH,
    flex: 1,
    alignSelf: 'center',
    alignItems: 'center',
    paddingHorizontal: '6.3%',
  },
  avatarContainer: {
    height: 42,
    width: 42,
    justifyContent: 'center',
  },
  avatar: {
    height: 42,
    width: 42,
    borderRadius: 20,
  },
  contentContainer: {
    flex: 5,
    marginLeft: '5%',
    marginRight: '3%',
    height: '80%',
    flexDirection: 'column',
    justifyContent: 'space-around',
  },
  actorName: {
    fontSize: normalize(12),
    fontWeight: '700',
    lineHeight: normalize(14.32),
  },
  moment: {
    height: normalize(42),
    width: normalize(42),
  },
  buttonsContainer: {
    height: '80%',
  },
  textContainerStyles: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  verbageStyles: {
    fontWeight: '500',
    fontSize: normalize(11),
    lineHeight: normalize(13.13),
  },
  timeStampStyles: {
    fontWeight: '500',
    fontSize: normalize(11),
    lineHeight: normalize(13.13),
    marginHorizontal: 2,
    color: '#828282',
    textAlignVertical: 'center',
  },
  imageFlex: {
    flex: 1,
  },
});

export default Notification;