add comment sorting and improve comment focus styles

This commit is contained in:
Sean Yesmunt 2020-10-06 15:35:13 -04:00
parent 136d73d2ff
commit 00c05437ca
17 changed files with 227 additions and 36 deletions

View file

@ -174,13 +174,9 @@ function Comment(props: Props) {
/> />
)} )}
<Button <Button
className="button--uri-indicator" className="comment__time"
navigate={`${uri}?lc=${commentId}`} navigate={`${uri}?lc=${commentId}`}
label={ label={<DateTime date={timePosted} timeAgo />}
<span className="comment__time">
<DateTime date={timePosted} timeAgo />
</span>
}
/> />
</div> </div>
<div className="comment__menu"> <div className="comment__menu">

View file

@ -1,5 +1,5 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { makeSelectClaimForUri, selectMyChannelClaims } from 'lbry-redux'; import { makeSelectClaimForUri, selectMyChannelClaims, selectFetchingMyChannels } from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app'; import { doOpenModal } from 'redux/actions/app';
import { doCommentCreate } from 'redux/actions/comments'; import { doCommentCreate } from 'redux/actions/comments';
import { CommentCreate } from './view'; import { CommentCreate } from './view';
@ -9,6 +9,7 @@ const select = (state, props) => ({
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true, commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
claim: makeSelectClaimForUri(props.uri)(state), claim: makeSelectClaimForUri(props.uri)(state),
channels: selectMyChannelClaims(state), channels: selectMyChannelClaims(state),
isFetchingChannels: selectFetchingMyChannels(state),
}); });
const perform = (dispatch, ownProps) => ({ const perform = (dispatch, ownProps) => ({

View file

@ -21,10 +21,20 @@ type Props = {
onDoneReplying?: () => void, onDoneReplying?: () => void,
onCancelReplying?: () => void, onCancelReplying?: () => void,
isNested: boolean, isNested: boolean,
isFetchingChannels: boolean,
}; };
export function CommentCreate(props: Props) { export function CommentCreate(props: Props) {
const { createComment, claim, channels, topLevelId, onDoneReplying, onCancelReplying, isNested } = props; const {
createComment,
claim,
channels,
topLevelId,
onDoneReplying,
onCancelReplying,
isNested,
isFetchingChannels,
} = props;
const buttonref: ElementRef<any> = React.useRef(); const buttonref: ElementRef<any> = React.useRef();
const { push } = useHistory(); const { push } = useHistory();
const { claim_id: claimId } = claim; const { claim_id: claimId } = claim;
@ -100,7 +110,15 @@ export function CommentCreate(props: Props) {
if (!hasChannels) { if (!hasChannels) {
return ( return (
<div role="button" onClick={() => push(`/$/${PAGES.CHANNEL_NEW}`)}> <div role="button" onClick={() => push(`/$/${PAGES.CHANNEL_NEW}`)}>
<FormField type="textarea" name={'comment_signup_prompt'} placeholder={__('Say something about this...')} /> <FormField
type="textarea"
name={'comment_signup_prompt'}
placeholder={__('Say something about this...')}
label={isFetchingChannels ? __('Comment') : undefined}
/>
<div className="section__actions">
<Button disabled button="primary" label={__('Post')} requiresAuth={IS_WEB} />
</div>
</div> </div>
); );
} }

View file

@ -4,6 +4,7 @@ import {
makeSelectTopLevelCommentsForUri, makeSelectTopLevelCommentsForUri,
selectIsFetchingComments, selectIsFetchingComments,
makeSelectTotalCommentsCountForUri, makeSelectTotalCommentsCountForUri,
selectOthersReactsById,
} from 'redux/selectors/comments'; } from 'redux/selectors/comments';
import { doCommentList, doCommentReactList } from 'redux/actions/comments'; import { doCommentList, doCommentReactList } from 'redux/actions/comments';
import CommentsList from './view'; import CommentsList from './view';
@ -17,6 +18,7 @@ const select = (state, props) => ({
isFetchingComments: selectIsFetchingComments(state), isFetchingComments: selectIsFetchingComments(state),
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true, commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
fetchingChannels: selectFetchingMyChannels(state), fetchingChannels: selectFetchingMyChannels(state),
reactionsById: selectOthersReactsById(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({

View file

@ -1,19 +1,22 @@
// @flow // @flow
import * as REACTION_TYPES from 'constants/reactions';
import * as ICONS from 'constants/icons'; import * as ICONS from 'constants/icons';
import { SORT_COMMENTS_NEW, SORT_COMMENTS_BEST, SORT_COMMENTS_CONTROVERSIAL } from 'constants/comment';
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
import Comment from 'component/comment'; import classnames from 'classnames';
import CommentView from 'component/comment';
import Spinner from 'component/spinner'; import Spinner from 'component/spinner';
import Button from 'component/button'; import Button from 'component/button';
import Card from 'component/common/card'; import Card from 'component/common/card';
import CommentCreate from 'component/commentCreate'; import CommentCreate from 'component/commentCreate';
import usePersistedState from 'effects/use-persisted-state'; import usePersistedState from 'effects/use-persisted-state';
import { ENABLE_COMMENT_REACTIONS } from 'config'; import { ENABLE_COMMENT_REACTIONS } from 'config';
import { useIsMobile } from 'effects/use-screensize'; import { sortComments } from 'util/comments';
type Props = { type Props = {
comments: Array<any>, comments: Array<Comment>,
fetchComments: string => void, fetchComments: string => void,
fetchReacts: string => void, fetchReacts: string => Promise<any>,
uri: string, uri: string,
claimIsMine: boolean, claimIsMine: boolean,
myChannels: ?Array<ChannelClaim>, myChannels: ?Array<ChannelClaim>,
@ -21,6 +24,7 @@ type Props = {
linkedComment: any, linkedComment: any,
totalComments: number, totalComments: number,
fetchingChannels: boolean, fetchingChannels: boolean,
reactionsById: { [string]: { [REACTION_TYPES.LIKE | REACTION_TYPES.DISLIKE]: number } },
}; };
function CommentList(props: Props) { function CommentList(props: Props) {
@ -35,13 +39,17 @@ function CommentList(props: Props) {
linkedComment, linkedComment,
totalComments, totalComments,
fetchingChannels, fetchingChannels,
reactionsById,
} = props; } = props;
const commentRef = React.useRef(); const commentRef = React.useRef();
const isMobile = useIsMobile(); const spinnerRef = React.useRef();
const [sort, setSort] = usePersistedState('comment-sort', SORT_COMMENTS_BEST);
const [activeChannel] = usePersistedState('comment-channel', ''); const [activeChannel] = usePersistedState('comment-channel', '');
const [start] = React.useState(0); const [start] = React.useState(0);
const [end, setEnd] = React.useState(9); const [end, setEnd] = React.useState(9);
// Display comments immediately if not fetching reactions
// If not, wait to show comments until reactions are fetched
const [readyToDisplayComments, setReadyToDisplayComments] = React.useState(!ENABLE_COMMENT_REACTIONS);
const linkedCommentId = linkedComment && linkedComment.comment_id; const linkedCommentId = linkedComment && linkedComment.comment_id;
const hasNoComments = totalComments === 0; const hasNoComments = totalComments === 0;
@ -58,11 +66,11 @@ function CommentList(props: Props) {
return false; return false;
}; };
const handleMoreBelow = () => { const handleMoreBelow = React.useCallback(() => {
if (moreBelow) { if (moreBelow) {
setEnd(end + 10); setEnd(end + 10);
} }
}; }, [end, setEnd, moreBelow]);
useEffect(() => { useEffect(() => {
fetchComments(uri); fetchComments(uri);
@ -70,7 +78,11 @@ function CommentList(props: Props) {
useEffect(() => { useEffect(() => {
if (totalComments && ENABLE_COMMENT_REACTIONS && !fetchingChannels) { if (totalComments && ENABLE_COMMENT_REACTIONS && !fetchingChannels) {
fetchReacts(uri); fetchReacts(uri)
.then(() => {
setReadyToDisplayComments(true);
})
.catch(() => setReadyToDisplayComments(true));
} }
}, [fetchReacts, uri, totalComments, activeChannel, fetchingChannels, ENABLE_COMMENT_REACTIONS]); }, [fetchReacts, uri, totalComments, activeChannel, fetchingChannels, ENABLE_COMMENT_REACTIONS]);
@ -83,19 +95,28 @@ function CommentList(props: Props) {
useEffect(() => { useEffect(() => {
function handleCommentScroll(e) { function handleCommentScroll(e) {
// Use some arbitrary amount so comments start loading before a user actually reaches the real bottom of the page
// $FlowFixMe // $FlowFixMe
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - (isMobile ? 2750 : 300)) { const rect = spinnerRef.current.getBoundingClientRect();
const isInViewport =
rect.top >= 0 &&
rect.left >= 0 &&
// $FlowFixMe
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
// $FlowFixMe
rect.right <= (window.innerWidth || document.documentElement.clientWidth);
if (isInViewport) {
handleMoreBelow(); handleMoreBelow();
} }
} }
if (moreBelow) { if (moreBelow && spinnerRef && spinnerRef.current) {
window.addEventListener('scroll', handleCommentScroll); window.addEventListener('scroll', handleCommentScroll);
} }
return () => window.removeEventListener('scroll', handleCommentScroll); return () => window.removeEventListener('scroll', handleCommentScroll);
}, [moreBelow, handleMoreBelow, isMobile]); }, [moreBelow, handleMoreBelow, spinnerRef]);
function prepareComments(arrayOfComments, linkedComment) { function prepareComments(arrayOfComments, linkedComment) {
let orderedComments = []; let orderedComments = [];
@ -107,7 +128,10 @@ function CommentList(props: Props) {
} else { } else {
const parentComment = arrayOfComments.find(c => c.comment_id === linkedComment.parent_id); const parentComment = arrayOfComments.find(c => c.comment_id === linkedComment.parent_id);
orderedComments = arrayOfComments.filter(c => c.comment_id !== linkedComment.parent_id); orderedComments = arrayOfComments.filter(c => c.comment_id !== linkedComment.parent_id);
orderedComments.unshift(parentComment);
if (parentComment) {
orderedComments.unshift(parentComment);
}
} }
} else { } else {
orderedComments = arrayOfComments; orderedComments = arrayOfComments;
@ -115,7 +139,12 @@ function CommentList(props: Props) {
return orderedComments; return orderedComments;
} }
const displayedComments = prepareComments(comments, linkedComment).slice(start, end); // Default to newest first for apps that don't have comment reactions
const sortedComments = ENABLE_COMMENT_REACTIONS ? sortComments(comments, reactionsById, sort) : comments;
const displayedComments = readyToDisplayComments
? prepareComments(sortedComments, linkedComment).slice(start, end)
: [];
return ( return (
<Card <Card
title={ title={
@ -126,24 +155,52 @@ function CommentList(props: Props) {
: __('Leave a comment') : __('Leave a comment')
} }
titleActions={ titleActions={
<Button button="alt" icon={ICONS.REFRESH} title={__('Refresh')} onClick={() => fetchComments(uri)} /> <>
{totalComments > 1 && ENABLE_COMMENT_REACTIONS && (
<span className="comment__sort">
<Button
button="alt"
label={'Best'}
icon={ICONS.TOP}
onClick={() => setSort(SORT_COMMENTS_BEST)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_COMMENTS_BEST,
})}
/>
<Button
button="alt"
label={'Controversial'}
icon={ICONS.CONTROVERSIAL}
onClick={() => setSort(SORT_COMMENTS_CONTROVERSIAL)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_COMMENTS_CONTROVERSIAL,
})}
/>
<Button
button="alt"
label={'New'}
icon={ICONS.NEW}
onClick={() => setSort(SORT_COMMENTS_NEW)}
className={classnames(`button-toggle`, {
'button-toggle--active': sort === SORT_COMMENTS_NEW,
})}
/>
</span>
)}
<Button button="alt" icon={ICONS.REFRESH} title={__('Refresh')} onClick={() => fetchComments(uri)} />
</>
} }
actions={ actions={
<> <>
<CommentCreate uri={uri} /> <CommentCreate uri={uri} />
{!isFetchingComments && hasNoComments && <div className="main--empty">{__('Be the first to comment!')}</div>} {!isFetchingComments && hasNoComments && <div className="main--empty">{__('Be the first to comment!')}</div>}
<ul className="comments" ref={commentRef}> <ul className="comments" ref={commentRef}>
{isFetchingComments && (
<div className="main--empty">
<Spinner />
</div>
)}
{!isFetchingComments && {!isFetchingComments &&
comments && comments &&
displayedComments && displayedComments &&
displayedComments.map(comment => { displayedComments.map(comment => {
return ( return (
<Comment <CommentView
isTopLevel isTopLevel
key={comment.comment_id} key={comment.comment_id}
uri={uri} uri={uri}
@ -161,8 +218,8 @@ function CommentList(props: Props) {
); );
})} })}
</ul> </ul>
{!isFetchingComments && moreBelow && ( {(isFetchingComments || moreBelow) && (
<div className="main--empty"> <div className="main--empty" ref={spinnerRef}>
<Spinner type="small" /> <Spinner type="small" />
</div> </div>
)} )}

View file

@ -839,4 +839,5 @@ export const icons = {
[ICONS.DOWNVOTE]: buildIcon( [ICONS.DOWNVOTE]: buildIcon(
<path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17" /> <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17" />
), ),
[ICONS.CONTROVERSIAL]: buildIcon(<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />),
}; };

View file

@ -1 +1,5 @@
export const LINKED_COMMENT_QUERY_PARAM = 'lc'; export const LINKED_COMMENT_QUERY_PARAM = 'lc';
export const SORT_COMMENTS_NEW = 'new';
export const SORT_COMMENTS_BEST = 'best';
export const SORT_COMMENTS_CONTROVERSIAL = 'controversial';

View file

@ -119,3 +119,4 @@ export const REPLY = 'Reply';
export const YOUTUBE = 'Youtube'; export const YOUTUBE = 'Youtube';
export const UPVOTE = 'Upvote'; export const UPVOTE = 'Upvote';
export const DOWNVOTE = 'Downvote'; export const DOWNVOTE = 'Downvote';
export const CONTROVERSIAL = 'Controversial';

View file

@ -66,7 +66,8 @@ export function doCommentReactList(uri: string | null, commentId?: string) {
params['channel_name'] = channel; params['channel_name'] = channel;
params['channel_id'] = channelId; params['channel_id'] = channelId;
} }
Lbry.comment_react_list(params)
return Lbry.comment_react_list(params)
.then((result: CommentReactListResponse) => { .then((result: CommentReactListResponse) => {
const { my_reactions: myReactions, others_reactions: othersReactions } = result; const { my_reactions: myReactions, others_reactions: othersReactions } = result;
dispatch({ dispatch({

View file

@ -14,6 +14,10 @@ export const selectIsFetchingComments = createSelector(selectState, state => sta
export const selectIsPostingComment = createSelector(selectState, state => state.isCommenting); export const selectIsPostingComment = createSelector(selectState, state => state.isCommenting);
export const selectIsFetchingReacts = createSelector(selectState, state => state.isFetchingReacts);
export const selectOthersReactsById = createSelector(selectState, state => state.othersReactsByCommentId);
export const selectCommentsByClaimId = createSelector(selectState, selectCommentsById, (state, byId) => { export const selectCommentsByClaimId = createSelector(selectState, selectCommentsById, (state, byId) => {
const byClaimId = state.byId || {}; const byClaimId = state.byId || {};
const comments = {}; const comments = {};

View file

@ -237,6 +237,7 @@
.card__header--between { .card__header--between {
@extend .card__header; @extend .card__header;
justify-content: space-between; justify-content: space-between;
align-items: center;
flex-wrap: wrap; flex-wrap: wrap;
} }

View file

@ -13,6 +13,16 @@ $thumbnailWidthSmall: 1.5rem;
flex: 1; flex: 1;
} }
.comment__sort {
margin: var(--spacing-s) 0;
display: block;
@media (min-width: $breakpoint-small) {
margin-top: 0;
display: inline;
}
}
.comment__create { .comment__create {
padding-bottom: var(--spacing-m); padding-bottom: var(--spacing-m);
font-size: var(--font-small); font-size: var(--font-small);
@ -146,18 +156,31 @@ $thumbnailWidthSmall: 1.5rem;
.comment__author { .comment__author {
text-overflow: ellipsis; text-overflow: ellipsis;
padding-right: var(--spacing-xs); margin-right: var(--spacing-xs);
height: 100%; height: 100%;
} }
.comment__time { .comment__time {
@extend .button--uri-indicator;
opacity: 0.5; opacity: 0.5;
white-space: nowrap; white-space: nowrap;
height: 100%; height: 100%;
&:focus {
@include linkFocus;
}
} }
.comment__menu { .comment__menu {
align-self: flex-end; align-self: flex-end;
button {
border-radius: var(--border-radius);
&:focus {
@include linkFocus;
}
}
} }
.comment__char-count { .comment__char-count {
@ -227,6 +250,13 @@ $thumbnailWidthSmall: 1.5rem;
font-size: var(--font-xsmall); font-size: var(--font-xsmall);
} }
.comment__action,
.comment__author {
&:focus {
@include linkFocus;
}
}
.comment__action--active { .comment__action--active {
.icon { .icon {
fill: var(--color-primary-alt); fill: var(--color-primary-alt);

View file

@ -88,7 +88,7 @@
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-items: flex-start; justify-items: flex-start;
padding: var(--spacing-s) var(--spacing-s); padding: var(--spacing-s);
&:not(:first-of-type) { &:not(:first-of-type) {
border-top: 1px solid transparent; border-top: 1px solid transparent;

View file

@ -158,6 +158,11 @@
box-shadow: 0 0 0 3px var(--color-focus); box-shadow: 0 0 0 3px var(--color-focus);
} }
@mixin linkFocus {
background-color: var(--color-link-focus-bg);
box-shadow: 0 0 0 5px var(--color-link-focus-bg);
}
@mixin underline($text-color: var(--lbry-black), $whitespace-color: var(--lbry-white)) { @mixin underline($text-color: var(--lbry-black), $whitespace-color: var(--lbry-white)) {
@include selection($text-color, $whitespace-color); @include selection($text-color, $whitespace-color);

View file

@ -33,6 +33,7 @@
--color-button-alt-text: #e2e9f0; --color-button-alt-text: #e2e9f0;
--color-header-button: #434b54; --color-header-button: #434b54;
--color-button-border: var(--color-gray-5); --color-button-border: var(--color-gray-5);
--color-link-focus-bg: #333a41;
// Color // Color
--color-focus: #2d69a5; --color-focus: #2d69a5;

View file

@ -7,6 +7,7 @@
--color-navigation-active-text: var(--color-primary); --color-navigation-active-text: var(--color-primary);
--color-navigation-hover: var(--color-gray-1); --color-navigation-hover: var(--color-gray-1);
--color-navigation-hover-text: #3f3f3f; --color-navigation-hover-text: #3f3f3f;
--color-link-focus-bg: #f1f1f1;
--color-header-button: var(--color-button-alt-bg); --color-header-button: var(--color-button-alt-bg);
--color-button-border: var(--color-gray-3); --color-button-border: var(--color-gray-3);

68
ui/util/comments.js Normal file
View file

@ -0,0 +1,68 @@
// @flow
import * as REACTION_TYPES from 'constants/reactions';
import { SORT_COMMENTS_NEW, SORT_COMMENTS_BEST, SORT_COMMENTS_CONTROVERSIAL } from 'constants/comment';
// Mostly taken from Reddit's sorting functions
// https://github.com/reddit-archive/reddit/blob/master/r2/r2/lib/db/_sorts.pyx
export function sortComments(comments: ?Array<Comment>, reactionsById: {}, method: string): Array<Comment> {
if (!comments) {
return [];
}
return comments.slice().sort((a, b) => {
if (method === SORT_COMMENTS_NEW) {
return 0;
}
const aReactions = reactionsById[a.comment_id];
const bReactions = reactionsById[b.comment_id];
const aLikes = (aReactions && aReactions[REACTION_TYPES.LIKE]) || 0;
const aDislikes = (aReactions && aReactions[REACTION_TYPES.DISLIKE]) || 0;
const bLikes = (bReactions && bReactions[REACTION_TYPES.LIKE]) || 0;
const bDislikes = (bReactions && bReactions[REACTION_TYPES.DISLIKE]) || 0;
if (method === SORT_COMMENTS_CONTROVERSIAL) {
if (aLikes === 0 && aDislikes === 0) {
return 1;
} else if (bLikes === 0 && bDislikes === 0) {
return -1;
}
const aMagnitude = aLikes + aDislikes;
const bMagnitude = bLikes + bDislikes;
const aBalance = aLikes > aDislikes ? aDislikes / aLikes : aLikes / aDislikes;
const bBalance = bLikes > bDislikes ? bDislikes / bLikes : bLikes / bDislikes;
return bMagnitude ** bBalance - aMagnitude ** aBalance;
}
if (method === SORT_COMMENTS_BEST) {
const aN = aLikes + aDislikes;
const bN = bLikes + bDislikes;
if (aN === 0) {
return 1;
} else if (bN === 0) {
return -1;
}
const z = 1.281551565545; // 80% confidence
const aP = aLikes / aN;
const bP = bLikes / bN;
const aLeft = aP + (1 / (2 * aN)) * z * z;
const aRight = z * Math.sqrt((aP * (1 - aP)) / aN + (z * z) / (4 * aN * aN));
const aUnder = 1 + (1 / aN) * z * z;
const bLeft = bP + (1 / (2 * bN)) * z * z;
const bRight = z * Math.sqrt((bP * (1 - bP)) / bN + (z * z) / (4 * bN * bN));
const bUnder = 1 + (1 / bN) * z * z;
return (bLeft - bRight) / bUnder - (aLeft - aRight) / aUnder;
}
return 0;
});
}