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

435 lines
14 KiB
React
Raw Normal View History

2019-05-17 20:21:07 +02:00
// @flow
import { COMMENT_PAGE_SIZE_TOP_LEVEL, SORT_BY } from 'constants/comment';
import { ENABLE_COMMENT_REACTIONS, COMMENT_SERVER_API, COMMENT_SERVER_NAME } from 'config';
2021-10-04 13:53:41 +02:00
import { useIsMobile, useIsMediumScreen } from 'effects/use-screensize';
2022-02-09 16:27:11 +01:00
import { getCommentsListTitle } from 'util/comments';
2021-10-04 13:53:41 +02:00
import * as ICONS from 'constants/icons';
import * as REACTION_TYPES from 'constants/reactions';
2020-08-24 19:35:21 +02:00
import Button from 'component/button';
import Card from 'component/common/card';
2021-10-04 13:53:41 +02:00
import classnames from 'classnames';
2020-08-24 19:35:21 +02:00
import CommentCreate from 'component/commentCreate';
2021-10-04 13:53:41 +02:00
import CommentView from 'component/comment';
import debounce from 'util/debounce';
2021-10-04 13:53:41 +02:00
import Empty from 'component/common/empty';
import React, { useEffect } from 'react';
import Spinner from 'component/spinner';
import usePersistedState from 'effects/use-persisted-state';
import { FormField } from 'component/common/form';
import Comments from 'comments';
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,
pinnedComments: Array<Comment>,
topLevelComments: Array<Comment>,
2022-02-09 16:27:11 +01:00
resolvedComments: Array<Comment>,
topLevelTotalPages: number,
2019-05-17 20:21:07 +02:00
uri: string,
2022-02-09 16:27:11 +01:00
claimId?: string,
channelId?: string,
claimIsMine: boolean,
isFetchingComments: boolean,
isFetchingCommentsById: 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,
settingsByChannelId: { [channelId: string]: PerChannelSettings },
commentsAreExpanded?: boolean,
2022-02-09 16:27:11 +01:00
fetchTopLevelComments: (uri: string, parentId: string, page: number, pageSize: number, sortBy: number) => void,
fetchComment: (commentId: string) => void,
fetchReacts: (commentIds: Array<string>) => Promise<any>,
resetComments: (claimId: string) => void,
doResolveUris: (uris: Array<string>, returnCachedClaims: boolean) => void,
customCommentServers: Array<CommentServerDetails>,
setCommentServer: (string) => void,
commentServer: string,
2019-05-17 20:21:07 +02:00
};
2022-02-09 16:27:11 +01:00
export default function CommentList(props: Props) {
2020-09-29 16:10:23 +02:00
const {
allCommentIds,
2020-09-29 16:10:23 +02:00
uri,
pinnedComments,
topLevelComments,
2022-02-09 16:27:11 +01:00
resolvedComments,
topLevelTotalPages,
2022-02-09 16:27:11 +01:00
claimId,
channelId,
2020-09-29 16:10:23 +02:00
claimIsMine,
isFetchingComments,
isFetchingReacts,
linkedCommentId,
2020-09-30 20:46:17 +02:00
totalComments,
fetchingChannels,
myReactsByCommentId,
othersReactsById,
activeChannelId,
settingsByChannelId,
commentsAreExpanded,
2021-10-04 13:53:41 +02:00
fetchTopLevelComments,
fetchComment,
2022-02-09 16:27:11 +01:00
fetchReacts,
2021-10-04 13:53:41 +02:00
resetComments,
2022-02-09 16:27:11 +01:00
doResolveUris,
customCommentServers,
setCommentServer,
commentServer,
2020-09-29 16:10:23 +02:00
} = props;
2021-10-04 13:53:41 +02:00
const isMobile = useIsMobile();
const isMediumScreen = useIsMediumScreen();
2022-02-09 16:27:11 +01:00
const defaultServer = { name: COMMENT_SERVER_NAME, url: COMMENT_SERVER_API };
const allServers = [defaultServer, ...(customCommentServers || [])];
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);
2022-02-09 16:27:11 +01:00
const [commentsToDisplay, setCommentsToDisplay] = React.useState(topLevelComments);
const [didInitialPageFetch, setInitialPageFetch] = React.useState(false);
const hasDefaultExpansion = commentsAreExpanded || !isMediumScreen || isMobile;
const [expandedComments, setExpandedComments] = React.useState(hasDefaultExpansion);
2022-02-09 16:27:11 +01:00
const totalFetchedComments = allCommentIds ? allCommentIds.length : 0;
const channelSettings = channelId ? settingsByChannelId[channelId] : undefined;
2021-10-04 13:53:41 +02:00
const moreBelow = page < topLevelTotalPages;
2022-02-09 16:27:11 +01:00
const isResolvingComments = topLevelComments && resolvedComments.length !== topLevelComments.length;
const alreadyResolved = !isResolvingComments && resolvedComments.length !== 0;
const canDisplayComments = commentsToDisplay && commentsToDisplay.length === topLevelComments.length;
const title = getCommentsListTitle(totalComments);
// 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
);
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) {
2022-02-09 16:27:11 +01:00
if (claimId) {
resetComments(claimId);
}
setPage(1);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, uri, resetComments]); // 'claim' is derived from 'uri'
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);
}
2022-02-09 16:27:11 +01:00
fetchTopLevelComments(uri, '', page, COMMENT_PAGE_SIZE_TOP_LEVEL, sort);
}
2021-10-04 13:53:41 +02:00
}, [fetchComment, fetchTopLevelComments, linkedCommentId, page, sort, uri]);
// 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));
}
}
}, [
2021-10-04 13:53:41 +02:00
activeChannelId,
allCommentIds,
fetchReacts,
fetchingChannels,
isFetchingReacts,
2021-10-04 13:53:41 +02:00
myReactsByCommentId,
othersReactsById,
totalFetchedComments,
]);
2020-09-29 16:10:23 +02:00
// Scroll to linked-comment
2020-08-24 19:35:21 +02:00
useEffect(() => {
2022-02-09 16:27:11 +01:00
if (linkedCommentId) {
window.pendingLinkedCommentScroll = true;
} else {
delete window.pendingLinkedCommentScroll;
2020-08-24 19:35:21 +02:00
}
2022-02-09 16:27:11 +01:00
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
2020-02-05 04:55:00 +01:00
// Infinite scroll
2020-10-05 23:25:23 +02:00
useEffect(() => {
2022-02-09 16:27:11 +01:00
function shouldFetchNextPage(page, topLevelTotalPages, yPrefetchPx = 1000) {
2021-10-04 13:53:41 +02:00
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(() => {
2022-02-09 16:27:11 +01:00
if (shouldFetchNextPage(page, topLevelTotalPages)) {
setPage(page + 1);
2022-02-09 16:27:11 +01:00
setInitialPageFetch(true);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
2022-02-09 16:27:11 +01:00
if (!didInitialPageFetch) {
handleCommentScroll();
setInitialPageFetch(true);
}
if (hasDefaultExpansion && !isFetchingComments && canDisplayComments && readyToDisplayComments && moreBelow) {
const commentsInDrawer = Boolean(document.querySelector('.MuiDrawer-root .card--enable-overflow'));
const scrollingElement = commentsInDrawer ? document.querySelector('.card--enable-overflow') : window;
if (scrollingElement) {
scrollingElement.addEventListener('scroll', handleCommentScroll);
return () => scrollingElement.removeEventListener('scroll', handleCommentScroll);
}
2020-10-05 23:25:23 +02:00
}
2022-02-09 16:27:11 +01:00
}, [
canDisplayComments,
hasDefaultExpansion,
didInitialPageFetch,
isFetchingComments,
isMobile,
moreBelow,
page,
readyToDisplayComments,
topLevelTotalPages,
]);
// Wait to only display topLevelComments after resolved or else
// other components will try to resolve again, like channelThumbnail
useEffect(() => {
if (!isResolvingComments) setCommentsToDisplay(topLevelComments);
}, [isResolvingComments, topLevelComments]);
// Batch resolve comment channel urls
useEffect(() => {
if (!topLevelComments || alreadyResolved) return;
const urisToResolve = [];
topLevelComments.map(({ channel_url }) => channel_url !== undefined && urisToResolve.push(channel_url));
if (urisToResolve.length > 0) doResolveUris(urisToResolve, true);
}, [alreadyResolved, doResolveUris, topLevelComments]);
const commentProps = { isTopLevel: true, threadDepth: 3, uri, claimIsMine, linkedCommentId };
const actionButtonsProps = {
totalComments,
sort,
changeSort,
setPage,
allServers,
commentServer,
defaultServer,
setCommentServer,
};
2019-06-27 01:59:27 +02:00
return (
2020-08-24 19:35:21 +02:00
<Card
className="card--enable-overflow"
2022-02-09 16:27:11 +01:00
title={!isMobile && title}
titleActions={<CommentActionButtons {...actionButtonsProps} />}
2020-08-24 19:35:21 +02:00
actions={
<>
2022-02-09 16:27:11 +01:00
{isMobile && <CommentActionButtons {...actionButtonsProps} />}
<CommentCreate uri={uri} />
2020-10-07 21:14:52 +02:00
2021-10-04 13:53:41 +02:00
{channelSettings && channelSettings.comments_enabled && !isFetchingComments && !totalComments && (
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
2021-08-03 17:03:08 +02:00
<ul
className={classnames({
2022-02-09 16:27:11 +01:00
comments: !isMediumScreen || expandedComments,
'comments--contracted': isMediumScreen && !expandedComments,
2021-08-03 17:03:08 +02:00
})}
>
2022-02-09 16:27:11 +01:00
{readyToDisplayComments && (
<>
{pinnedComments && <CommentElements comments={pinnedComments} {...commentProps} />}
{commentsToDisplay && <CommentElements comments={commentsToDisplay} {...commentProps} />}
</>
)}
2020-08-24 19:35:21 +02:00
</ul>
2020-10-07 21:14:52 +02:00
2022-02-09 16:27:11 +01:00
{!hasDefaultExpansion && (
2021-07-15 15:25:48 +02:00
<div className="card__bottom-actions--comments">
2021-08-04 14:44:36 +02:00
{(!expandedComments || moreBelow) && (
2021-07-15 15:25:48 +02:00
<Button
2021-08-03 17:03:08 +02:00
button="link"
2021-10-04 13:53:41 +02:00
title={!expandedComments ? __('Expand') : __('More')}
2021-08-03 17:03:08 +02:00
label={!expandedComments ? __('Expand') : __('More')}
2021-10-04 13:53:41 +02:00
onClick={() => (!expandedComments ? setExpandedComments(true) : setPage(page + 1))}
2021-07-15 15:25:48 +02:00
/>
)}
{expandedComments && (
<Button
2021-08-03 17:03:08 +02:00
button="link"
2021-10-04 13:53:41 +02:00
title={__('Collapse')}
2021-08-03 17:03:08 +02:00
label={__('Collapse')}
2021-10-04 13:53:41 +02:00
onClick={() => setExpandedComments(false)}
2021-07-15 15:25:48 +02:00
/>
)}
</div>
)}
2022-02-09 16:27:11 +01:00
{(isFetchingComments || (hasDefaultExpansion && moreBelow) || !canDisplayComments) && (
<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
}
2022-02-09 16:27:11 +01:00
type CommentProps = {
comments: Array<Comment>,
};
const CommentElements = (commentProps: CommentProps) => {
const { comments, ...commentsProps } = commentProps;
return comments.map((comment) => <CommentView key={comment.comment_id} comment={comment} {...commentsProps} />);
};
type ActionButtonsProps = {
totalComments: number,
sort: string,
changeSort: (string) => void,
setPage: (number) => void,
allServers: Array<CommentServerDetails>,
commentServer: string,
setCommentServer: (string) => void,
defaultServer: CommentServerDetails,
2022-02-09 16:27:11 +01:00
};
const CommentActionButtons = (actionButtonsProps: ActionButtonsProps) => {
const { totalComments, sort, changeSort, setPage, allServers, commentServer, setCommentServer, defaultServer } =
actionButtonsProps;
2022-02-09 16:27:11 +01:00
const sortButtonProps = { activeSort: sort, changeSort };
return (
2022-11-04 15:44:36 +01:00
<div className={'comment__actions-row'}>
2022-02-09 16:27:11 +01:00
{totalComments > 1 && ENABLE_COMMENT_REACTIONS && (
2022-11-04 15:44:36 +01:00
<div className="comment__sort-group">
2022-02-09 16:27:11 +01:00
<SortButton {...sortButtonProps} label={__('Best')} icon={ICONS.BEST} sortOption={SORT_BY.POPULARITY} />
<SortButton
{...sortButtonProps}
label={__('Controversial')}
icon={ICONS.CONTROVERSIAL}
sortOption={SORT_BY.CONTROVERSY}
/>
<SortButton {...sortButtonProps} label={__('New')} icon={ICONS.NEW} sortOption={SORT_BY.NEWEST} />
2022-11-04 15:44:36 +01:00
</div>
2022-02-09 16:27:11 +01:00
)}
2022-11-04 15:44:36 +01:00
{allServers.length >= 2 && (
<div className="button__selected-server">
<FormField
type="select-tiny"
onChange={function (x) {
const selectedServer = x.target.value;
setPage(0);
setCommentServer(selectedServer);
if (selectedServer === defaultServer.url) {
Comments.setServerUrl(undefined);
} else {
Comments.setServerUrl(selectedServer);
}
}}
value={commentServer}
>
{allServers.map(function (server) {
return (
<option key={server.url} value={server.url}>
{server.name}
</option>
);
})}
</FormField>
</div>
)}
2022-11-04 15:44:36 +01:00
<div className="button_refresh">
<Button button="alt" icon={ICONS.REFRESH} title={__('Refresh')} onClick={() => setPage(0)} />
</div>
</div>
2022-02-09 16:27:11 +01:00
);
};
type SortButtonProps = {
activeSort: string,
sortOption: string,
changeSort: (string) => void,
};
const SortButton = (sortButtonProps: SortButtonProps) => {
const { activeSort, sortOption, changeSort, ...buttonProps } = sortButtonProps;
return (
<Button
{...buttonProps}
className={classnames(`button-toggle`, { 'button-toggle--active': activeSort === sortOption })}
button="alt"
iconSize={18}
onClick={() => changeSort(sortOption)}
/>
);
};