// From https://tailwindui.com/components/application-ui/lists/feeds
import { useState } from 'react'
import _ from 'lodash'
import {
BanIcon,
CheckIcon,
DotsVerticalIcon,
LockClosedIcon,
StarIcon,
UserIcon,
UsersIcon,
XIcon,
} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import clsx from 'clsx'
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 } 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, withoutAnteBets } from '../lib/firebase/bets'
import { Comment, mapCommentsByBetId } from '../lib/firebase/comments'
import { JoinSpans } from './join-spans'
import Textarea from 'react-expanding-textarea'
import { outcome } from '../../common/contract'
import { fromNow } from '../lib/util/time'
import BetRow from './bet-row'
import { parseTags } from '../../common/util/parse'
import { Avatar } from './avatar'
function FeedComment(props: {
activityItem: any
moreHref: string
feedType: 'activity' | 'market'
}) {
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 (
<>
{' '}
{bought} {money} of {' '}
>
)
}
function Timestamp(props: { time: number }) {
const { time } = props
return (
{fromNow(time)}
)
}
function FeedBet(props: { activityItem: any }) {
const { activityItem } = props
const { id, contractId, amount, outcome, createdTime } = activityItem
const user = useUser()
const isSelf = user?.id == activityItem.userId
// The creator can comment if the 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 ? 'You' : 'A trader'} {bought} {money} of{' '}
{canComment && (
// Allow user to comment in an textarea if they are the creator
)}
>
)
}
export function ContractDescription(props: {
contract: Contract
isCreator: boolean
}) {
const { contract, isCreator } = props
const [editing, setEditing] = useState(false)
const editStatement = () => `${dayjs().format('MMM D, h:mma')}: `
const [description, setDescription] = useState(editStatement())
// Append the new description (after a newline)
async function saveDescription(e: any) {
e.preventDefault()
setEditing(false)
const newDescription = `${contract.description}\n\n${description}`.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,
})
setDescription(editStatement())
}
if (!isCreator && !contract.description.trim()) return null
return (
{isCreator &&
(editing ? (
) : (
))}
)
}
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 }) {
const { contract } = props
const { creatorName, creatorUsername, createdTime, question, resolution } =
contract
const { probPercent, truePool } = contractMetrics(contract)
// Currently hidden on mobile; ideally we'd fit this in somewhere.
const closeMessage =
contract.isResolved || !contract.closeTime ? null : (
{formatMoney(truePool)} pool
•
{contract.closeTime > Date.now() ? 'Closes' : 'Closed'}
)
return (
<>
{' '}
asked
{closeMessage}
{question}
>
)
}
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 OutcomeIcon(props: { outcome?: outcome }) {
const { outcome } = props
switch (outcome) {
case 'YES':
return
case 'NO':
return
case 'CANCEL':
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) {
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),
}
}
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
// Return a list of ActivityItems
function groupBets(
bets: Bet[],
comments: Comment[],
windowMs: number,
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]))
} else if (group.length > 1) {
items.push({ type: 'betgroup', bets: [...group], id: group[0].id })
}
group = []
}
function toActivityItem(bet: Bet) {
const comment = commentsMap[bet.id]
return comment ? toFeedComment(bet, comment) : toFeedBet(bet)
}
for (const bet of bets) {
const isCreator = userId === bet.userId
if (commentsMap[bet.id] || isCreator) {
pushGroup()
// Create a single item for this
items.push(toActivityItem(bet))
} 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: 'YES' | 'NO' }) {
const { 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 (
{numberTraders} {numberTraders > 1 ? 'traders' : 'trader'}{' '}
{buyTotal > 0 && <>bought {formatMoney(buyTotal)} >}
{sellTotal > 0 && <>sold {formatMoney(sellTotal)} >}
of
)
}
// TODO: Make this expandable to show all grouped bets?
function FeedBetGroup(props: { activityItem: any }) {
const { activityItem } = props
const bets: Bet[] = activityItem.bets
const [yesBets, noBets] = _.partition(bets, (bet) => bet.outcome === 'YES')
// Use the time of the last bet for the entire group
const createdTime = bets[bets.length - 1].createdTime
return (
<>
{yesBets.length > 0 && }
{yesBets.length > 0 && noBets.length > 0 &&
}
{noBets.length > 0 && }
>
)
}
// TODO: Should highlight the entire Feed segment
function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) {
const { setExpanded } = props
return (
<>
>
)
}
// Missing feed items:
// - Bet sold?
type ActivityItem = {
id: string
type:
| 'bet'
| 'comment'
| 'start'
| 'betgroup'
| 'close'
| 'resolve'
| 'expand'
}
export function ContractFeed(props: {
contract: Contract
bets: Bet[]
comments: Comment[]
// Feed types: 'activity' = Activity feed, 'market' = Comments feed on a market
feedType: 'activity' | 'market'
betRowClassName?: string
}) {
const { contract, feedType, betRowClassName } = props
const { id } = contract
const [expanded, setExpanded] = useState(false)
const user = useUser()
let bets = useBets(id) ?? props.bets
bets = withoutAnteBets(contract, bets)
const comments = useComments(id) ?? props.comments
const groupWindow = feedType == 'activity' ? 10 * DAY_IN_MS : DAY_IN_MS
const allItems = [
{ type: 'start', id: 0 },
...groupBets(bets, comments, groupWindow, 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 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 (
{items.map((activityItem, activityItemIdx) => (
-
{activityItemIdx !== items.length - 1 ? (
) : null}
{activityItem.type === 'start' ? (
feedType == 'activity' ? (
) : (
)
) : activityItem.type === 'comment' ? (
) : activityItem.type === 'bet' ? (
) : activityItem.type === 'betgroup' ? (
) : activityItem.type === 'close' ? (
) : activityItem.type === 'resolve' ? (
) : activityItem.type === 'expand' ? (
) : null}
))}
{tradingAllowed(contract) && (
)}
)
}