lbry-desktop/ui/component/commentsList/view.jsx

321 lines
10 KiB
React
Raw Normal View History

2019-05-17 20:21:07 +02:00
// @flow
import * as REACTION_TYPES from 'constants/reactions';
2020-09-30 20:46:17 +02:00
import * as ICONS from 'constants/icons';
import { COMMENT_PAGE_SIZE_TOP_LEVEL, SORT_BY } from 'constants/comment';
2019-06-27 01:59:27 +02:00
import React, { useEffect } from 'react';
import classnames from 'classnames';
import CommentView from 'component/comment';
import Spinner from 'component/spinner';
2020-08-24 19:35:21 +02:00
import Button from 'component/button';
import Card from 'component/common/card';
import CommentCreate from 'component/commentCreate';
2020-10-01 20:43:44 +02:00
import usePersistedState from 'effects/use-persisted-state';
import { ENABLE_COMMENT_REACTIONS } from 'config';
import Empty from 'component/common/empty';
import debounce from 'util/debounce';
const DEBOUNCE_SCROLL_HANDLER_MS = 200;
function scaleToDevicePixelRatio(value) {
const devicePixelRatio = window.devicePixelRatio || 1.0;
if (devicePixelRatio < 1.0) {
return Math.ceil(value / devicePixelRatio);
}
return Math.ceil(value * devicePixelRatio);
}
2019-05-17 20:21:07 +02:00
2019-06-27 01:59:27 +02:00
type Props = {
allCommentIds: any,
topLevelComments: Array<Comment>,
topLevelTotalPages: number,
commentsDisabledBySettings: boolean,
fetchTopLevelComments: (string, number, number, number) => void,
fetchComment: (string) => void,
fetchReacts: (Array<string>) => Promise<any>,
resetComments: (string) => void,
2019-05-17 20:21:07 +02:00
uri: string,
claimIsMine: boolean,
myChannels: ?Array<ChannelClaim>,
isFetchingComments: boolean,
isFetchingReacts: boolean,
linkedCommentId?: string,
2020-09-30 20:46:17 +02:00
totalComments: number,
fetchingChannels: boolean,
myReactsByCommentId: ?{ [string]: Array<string> }, // "CommentId:MyChannelId" -> reaction array (note the ID concatenation)
othersReactsById: ?{ [string]: { [REACTION_TYPES.LIKE | REACTION_TYPES.DISLIKE]: number } },
activeChannelId: ?string,
2019-05-17 20:21:07 +02:00
};
2019-06-27 01:59:27 +02:00
function CommentList(props: Props) {
2020-09-29 16:10:23 +02:00
const {
allCommentIds,
fetchTopLevelComments,
fetchComment,
2020-10-01 20:43:44 +02:00
fetchReacts,
resetComments,
2020-09-29 16:10:23 +02:00
uri,
topLevelComments,
topLevelTotalPages,
commentsDisabledBySettings,
2020-09-29 16:10:23 +02:00
claimIsMine,
myChannels,
isFetchingComments,
isFetchingReacts,
linkedCommentId,
2020-09-30 20:46:17 +02:00
totalComments,
fetchingChannels,
myReactsByCommentId,
othersReactsById,
activeChannelId,
2020-09-29 16:10:23 +02:00
} = props;
2020-10-01 20:43:44 +02:00
const commentRef = React.useRef();
const spinnerRef = React.useRef();
const DEFAULT_SORT = ENABLE_COMMENT_REACTIONS ? SORT_BY.POPULARITY : SORT_BY.NEWEST;
const [sort, setSort] = usePersistedState('comment-sort-by', DEFAULT_SORT);
const [page, setPage] = React.useState(0);
const totalFetchedComments = allCommentIds ? allCommentIds.length : 0;
// Display comments immediately if not fetching reactions
// If not, wait to show comments until reactions are fetched
const [readyToDisplayComments, setReadyToDisplayComments] = React.useState(
Boolean(othersReactsById) || !ENABLE_COMMENT_REACTIONS
);
const hasNoComments = !totalComments;
const moreBelow = page < topLevelTotalPages;
const isMyComment = (channelId: string): boolean => {
if (myChannels != null && channelId != null) {
for (let i = 0; i < myChannels.length; i++) {
if (myChannels[i].claim_id === channelId) {
return true;
}
}
}
return false;
};
function changeSort(newSort) {
if (sort !== newSort) {
setSort(newSort);
setPage(0); // Invalidate existing comments
2020-08-24 19:35:21 +02:00
}
}
2020-08-24 19:35:21 +02:00
// Reset comments
2019-06-27 01:59:27 +02:00
useEffect(() => {
if (page === 0) {
resetComments(uri);
setPage(1);
}
}, [page, uri, resetComments]);
2019-06-27 01:59:27 +02:00
// Fetch top-level comments
2020-10-01 20:43:44 +02:00
useEffect(() => {
if (page !== 0) {
if (page === 1 && linkedCommentId) {
fetchComment(linkedCommentId);
}
fetchTopLevelComments(uri, page, COMMENT_PAGE_SIZE_TOP_LEVEL, sort);
}
}, [fetchTopLevelComments, uri, page, resetComments, sort, linkedCommentId, fetchComment]);
// Fetch reacts
useEffect(() => {
if (totalFetchedComments > 0 && ENABLE_COMMENT_REACTIONS && !fetchingChannels && !isFetchingReacts) {
let idsForReactionFetch;
if (!othersReactsById || !myReactsByCommentId) {
idsForReactionFetch = allCommentIds;
} else {
idsForReactionFetch = allCommentIds.filter((commentId) => {
const key = activeChannelId ? `${commentId}:${activeChannelId}` : commentId;
return !othersReactsById[key] || (activeChannelId && !myReactsByCommentId[key]);
});
}
if (idsForReactionFetch.length !== 0) {
fetchReacts(idsForReactionFetch)
.then(() => {
setReadyToDisplayComments(true);
})
.catch(() => setReadyToDisplayComments(true));
}
}
}, [
totalFetchedComments,
allCommentIds,
othersReactsById,
myReactsByCommentId,
fetchReacts,
uri,
activeChannelId,
fetchingChannels,
isFetchingReacts,
]);
2020-09-29 16:10:23 +02:00
// Scroll to linked-comment
2020-08-24 19:35:21 +02:00
useEffect(() => {
if (readyToDisplayComments && linkedCommentId && commentRef && commentRef.current) {
2020-08-24 19:35:21 +02:00
commentRef.current.scrollIntoView({ block: 'start' });
window.scrollBy(0, -125);
2020-08-24 19:35:21 +02:00
}
}, [readyToDisplayComments, linkedCommentId]);
2020-02-05 04:55:00 +01:00
// Infinite scroll
2020-10-05 23:25:23 +02:00
useEffect(() => {
function shouldFetchNextPage(page, topLevelTotalPages, window, document, yPrefetchPx = 1000) {
if (!spinnerRef || !spinnerRef.current) {
return false;
}
const rect = spinnerRef.current.getBoundingClientRect(); // $FlowFixMe
const windowH = window.innerHeight || document.documentElement.clientHeight; // $FlowFixMe
const windowW = window.innerWidth || document.documentElement.clientWidth; // $FlowFixMe
const isApproachingViewport = yPrefetchPx !== 0 && rect.top < windowH + scaleToDevicePixelRatio(yPrefetchPx);
const isInViewport =
rect.width > 0 &&
rect.height > 0 &&
rect.bottom >= 0 &&
rect.right >= 0 &&
// $FlowFixMe
rect.top <= windowH &&
// $FlowFixMe
rect.left <= windowW;
return (isInViewport || isApproachingViewport) && page < topLevelTotalPages;
}
2020-10-05 23:25:23 +02:00
const handleCommentScroll = debounce(() => {
if (shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
setPage(page + 1);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
if (!isFetchingComments && readyToDisplayComments && moreBelow && spinnerRef && spinnerRef.current) {
if (shouldFetchNextPage(page, topLevelTotalPages, window, document, 0)) {
setPage(page + 1);
} else {
window.addEventListener('scroll', handleCommentScroll);
return () => window.removeEventListener('scroll', handleCommentScroll);
}
2020-10-05 23:25:23 +02:00
}
}, [
page,
moreBelow,
spinnerRef,
isFetchingComments,
readyToDisplayComments,
topLevelComments.length,
topLevelTotalPages,
]);
2020-02-05 04:55:00 +01:00
const displayedComments = readyToDisplayComments ? topLevelComments : [];
2019-06-27 01:59:27 +02:00
return (
2020-08-24 19:35:21 +02:00
<Card
2020-08-31 18:28:28 +02:00
title={
totalComments > 0
? totalComments === 1
? __('1 comment')
: __('%total_comments% comments', { total_comments: totalComments })
: __('Leave a comment')
}
titleActions={
<>
{totalComments > 1 && ENABLE_COMMENT_REACTIONS && (
<span className="comment__sort">
<Button
button="alt"
2020-10-07 13:16:13 +02:00
label={__('Best')}
icon={ICONS.BEST}
iconSize={18}
onClick={() => changeSort(SORT_BY.POPULARITY)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_BY.POPULARITY,
})}
/>
<Button
button="alt"
2020-10-07 13:16:13 +02:00
label={__('Controversial')}
icon={ICONS.CONTROVERSIAL}
iconSize={18}
onClick={() => changeSort(SORT_BY.CONTROVERSY)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_BY.CONTROVERSY,
})}
/>
<Button
button="alt"
2020-10-07 13:16:13 +02:00
label={__('New')}
icon={ICONS.NEW}
iconSize={18}
onClick={() => changeSort(SORT_BY.NEWEST)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_BY.NEWEST,
})}
/>
</span>
)}
2020-10-27 17:24:31 +01:00
<Button
button="alt"
icon={ICONS.REFRESH}
title={__('Refresh')}
onClick={() => {
setPage(0);
2020-10-27 17:24:31 +01:00
}}
/>
</>
}
2020-08-24 19:35:21 +02:00
actions={
<>
<CommentCreate uri={uri} />
2020-10-07 21:14:52 +02:00
{!commentsDisabledBySettings && !isFetchingComments && hasNoComments && (
2020-12-16 19:31:07 +01:00
<Empty padded text={__('That was pretty deep. What do you think?')} />
)}
2020-10-07 21:14:52 +02:00
2020-08-24 19:35:21 +02:00
<ul className="comments" ref={commentRef}>
{topLevelComments &&
2020-08-24 19:35:21 +02:00
displayedComments &&
2021-04-23 21:59:48 +02:00
displayedComments.map((comment) => {
2020-08-24 19:35:21 +02:00
return (
<CommentView
isTopLevel
2020-10-07 21:14:52 +02:00
threadDepth={3}
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
author={comment.channel_name}
claimId={comment.claim_id}
commentId={comment.comment_id}
message={comment.comment}
timePosted={comment.timestamp * 1000}
claimIsMine={claimIsMine}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
linkedCommentId={linkedCommentId}
isPinned={comment.is_pinned}
2021-04-23 21:59:48 +02:00
supportAmount={comment.support_amount}
numDirectReplies={comment.replies}
/>
2020-08-24 19:35:21 +02:00
);
})}
</ul>
2020-10-07 21:14:52 +02:00
{(isFetchingComments || moreBelow) && (
<div className="main--empty" ref={spinnerRef}>
2020-10-05 23:25:23 +02:00
<Spinner type="small" />
2020-08-24 19:35:21 +02:00
</div>
)}
</>
}
/>
2019-06-27 01:59:27 +02:00
);
2019-05-17 20:21:07 +02:00
}
export default CommentList;