aboutsummaryrefslogtreecommitdiff
path: root/src/components/profile/Content.tsx
blob: 4082f7346424f7123a44503941055d6fd076e39b (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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import React, {useCallback, useEffect, useState} from 'react';
import {
  Alert,
  LayoutChangeEvent,
  NativeScrollEvent,
  NativeSyntheticEvent,
  RefreshControl,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import Animated from 'react-native-reanimated';
import {CategorySelectionScreenType, MomentType, ScreenType} from '../../types';
import {COVER_HEIGHT, TAGG_TEXT_LIGHT_BLUE} from '../../constants';
import {
  fetchUserX,
  getUserAsProfilePreviewType,
  moveCategory,
  normalize,
  SCREEN_HEIGHT,
  userLogin,
} from '../../utils';
import TaggsBar from '../taggs/TaggsBar';
import {Moment} from '../moments';
import ProfileBody from './ProfileBody';
import ProfileCutout from './ProfileCutout';
import ProfileHeader from './ProfileHeader';
import {useDispatch, useSelector, useStore} from 'react-redux';
import {RootState} from '../../store/rootreducer';
import {
  friendUnfriendUser,
  blockUnblockUser,
  loadFriendsData,
  updateUserXFriends,
  updateMomentCategories,
  deleteUserMomentsForCategory,
  updateUserXProfileAllScreens,
} from '../../store/actions';
import {
  NO_USER,
  NO_PROFILE,
  EMPTY_PROFILE_PREVIEW_LIST,
  EMPTY_MOMENTS_LIST,
} from '../../store/initialStates';
import {Cover} from '.';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import GreyPlusLogo from '../../assets/icons/grey-plus-logo.svg';
import {TaggPrompt} from '../common';
import {
  UPLOAD_MOMENT_PROMPT_THREE_HEADER,
  UPLOAD_MOMENT_PROMPT_THREE_MESSAGE,
  UPLOAD_MOMENT_PROMPT_TWO_HEADER,
  UPLOAD_MOMENT_PROMPT_TWO_MESSAGE,
} from '../../constants/strings';

interface ContentProps {
  y: Animated.Value<number>;
  userXId: string | undefined;
  screenType: ScreenType;
}

const Content: React.FC<ContentProps> = ({y, userXId, screenType}) => {
  const dispatch = useDispatch();

  const {user = NO_USER, profile = NO_PROFILE} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.user);

  const {friends = EMPTY_PROFILE_PREVIEW_LIST} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.friends);

  const {
    friends: friendsLoggedInUser = EMPTY_PROFILE_PREVIEW_LIST,
  } = useSelector((state: RootState) => state.friends);

  const {moments = EMPTY_MOMENTS_LIST} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.moments);

  const {momentCategories = []} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.momentCategories);

  const {blockedUsers = EMPTY_PROFILE_PREVIEW_LIST} = useSelector(
    (state: RootState) => state.blocked,
  );
  const {user: loggedInUser = NO_USER} = useSelector(
    (state: RootState) => state.user,
  );
  const state = useStore().getState();

  const navigation = useNavigation();

  /**
   * States
   */
  const [imagesMap, setImagesMap] = useState<Map<string, MomentType[]>>(
    new Map(),
  );
  const [isFriend, setIsFriend] = useState<boolean>(false);
  const [isBlocked, setIsBlocked] = useState<boolean>(false);
  const [profileBodyHeight, setProfileBodyHeight] = useState(0);
  const [shouldBounce, setShouldBounce] = useState<boolean>(true);
  const [refreshing, setRefreshing] = useState<boolean>(false);

  const [isStageTwoPromptClosed, setIsStageTwoPromptClosed] = useState<boolean>(
    false,
  );
  const [isStageOnePromptClosed, setIsStageOnePromptClosed] = useState<boolean>(
    false,
  );
  const [
    isStageThreePromptClosed,
    setIsStageThreePromptClosed,
  ] = useState<boolean>(false);

  const onRefresh = useCallback(() => {
    const refrestState = async () => {
      if (!userXId) {
        await userLogin(dispatch, loggedInUser);
      } else {
        await fetchUserX(dispatch, user, screenType);
      }
    };
    setRefreshing(true);
    refrestState().then(() => {
      setRefreshing(false);
    });
  }, []);

  const onLayout = (e: LayoutChangeEvent) => {
    const {height} = e.nativeEvent.layout;
    setProfileBodyHeight(height);
  };

  const createImagesMap = useCallback(() => {
    var map = new Map();
    moments.forEach(function (imageObject) {
      var moment_category = imageObject.moment_category;
      if (map.has(moment_category)) {
        map.get(moment_category).push(imageObject);
      } else {
        map.set(moment_category, [imageObject]);
      }
    });
    setImagesMap(map);
  }, [moments]);

  useEffect(() => {
    createImagesMap();
  }, [createImagesMap]);

  const move = (direction: 'up' | 'down', title: string) => {
    let categories = [...momentCategories];
    categories = moveCategory(categories, title, direction === 'up');
    dispatch(updateMomentCategories(categories, false));
  };

  /**
   * Prompt user to perform an activity based on their profile completion stage
   * To fire 2 seconds after the screen comes in focus
   * 1 means STAGE_1:
   *    The user must upload a moment, so take them to a screen  guiding them to post a moment
   * 2 means STAGE_2:
   *    The user must create another category so show a prompt on top of the screen
   * 3 means STAGE_3:
   *    The user must upload a moment to the second category, so show a prompt on top of the screen
   * Else, profile is complete and no prompt needs to be shown
   */
  useFocusEffect(
    useCallback(() => {
      const navigateToMomentUploadPrompt = () => {
        switch (profile.profile_completion_stage) {
          case 1:
            if (
              momentCategories &&
              momentCategories[0] &&
              !isStageOnePromptClosed
            ) {
              navigation.navigate('MomentUploadPrompt', {
                screenType,
                momentCategory: momentCategories[0],
              });
              setIsStageOnePromptClosed(true);
            }
            break;
          case 2:
            setIsStageTwoPromptClosed(false);
            break;
          case 3:
            setIsStageThreePromptClosed(false);
            break;
          default:
            break;
        }
      };
      if (!userXId) {
        setTimeout(navigateToMomentUploadPrompt, 2000);
      }
    }, [
      profile.profile_completion_stage,
      momentCategories,
      userXId,
      isStageOnePromptClosed,
    ]),
  );

  useEffect(() => {
    const isActuallyBlocked = blockedUsers.some(
      (cur_user) => user.username === cur_user.username,
    );
    if (isBlocked != isActuallyBlocked) {
      setIsBlocked(isActuallyBlocked);
    }
  }, [blockedUsers, user]);

  // Handles click on friend/requested/unfriend button
  /*
   * When user logged in clicks on the friend button:
   A request is sent.
   Which means you have to update the status of their friendshpi to requested
   When the status is changed to requested the button should change to requested.
   When the button is changed to requested and thr user clicks on it,
   a request much go to the backend to delete that request
   When that succeeds, their friendship must be updated to no-record again;
   When the button is changed to no_record, the add friends button should be displayed again
   */
  const handleFriendUnfriend = async () => {
    const {friendship_status} = profile;
    await dispatch(
      friendUnfriendUser(
        loggedInUser,
        getUserAsProfilePreviewType(user, profile),
        friendship_status,
        screenType,
      ),
    );
    await dispatch(updateUserXFriends(user.userId, state));
    dispatch(updateUserXProfileAllScreens(user.userId, state));
  };

  /**
   * Handles a click on the block / unblock button.
   * loadFriends updates friends list for the logged in user
   * updateUserXFriends updates friends list for the user.
   */
  const handleBlockUnblock = async (callback?: () => void) => {
    await dispatch(
      blockUnblockUser(
        loggedInUser,
        getUserAsProfilePreviewType(user, profile),
        isBlocked,
      ),
    );
    await dispatch(loadFriendsData(loggedInUser.userId));
    await dispatch(updateUserXFriends(user.userId, state));
    if (callback) {
      callback();
    }
  };

  /**
   * Handle deletion of a category
   * Confirm with user before deleting the category
   * @param category category to be deleted
   */
  const handleCategoryDeletion = (category: string) => {
    Alert.alert(
      'Category Deletion',
      `Are you sure that you want to delete the category ${category} ?`,
      [
        {
          text: 'Cancel',
          style: 'cancel',
        },
        {
          text: 'Yes',
          onPress: () => {
            dispatch(
              updateMomentCategories(
                momentCategories.filter((mc) => mc !== category),
                false,
              ),
            );
            dispatch(deleteUserMomentsForCategory(category));
          },
        },
      ],
      {cancelable: true},
    );
  };

  const handleScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
    /**
     * Set the new y position
     */
    const newY = e.nativeEvent.contentOffset.y;
    y.setValue(newY);

    /**
     * Do not allow overflow of scroll on bottom of the screen
     * SCREEN_HEIGHT - COVER_HEIGHT = Height of the scroll view
     */
    if (newY >= SCREEN_HEIGHT - COVER_HEIGHT) {
      setShouldBounce(false);
    } else if (newY === 0) {
      setShouldBounce(true);
    }
  };

  return (
    <Animated.ScrollView
      style={styles.container}
      onScroll={(e) => handleScroll(e)}
      bounces={shouldBounce}
      showsVerticalScrollIndicator={false}
      scrollEventThrottle={1}
      stickyHeaderIndices={[4]}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }>
      <Cover {...{userXId, screenType}} />
      <ProfileCutout />
      <ProfileHeader
        {...{userXId, screenType, handleBlockUnblock, isBlocked}}
      />
      <ProfileBody
        {...{
          onLayout,
          userXId,
          screenType,
          isFriend,
          handleFriendUnfriend,
          handleBlockUnblock,
          isBlocked,
        }}
      />
      <TaggsBar {...{y, profileBodyHeight, userXId, screenType}} />
      <View style={styles.momentsContainer}>
        {userXId && moments.length === 0 && (
          <View style={styles.plusIconContainer}>
            <GreyPlusLogo width={90} height={90} />
            <Text style={styles.noMomentsText}>{`Looks like ${
              profile.name.split(' ')[0]
            } has not posted any moments yet`}</Text>
          </View>
        )}
        {!userXId &&
          profile.profile_completion_stage === 2 &&
          !isStageTwoPromptClosed && (
            <TaggPrompt
              messageHeader={UPLOAD_MOMENT_PROMPT_TWO_HEADER}
              messageBody={UPLOAD_MOMENT_PROMPT_TWO_MESSAGE}
              logoType=""
              onClose={() => {
                setIsStageTwoPromptClosed(true);
              }}
            />
          )}
        {!userXId &&
          profile.profile_completion_stage === 3 &&
          !isStageThreePromptClosed && (
            <TaggPrompt
              messageHeader={UPLOAD_MOMENT_PROMPT_THREE_HEADER}
              messageBody={UPLOAD_MOMENT_PROMPT_THREE_MESSAGE}
              logoType=""
              onClose={() => {
                setIsStageThreePromptClosed(true);
              }}
            />
          )}
        {momentCategories.map(
          (title, index) =>
            (!userXId || imagesMap.get(title)) && (
              <Moment
                key={index}
                title={title}
                images={imagesMap.get(title)}
                userXId={userXId}
                screenType={screenType}
                handleMomentCategoryDelete={handleCategoryDeletion}
                shouldAllowDeletion={momentCategories.length > 1}
                showUpButton={index !== 0}
                showDownButton={index !== momentCategories.length - 1}
                move={move}
              />
            ),
        )}
        {!userXId && (
          <TouchableOpacity
            onPress={() =>
              navigation.push('CategorySelection', {
                screenType: CategorySelectionScreenType.Profile,
                user: loggedInUser,
              })
            }
            style={styles.createCategoryButton}>
            <Text style={styles.createCategoryButtonLabel}>
              Create a new category
            </Text>
          </TouchableOpacity>
        )}
      </View>
    </Animated.ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  momentsContainer: {
    backgroundColor: '#f2f2f2',
    paddingBottom: SCREEN_HEIGHT / 10,
    flex: 1,
    flexDirection: 'column',
  },
  createCategoryButton: {
    backgroundColor: TAGG_TEXT_LIGHT_BLUE,
    justifyContent: 'center',
    alignItems: 'center',
    width: '70%',
    height: 30,
    marginTop: '15%',
    alignSelf: 'center',
  },
  createCategoryButtonLabel: {
    fontSize: normalize(16),
    fontWeight: '500',
    color: 'white',
  },
  plusIconContainer: {
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    marginVertical: '10%',
  },
  noMomentsText: {
    fontSize: normalize(14),
    fontWeight: 'bold',
    color: 'gray',
    marginVertical: '8%',
  },
});

export default Content;