Comments ux improvements and bugfixes (#246)

* Show majority stake on comments

* Darken comment input text

* Fix old FR comments displayed in general section

* Refactor feed comments and bets into files

* Only allow user to comment on most recent bet

* Fix overlapping sign in to comment

* Only calculate current users bets once

* Minor tweaks & is betting @ prob
This commit is contained in:
Boa 2022-05-18 08:42:13 -06:00 committed by GitHub
parent d50cc39c27
commit 7b3c21cf98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 686 additions and 631 deletions

View File

@ -28,7 +28,7 @@ type BaseActivityItem = {
export type CommentInputItem = BaseActivityItem & { export type CommentInputItem = BaseActivityItem & {
type: 'commentInput' type: 'commentInput'
betsByCurrentUser: Bet[] betsByCurrentUser: Bet[]
comments: Comment[] commentsByCurrentUser: Comment[]
answerOutcome?: string answerOutcome?: string
} }
@ -76,7 +76,7 @@ export type AnswerGroupItem = BaseActivityItem & {
answer: Answer answer: Answer
items: ActivityItem[] items: ActivityItem[]
betsByCurrentUser?: Bet[] betsByCurrentUser?: Bet[]
comments?: Comment[] commentsByCurrentUser?: Comment[]
} }
export type CloseItem = BaseActivityItem & { export type CloseItem = BaseActivityItem & {
@ -87,7 +87,6 @@ export type ResolveItem = BaseActivityItem & {
type: 'resolve' type: 'resolve'
} }
export const GENERAL_COMMENTS_OUTCOME_ID = 'General Comments'
const DAY_IN_MS = 24 * 60 * 60 * 1000 const DAY_IN_MS = 24 * 60 * 60 * 1000
const ABBREVIATED_NUM_COMMENTS_OR_BETS_TO_SHOW = 3 const ABBREVIATED_NUM_COMMENTS_OR_BETS_TO_SHOW = 3
@ -280,6 +279,7 @@ function getAnswerAndCommentInputGroups(
outcomes = _.sortBy(outcomes, (outcome) => outcomes = _.sortBy(outcomes, (outcome) =>
getOutcomeProbability(contract, outcome) getOutcomeProbability(contract, outcome)
) )
const betsByCurrentUser = bets.filter((bet) => bet.userId === user?.id)
const answerGroups = outcomes const answerGroups = outcomes
.map((outcome) => { .map((outcome) => {
@ -293,9 +293,7 @@ function getAnswerAndCommentInputGroups(
comment.answerOutcome === outcome || comment.answerOutcome === outcome ||
answerBets.some((bet) => bet.id === comment.betId) answerBets.some((bet) => bet.id === comment.betId)
) )
const items = getCommentThreads(answerBets, answerComments, contract) const items = getCommentThreads(bets, answerComments, contract)
if (outcome === GENERAL_COMMENTS_OUTCOME_ID) items.reverse()
return { return {
id: outcome, id: outcome,
@ -304,8 +302,10 @@ function getAnswerAndCommentInputGroups(
answer, answer,
items, items,
user, user,
betsByCurrentUser: answerBets.filter((bet) => bet.userId === user?.id), betsByCurrentUser,
comments: answerComments, commentsByCurrentUser: answerComments.filter(
(comment) => comment.userId === user?.id
),
} }
}) })
.filter((group) => group.answer) as ActivityItem[] .filter((group) => group.answer) as ActivityItem[]
@ -433,7 +433,7 @@ export function getAllContractActivityItems(
id: 'commentInput', id: 'commentInput',
contract, contract,
betsByCurrentUser: [], betsByCurrentUser: [],
comments: [], commentsByCurrentUser: [],
}) })
} else { } else {
items.push( items.push(
@ -459,7 +459,7 @@ export function getAllContractActivityItems(
id: 'commentInput', id: 'commentInput',
contract, contract,
betsByCurrentUser: [], betsByCurrentUser: [],
comments: [], commentsByCurrentUser: [],
}) })
} }
@ -520,6 +520,15 @@ export function getRecentContractActivityItems(
return [questionItem, ...items] return [questionItem, ...items]
} }
function commentIsGeneralComment(comment: Comment, contract: Contract) {
return (
comment.answerOutcome === undefined &&
(contract.outcomeType === 'FREE_RESPONSE'
? comment.betId === undefined
: true)
)
}
export function getSpecificContractActivityItems( export function getSpecificContractActivityItems(
contract: Contract, contract: Contract,
bets: Bet[], bets: Bet[],
@ -550,8 +559,8 @@ export function getSpecificContractActivityItems(
break break
case 'comments': case 'comments':
const nonFreeResponseComments = comments.filter( const nonFreeResponseComments = comments.filter((comment) =>
(comment) => comment.answerOutcome === undefined commentIsGeneralComment(comment, contract)
) )
const nonFreeResponseBets = const nonFreeResponseBets =
contract.outcomeType === 'FREE_RESPONSE' ? [] : bets contract.outcomeType === 'FREE_RESPONSE' ? [] : bets
@ -567,10 +576,12 @@ export function getSpecificContractActivityItems(
type: 'commentInput', type: 'commentInput',
id: 'commentInput', id: 'commentInput',
contract, contract,
betsByCurrentUser: user betsByCurrentUser: nonFreeResponseBets.filter(
? nonFreeResponseBets.filter((bet) => bet.userId === user.id) (bet) => bet.userId === user?.id
: [], ),
comments: nonFreeResponseComments, commentsByCurrentUser: nonFreeResponseComments.filter(
(comment) => comment.userId === user?.id
),
}) })
break break
case 'free-response-comment-answer-groups': case 'free-response-comment-answer-groups':

View File

