aboutsummaryrefslogtreecommitdiff
path: root/src/components/comments/CommentsContainer.tsx
blob: d5d02a92f5c8226e759845ac3756c87056c77e55 (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
import moment from 'moment';
import React, {useContext, useEffect, useRef, useState} from 'react';
import {StyleSheet} from 'react-native';
import {FlatList} from 'react-native-gesture-handler';
import {useDispatch, useSelector} from 'react-redux';
import {CommentContext} from '../../screens/profile/MomentCommentsScreen';
import {getComments} from '../../services';
import {updateReplyPosted} from '../../store/actions';
import {RootState} from '../../store/rootReducer';
import {CommentThreadType, CommentType, ScreenType} from '../../types';
import {SCREEN_HEIGHT} from '../../utils';
import CommentTile from './CommentTile';

export type CommentsContainerProps = {
  screenType: ScreenType;
  objectId: string;
  commentId?: string;
  shouldUpdate: boolean;
  setShouldUpdate: (update: boolean) => void;
  isThread: boolean;
};

/**
 * Comments Container to be used for both comments and replies
 */

const CommentsContainer: React.FC<CommentsContainerProps> = ({
  screenType,
  objectId,
  isThread,
  shouldUpdate,
  setShouldUpdate,
  commentId,
}) => {
  const {setCommentsLength, commentTapped} = useContext(CommentContext);
  const {username: loggedInUsername} = useSelector(
    (state: RootState) => state.user.user,
  );
  const [commentsList, setCommentsList] = useState<CommentType[]>([]);
  const dispatch = useDispatch();
  const ref = useRef<FlatList<CommentType>>(null);

  useEffect(() => {
    const loadComments = async () => {
      await getComments(objectId, isThread).then((comments) => {
        if (comments && subscribedToLoadComments) {
          setCommentsList(comments);
          if (setCommentsLength) {
            setCommentsLength(comments.length);
          }
          setShouldUpdate(false);
        }
      });
    };
    let subscribedToLoadComments = true;
    if (shouldUpdate) {
      loadComments();
    }
    return () => {
      subscribedToLoadComments = false;
    };
  }, [shouldUpdate]);

  useEffect(() => {
    const performAction = () => {
      if (commentId) {
        swapCommentTo(commentId, 0);
      } else if (!isThread && !commentTapped) {
        setTimeout(() => {
          ref.current?.scrollToEnd({animated: true});
        }, 500);
      }
    };
    if (commentsList) {
      //Bring the relevant comment to top if a comment id is present else scroll if necessary
      performAction();
    }

    //Clean up the reply id present in store
    return () => {
      if (commentId && isThread) {
        setTimeout(() => {
          dispatch(updateReplyPosted(undefined));
        }, 200);
      }
    };
  }, [commentsList, commentId]);

  // eslint-disable-next-line no-shadow
  const swapCommentTo = (commentId: string, toIndex: number) => {
    const index = commentsList.findIndex(
      (item) => item.comment_id === commentId,
    );
    if (index > 0) {
      let comments = [...commentsList];
      const temp = comments[index];
      comments[index] = comments[toIndex];
      comments[toIndex] = temp;
      setCommentsList(comments);
    }
  };

  const ITEM_HEIGHT = SCREEN_HEIGHT / 7.0;

  const renderComment = ({item}: {item: CommentType | CommentThreadType}) => (
    <CommentTile
      key={item.comment_id}
      commentObject={item}
      screenType={screenType}
      isThread={isThread}
      shouldUpdateParent={shouldUpdate}
      setShouldUpdateParent={setShouldUpdate}
      canDelete={item.commenter.username === loggedInUsername}
    />
  );

  return (
    <FlatList
      data={commentsList.sort(
        (a, b) => moment(a.date_created).unix() - moment(b.date_created).unix(),
      )}
      ref={ref}
      keyExtractor={(item, index) => index.toString()}
      decelerationRate={'fast'}
      snapToAlignment={'start'}
      snapToInterval={ITEM_HEIGHT}
      renderItem={renderComment}
      showsVerticalScrollIndicator={false}
      contentContainerStyle={styles.scrollViewContent}
      getItemLayout={(data, index) => ({
        length: ITEM_HEIGHT,
        offset: ITEM_HEIGHT * index,
        index,
      })}
      pagingEnabled
    />
  );
};

const styles = StyleSheet.create({
  scrollView: {},
  scrollViewContent: {
    justifyContent: 'center',
  },
});

export default CommentsContainer;