aboutsummaryrefslogtreecommitdiff
path: root/src/components/profile/Content.tsx
blob: 13db60a5d0d6b828333ae2e5dbfbec6ccbb293eb (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
import AsyncStorage from '@react-native-community/async-storage';
import React, {useCallback, useEffect, useState} from 'react';
import {LayoutChangeEvent, StyleSheet, View} from 'react-native';
import Animated from 'react-native-reanimated';
import {AuthContext, ProfileContext} from '../../routes/';
import {MomentType} from 'src/types';
import {defaultMoments} from '../../constants';
import {SCREEN_HEIGHT} from '../../utils';
import TaggsBar from '../taggs/TaggsBar';
import {Moment} from '../moments';
import ProfileBody from './ProfileBody';
import ProfileCutout from './ProfileCutout';
import ProfileHeader from './ProfileHeader';
import {followOrUnfollowUser, blockOrUnblockUser} from '../../services';

interface ContentProps {
  y: Animated.Value<number>;
  isProfileView: boolean;
}

const Content: React.FC<ContentProps> = ({y, isProfileView}) => {
  const [profileBodyHeight, setProfileBodyHeight] = useState(0);
  const {user, moments, followers, following, updateFollowers} = isProfileView
    ? React.useContext(ProfileContext)
    : React.useContext(AuthContext);

  const {
    logout,
    user: loggedInUser,
    updateFollowers: updateLoggedInUserFollowers,
    blockedUsers,
    updateBlockedUsers,
  } = React.useContext(AuthContext);

  /**
   * States
   */
  const [imagesMap, setImagesMap] = useState<Map<string, MomentType[]>>(
    new Map(),
  );
  const [isFollowed, setIsFollowed] = React.useState<boolean>(false);
  const [isBlocked, setIsBlocked] = React.useState<boolean>(false);

  /**
   * If own profile is being viewed then do not show the follow button.
   */
  const isOwnProfile = loggedInUser.username === user.username;

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

  const {userId} = user;

  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(() => {
    if (!userId) {
      return;
    }
    createImagesMap();
  }, [createImagesMap]);

  /**
   * This hook is called on load of profile and when you update the followers list.
   */
  useEffect(() => {
    if (!userId) {
      return;
    }
    const isActuallyFollowed = followers.some(
      (follower) => follower.username === loggedInUser.username,
    );
    if (isFollowed != isActuallyFollowed) {
      setIsFollowed(isActuallyFollowed);
    }
  }, [followers]);

  useEffect(() => {
    if (!userId) {
      return;
    }

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

  /**
   * Handles a click on the follow / unfollow button.
   * updateFollowers and updateLoggedInUerFollowers to make sure that we update followers list / count for both the users in context.
   */
  const handleFollowUnfollow = async () => {
    const token = await AsyncStorage.getItem('token');
    if (!token) {
      logout();
      return;
    }
    const isUpdatedSuccessful = await followOrUnfollowUser(
      loggedInUser.userId,
      userId,
      token,
      isFollowed,
    );
    if (isUpdatedSuccessful) {
      setIsFollowed(!isFollowed);
      updateFollowers(true);
      updateLoggedInUserFollowers(true);
    }
  };

  /**
   * Handles a click on the block / unblock button.
   */
  const handleBlockUnblock = async () => {
    const token = await AsyncStorage.getItem('token');
    if (!token) {
      logout();
      return;
    }
    const isUpdatedSuccessful = await blockOrUnblockUser(
      loggedInUser.userId,
      userId,
      token,
      isBlocked,
    );
    if (isUpdatedSuccessful) {
      setIsBlocked(!isBlocked);
      updateBlockedUsers(true);
      updateFollowers(true);
      updateLoggedInUserFollowers(true);
    }
  };

  return (
    <Animated.ScrollView
      style={styles.container}
      onScroll={(e) => y.setValue(e.nativeEvent.contentOffset.y)}
      showsVerticalScrollIndicator={false}
      scrollEventThrottle={1}>
      <ProfileCutout />
      <ProfileHeader
        isProfileView={isProfileView}
        numFollowing={following.length}
        numFollowers={followers.length}
      />
      <ProfileBody
        {...{
          onLayout,
          isProfileView,
          isOwnProfile,
          isFollowed,
          handleFollowUnfollow,
          isBlocked,
          handleBlockUnblock,
        }}
      />
      <TaggsBar {...{y, profileBodyHeight, isProfileView}} />
      <View style={styles.momentsContainer}>
        {defaultMoments.map((title, index) => (
          <Moment
            key={index}
            title={title}
            images={imagesMap.get(title)}
            isProfileView={isProfileView}
          />
        ))}
      </View>
    </Animated.ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  momentsContainer: {
    backgroundColor: '#f2f2f2',
    paddingBottom: SCREEN_HEIGHT / 10,
  },
});

export default Content;