@ -17,8 +17,11 @@ import { Linkify } from 'web/components/linkify'
import clsx from 'clsx' import clsx from 'clsx'
import { tradingAllowed } from 'web/lib/firebase/contracts' import { tradingAllowed } from 'web/lib/firebase/contracts'
import { BuyButton } from 'web/components/yes-no-selector' import { BuyButton } from 'web/components/yes-no-selector'
import { CommentInput, FeedItem } from 'web/components/feed/feed-items' import { FeedItem } from 'web/components/feed/feed-items'
import { getMostRecentCommentableBet } from 'web/components/feed/feed-comments' import {
CommentInput,
getMostRecentCommentableBet,
} from 'web/components/feed/feed-comments'
import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time' import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
@ -28,15 +31,16 @@ export function FeedAnswerCommentGroup(props: {
items: ActivityItem[] items: ActivityItem[]
type: string type: string
betsByCurrentUser?: Bet[] betsByCurrentUser?: Bet[]
comments?: Comment[] commentsByCurrentUser?: Comment[]
}) { }) {
const { answer, items, contract, betsByCurrentUser, comments } = props const { answer, items, contract, betsByCurrentUser, commentsByCurrentUser } =
props
const { username, avatarUrl, name, text } = answer const { username, avatarUrl, name, text } = answer
const answerElementId = `answer-${answer.id}` const answerElementId = `answer-${answer.id}`
const user = useUser() const user = useUser()
const mostRecentCommentableBet = getMostRecentCommentableBet( const mostRecentCommentableBet = getMostRecentCommentableBet(
betsByCurrentUser ?? [], betsByCurrentUser ?? [],
comments ?? [], commentsByCurrentUser ?? [],
user, user,
answer.number + '' answer.number + ''
) )
@ -44,7 +48,7 @@ export function FeedAnswerCommentGroup(props: {
const probPercent = formatPercent(prob) const probPercent = formatPercent(prob)
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [showReply, setShowReply] = useState(false) const [showReply, setShowReply] = useState(false)
const isFreeResponseContractPage = comments const isFreeResponseContractPage = !!commentsByCurrentUser
if (mostRecentCommentableBet && !showReply) setShowReplyAndFocus(true) if (mostRecentCommentableBet && !showReply) setShowReplyAndFocus(true)
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null) const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
@ -174,7 +178,7 @@ export function FeedAnswerCommentGroup(props: {
<CommentInput <CommentInput
contract={contract} contract={contract}
betsByCurrentUser={betsByCurrentUser ?? []} betsByCurrentUser={betsByCurrentUser ?? []}
comments={comments ?? []} commentsByCurrentUser={commentsByCurrentUser ?? []}
answerOutcome={answer.number + ''} answerOutcome={answer.number + ''}
replyToUsername={answer.username} replyToUsername={answer.username}
setRef={setInputRef} setRef={setInputRef}

View File

@ -0,0 +1,173 @@
import { Contract } from 'common/contract'
import { Bet } from 'common/bet'
import { User } from 'common/user'
import { useUser } from 'web/hooks/use-user'
import { Row } from 'web/components/layout/row'
import { Avatar } from 'web/components/avatar'
import clsx from 'clsx'
import { UserIcon, UsersIcon } from '@heroicons/react/solid'
import { formatMoney } from 'common/util/format'
import { OutcomeLabel } from 'web/components/outcome-label'
import { RelativeTimestamp } from 'web/components/relative-timestamp'
import React, { Fragment } from 'react'
import * as _ from 'lodash'
import { JoinSpans } from 'web/components/join-spans'
export function FeedBet(props: {
contract: Contract
bet: Bet
hideOutcome: boolean
smallAvatar: boolean
bettor?: User // If set: reveal bettor identity
}) {
const { contract, bet, hideOutcome, smallAvatar, bettor } = props
const { userId } = bet
const user = useUser()
const isSelf = user?.id === userId
return (
<>
<Row className={'flex w-full gap-2 pt-3'}>
{isSelf ? (
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
avatarUrl={user.avatarUrl}
username={user.username}
/>
) : bettor ? (
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
avatarUrl={bettor.avatarUrl}
username={bettor.username}
/>
) : (
<div className="relative px-1">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
<UserIcon className="h-5 w-5 text-gray-500" aria-hidden="true" />
</div>
</div>
)}
<div className={'min-w-0 flex-1 py-1.5'}>
<BetStatusText
bet={bet}
contract={contract}
isSelf={isSelf}
bettor={bettor}
hideOutcome={hideOutcome}
/>
</div>
</Row>
</>
)
}
export function BetStatusText(props: {
contract: Contract
bet: Bet
isSelf: boolean
bettor?: User
hideOutcome?: boolean
}) {
const { bet, contract, bettor, isSelf, hideOutcome } = props
const { amount, outcome, createdTime } = bet
const bought = amount >= 0 ? 'bought' : 'sold'
const money = formatMoney(Math.abs(amount))
return (
<div className="text-sm text-gray-500">
<span>{isSelf ? 'You' : bettor ? bettor.name : 'A trader'}</span> {bought}{' '}
{money}
{!hideOutcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={outcome}
contract={contract}
truncate="short"
/>
</>
)}
<RelativeTimestamp time={createdTime} />
</div>
)
}
function BetGroupSpan(props: {
contract: Contract
bets: Bet[]
outcome?: string
}) {
const { contract, bets, outcome } = props
const numberTraders = _.uniqBy(bets, (b) => b.userId).length
const [buys, sells] = _.partition(bets, (bet) => bet.amount >= 0)
const buyTotal = _.sumBy(buys, (b) => b.amount)
const sellTotal = _.sumBy(sells, (b) => -b.amount)
return (
<span>
{numberTraders} {numberTraders > 1 ? 'traders' : 'trader'}{' '}
<JoinSpans>
{buyTotal > 0 && <>bought {formatMoney(buyTotal)} </>}
{sellTotal > 0 && <>sold {formatMoney(sellTotal)} </>}
</JoinSpans>
{outcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={outcome}
contract={contract}
truncate="short"
/>
</>
)}{' '}
</span>
)
}
export function FeedBetGroup(props: {
contract: Contract
bets: Bet[]
hideOutcome: boolean
}) {
const { contract, bets, hideOutcome } = props
const betGroups = _.groupBy(bets, (bet) => bet.outcome)
const outcomes = Object.keys(betGroups)
// Use the time of the last bet for the entire group
const createdTime = bets[bets.length - 1].createdTime
return (
<>
<div>
<div className="relative px-1">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
<UsersIcon className="h-5 w-5 text-gray-500" aria-hidden="true" />
</div>
</div>
</div>
<div className={clsx('min-w-0 flex-1', outcomes.length === 1 && 'mt-1')}>
<div className="text-sm text-gray-500">
{outcomes.map((outcome, index) => (
<Fragment key={outcome}>
<BetGroupSpan
contract={contract}
outcome={hideOutcome ? undefined : outcome}
bets={betGroups[outcome]}
/>
{index !== outcomes.length - 1 && <br />}
</Fragment>
))}
<RelativeTimestamp time={createdTime} />
</div>
</div>
</>
)
}

View File

@ -1,12 +1,206 @@
import { Bet } from 'common/bet' import { Bet } from 'common/bet'
import { Comment } from 'common/comment' import { Comment } from 'common/comment'
import { User } from 'common/user' import { User } from 'common/user'
import { GENERAL_COMMENTS_OUTCOME_ID } from 'web/components/feed/activity-items' import { Contract } from 'common/contract'
import { Dictionary } from 'lodash'
import React, { useEffect, useState } from 'react'
import { useUser } from 'web/hooks/use-user'
import { formatMoney } from 'common/util/format'
import { useRouter } from 'next/router'
import { Row } from 'web/components/layout/row'
import clsx from 'clsx'
import { Avatar } from 'web/components/avatar'
import { UserLink } from 'web/components/user-page'
import { OutcomeLabel } from 'web/components/outcome-label'
import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time'
import { contractPath } from 'web/lib/firebase/contracts'
import { firebaseLogin } from 'web/lib/firebase/users'
import { createComment, MAX_COMMENT_LENGTH } from 'web/lib/firebase/comments'
import Textarea from 'react-expanding-textarea'
import * as _ from 'lodash'
import { Linkify } from 'web/components/linkify'
import { SiteLink } from 'web/components/site-link'
import { BetStatusText } from 'web/components/feed/feed-bets'
import { Col } from 'web/components/layout/col'
import { getOutcomeProbability } from 'common/calculate'
export function FeedCommentThread(props: {
contract: Contract
comments: Comment[]
parentComment: Comment
betsByUserId: Dictionary<[Bet, ...Bet[]]>
truncate?: boolean
smallAvatar?: boolean
}) {
const {
contract,
comments,
betsByUserId,
truncate,
smallAvatar,
parentComment,
} = props
const [showReply, setShowReply] = useState(false)
const [replyToUsername, setReplyToUsername] = useState('')
const user = useUser()
const commentsList = comments.filter(
(comment) => comment.replyToCommentId === parentComment.id
)
commentsList.unshift(parentComment)
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
function scrollAndOpenReplyInput(comment: Comment) {
setReplyToUsername(comment.userUsername)
setShowReply(true)
inputRef?.focus()
}
useEffect(() => {
if (showReply && inputRef) inputRef.focus()
}, [inputRef, showReply])
return (
<div className={'w-full flex-col flex-col pr-6'}>
{commentsList.map((comment, commentIdx) => (
<div
key={comment.id}
id={comment.id}
className={commentIdx === 0 ? '' : 'mt-4 ml-8'}
>
<FeedComment
contract={contract}
comment={comment}
betsBySameUser={betsByUserId[comment.userId] ?? []}
onReplyClick={scrollAndOpenReplyInput}
smallAvatar={smallAvatar}
truncate={truncate}
/>
</div>
))}
{showReply && (
<div className={'ml-8 w-full pt-6'}>
<CommentInput
contract={contract}
betsByCurrentUser={(user && betsByUserId[user.id]) ?? []}
commentsByCurrentUser={comments}
parentComment={parentComment}
replyToUsername={replyToUsername}
answerOutcome={comments[0].answerOutcome}
setRef={setInputRef}
/>
</div>
)}
</div>
)
}
export function FeedComment(props: {
contract: Contract
comment: Comment
betsBySameUser: Bet[]
truncate?: boolean
smallAvatar?: boolean
onReplyClick?: (comment: Comment) => void
}) {
const {
contract,
comment,
betsBySameUser,
truncate,
smallAvatar,
onReplyClick,
} = props
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
let betOutcome: string | undefined,
bought: string | undefined,
money: string | undefined
const matchedBet = betsBySameUser.find((bet) => bet.id === comment.betId)
if (matchedBet) {
betOutcome = matchedBet.outcome
bought = matchedBet.amount >= 0 ? 'bought' : 'sold'
money = formatMoney(Math.abs(matchedBet.amount))
}
const [highlighted, setHighlighted] = useState(false)
const router = useRouter()
useEffect(() => {
if (router.asPath.endsWith(`#${comment.id}`)) {
setHighlighted(true)
}
}, [router.asPath])
// Only calculated if they don't have a matching bet
const { userPosition, outcome } = getBettorsPosition(
contract,
comment.createdTime,
matchedBet ? [] : betsBySameUser
)
return (
<Row
className={clsx(
'flex space-x-3 transition-all duration-1000',
highlighted ? `-m-2 rounded bg-indigo-500/[0.2] p-2` : ''
)}
>
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
username={userUsername}
avatarUrl={userAvatarUrl}
/>
<div className="min-w-0 flex-1">
<p className="mt-0.5 text-sm text-gray-500">
<UserLink
className="text-gray-500"
username={userUsername}
name={userName}
/>{' '}
{!matchedBet && userPosition > 0 && (
<>
{'is '}
<CommentStatus outcome={outcome} contract={contract} />
</>
)}
<>
{bought} {money}
{contract.outcomeType !== 'FREE_RESPONSE' && betOutcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={betOutcome ? betOutcome : ''}
contract={contract}
truncate="short"
/>
</>
)}
</>
<CopyLinkDateTimeComponent
contract={contract}
createdTime={createdTime}
elementId={comment.id}
/>
</p>
<TruncatedComment
comment={text}
moreHref={contractPath(contract)}
shouldTruncate={truncate}
/>
{onReplyClick && (
<button
className={'text-xs font-bold text-gray-500 hover:underline'}
onClick={() => onReplyClick(comment)}
>
Reply
</button>
)}
</div>
</Row>
)
}
// TODO: move feed commment and comment thread in here when sinclair confirms they're not working on them rn
export function getMostRecentCommentableBet( export function getMostRecentCommentableBet(
betsByCurrentUser: Bet[], betsByCurrentUser: Bet[],
comments: Comment[], commentsByCurrentUser: Comment[],
user?: User | null, user?: User | null,
answerOutcome?: string answerOutcome?: string
) { ) {
@ -14,15 +208,13 @@ export function getMostRecentCommentableBet(
.filter((bet) => { .filter((bet) => {
if ( if (
canCommentOnBet(bet, user) && canCommentOnBet(bet, user) &&
// The bet doesn't already have a comment !commentsByCurrentUser.some(
!comments.some((comment) => comment.betId == bet.id) (comment) => comment.createdTime > bet.createdTime
)
) { ) {
if (!answerOutcome) return true if (!answerOutcome) return true
// If we're in free response, don't allow commenting on ante bet // If we're in free response, don't allow commenting on ante bet
return ( return answerOutcome === bet.outcome
bet.outcome !== GENERAL_COMMENTS_OUTCOME_ID &&
answerOutcome === bet.outcome
)
} }
return false return false
}) })
@ -30,6 +222,270 @@ export function getMostRecentCommentableBet(
.pop() .pop()
} }
function CommentStatus(props: { contract: Contract; outcome: string }) {
const { contract, outcome } = props
return (
<>
{' betting '}
<OutcomeLabel outcome={outcome} contract={contract} truncate="short" />
{' at ' +
Math.round(getOutcomeProbability(contract, outcome) * 100) +
'%'}
</>
)
}
export function CommentInput(props: {
contract: Contract
betsByCurrentUser: Bet[]
commentsByCurrentUser: Comment[]
// Tie a comment to an free response answer outcome
answerOutcome?: string
// Tie a comment to another comment
parentComment?: Comment
replyToUsername?: string
setRef?: (ref: HTMLTextAreaElement) => void
}) {
const {
contract,
betsByCurrentUser,
commentsByCurrentUser,
answerOutcome,
parentComment,
replyToUsername,
setRef,
} = props
const user = useUser()
const [comment, setComment] = useState('')
const [focused, setFocused] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const mostRecentCommentableBet = getMostRecentCommentableBet(
betsByCurrentUser,
commentsByCurrentUser,
user,
answerOutcome
)
const { id } = mostRecentCommentableBet || { id: undefined }
useEffect(() => {
if (!replyToUsername || !user || replyToUsername === user.username) return
const replacement = `@${replyToUsername} `
setComment(replacement + comment.replace(replacement, ''))
}, [user, replyToUsername])
async function submitComment(betId: string | undefined) {
if (!user) {
return await firebaseLogin()
}
if (!comment || isSubmitting) return
setIsSubmitting(true)
await createComment(
contract.id,
comment,
user,
betId,
answerOutcome,
parentComment?.id
)
setComment('')
setFocused(false)
setIsSubmitting(false)
}
const { userPosition, outcome } = getBettorsPosition(
contract,
Date.now(),
betsByCurrentUser
)
const shouldCollapseAfterClickOutside = false
return (
<>
<Row className={'mb-2 flex w-full gap-2'}>
<div className={'mt-1'}>
<Avatar avatarUrl={user?.avatarUrl} username={user?.username} />
</div>
<div className={'min-w-0 flex-1'}>
<div className="text-sm text-gray-500">
<div className={'mb-1'}>
{mostRecentCommentableBet && (
<BetStatusText
contract={contract}
bet={mostRecentCommentableBet}
isSelf={true}
hideOutcome={contract.outcomeType === 'FREE_RESPONSE'}
/>
)}
{!mostRecentCommentableBet && user && userPosition > 0 && (
<>
{"You're"}
<CommentStatus outcome={outcome} contract={contract} />
</>
)}
</div>
<Row className="grid grid-cols-8 gap-1.5 text-gray-700">
<Col className={'col-span-4 sm:col-span-6'}>
<Textarea
ref={setRef}
value={comment}
onChange={(e) => setComment(e.target.value)}
className={clsx('textarea textarea-bordered resize-none')}
placeholder={
parentComment || answerOutcome
? 'Write a reply... '
: 'Write a comment...'
}
autoFocus={focused}
rows={focused ? 3 : 1}
onFocus={() => setFocused(true)}
onBlur={() =>
shouldCollapseAfterClickOutside && setFocused(false)
}
maxLength={MAX_COMMENT_LENGTH}
disabled={isSubmitting}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault()
submitComment(id)
e.currentTarget.blur()
}
}}
/>
</Col>
<Col
className={clsx(
'col-span-4 sm:col-span-2',
focused ? 'justify-end' : 'justify-center'
)}
>
{!user && (
<button
className={
'btn btn-outline btn-sm text-transform: capitalize'
}
onClick={() => submitComment(id)}
>
Sign in to Comment
</button>
)}
{user && (
<button
disabled={isSubmitting}
className={clsx(
'btn text-transform: block capitalize',
focused && comment
? 'btn-outline btn-sm '
: 'btn-ghost btn-sm text-gray-500'
)}
onClick={() => {
if (!focused) return
else {
submitComment(id)
}
}}
>
{parentComment || answerOutcome ? 'Reply' : 'Comment'}
</button>
)}
</Col>
</Row>
</div>
</div>
</Row>
</>
)
}
export function TruncatedComment(props: {
comment: string
moreHref: string
shouldTruncate?: boolean
}) {
const { comment, moreHref, shouldTruncate } = props
let truncated = comment
// Keep descriptions to at most 400 characters
const MAX_CHARS = 400
if (shouldTruncate && truncated.length > MAX_CHARS) {
truncated = truncated.slice(0, MAX_CHARS)
// Make sure to end on a space
const i = truncated.lastIndexOf(' ')
truncated = truncated.slice(0, i)
}
return (
<div
className="mt-2 whitespace-pre-line break-words text-gray-700"
style={{ fontSize: 15 }}
>
<Linkify text={truncated} />
{truncated != comment && (
<SiteLink href={moreHref} className="text-indigo-700">
... (show more)
</SiteLink>
)}
</div>
)
}
function getBettorsPosition(
contract: Contract,
createdTime: number,
bets: Bet[]
) {
let yesFloorShares = 0,
yesShares = 0,
noShares = 0,
noFloorShares = 0
const emptyReturn = {
userPosition: 0,
outcome: '',
}
const previousBets = bets.filter(
(prevBet) => prevBet.createdTime < createdTime && !prevBet.isAnte
)
if (contract.outcomeType === 'FREE_RESPONSE') {
const answerCounts: { [outcome: string]: number } = {}
for (const bet of previousBets) {
if (bet.outcome) {
if (!answerCounts[bet.outcome]) {
answerCounts[bet.outcome] = bet.amount
} else {
answerCounts[bet.outcome] += bet.amount
}
}
}
const majorityAnswer =
_.maxBy(Object.keys(answerCounts), (outcome) => answerCounts[outcome]) ??
''
return {
userPosition: answerCounts[majorityAnswer] || 0,
outcome: majorityAnswer,
}
}
if (bets.length === 0) {
return emptyReturn
}
const [yesBets, noBets] = _.partition(
previousBets ?? [],
(bet) => bet.outcome === 'YES'
)
yesShares = _.sumBy(yesBets, (bet) => bet.shares)
noShares = _.sumBy(noBets, (bet) => bet.shares)
yesFloorShares = Math.floor(yesShares)
noFloorShares = Math.floor(noShares)
const userPosition = yesFloorShares || noFloorShares
const outcome = yesFloorShares > noFloorShares ? 'YES' : 'NO'
return { userPosition, outcome }
}
function canCommentOnBet(bet: Bet, user?: User | null) { function canCommentOnBet(bet: Bet, user?: User | null) {
const { userId, createdTime, isRedemption } = bet const { userId, createdTime, isRedemption } = bet
const isSelf = user?.id === userId const isSelf = user?.id === userId

View File

@ -1,18 +1,15 @@
// From https://tailwindui.com/components/application-ui/lists/feeds // From https://tailwindui.com/components/application-ui/lists/feeds
import React, { Fragment, useEffect, useRef, useState } from 'react' import React, { Fragment, useRef } from 'react'
import * as _ from 'lodash' import * as _ from 'lodash'
import { Dictionary } from 'lodash'
import { import {
BanIcon, BanIcon,
CheckIcon, CheckIcon,
DotsVerticalIcon, DotsVerticalIcon,
LockClosedIcon, LockClosedIcon,
UserIcon,
UsersIcon, UsersIcon,
XIcon, XIcon,
} from '@heroicons/react/solid' } from '@heroicons/react/solid'
import clsx from 'clsx' import clsx from 'clsx'
import Textarea from 'react-expanding-textarea'
import { OutcomeLabel } from '../outcome-label' import { OutcomeLabel } from '../outcome-label'
import { import {
@ -22,11 +19,7 @@ import {
tradingAllowed, tradingAllowed,
} from 'web/lib/firebase/contracts' } from 'web/lib/firebase/contracts'
import { useUser } from 'web/hooks/use-user' import { useUser } from 'web/hooks/use-user'
import { Linkify } from '../linkify'
import { Row } from '../layout/row'
import { createComment, MAX_COMMENT_LENGTH } from 'web/lib/firebase/comments'
import { formatMoney } from 'common/util/format' import { formatMoney } from 'common/util/format'
import { Comment } from 'common/comment'
import { BinaryResolutionOrChance } from '../contract/contract-card' import { BinaryResolutionOrChance } from '../contract/contract-card'
import { SiteLink } from '../site-link' import { SiteLink } from '../site-link'
import { Col } from '../layout/col' import { Col } from '../layout/col'
@ -36,19 +29,19 @@ import { JoinSpans } from '../join-spans'
import BetRow from '../bet-row' import BetRow from '../bet-row'
import { Avatar } from '../avatar' import { Avatar } from '../avatar'
import { ActivityItem } from './activity-items' import { ActivityItem } from './activity-items'
import { Binary, CPMM, FullContract } from 'common/contract'
import { useSaveSeenContract } from 'web/hooks/use-seen-contracts' import { useSaveSeenContract } from 'web/hooks/use-seen-contracts'
import { User } from 'common/user'
import { trackClick } from 'web/lib/firebase/tracking' import { trackClick } from 'web/lib/firebase/tracking'
import { firebaseLogin } from 'web/lib/firebase/users'
import { DAY_MS } from 'common/util/time' import { DAY_MS } from 'common/util/time'
import NewContractBadge from '../new-contract-badge' import NewContractBadge from '../new-contract-badge'
import { RelativeTimestamp } from '../relative-timestamp' import { RelativeTimestamp } from '../relative-timestamp'
import { calculateCpmmSale } from 'common/calculate-cpmm'
import { useRouter } from 'next/router'
import { FeedAnswerCommentGroup } from 'web/components/feed/feed-answer-comment-group' import { FeedAnswerCommentGroup } from 'web/components/feed/feed-answer-comment-group'
import { getMostRecentCommentableBet } from 'web/components/feed/feed-comments' import {
import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time' FeedCommentThread,
FeedComment,
CommentInput,
TruncatedComment,
} from 'web/components/feed/feed-comments'
import { FeedBet, FeedBetGroup } from 'web/components/feed/feed-bets'
export function FeedItems(props: { export function FeedItems(props: {
contract: Contract contract: Contract
@ -114,513 +107,6 @@ export function FeedItem(props: { item: ActivityItem }) {
} }
} }
export function FeedCommentThread(props: {
contract: Contract
comments: Comment[]
parentComment: Comment
betsByUserId: Dictionary<[Bet, ...Bet[]]>
truncate?: boolean
smallAvatar?: boolean
}) {
const {
contract,
comments,
betsByUserId,
truncate,
smallAvatar,
parentComment,
} = props
const [showReply, setShowReply] = useState(false)
const [replyToUsername, setReplyToUsername] = useState('')
const user = useUser()
const commentsList = comments.filter(
(comment) => comment.replyToCommentId === parentComment.id
)
commentsList.unshift(parentComment)
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
function scrollAndOpenReplyInput(comment: Comment) {
setReplyToUsername(comment.userUsername)
setShowReply(true)
inputRef?.focus()
}
useEffect(() => {
if (showReply && inputRef) inputRef.focus()
}, [inputRef, showReply])
return (
<div className={'w-full flex-col flex-col pr-6'}>
{commentsList.map((comment, commentIdx) => (
<div
key={comment.id}
id={comment.id}
className={commentIdx === 0 ? '' : 'mt-4 ml-8'}
>
<FeedComment
contract={contract}
comment={comment}
betsBySameUser={betsByUserId[comment.userId] ?? []}
onReplyClick={scrollAndOpenReplyInput}
smallAvatar={smallAvatar}
truncate={truncate}
/>
</div>
))}
{showReply && (
<div className={'ml-8 w-full pt-6'}>
<CommentInput
contract={contract}
// Should we allow replies to contain recent bet info?
betsByCurrentUser={(user && betsByUserId[user.id]) ?? []}
comments={comments}
parentComment={parentComment}
replyToUsername={replyToUsername}
answerOutcome={comments[0].answerOutcome}
setRef={setInputRef}
/>
</div>
)}
</div>
)
}
export function FeedComment(props: {
contract: Contract
comment: Comment
betsBySameUser: Bet[]
truncate?: boolean
smallAvatar?: boolean
onReplyClick?: (comment: Comment) => void
}) {
const {
contract,
comment,
betsBySameUser,
truncate,
smallAvatar,
onReplyClick,
} = props
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
let outcome: string | undefined,
bought: string | undefined,
money: string | undefined
const matchedBet = betsBySameUser.find((bet) => bet.id === comment.betId)
if (matchedBet) {
outcome = matchedBet.outcome
bought = matchedBet.amount >= 0 ? 'bought' : 'sold'
money = formatMoney(Math.abs(matchedBet.amount))
}
const [highlighted, setHighlighted] = useState(false)
const router = useRouter()
useEffect(() => {
if (router.asPath.endsWith(`#${comment.id}`)) {
setHighlighted(true)
}
}, [router.asPath])
// Only calculated if they don't have a matching bet
const { userPosition, userPositionMoney, yesFloorShares, noFloorShares } =
getBettorsPosition(
contract,
comment.createdTime,
matchedBet ? [] : betsBySameUser
)
return (
<Row
className={clsx(
'flex space-x-3 transition-all duration-1000',
highlighted ? `-m-2 rounded bg-indigo-500/[0.2] p-2` : ''
)}
>
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
username={userUsername}
avatarUrl={userAvatarUrl}
/>
<div className="min-w-0 flex-1">
<p className="mt-0.5 text-sm text-gray-500">
<UserLink
className="text-gray-500"
username={userUsername}
name={userName}
/>{' '}
{!matchedBet && userPosition > 0 && (
<>
{'had ' + userPositionMoney + ' '}
<>
{' of '}
<OutcomeLabel
outcome={yesFloorShares > noFloorShares ? 'YES' : 'NO'}
contract={contract}
truncate="short"
/>
</>
</>
)}
<>
{bought} {money}
{contract.outcomeType !== 'FREE_RESPONSE' && outcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={outcome ? outcome : ''}
contract={contract}
truncate="short"
/>
</>
)}
</>
<CopyLinkDateTimeComponent
contract={contract}
createdTime={createdTime}
elementId={comment.id}
/>
</p>
<TruncatedComment
comment={text}
moreHref={contractPath(contract)}
shouldTruncate={truncate}
/>
{onReplyClick && (
<button
className={'text-xs font-bold text-gray-500 hover:underline'}
onClick={() => onReplyClick(comment)}
>
Reply
</button>
)}
</div>
</Row>
)
}
export function CommentInput(props: {
contract: Contract
betsByCurrentUser: Bet[]
comments: Comment[]
// Tie a comment to an free response answer outcome
answerOutcome?: string
// Tie a comment to another comment
parentComment?: Comment
replyToUsername?: string
setRef?: (ref: HTMLTextAreaElement) => void
}) {
const {
contract,
betsByCurrentUser,
comments,
answerOutcome,
parentComment,
replyToUsername,
setRef,
} = props
const user = useUser()
const [comment, setComment] = useState('')
const [focused, setFocused] = useState(false)
const mostRecentCommentableBet = getMostRecentCommentableBet(
betsByCurrentUser,
comments,
user,
answerOutcome
)
const { id } = mostRecentCommentableBet || { id: undefined }
useEffect(() => {
if (!replyToUsername || !user || replyToUsername === user.username) return
const replacement = `@${replyToUsername} `
setComment(replacement + comment.replace(replacement, ''))
}, [user, replyToUsername])
async function submitComment(betId: string | undefined) {
if (!user) {
return await firebaseLogin()
}
if (!comment) return
// Update state asap to avoid double submission.
const commentValue = comment.toString()
setComment('')
await createComment(
contract.id,
commentValue,
user,
betId,
answerOutcome,
parentComment?.id
)
}
const { userPosition, userPositionMoney, yesFloorShares, noFloorShares } =
getBettorsPosition(contract, Date.now(), betsByCurrentUser)
const shouldCollapseAfterClickOutside = false
return (
<>
<Row className={'mb-2 flex w-full gap-2'}>
<div className={'mt-1'}>
<Avatar avatarUrl={user?.avatarUrl} username={user?.username} />
</div>
<div className={'min-w-0 flex-1'}>
<div className="text-sm text-gray-500">
<div className={'mb-1'}>
{mostRecentCommentableBet && (
<BetStatusText
contract={contract}
bet={mostRecentCommentableBet}
isSelf={true}
hideOutcome={contract.outcomeType === 'FREE_RESPONSE'}
/>
)}
{!mostRecentCommentableBet && user && userPosition > 0 && (
<>
{'You have ' + userPositionMoney + ' '}
<>
{' of '}
<OutcomeLabel
outcome={yesFloorShares > noFloorShares ? 'YES' : 'NO'}
contract={contract}
truncate="short"
/>
</>
</>
)}
</div>
<Row className="gap-1.5">
<Textarea
ref={(ref: HTMLTextAreaElement) => setRef?.(ref)}
value={comment}
onChange={(e) => setComment(e.target.value)}
className="textarea textarea-bordered w-full resize-none"
placeholder={
parentComment || answerOutcome
? 'Write a reply... '
: 'Write a comment...'
}
autoFocus={focused}
rows={focused ? 3 : 1}
onFocus={() => setFocused(true)}
onBlur={() =>
shouldCollapseAfterClickOutside && setFocused(false)
}
maxLength={MAX_COMMENT_LENGTH}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault()
submitComment(id)
}
}}
/>
<div
className={clsx(
'flex justify-center',
focused ? 'items-end' : 'items-center'
)}
>
{!user && (
<button
className={
'btn btn-outline btn-sm text-transform: capitalize'
}
onClick={() => submitComment(id)}
>
Sign in to Comment
</button>
)}
{user && (
<button
className={clsx(
'btn text-transform: block capitalize',
focused && comment
? 'btn-outline btn-sm '
: 'btn-ghost btn-sm text-gray-500'
)}
onClick={() => {
if (!focused) return
else {
submitComment(id)
setFocused(false)
}
}}
>
{parentComment || answerOutcome ? 'Reply' : 'Comment'}
</button>
)}
</div>
</Row>
</div>
</div>
</Row>
</>
)
}
function getBettorsPosition(
contract: Contract,
createdTime: number,
bets: Bet[]
) {
let yesFloorShares = 0,
yesShares = 0,
noShares = 0,
noFloorShares = 0
const emptyReturn = {
userPosition: 0,
userPositionMoney: 0,
yesFloorShares,
noFloorShares,
}
// TODO: show which of the answers was their majority stake at time of comment for FR?
if (contract.outcomeType != 'BINARY') {
return emptyReturn
}
if (bets.length === 0) {
return emptyReturn
}
// Calculate the majority shares they had when they made the comment
const betsBefore = bets.filter((prevBet) => prevBet.createdTime < createdTime)
const [yesBets, noBets] = _.partition(
betsBefore ?? [],
(bet) => bet.outcome === 'YES'
)
yesShares = _.sumBy(yesBets, (bet) => bet.shares)
noShares = _.sumBy(noBets, (bet) => bet.shares)
yesFloorShares = Math.floor(yesShares)
noFloorShares = Math.floor(noShares)
const userPosition = yesFloorShares || noFloorShares
const { saleValue } = calculateCpmmSale(
contract as FullContract<CPMM, Binary>,
yesShares || noShares,
yesFloorShares > noFloorShares ? 'YES' : 'NO'
)
const userPositionMoney = formatMoney(Math.abs(saleValue))
return { userPosition, userPositionMoney, yesFloorShares, noFloorShares }
}
export function FeedBet(props: {
contract: Contract
bet: Bet
hideOutcome: boolean
smallAvatar: boolean
bettor?: User // If set: reveal bettor identity
}) {
const { contract, bet, hideOutcome, smallAvatar, bettor } = props
const { userId } = bet
const user = useUser()
const isSelf = user?.id === userId
return (
<>
<Row className={'flex w-full gap-2 pt-3'}>
{isSelf ? (
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
avatarUrl={user.avatarUrl}
username={user.username}
/>
) : bettor ? (
<Avatar
className={clsx(smallAvatar && 'ml-1')}
size={smallAvatar ? 'sm' : undefined}
avatarUrl={bettor.avatarUrl}
username={bettor.username}
/>
) : (
<div className="relative px-1">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
<UserIcon className="h-5 w-5 text-gray-500" aria-hidden="true" />
</div>
</div>
)}
<div className={'min-w-0 flex-1 py-1.5'}>
<BetStatusText
bet={bet}
contract={contract}
isSelf={isSelf}
bettor={bettor}
hideOutcome={hideOutcome}
/>
</div>
</Row>
</>
)
}
function BetStatusText(props: {
contract: Contract
bet: Bet
isSelf: boolean
bettor?: User
hideOutcome?: boolean
}) {
const { bet, contract, bettor, isSelf, hideOutcome } = props
const { amount, outcome, createdTime } = bet
const bought = amount >= 0 ? 'bought' : 'sold'
const money = formatMoney(Math.abs(amount))
return (
<div className="text-sm text-gray-500">
<span>{isSelf ? 'You' : bettor ? bettor.name : 'A trader'}</span> {bought}{' '}
{money}
{!hideOutcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={outcome}
contract={contract}
truncate="short"
/>
</>
)}
<RelativeTimestamp time={createdTime} />
</div>
)
}
function TruncatedComment(props: {
comment: string
moreHref: string
shouldTruncate?: boolean
}) {
const { comment, moreHref, shouldTruncate } = props
let truncated = comment
// Keep descriptions to at most 400 characters
const MAX_CHARS = 400
if (shouldTruncate && truncated.length > MAX_CHARS) {
truncated = truncated.slice(0, MAX_CHARS)
// Make sure to end on a space
const i = truncated.lastIndexOf(' ')
truncated = truncated.slice(0, i)
}
return (
<div
className="mt-2 whitespace-pre-line break-words text-gray-700"
style={{ fontSize: 15 }}
>
<Linkify text={truncated} />
{truncated != comment && (
<SiteLink href={moreHref} className="text-indigo-700">
... (show more)
</SiteLink>
)}
</div>
)
}
export function FeedQuestion(props: { export function FeedQuestion(props: {
contract: Contract contract: Contract
showDescription: boolean showDescription: boolean
@ -792,82 +278,6 @@ function FeedClose(props: { contract: Contract }) {
) )
} }
function BetGroupSpan(props: {
contract: Contract
bets: Bet[]
outcome?: string
}) {
const { contract, bets, outcome } = props
const numberTraders = _.uniqBy(bets, (b) => b.userId).length
const [buys, sells] = _.partition(bets, (bet) => bet.amount >= 0)
const buyTotal = _.sumBy(buys, (b) => b.amount)
const sellTotal = _.sumBy(sells, (b) => -b.amount)
return (
<span>
{numberTraders} {numberTraders > 1 ? 'traders' : 'trader'}{' '}
<JoinSpans>
{buyTotal > 0 && <>bought {formatMoney(buyTotal)} </>}
{sellTotal > 0 && <>sold {formatMoney(sellTotal)} </>}
</JoinSpans>
{outcome && (
<>
{' '}
of{' '}
<OutcomeLabel
outcome={outcome}
contract={contract}
truncate="short"
/>
</>
)}{' '}
</span>
)
}
function FeedBetGroup(props: {
contract: Contract
bets: Bet[]
hideOutcome: boolean
}) {
const { contract, bets, hideOutcome } = props
const betGroups = _.groupBy(bets, (bet) => bet.outcome)
const outcomes = Object.keys(betGroups)
// Use the time of the last bet for the entire group
const createdTime = bets[bets.length - 1].createdTime
return (
<>
<div>
<div className="relative px-1">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
<UsersIcon className="h-5 w-5 text-gray-500" aria-hidden="true" />
</div>
</div>
</div>
<div className={clsx('min-w-0 flex-1', outcomes.length === 1 && 'mt-1')}>
<div className="text-sm text-gray-500">
{outcomes.map((outcome, index) => (
<Fragment key={outcome}>
<BetGroupSpan
contract={contract}
outcome={hideOutcome ? undefined : outcome}
bets={betGroups[outcome]}
/>
{index !== outcomes.length - 1 && <br />}
</Fragment>
))}
<RelativeTimestamp time={createdTime} />
</div>
</div>
</>
)
}
// TODO: Should highlight the entire Feed segment // TODO: Should highlight the entire Feed segment
function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) { function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) {
const { setExpanded } = props const { setExpanded } = props

View File

@ -27,7 +27,6 @@ import { Leaderboard } from 'web/components/leaderboard'
import _ from 'lodash' import _ from 'lodash'
import { resolvedPayout } from 'common/calculate' import { resolvedPayout } from 'common/calculate'
import { formatMoney } from 'common/util/format' import { formatMoney } from 'common/util/format'
import { FeedBet, FeedComment } from 'web/components/feed/feed-items'
import { useUserById } from 'web/hooks/use-users' import { useUserById } from 'web/hooks/use-users'
import { ContractTabs } from 'web/components/contract/contract-tabs' import { ContractTabs } from 'web/components/contract/contract-tabs'
import { FirstArgument } from 'common/util/types' import { FirstArgument } from 'common/util/types'
@ -35,6 +34,8 @@ import { DPM, FreeResponse, FullContract } from 'common/contract'
import { contractTextDetails } from 'web/components/contract/contract-details' import { contractTextDetails } from 'web/components/contract/contract-details'
import { useWindowSize } from 'web/hooks/use-window-size' import { useWindowSize } from 'web/hooks/use-window-size'
import Confetti from 'react-confetti' import Confetti from 'react-confetti'
import { FeedComment } from 'web/components/feed/feed-comments'
import { FeedBet } from 'web/components/feed/feed-bets'
export const getStaticProps = fromPropz(getStaticPropz) export const getStaticProps = fromPropz(getStaticPropz)
export async function getStaticPropz(props: { export async function getStaticPropz(props: {