// From https://tailwindui.com/components/application-ui/lists/feeds
import { Fragment, useState } from 'react'
import _ from 'lodash'
import {
BanIcon,
CheckIcon,
DotsVerticalIcon,
LockClosedIcon,
UserIcon,
UsersIcon,
XIcon,
} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import clsx from 'clsx'
import Textarea from 'react-expanding-textarea'
import { OutcomeLabel } from './outcome-label'
import {
contractMetrics,
Contract,
contractPath,
updateContract,
tradingAllowed,
} from '../lib/firebase/contracts'
import { useUser } from '../hooks/use-user'
import { Linkify } from './linkify'
import { Row } from './layout/row'
import { createComment, MAX_COMMENT_LENGTH } from '../lib/firebase/comments'
import { useComments } from '../hooks/use-comments'
import { formatMoney } from '../../common/util/format'
import { ResolutionOrChance } from './contract-card'
import { SiteLink } from './site-link'
import { Col } from './layout/col'
import { UserLink } from './user-page'
import { DateTimeTooltip } from './datetime-tooltip'
import { useBets } from '../hooks/use-bets'
import { Bet } from '../lib/firebase/bets'
import { Comment, mapCommentsByBetId } from '../lib/firebase/comments'
import { JoinSpans } from './join-spans'
import { fromNow } from '../lib/util/time'
import BetRow from './bet-row'
import { parseTags } from '../../common/util/parse'
import { Avatar } from './avatar'
import { useAdmin } from '../hooks/use-admin'
function FeedComment(props: {
activityItem: any
moreHref: string
feedType: FeedType
}) {
const { activityItem, moreHref, feedType } = props
const { person, text, amount, outcome, createdTime } = activityItem
const bought = amount >= 0 ? 'bought' : 'sold'
const money = formatMoney(Math.abs(amount))
return (
<>
>
)
}
function Timestamp(props: { time: number }) {
const { time } = props
return (
{fromNow(time)}
)
}
function FeedBet(props: { activityItem: any; feedType: FeedType }) {
const { activityItem, feedType } = props
const { id, contractId, amount, outcome, createdTime, contract } =
activityItem
const user = useUser()
const isSelf = user?.id == activityItem.userId
const isCreator = contract.creatorId == activityItem.userId
// You can comment if your bet was posted in the last hour
const canComment = isSelf && Date.now() - createdTime < 60 * 60 * 1000
const [comment, setComment] = useState('')
async function submitComment() {
if (!user || !comment) return
await createComment(contractId, id, comment, user)
}
const bought = amount >= 0 ? 'bought' : 'sold'
const money = formatMoney(Math.abs(amount))
return (
<>
{isSelf ? (
) : isCreator ? (
) : (
)}
{isSelf ? 'You' : isCreator ? contract.creatorName : 'A trader'}
{' '}
{bought} {money}
{canComment && (
// Allow user to comment in an textarea if they are the creator
)}
>
)
}
function EditContract(props: {
text: string
onSave: (newText: string) => void
buttonText: string
}) {
const [text, setText] = useState(props.text)
const [editing, setEditing] = useState(false)
const onSave = (newText: string) => {
setEditing(false)
setText(props.text) // Reset to original text
props.onSave(newText)
}
return editing ? (
) : (
setEditing(true)}
>
{props.buttonText}
)
}
export function ContractDescription(props: {
contract: Contract
isCreator: boolean
}) {
const { contract, isCreator } = props
const descriptionTimestamp = () => `${dayjs().format('MMM D, h:mma')}: `
const isAdmin = useAdmin()
// Append the new description (after a newline)
async function saveDescription(newText: string) {
const newDescription = `${contract.description}\n\n${newText}`.trim()
const tags = parseTags(
`${newDescription} ${contract.tags.map((tag) => `#${tag}`).join(' ')}`
)
const lowercaseTags = tags.map((tag) => tag.toLowerCase())
await updateContract(contract.id, {
description: newDescription,
tags,
lowercaseTags,
})
}
if (!isCreator && !contract.description.trim()) return null
return (
{isCreator && (
)}
{isAdmin && (
updateContract(contract.id, { question })}
buttonText="ADMIN: Edit question"
/>
)}
{/* {isAdmin && (
updateContract(contract.id, { createdTime: Number(time) })
}
buttonText="ADMIN: Edit createdTime"
/>
)} */}
)
}
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 (
{truncated != comment && (
... (show more)
)}
)
}
function FeedQuestion(props: {
contract: Contract
showDescription?: boolean
}) {
const { contract, showDescription } = props
const { creatorName, creatorUsername, question, resolution, outcomeType } =
contract
const { truePool } = contractMetrics(contract)
const isBinary = outcomeType === 'BINARY'
const closeMessage =
contract.isResolved || !contract.closeTime ? null : (
<>
•
{contract.closeTime > Date.now() ? 'Closes' : 'Closed'}
>
)
return (
<>
{' '}
asked
{/* Currently hidden on mobile; ideally we'd fit this in somewhere. */}
{formatMoney(truePool)} pool
{closeMessage}
{question}
{!showDescription && (
See more...
)}
{(isBinary || resolution) && (
)}
{showDescription && (
)}
>
)
}
function FeedDescription(props: { contract: Contract }) {
const { contract } = props
const { creatorName, creatorUsername } = contract
const user = useUser()
const isCreator = user?.id === contract.creatorId
return (
<>
{' '}
created this market
>
)
}
function FeedAnswer(props: { contract: Contract; outcome: string }) {
const { contract, outcome } = props
const answer = contract?.answers?.[Number(outcome) - 1]
if (!answer) return null
return (
<>
{' '}
submitted answer {' '}
>
)
}
function OutcomeIcon(props: { outcome?: string }) {
const { outcome } = props
switch (outcome) {
case 'YES':
return
case 'NO':
return
case 'CANCEL':
return
default:
return
}
}
function FeedResolve(props: { contract: Contract }) {
const { contract } = props
const { creatorName, creatorUsername } = contract
const resolution = contract.resolution || 'CANCEL'
return (
<>
{' '}
resolved this market to {' '}
>
)
}
function FeedClose(props: { contract: Contract }) {
const { contract } = props
return (
<>
Trading closed in this market{' '}
>
)
}
function toFeedBet(bet: Bet, contract: Contract) {
return {
id: bet.id,
contractId: bet.contractId,
userId: bet.userId,
type: 'bet',
amount: bet.sale ? -bet.sale.amount : bet.amount,
outcome: bet.outcome,
createdTime: bet.createdTime,
date: fromNow(bet.createdTime),
contract,
}
}
function toFeedComment(bet: Bet, comment: Comment) {
return {
id: bet.id,
contractId: bet.contractId,
userId: bet.userId,
type: 'comment',
amount: bet.sale ? -bet.sale.amount : bet.amount,
outcome: bet.outcome,
createdTime: bet.createdTime,
date: fromNow(bet.createdTime),
// Invariant: bet.comment exists
text: comment.text,
person: {
username: comment.userUsername,
name: comment.userName,
avatarUrl: comment.userAvatarUrl,
},
}
}
const DAY_IN_MS = 24 * 60 * 60 * 1000
// Group together bets that are:
// - Within `windowMs` of the first in the group
// - Do not have a comment
// - Were not created by this user or the contract creator
// Return a list of ActivityItems
function groupBets(
bets: Bet[],
comments: Comment[],
windowMs: number,
contract: Contract,
userId?: string
) {
const commentsMap = mapCommentsByBetId(comments)
const items: any[] = []
let group: Bet[] = []
// Turn the current group into an ActivityItem
function pushGroup() {
if (group.length == 1) {
items.push(toActivityItem(group[0], false))
} else if (group.length > 1) {
items.push({ type: 'betgroup', bets: [...group], id: group[0].id })
}
group = []
}
function toActivityItem(bet: Bet, isPublic: boolean) {
const comment = commentsMap[bet.id]
return comment ? toFeedComment(bet, comment) : toFeedBet(bet, contract)
}
for (const bet of bets) {
const isCreator = userId === bet.userId || contract.creatorId === bet.userId
if (commentsMap[bet.id] || isCreator) {
pushGroup()
// Create a single item for this
items.push(toActivityItem(bet, true))
} else {
if (
group.length > 0 &&
bet.createdTime - group[0].createdTime > windowMs
) {
// More than `windowMs` has passed; start a new group
pushGroup()
}
group.push(bet)
}
}
if (group.length > 0) {
pushGroup()
}
return items as ActivityItem[]
}
function BetGroupSpan(props: {
bets: Bet[]
outcome: string
feedType: FeedType
}) {
const { bets, outcome, feedType } = 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 (
{numberTraders} {numberTraders > 1 ? 'traders' : 'trader'}{' '}
{buyTotal > 0 && <>bought {formatMoney(buyTotal)} >}
{sellTotal > 0 && <>sold {formatMoney(sellTotal)} >}
{' '}
)
}
// TODO: Make this expandable to show all grouped bets?
function FeedBetGroup(props: { activityItem: any; feedType: FeedType }) {
const { activityItem, feedType } = props
const bets: Bet[] = activityItem.bets
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 (
<>
{outcomes.map((outcome, index) => (
{index !== outcomes.length - 1 && }
))}
>
)
}
// TODO: Should highlight the entire Feed segment
function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) {
const { setExpanded } = props
return (
<>
setExpanded(true)}>
setExpanded(true)}>
>
)
}
// On 'multi' feeds, the outcome is redundant, so we hide it
function MaybeOutcomeLabel(props: { outcome: string; feedType: FeedType }) {
const { outcome, feedType } = props
return feedType === 'multi' ? null : (
{' '}
of
{/* TODO: Link to the correct e.g. #23 */}
)
}
// Missing feed items:
// - Bet sold?
type ActivityItem = {
id: string
type:
| 'bet'
| 'comment'
| 'start'
| 'betgroup'
| 'close'
| 'resolve'
| 'expand'
| undefined
}
type FeedType =
// Main homepage/fold feed,
| 'activity'
// Comments feed on a market
| 'market'
// Grouped for a multi-category outcome
| 'multi'
function FeedItems(props: {
contract: Contract
items: ActivityItem[]
feedType: FeedType
setExpanded: (expanded: boolean) => void
outcome?: string // Which multi-category outcome to filter
betRowClassName?: string
}) {
const { contract, items, feedType, outcome, setExpanded, betRowClassName } =
props
const { outcomeType } = contract
const isBinary = outcomeType === 'BINARY'
const filteredItems =
outcomeType === 'FREE_RESPONSE' && feedType !== 'multi'
? items.filter((item) => item.type !== 'bet' && item.type !== 'betgroup')
: items
return (
{filteredItems.map((activityItem, activityItemIdx) => (
{activityItemIdx !== filteredItems.length - 1 ? (
) : null}
{activityItem.type === 'start' ? (
feedType === 'activity' ? (
) : feedType === 'market' ? (
) : feedType === 'multi' ? (
) : null
) : activityItem.type === 'comment' ? (
) : activityItem.type === 'bet' ? (
) : activityItem.type === 'betgroup' ? (
) : activityItem.type === 'close' ? (
) : activityItem.type === 'resolve' ? (
) : activityItem.type === 'expand' ? (
) : null}
))}
{isBinary && tradingAllowed(contract) && (
)}
)
}
export function ContractFeed(props: {
contract: Contract
bets: Bet[]
comments: Comment[]
feedType: FeedType
outcome?: string // Which multi-category outcome to filter
betRowClassName?: string
}) {
const { contract, feedType, outcome, betRowClassName } = props
const { id, outcomeType } = contract
const isBinary = outcomeType === 'BINARY'
const [expanded, setExpanded] = useState(false)
const user = useUser()
let bets = useBets(contract.id) ?? props.bets
bets = isBinary
? bets.filter((bet) => !bet.isAnte)
: bets.filter((bet) => !(bet.isAnte && (bet.outcome as string) === '0'))
if (feedType === 'multi') {
bets = bets.filter((bet) => bet.outcome === outcome)
}
const comments = useComments(id) ?? props.comments
const groupWindow = feedType == 'activity' ? 10 * DAY_IN_MS : DAY_IN_MS
const allItems: ActivityItem[] = [
{ type: 'start', id: '0' },
...groupBets(bets, comments, groupWindow, contract, user?.id),
]
if (contract.closeTime && contract.closeTime <= Date.now()) {
allItems.push({ type: 'close', id: `${contract.closeTime}` })
}
if (contract.resolution) {
allItems.push({ type: 'resolve', id: `${contract.resolutionTime}` })
}
if (feedType === 'multi') {
// Hack to add some more padding above the 'multi' feedType, by adding a null item
allItems.unshift({ type: undefined, id: '-1' })
}
// If there are more than 5 items, only show the first, an expand item, and last 3
let items = allItems
if (!expanded && allItems.length > 5 && feedType == 'activity') {
items = [
allItems[0],
{ type: 'expand', id: 'expand' },
...allItems.slice(-3),
]
}
return (
)
}
export function ContractActivityFeed(props: {
contract: Contract
bets: Bet[]
comments: Comment[]
betRowClassName?: string
}) {
const { contract, betRowClassName, bets, comments } = props
const user = useUser()
bets.sort((b1, b2) => b1.createdTime - b2.createdTime)
comments.sort((c1, c2) => c1.createdTime - c2.createdTime)
const allItems: ActivityItem[] = [
{ type: 'start', id: '0' },
...groupBets(bets, comments, DAY_IN_MS, contract, user?.id),
]
if (contract.closeTime && contract.closeTime <= Date.now()) {
allItems.push({ type: 'close', id: `${contract.closeTime}` })
}
if (contract.resolution) {
allItems.push({ type: 'resolve', id: `${contract.resolutionTime}` })
}
// Remove all but last bet group.
const betGroups = allItems.filter((item) => item.type === 'betgroup')
const lastBetGroup = betGroups[betGroups.length - 1]
const filtered = allItems.filter(
(item) => item.type !== 'betgroup' || item.id === lastBetGroup?.id
)
// Only show the first item plus the last three items.
const items =
filtered.length > 3 ? [filtered[0], ...filtered.slice(-3)] : filtered
return (
{}}
betRowClassName={betRowClassName}
/>
)
}
export function ContractSummaryFeed(props: {
contract: Contract
betRowClassName?: string
}) {
const { contract, betRowClassName } = props
const { outcomeType } = contract
const isBinary = outcomeType === 'BINARY'
return (
{isBinary && tradingAllowed(contract) && (
)}
)
}