/
component.js
383 lines (342 loc) · 11.3 KB
/
component.js
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
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { View, TouchableOpacity, ActivityIndicator, FlatList, Text, Dimensions } from 'react-native';
import moment from 'moment';
import Icon from 'react-native-vector-icons/Ionicons';
import { defaultAvatar } from 'kitsu/constants/app';
import { Avatar } from 'kitsu/screens/Feed/components/Avatar';
import * as Layout from 'kitsu/screens/Feed/components/Layout';
import { CommentTextInput } from 'kitsu/screens/Feed/components/CommentTextInput';
import Hyperlink from 'react-native-hyperlink';
import { StyledText, ViewMoreStyledText } from 'kitsu/components/StyledText';
import { listBackPurple } from 'kitsu/constants/colors';
import { Kitsu } from 'kitsu/config/api';
import { isEmpty, uniqBy } from 'lodash';
import { preprocessFeedPosts } from 'kitsu/utils/preprocessFeed';
import { EmbeddedContent } from 'kitsu/screens/Feed/components/EmbeddedContent';
import { scenePadding } from 'kitsu/screens/Feed/constants';
import { handleURL } from 'kitsu/utils/url';
import { BasicCache } from 'kitsu/utils/cache';
import { styles } from './styles';
const CACHE_WIDTH_KEYS = {
comment: 'commentWidth',
reply: 'commentReplyWidth',
};
export class Comment extends PureComponent {
constructor(props) {
super(props);
const key = props.isCommentReply ? CACHE_WIDTH_KEYS.reply : CACHE_WIDTH_KEYS.comment;
this.state = {
likesCount: props.comment.likesCount,
isLiked: false,
like: null,
replies: [],
repliesCount: props.comment.repliesCount,
isLoadingNextPage: false,
commentWidth: BasicCache.get(key) || null,
};
}
componentDidMount() {
this.mounted = true;
if (!this.props.isTruncated) {
this.fetchLikes();
}
}
componentWillUnmount() {
this.mounted = false;
}
onPagination = async () => {
this.setState({ isLoadingNextPage: true });
try {
await this.fetchReplies({
page: {
offset: this.state.replies.length,
limit: 5,
},
});
} catch (err) {
console.log('Error fetching replies: ', err);
}
this.setState({ isLoadingNextPage: false });
}
onReplyPress = (item) => {
this.props.onReplyPress(item.user, (comment) => {
this.setState({
replies: [...this.state.replies, comment],
repliesCount: this.state.repliesCount + 1,
});
});
}
onCommentLayout = (event) => {
// Only calculate this once, else we'll have lots of updates
if (this.state.commentWidth) return;
// Set the width, we should clear this if we detect dimension change
const { width } = event.nativeEvent.layout;
// The width - left padding
const newWidth = width - scenePadding;
this.setState({ commentWidth: newWidth });
// Cache the value
const key = this.props.isCommentReply ? CACHE_WIDTH_KEYS.reply : CACHE_WIDTH_KEYS.comment;
BasicCache.set(key, newWidth);
}
fetchLikes = async () => {
const { currentUser, comment } = this.props;
try {
const likes = await Kitsu.findAll('commentLikes', {
filter: {
commentId: comment.id,
userId: currentUser.id,
},
});
const like = likes.length && likes[0];
if (this.mounted) {
this.setState({ like, isLiked: !!like });
}
} catch (err) {
console.log('Error fetching likes: ', err);
}
}
toggleLike = async () => {
try {
const { likesCount, isLiked, like } = this.state;
const { comment, currentUser } = this.props;
this.setState({
isLiked: !isLiked,
likesCount: isLiked ? likesCount - 1 : likesCount + 1,
});
if (like) {
await Kitsu.destroy('commentLikes', like.id);
this.setState({ like: null });
} else {
const record = await Kitsu.create('commentLikes', {
comment: {
id: comment.id,
type: 'comments',
},
user: {
id: currentUser.id,
type: 'users',
},
});
this.setState({ like: record });
}
} catch (err) {
console.log('Error toggling like: ', err);
const { isLiked, likesCount } = this.state;
this.setState({
isLiked: !isLiked,
likesCount: isLiked ? likesCount - 1 : likesCount + 1,
});
}
}
fetchReplies = async (requestOptions = {}) => {
try {
this.setState({ isLoadingNextPage: true });
const replies = await Kitsu.findAll('comments', {
filter: {
parentId: this.props.comment.id,
},
fields: {
users: 'slug,avatar,name',
},
include: 'user,uploads',
sort: '-createdAt',
page: { limit: 5 },
...requestOptions,
});
const processed = preprocessFeedPosts(replies);
const uniqueReplies = uniqBy([...processed.reverse(), ...this.state.replies], 'id');
this.setState({ replies: uniqueReplies });
} catch (err) {
console.log('Error fetching replies: ', err);
} finally {
this.setState({ isLoadingNextPage: false });
}
}
renderItem = ({ item }) => (
<Comment
post={this.props.post}
comment={item}
currentUser={this.props.currentUser}
onAvatarPress={this.props.onAvatarPress}
onReplyPress={() => this.onReplyPress(item)}
hideEmbeds={this.props.hideEmbeds}
componentId={this.props.componentId}
isCommentReply
/>
)
render() {
const {
componentId,
comment,
isTruncated,
onAvatarPress,
hideEmbeds,
} = this.props;
const { isLiked, likesCount, replies, repliesCount, commentWidth } = this.state;
const { id, content, createdAt, user, embed, uploads, updatedAt } = comment;
// Get the user avatar and name
const avatar = (user && user.avatar);
const name = (user && user.name) || '-';
const AvatarContainer = props => (
user && onAvatarPress ?
<TouchableOpacity onPress={() => onAvatarPress(user.id)} {...props} />
:
<View {...props} />
);
// The width of the embeds
const maxEmbedWidth = commentWidth || 200;
const minEmbedWidth = Math.max(100, maxEmbedWidth / 2);
return (
<Layout.RowWrap>
<AvatarContainer>
<Avatar avatar={(avatar && avatar.medium) || defaultAvatar} size="medium" />
</AvatarContainer>
<Layout.RowMain onLayout={this.onCommentLayout}>
<View style={[styles.bubble, isEmpty(content) && styles.emptyBubble]}>
<StyledText size="xxsmall" color="dark" bold>{name}</StyledText>
{!isEmpty(content) &&
<Hyperlink linkStyle={styles.linkStyle} onPress={url => handleURL(url)}>
<ViewMoreStyledText
cacheKey={`${id}-${updatedAt}`}
size="xsmall"
color="dark"
textStyle={{ lineHeight: null }}
numberOfLines={(isTruncated && 3) || 8}
selectable
>
{content}
</ViewMoreStyledText>
</Hyperlink>
}
</View>
{(embed || !isEmpty(uploads)) && !hideEmbeds &&
<EmbeddedContent
embed={embed}
uploads={uploads}
maxWidth={maxEmbedWidth}
minWidth={minEmbedWidth}
borderRadius={20}
style={isEmpty(content) ? null : styles.embed}
componentId={componentId}
compact
/>
}
{!isTruncated && (
<View style={styles.commentActions}>
<StyledText color="grey" size="xxsmall">{moment(createdAt).fromNow()}</StyledText>
<TouchableOpacity onPress={this.toggleLike} style={styles.commentActionItem}>
<StyledText color="grey" size="xxsmall">{`Like${isLiked ? 'd' : ''}`}</StyledText>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.onReplyPress(comment)} style={styles.commentActionItem}>
<StyledText color="grey" size="xxsmall">Reply</StyledText>
</TouchableOpacity>
<View style={styles.commentActionItem}>
<Icon name={isLiked ? 'md-heart' : 'md-heart-empty'} style={[styles.likeIcon, isLiked && styles.likeIcon__active]} />
<StyledText color={isLiked ? 'red' : 'grey'} size="xxsmall">{likesCount}</StyledText>
</View>
</View>
)}
{!isTruncated && repliesCount > 0 && (
<View style={styles.nestedComments}>
{replies.length === 0 && (
<ToggleReplies
onPress={() => { this.fetchReplies(); }}
isLoading={this.state.isLoadingNextPage}
repliesCount={repliesCount}
/>
)}
{replies.length > 0 && (
<View>
{repliesCount > replies.length && (
<CommentPagination
onPress={this.onPagination}
isLoading={this.state.isLoadingNextPage}
/>
)}
<FlatList
listKey={`${comment.id}`}
data={replies}
keyExtractor={item => `${item.id}`}
renderItem={this.renderItem}
ItemSeparatorComponent={() => <View style={{ height: 17 }} />}
/>
</View>
)}
</View>
)}
</Layout.RowMain>
</Layout.RowWrap>
);
}
}
Comment.propTypes = {
post: PropTypes.shape({
id: PropTypes.string,
}).isRequired,
comment: PropTypes.shape({
avatar: PropTypes.string,
name: PropTypes.string,
content: PropTypes.string,
time: PropTypes.string,
likesCount: PropTypes.number,
repliesCount: PropTypes.number,
createdAt: PropTypes.string,
}).isRequired,
componentId: PropTypes.any,
isTruncated: PropTypes.bool,
onAvatarPress: PropTypes.func,
onReplyPress: PropTypes.func,
hideEmbeds: PropTypes.bool,
isCommentReply: PropTypes.bool,
};
Comment.defaultProps = {
isTruncated: false,
onAvatarPress: null,
onReplyPress: null,
hideEmbeds: false,
isCommentReply: false,
componentId: null,
};
export const ToggleReplies = ({ onPress, isLoading, repliesCount }) => (
<View>
{isLoading && (
<ActivityIndicator color={listBackPurple} />
)}
{!isLoading && (
<TouchableOpacity onPress={onPress}>
<StyledText color="dark" size="xxsmall" bold>View replies ({repliesCount})</StyledText>
</TouchableOpacity>
)}
</View>
);
ToggleReplies.propTypes = {
onPress: PropTypes.func,
isLoading: PropTypes.bool,
repliesCount: PropTypes.number,
};
ToggleReplies.defaultProps = {
onPress: null,
isLoading: false,
repliesCount: 0,
};
export const CommentPagination = ({ onPress, isLoading }) => (
<View style={{ marginBottom: 14 }}>
{isLoading && (
<ActivityIndicator color={listBackPurple} />
)}
{!isLoading && (
<TouchableOpacity onPress={onPress}>
<StyledText color="dark" size="xxsmall" bold>View previous comments</StyledText>
</TouchableOpacity>
)}
</View>
);
CommentPagination.propTypes = {
onPress: PropTypes.func,
isLoading: PropTypes.bool,
};
CommentPagination.defaultProps = {
onPress: null,
isLoading: false,
};