aboutsummaryrefslogtreecommitdiff
path: root/src/components/comments/AddComment.tsx
blob: 8a4ec08244044451e4d605c418627dbc9842e603 (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
import React, {useContext, useEffect, useRef, useState} from 'react';
import {
  Keyboard,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
  TextInput,
  View,
} from 'react-native';
import {useDispatch} from 'react-redux';
import {TAGG_LIGHT_BLUE} from '../../constants';
import {CommentContext} from '../../screens/profile/MomentCommentsScreen';
import {postComment} from '../../services';
import {updateReplyPosted} from '../../store/actions';
import {CommentThreadType, CommentType} from '../../types';
import {SCREEN_HEIGHT, SCREEN_WIDTH, normalize} from '../../utils';
import {mentionPartTypes} from '../../utils/comments';
import {CommentTextField} from './CommentTextField';
import MentionInputControlled from './MentionInputControlled';

export interface AddCommentProps {
  momentId: string;
  placeholderText: string;
  callback?: (message: string) => void;
  onFocus?: () => void;
  isKeyboardAvoiding?: boolean;
  theme?: 'dark' | 'white';
}

const AddComment: React.FC<AddCommentProps> = ({
  momentId,
  placeholderText,
  callback = (_) => null,
  onFocus = () => null,
  isKeyboardAvoiding = true,
  theme = 'white',
}) => {
  const {setShouldUpdateAllComments, commentTapped} =
    useContext(CommentContext);
  const [inReplyToMention, setInReplyToMention] = useState('');
  const [comment, setComment] = useState('');
  const [keyboardVisible, setKeyboardVisible] = useState(false);
  const dispatch = useDispatch();
  const ref = useRef<TextInput>(null);
  const isReplyingToComment =
    commentTapped !== undefined && !('parent_comment' in commentTapped);
  const isReplyingToReply =
    commentTapped !== undefined && 'parent_comment' in commentTapped;
  const objectId: string = commentTapped
    ? 'parent_comment' in commentTapped
      ? (commentTapped as CommentThreadType).parent_comment.comment_id
      : (commentTapped as CommentType).comment_id
    : momentId;

  const addComment = async () => {
    const trimmed = comment.trim();
    if (trimmed === '') {
      return;
    }
    const message = inReplyToMention + trimmed;
    const postedComment = await postComment(
      message,
      objectId,
      isReplyingToComment || isReplyingToReply,
    );

    if (postedComment) {
      callback(message);
      setComment('');
      setInReplyToMention('');

      //Set new reply posted object
      //This helps us show the latest reply on top
      //Data set is kind of stale but it works
      if (isReplyingToComment || isReplyingToReply) {
        dispatch(
          updateReplyPosted({
            comment_id: postedComment.comment_id,
            parent_comment: {comment_id: objectId},
          }),
        );
      }
      setShouldUpdateAllComments(true);
    }
  };

  useEffect(() => {
    const showKeyboard = () => setKeyboardVisible(true);
    Keyboard.addListener('keyboardWillShow', showKeyboard);
    return () => Keyboard.removeListener('keyboardWillShow', showKeyboard);
  }, []);

  useEffect(() => {
    const hideKeyboard = () => setKeyboardVisible(false);
    Keyboard.addListener('keyboardWillHide', hideKeyboard);
    return () => Keyboard.removeListener('keyboardWillHide', hideKeyboard);
  }, []);

  useEffect(() => {
    if (isReplyingToComment || isReplyingToReply) {
      // bring up keyboard
      ref.current?.focus();
    }
    if (commentTapped && isReplyingToReply) {
      const commenter = (commentTapped as CommentThreadType).commenter;
      setInReplyToMention(`@[${commenter.username}](${commenter.id}) `);
    } else {
      setInReplyToMention('');
    }
  }, [isReplyingToComment, isReplyingToReply, commentTapped]);

  const mainContent = () => (
    <View
      style={[
        theme === 'white' ? styles.containerWhite : styles.containerDark,
        keyboardVisible && theme !== 'dark' ? styles.whiteBackround : {},
      ]}>
      <View style={styles.textContainer}>
        <MentionInputControlled
          containerStyle={styles.text}
          placeholderTextColor={theme === 'dark' ? '#828282' : undefined}
          placeholder={placeholderText}
          value={inReplyToMention + comment}
          onFocus={onFocus}
          onChange={(newText: string) => {
            // skipping the `inReplyToMention` text
            setComment(
              newText.substring(inReplyToMention.length, newText.length),
            );
          }}
          inputRef={ref}
          partTypes={mentionPartTypes('blue', 'comment')}
          addComment={addComment}
          NewText={CommentTextField}
          theme={theme}
          keyboardVisible={keyboardVisible}
          comment={comment}
        />
      </View>
    </View>
  );

  return isKeyboardAvoiding ? (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={SCREEN_HEIGHT * 0.1}>
      {mainContent()}
    </KeyboardAvoidingView>
  ) : (
    mainContent()
  );
};

const styles = StyleSheet.create({
  containerDark: {
    alignItems: 'center',
    width: SCREEN_WIDTH,
  },
  containerWhite: {
    backgroundColor: '#f7f7f7',
    alignItems: 'center',
    width: SCREEN_WIDTH,
  },
  textContainer: {
    width: '95%',
    backgroundColor: '#e8e8e8',
    alignItems: 'center',
    justifyContent: 'space-between',
    margin: '3%',
    borderRadius: 25,
    height: normalize(45),
  },
  text: {
    flex: 1,
    maxHeight: 100,
  },
  avatar: {
    height: 35,
    width: 35,
    borderRadius: 30,
    marginRight: 10,
    marginLeft: '3%',
    marginVertical: '2%',
    alignSelf: 'flex-end',
  },
  submitButton: {
    height: 35,
    width: 35,
    backgroundColor: TAGG_LIGHT_BLUE,
    borderRadius: 999,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: '3%',
    marginVertical: '2%',
    alignSelf: 'flex-end',
  },
  whiteBackround: {
    backgroundColor: '#fff',
  },
});

export default AddComment;