Merge branch 'main' into cfmm
This commit is contained in:
commit
03ca84082a
|
@ -10,7 +10,7 @@ export type Comment = {
|
|||
createdTime: number
|
||||
|
||||
// Denormalized, for rendering comments
|
||||
userName?: string
|
||||
userUsername?: string
|
||||
userName: string
|
||||
userUsername: string
|
||||
userAvatarUrl?: string
|
||||
}
|
||||
|
|
|
@ -1,135 +0,0 @@
|
|||
import _ from 'lodash'
|
||||
import {
|
||||
ContractActivityFeed,
|
||||
ContractFeed,
|
||||
ContractSummaryFeed,
|
||||
} from './contract-feed'
|
||||
import { Contract } from '../lib/firebase/contracts'
|
||||
import { Comment } from '../lib/firebase/comments'
|
||||
import { Col } from './layout/col'
|
||||
import { Bet } from '../../common/bet'
|
||||
|
||||
const MAX_ACTIVE_CONTRACTS = 75
|
||||
|
||||
// This does NOT include comment times, since those aren't part of the contract atm.
|
||||
// TODO: Maybe store last activity time directly in the contract?
|
||||
// Pros: simplifies this code; cons: harder to tweak "activity" definition later
|
||||
function lastActivityTime(contract: Contract) {
|
||||
return Math.max(
|
||||
contract.resolutionTime || 0,
|
||||
contract.lastUpdatedTime,
|
||||
contract.createdTime
|
||||
)
|
||||
}
|
||||
|
||||
// Types of activity to surface:
|
||||
// - Comment on a market
|
||||
// - New market created
|
||||
// - Market resolved
|
||||
// - Bet on market
|
||||
export function findActiveContracts(
|
||||
allContracts: Contract[],
|
||||
recentComments: Comment[],
|
||||
recentBets: Bet[]
|
||||
) {
|
||||
const idToActivityTime = new Map<string, number>()
|
||||
function record(contractId: string, time: number) {
|
||||
// Only record if the time is newer
|
||||
const oldTime = idToActivityTime.get(contractId)
|
||||
idToActivityTime.set(contractId, Math.max(oldTime ?? 0, time))
|
||||
}
|
||||
|
||||
const contractsById = new Map(allContracts.map((c) => [c.id, c]))
|
||||
|
||||
// Record contract activity.
|
||||
for (const contract of allContracts) {
|
||||
record(contract.id, lastActivityTime(contract))
|
||||
}
|
||||
|
||||
// Add every contract that had a recent comment, too
|
||||
for (const comment of recentComments) {
|
||||
const contract = contractsById.get(comment.contractId)
|
||||
if (contract) record(contract.id, comment.createdTime)
|
||||
}
|
||||
|
||||
// Add contracts by last bet time.
|
||||
const contractBets = _.groupBy(recentBets, (bet) => bet.contractId)
|
||||
const contractMostRecentBet = _.mapValues(
|
||||
contractBets,
|
||||
(bets) => _.maxBy(bets, (bet) => bet.createdTime) as Bet
|
||||
)
|
||||
for (const bet of Object.values(contractMostRecentBet)) {
|
||||
const contract = contractsById.get(bet.contractId)
|
||||
if (contract) record(contract.id, bet.createdTime)
|
||||
}
|
||||
|
||||
let activeContracts = allContracts.filter(
|
||||
(contract) => contract.visibility === 'public' && !contract.isResolved
|
||||
)
|
||||
activeContracts = _.sortBy(
|
||||
activeContracts,
|
||||
(c) => -(idToActivityTime.get(c.id) ?? 0)
|
||||
)
|
||||
return activeContracts.slice(0, MAX_ACTIVE_CONTRACTS)
|
||||
}
|
||||
|
||||
export function ActivityFeed(props: {
|
||||
contracts: Contract[]
|
||||
recentBets: Bet[]
|
||||
recentComments: Comment[]
|
||||
loadBetAndCommentHistory?: boolean
|
||||
}) {
|
||||
const { contracts, recentBets, recentComments, loadBetAndCommentHistory } =
|
||||
props
|
||||
|
||||
const groupedBets = _.groupBy(recentBets, (bet) => bet.contractId)
|
||||
const groupedComments = _.groupBy(
|
||||
recentComments,
|
||||
(comment) => comment.contractId
|
||||
)
|
||||
|
||||
return (
|
||||
<Col className="items-center">
|
||||
<Col className="w-full">
|
||||
<Col className="w-full divide-y divide-gray-300 self-center bg-white">
|
||||
{contracts.map((contract) => (
|
||||
<div key={contract.id} className="py-6 px-2 sm:px-4">
|
||||
{loadBetAndCommentHistory ? (
|
||||
<ContractFeed
|
||||
contract={contract}
|
||||
bets={groupedBets[contract.id] ?? []}
|
||||
comments={groupedComments[contract.id] ?? []}
|
||||
feedType="activity"
|
||||
/>
|
||||
) : (
|
||||
<ContractActivityFeed
|
||||
contract={contract}
|
||||
bets={groupedBets[contract.id] ?? []}
|
||||
comments={groupedComments[contract.id] ?? []}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Col>
|
||||
</Col>
|
||||
</Col>
|
||||
)
|
||||
}
|
||||
|
||||
export function SummaryActivityFeed(props: { contracts: Contract[] }) {
|
||||
const { contracts } = props
|
||||
|
||||
return (
|
||||
<Col className="items-center">
|
||||
<Col className="w-full max-w-3xl">
|
||||
<Col className="w-full divide-y divide-gray-300 self-center bg-white">
|
||||
{contracts.map((contract) => (
|
||||
<div key={contract.id} className="py-6 px-2 sm:px-4">
|
||||
<ContractSummaryFeed contract={contract} />
|
||||
</div>
|
||||
))}
|
||||
</Col>
|
||||
</Col>
|
||||
</Col>
|
||||
)
|
||||
}
|
|
@ -13,12 +13,14 @@ import { formatPercent } from '../../../common/util/format'
|
|||
import { getDpmOutcomeProbability } from '../../../common/calculate-dpm'
|
||||
import { tradingAllowed } from '../../lib/firebase/contracts'
|
||||
import { AnswerBetPanel } from './answer-bet-panel'
|
||||
import { ContractFeed } from '../contract-feed'
|
||||
import { Linkify } from '../linkify'
|
||||
import { User } from '../../../common/user'
|
||||
import { ContractActivity } from '../feed/contract-activity'
|
||||
|
||||
export function AnswerItem(props: {
|
||||
answer: Answer
|
||||
contract: FullContract<DPM, FreeResponse>
|
||||
user: User | null | undefined
|
||||
showChoice: 'radio' | 'checkbox' | undefined
|
||||
chosenProb: number | undefined
|
||||
totalChosenProb?: number
|
||||
|
@ -28,6 +30,7 @@ export function AnswerItem(props: {
|
|||
const {
|
||||
answer,
|
||||
contract,
|
||||
user,
|
||||
showChoice,
|
||||
chosenProb,
|
||||
totalChosenProb,
|
||||
|
@ -82,12 +85,13 @@ export function AnswerItem(props: {
|
|||
</Row>
|
||||
|
||||
{isBetting && (
|
||||
<ContractFeed
|
||||
<ContractActivity
|
||||
contract={contract}
|
||||
bets={[]}
|
||||
comments={[]}
|
||||
feedType="multi"
|
||||
outcome={answer.id}
|
||||
user={user}
|
||||
filterToOutcome={answer.id}
|
||||
mode="all"
|
||||
/>
|
||||
)}
|
||||
</Col>
|
||||
|
|
|
@ -89,6 +89,7 @@ export function AnswersPanel(props: {
|
|||
key={answer.id}
|
||||
answer={answer}
|
||||
contract={contract}
|
||||
user={user}
|
||||
showChoice={showChoice}
|
||||
chosenProb={chosenAnswers[answer.id]}
|
||||
totalChosenProb={chosenTotal}
|
||||
|
|
|
@ -6,11 +6,11 @@ export function Avatar(props: {
|
|||
username?: string
|
||||
avatarUrl?: string
|
||||
noLink?: boolean
|
||||
size?: number
|
||||
size?: number | 'xs' | 'sm'
|
||||
className?: string
|
||||
}) {
|
||||
const { username, avatarUrl, noLink, size, className } = props
|
||||
const s = size || 10
|
||||
const s = size == 'xs' ? 6 : size === 'sm' ? 8 : size || 10
|
||||
|
||||
const onClick =
|
||||
noLink && username
|
||||
|
|
|
@ -38,6 +38,7 @@ import {
|
|||
} from '../../common/calculate'
|
||||
|
||||
type BetSort = 'newest' | 'profit' | 'settled' | 'value'
|
||||
type BetFilter = 'open' | 'closed' | 'resolved' | 'all'
|
||||
|
||||
export function BetsList(props: { user: User }) {
|
||||
const { user } = props
|
||||
|
@ -46,6 +47,7 @@ export function BetsList(props: { user: User }) {
|
|||
const [contracts, setContracts] = useState<Contract[] | undefined>()
|
||||
|
||||
const [sort, setSort] = useState<BetSort>('value')
|
||||
const [filter, setFilter] = useState<BetFilter>('open')
|
||||
|
||||
useEffect(() => {
|
||||
if (bets) {
|
||||
|
@ -69,11 +71,10 @@ export function BetsList(props: { user: User }) {
|
|||
}
|
||||
|
||||
if (bets.length === 0) return <NoBets />
|
||||
|
||||
// Decending creation time.
|
||||
bets.sort((bet1, bet2) => bet2.createdTime - bet1.createdTime)
|
||||
|
||||
const contractBets = _.groupBy(bets, 'contractId')
|
||||
const contractsById = _.fromPairs(contracts.map((c) => [c.id, c]))
|
||||
|
||||
const contractsCurrentValue = _.mapValues(
|
||||
contractBets,
|
||||
|
@ -81,7 +82,7 @@ export function BetsList(props: { user: User }) {
|
|||
return _.sumBy(bets, (bet) => {
|
||||
if (bet.isSold || bet.sale) return 0
|
||||
|
||||
const contract = contracts.find((c) => c.id === contractId)
|
||||
const contract = contractsById[contractId]
|
||||
const payout = contract ? calculatePayout(contract, bet, 'MKT') : 0
|
||||
return payout - (bet.loanAmount ?? 0)
|
||||
})
|
||||
|
@ -94,29 +95,30 @@ export function BetsList(props: { user: User }) {
|
|||
})
|
||||
})
|
||||
|
||||
let sortedContracts = contracts
|
||||
if (sort === 'profit') {
|
||||
sortedContracts = _.sortBy(
|
||||
contracts,
|
||||
(c) => -1 * (contractsCurrentValue[c.id] - contractsInvestment[c.id])
|
||||
)
|
||||
} else if (sort === 'value') {
|
||||
sortedContracts = _.sortBy(contracts, (c) => -contractsCurrentValue[c.id])
|
||||
} else if (sort === 'newest')
|
||||
sortedContracts = _.sortBy(
|
||||
contracts,
|
||||
(c) => -1 * Math.max(...contractBets[c.id].map((bet) => bet.createdTime))
|
||||
)
|
||||
else if (sort === 'settled')
|
||||
sortedContracts = _.sortBy(contracts, (c) => -1 * (c.resolutionTime ?? 0))
|
||||
const FILTERS: Record<BetFilter, (c: Contract) => boolean> = {
|
||||
resolved: (c) => !!c.resolutionTime,
|
||||
closed: (c) =>
|
||||
!FILTERS.resolved(c) && (c.closeTime ?? Infinity) < Date.now(),
|
||||
open: (c) => !(FILTERS.closed(c) || FILTERS.resolved(c)),
|
||||
all: () => true,
|
||||
// Pepe notes: most users want "settled", to see when their bets or sold; or "realized profit"
|
||||
}
|
||||
const SORTS: Record<BetSort, (c: Contract) => number> = {
|
||||
profit: (c) => contractsCurrentValue[c.id] - contractsInvestment[c.id],
|
||||
value: (c) => contractsCurrentValue[c.id],
|
||||
newest: (c) =>
|
||||
Math.max(...contractBets[c.id].map((bet) => bet.createdTime)),
|
||||
settled: (c) => c.resolutionTime ?? 0,
|
||||
}
|
||||
const displayedContracts = _.sortBy(contracts, SORTS[sort])
|
||||
.reverse()
|
||||
.filter(FILTERS[filter])
|
||||
|
||||
const [settled, unsettled] = _.partition(
|
||||
sortedContracts,
|
||||
contracts,
|
||||
(c) => c.isResolved || contractsInvestment[c.id] === 0
|
||||
)
|
||||
|
||||
const displayedContracts = sort === 'settled' ? settled : unsettled
|
||||
|
||||
const currentInvestment = _.sumBy(unsettled, (c) => contractsInvestment[c.id])
|
||||
|
||||
const currentBetsValue = _.sumBy(
|
||||
|
@ -151,16 +153,29 @@ export function BetsList(props: { user: User }) {
|
|||
</Col>
|
||||
</Row>
|
||||
|
||||
<select
|
||||
className="select select-bordered self-start"
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value as BetSort)}
|
||||
>
|
||||
<option value="value">By value</option>
|
||||
<option value="profit">By profit</option>
|
||||
<option value="newest">Most recent</option>
|
||||
<option value="settled">Resolved</option>
|
||||
</select>
|
||||
<Row className="gap-8">
|
||||
<select
|
||||
className="select select-bordered self-start"
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value as BetFilter)}
|
||||
>
|
||||
<option value="open">Open</option>
|
||||
<option value="closed">Closed</option>
|
||||
<option value="resolved">Resolved</option>
|
||||
<option value="all">All</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
className="select select-bordered self-start"
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value as BetSort)}
|
||||
>
|
||||
<option value="value">By value</option>
|
||||
<option value="profit">By profit</option>
|
||||
<option value="newest">Most recent</option>
|
||||
<option value="settled">By resolution time</option>
|
||||
</select>
|
||||
</Row>
|
||||
</Col>
|
||||
|
||||
{displayedContracts.length === 0 ? (
|
||||
|
|
|
@ -12,13 +12,13 @@ import { Row } from './layout/row'
|
|||
import { Linkify } from './linkify'
|
||||
import clsx from 'clsx'
|
||||
import { ContractDetails, ResolutionOrChance } from './contract-card'
|
||||
import { ContractFeed } from './contract-feed'
|
||||
import { Bet } from '../../common/bet'
|
||||
import { Comment } from '../../common/comment'
|
||||
import { RevealableTagsInput, TagsInput } from './tags-input'
|
||||
import BetRow from './bet-row'
|
||||
import { Fold } from '../../common/fold'
|
||||
import { FoldTagList } from './tags-list'
|
||||
import { ContractActivity } from './feed/contract-activity'
|
||||
|
||||
export const ContractOverview = (props: {
|
||||
contract: Contract
|
||||
|
@ -119,11 +119,12 @@ export const ContractOverview = (props: {
|
|||
|
||||
<Spacer h={12} />
|
||||
|
||||
<ContractFeed
|
||||
<ContractActivity
|
||||
contract={contract}
|
||||
bets={bets}
|
||||
comments={comments}
|
||||
feedType="market"
|
||||
user={user}
|
||||
mode="all"
|
||||
betRowClassName="!mt-0"
|
||||
/>
|
||||
</Col>
|
||||
|
|
|
@ -310,6 +310,7 @@ export function CreatorContractsList(props: { creator: User }) {
|
|||
|
||||
const { query, setQuery, sort, setSort } = useQueryAndSortParams({
|
||||
defaultSort: 'all',
|
||||
shouldLoadFromStorage: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
|
|
99
web/components/feed/activity-feed.tsx
Normal file
99
web/components/feed/activity-feed.tsx
Normal file
|
@ -0,0 +1,99 @@
|
|||
import _ from 'lodash'
|
||||
import clsx from 'clsx'
|
||||
|
||||
import { Contract, tradingAllowed } from '../../lib/firebase/contracts'
|
||||
import { Comment } from '../../lib/firebase/comments'
|
||||
import { Col } from '../layout/col'
|
||||
import { Bet } from '../../../common/bet'
|
||||
import { useUser } from '../../hooks/use-user'
|
||||
import BetRow from '../bet-row'
|
||||
import { FeedQuestion } from './feed-items'
|
||||
import { ContractActivity } from './contract-activity'
|
||||
|
||||
export function ActivityFeed(props: {
|
||||
contracts: Contract[]
|
||||
recentBets: Bet[]
|
||||
recentComments: Comment[]
|
||||
mode: 'only-recent' | 'abbreviated' | 'all'
|
||||
}) {
|
||||
const { contracts, recentBets, recentComments, mode } = props
|
||||
|
||||
const user = useUser()
|
||||
|
||||
const groupedBets = _.groupBy(recentBets, (bet) => bet.contractId)
|
||||
const groupedComments = _.groupBy(
|
||||
recentComments,
|
||||
(comment) => comment.contractId
|
||||
)
|
||||
|
||||
return (
|
||||
<FeedContainer
|
||||
contracts={contracts}
|
||||
renderContract={(contract) => (
|
||||
<ContractActivity
|
||||
user={user}
|
||||
contract={contract}
|
||||
bets={groupedBets[contract.id] ?? []}
|
||||
comments={groupedComments[contract.id] ?? []}
|
||||
mode={mode}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function SummaryActivityFeed(props: { contracts: Contract[] }) {
|
||||
const { contracts } = props
|
||||
|
||||
return (
|
||||
<FeedContainer
|
||||
contracts={contracts}
|
||||
renderContract={(contract) => <ContractSummary contract={contract} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FeedContainer(props: {
|
||||
contracts: Contract[]
|
||||
renderContract: (contract: Contract) => any
|
||||
}) {
|
||||
const { contracts, renderContract } = props
|
||||
|
||||
return (
|
||||
<Col className="items-center">
|
||||
<Col className="w-full max-w-3xl">
|
||||
<Col className="w-full divide-y divide-gray-300 self-center bg-white">
|
||||
{contracts.map((contract) => (
|
||||
<div key={contract.id} className="py-6 px-2 sm:px-4">
|
||||
{renderContract(contract)}
|
||||
</div>
|
||||
))}
|
||||
</Col>
|
||||
</Col>
|
||||
</Col>
|
||||
)
|
||||
}
|
||||
|
||||
function ContractSummary(props: {
|
||||
contract: Contract
|
||||
betRowClassName?: string
|
||||
}) {
|
||||
const { contract, betRowClassName } = props
|
||||
const { outcomeType } = contract
|
||||
const isBinary = outcomeType === 'BINARY'
|
||||
|
||||
return (
|
||||
<div className="flow-root pr-2 md:pr-0">
|
||||
<div className={clsx(tradingAllowed(contract) ? '' : '-mb-8')}>
|
||||
<div className="relative pb-8">
|
||||
<div className="relative flex items-start space-x-3">
|
||||
<FeedQuestion contract={contract} showDescription />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isBinary && tradingAllowed(contract) && (
|
||||
<BetRow contract={contract} className={clsx('mb-2', betRowClassName)} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
350
web/components/feed/activity-items.ts
Normal file
350
web/components/feed/activity-items.ts
Normal file
|
@ -0,0 +1,350 @@
|
|||
import _ from 'lodash'
|
||||
|
||||
import { Answer } from '../../../common/answer'
|
||||
import { Bet } from '../../../common/bet'
|
||||
import { getOutcomeProbability } from '../../../common/calculate'
|
||||
import { Comment } from '../../../common/comment'
|
||||
import {
|
||||
Contract,
|
||||
DPM,
|
||||
FreeResponse,
|
||||
FullContract,
|
||||
} from '../../../common/contract'
|
||||
import { User } from '../../../common/user'
|
||||
import { mapCommentsByBetId } from '../../lib/firebase/comments'
|
||||
|
||||
export type ActivityItem =
|
||||
| DescriptionItem
|
||||
| QuestionItem
|
||||
| BetItem
|
||||
| CommentItem
|
||||
| CreateAnswerItem
|
||||
| BetGroupItem
|
||||
| AnswerGroupItem
|
||||
| CloseItem
|
||||
| ResolveItem
|
||||
|
||||
type BaseActivityItem = {
|
||||
id: string
|
||||
contract: Contract
|
||||
}
|
||||
|
||||
export type DescriptionItem = BaseActivityItem & {
|
||||
type: 'description'
|
||||
}
|
||||
|
||||
export type QuestionItem = BaseActivityItem & {
|
||||
type: 'question'
|
||||
showDescription: boolean
|
||||
}
|
||||
|
||||
export type BetItem = BaseActivityItem & {
|
||||
type: 'bet'
|
||||
bet: Bet
|
||||
hideOutcome: boolean
|
||||
smallAvatar: boolean
|
||||
}
|
||||
|
||||
export type CommentItem = BaseActivityItem & {
|
||||
type: 'comment'
|
||||
comment: Comment
|
||||
bet: Bet
|
||||
hideOutcome: boolean
|
||||
truncate: boolean
|
||||
smallAvatar: boolean
|
||||
}
|
||||
|
||||
export type CreateAnswerItem = BaseActivityItem & {
|
||||
type: 'createanswer'
|
||||
answer: Answer
|
||||
}
|
||||
|
||||
export type BetGroupItem = BaseActivityItem & {
|
||||
type: 'betgroup'
|
||||
bets: Bet[]
|
||||
hideOutcome: boolean
|
||||
}
|
||||
|
||||
export type AnswerGroupItem = BaseActivityItem & {
|
||||
type: 'answergroup'
|
||||
answer: Answer
|
||||
items: ActivityItem[]
|
||||
}
|
||||
|
||||
export type CloseItem = BaseActivityItem & {
|
||||
type: 'close'
|
||||
}
|
||||
|
||||
export type ResolveItem = BaseActivityItem & {
|
||||
type: 'resolve'
|
||||
}
|
||||
|
||||
const DAY_IN_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
// Group together bets that are:
|
||||
// - Within a day of the first in the group
|
||||
// (Unless the bets are older: then are grouped by 7-days.)
|
||||
// - 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[],
|
||||
contract: Contract,
|
||||
userId: string | undefined,
|
||||
options: {
|
||||
hideOutcome: boolean
|
||||
abbreviated: boolean
|
||||
smallAvatar: boolean
|
||||
}
|
||||
) {
|
||||
const { hideOutcome, abbreviated, smallAvatar } = options
|
||||
|
||||
const commentsMap = mapCommentsByBetId(comments)
|
||||
const items: ActivityItem[] = []
|
||||
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,
|
||||
contract,
|
||||
hideOutcome,
|
||||
})
|
||||
}
|
||||
group = []
|
||||
}
|
||||
|
||||
function toActivityItem(bet: Bet): ActivityItem {
|
||||
const comment = commentsMap[bet.id]
|
||||
return comment
|
||||
? {
|
||||
type: 'comment' as const,
|
||||
id: bet.id,
|
||||
comment,
|
||||
bet,
|
||||
contract,
|
||||
hideOutcome,
|
||||
truncate: abbreviated,
|
||||
smallAvatar,
|
||||
}
|
||||
: {
|
||||
type: 'bet' as const,
|
||||
id: bet.id,
|
||||
bet,
|
||||
contract,
|
||||
hideOutcome,
|
||||
smallAvatar,
|
||||
}
|
||||
}
|
||||
|
||||
for (const bet of bets) {
|
||||
const isCreator = userId === bet.userId
|
||||
|
||||
// If first bet in group is older than 3 days, group by 7 days. Otherwise, group by 1 day.
|
||||
const windowMs =
|
||||
Date.now() - (group[0]?.createdTime ?? bet.createdTime) > DAY_IN_MS * 3
|
||||
? DAY_IN_MS * 7
|
||||
: DAY_IN_MS
|
||||
|
||||
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 abbreviated ? items.slice(-3) : items
|
||||
}
|
||||
|
||||
function getAnswerGroups(
|
||||
contract: FullContract<DPM, FreeResponse>,
|
||||
bets: Bet[],
|
||||
comments: Comment[],
|
||||
user: User | undefined | null,
|
||||
options: {
|
||||
sortByProb: boolean
|
||||
abbreviated: boolean
|
||||
}
|
||||
) {
|
||||
const { sortByProb, abbreviated } = options
|
||||
|
||||
let outcomes = _.uniq(bets.map((bet) => bet.outcome)).filter(
|
||||
(outcome) => getOutcomeProbability(contract, outcome) > 0.01
|
||||
)
|
||||
if (abbreviated) {
|
||||
const lastComment = _.last(comments)
|
||||
const lastCommentOutcome = bets.find(
|
||||
(bet) => bet.id === lastComment?.betId
|
||||
)?.outcome
|
||||
const lastBetOutcome = _.last(bets)?.outcome
|
||||
if (lastCommentOutcome && lastBetOutcome) {
|
||||
outcomes = _.uniq([
|
||||
...outcomes.filter(
|
||||
(outcome) =>
|
||||
outcome !== lastCommentOutcome && outcome !== lastBetOutcome
|
||||
),
|
||||
lastCommentOutcome,
|
||||
lastBetOutcome,
|
||||
])
|
||||
}
|
||||
outcomes = outcomes.slice(-2)
|
||||
}
|
||||
if (sortByProb) {
|
||||
outcomes = _.sortBy(
|
||||
outcomes,
|
||||
(outcome) => -1 * getOutcomeProbability(contract, outcome)
|
||||
)
|
||||
} else {
|
||||
// Sort by recent bet.
|
||||
outcomes = _.sortBy(outcomes, (outcome) =>
|
||||
_.findLastIndex(bets, (bet) => bet.outcome === outcome)
|
||||
)
|
||||
}
|
||||
|
||||
const answerGroups = outcomes
|
||||
.map((outcome) => {
|
||||
const answerBets = bets.filter((bet) => bet.outcome === outcome)
|
||||
const answerComments = comments.filter((comment) =>
|
||||
answerBets.some((bet) => bet.id === comment.betId)
|
||||
)
|
||||
const answer = contract.answers?.find(
|
||||
(answer) => answer.id === outcome
|
||||
) as Answer
|
||||
|
||||
let items = groupBets(answerBets, answerComments, contract, user?.id, {
|
||||
hideOutcome: true,
|
||||
abbreviated,
|
||||
smallAvatar: true,
|
||||
})
|
||||
|
||||
if (abbreviated) items = items.slice(-2)
|
||||
|
||||
return {
|
||||
id: outcome,
|
||||
type: 'answergroup' as const,
|
||||
contract,
|
||||
answer,
|
||||
items,
|
||||
user,
|
||||
}
|
||||
})
|
||||
.filter((group) => group.answer)
|
||||
|
||||
return answerGroups
|
||||
}
|
||||
|
||||
export function getAllContractActivityItems(
|
||||
contract: Contract,
|
||||
bets: Bet[],
|
||||
comments: Comment[],
|
||||
user: User | null | undefined,
|
||||
filterToOutcome: string | undefined,
|
||||
options: {
|
||||
abbreviated: boolean
|
||||
}
|
||||
) {
|
||||
const { abbreviated } = options
|
||||
const { outcomeType } = contract
|
||||
|
||||
bets =
|
||||
outcomeType === 'BINARY'
|
||||
? bets.filter((bet) => !bet.isAnte)
|
||||
: bets.filter((bet) => !(bet.isAnte && (bet.outcome as string) === '0'))
|
||||
|
||||
let answer: Answer | undefined
|
||||
if (filterToOutcome) {
|
||||
bets = bets.filter((bet) => bet.outcome === filterToOutcome)
|
||||
answer = (contract as FullContract<DPM, FreeResponse>).answers?.find(
|
||||
(answer) => answer.id === filterToOutcome
|
||||
)
|
||||
}
|
||||
|
||||
const items: ActivityItem[] =
|
||||
filterToOutcome && answer
|
||||
? [{ type: 'createanswer', id: answer.id, contract, answer }]
|
||||
: abbreviated
|
||||
? [{ type: 'question', id: '0', contract, showDescription: false }]
|
||||
: [{ type: 'description', id: '0', contract }]
|
||||
|
||||
items.push(
|
||||
...(outcomeType === 'FREE_RESPONSE' && !filterToOutcome
|
||||
? getAnswerGroups(
|
||||
contract as FullContract<DPM, FreeResponse>,
|
||||
bets,
|
||||
comments,
|
||||
user,
|
||||
{
|
||||
sortByProb: true,
|
||||
abbreviated,
|
||||
}
|
||||
)
|
||||
: groupBets(bets, comments, contract, user?.id, {
|
||||
hideOutcome: !!filterToOutcome,
|
||||
abbreviated,
|
||||
smallAvatar: !!filterToOutcome,
|
||||
}))
|
||||
)
|
||||
|
||||
if (contract.closeTime && contract.closeTime <= Date.now()) {
|
||||
items.push({ type: 'close', id: `${contract.closeTime}`, contract })
|
||||
}
|
||||
if (contract.resolution) {
|
||||
items.push({ type: 'resolve', id: `${contract.resolutionTime}`, contract })
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
export function getRecentContractActivityItems(
|
||||
contract: Contract,
|
||||
bets: Bet[],
|
||||
comments: Comment[],
|
||||
user: User | null | undefined
|
||||
) {
|
||||
bets = bets.sort((b1, b2) => b1.createdTime - b2.createdTime)
|
||||
comments = comments.sort((c1, c2) => c1.createdTime - c2.createdTime)
|
||||
|
||||
const questionItem: QuestionItem = {
|
||||
type: 'question',
|
||||
id: '0',
|
||||
contract,
|
||||
showDescription: false,
|
||||
}
|
||||
|
||||
const items =
|
||||
contract.outcomeType === 'FREE_RESPONSE'
|
||||
? getAnswerGroups(
|
||||
contract as FullContract<DPM, FreeResponse>,
|
||||
bets,
|
||||
comments,
|
||||
user,
|
||||
{
|
||||
sortByProb: false,
|
||||
abbreviated: true,
|
||||
}
|
||||
)
|
||||
: groupBets(bets, comments, contract, user?.id, {
|
||||
hideOutcome: false,
|
||||
abbreviated: true,
|
||||
smallAvatar: false,
|
||||
})
|
||||
|
||||
return [questionItem, ...items]
|
||||
}
|
54
web/components/feed/contract-activity.tsx
Normal file
54
web/components/feed/contract-activity.tsx
Normal file
|
@ -0,0 +1,54 @@
|
|||
import _ from 'lodash'
|
||||
|
||||
import { Contract } from '../../lib/firebase/contracts'
|
||||
import { Comment } from '../../lib/firebase/comments'
|
||||
import { Bet } from '../../../common/bet'
|
||||
import { useBets } from '../../hooks/use-bets'
|
||||
import { useComments } from '../../hooks/use-comments'
|
||||
import {
|
||||
getAllContractActivityItems,
|
||||
getRecentContractActivityItems,
|
||||
} from './activity-items'
|
||||
import { FeedItems } from './feed-items'
|
||||
import { User } from '../../../common/user'
|
||||
|
||||
export function ContractActivity(props: {
|
||||
contract: Contract
|
||||
bets: Bet[]
|
||||
comments: Comment[]
|
||||
user: User | null | undefined
|
||||
mode: 'only-recent' | 'abbreviated' | 'all'
|
||||
filterToOutcome?: string // Which multi-category outcome to filter
|
||||
betRowClassName?: string
|
||||
}) {
|
||||
const { contract, user, filterToOutcome, mode, betRowClassName } = props
|
||||
|
||||
const updatedComments =
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
mode === 'only-recent' ? undefined : useComments(contract.id)
|
||||
const comments = updatedComments ?? props.comments
|
||||
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
const updatedBets = mode === 'only-recent' ? undefined : useBets(contract.id)
|
||||
const bets = updatedBets ?? props.bets
|
||||
|
||||
const items =
|
||||
mode === 'only-recent'
|
||||
? getRecentContractActivityItems(contract, bets, comments, user)
|
||||
: getAllContractActivityItems(
|
||||
contract,
|
||||
bets,
|
||||
comments,
|
||||
user,
|
||||
filterToOutcome,
|
||||
{ abbreviated: mode === 'abbreviated' }
|
||||
)
|
||||
|
||||
return (
|
||||
<FeedItems
|
||||
contract={contract}
|
||||
items={items}
|
||||
betRowClassName={betRowClassName}
|
||||
/>
|
||||
)
|
||||
}
|
|
@ -14,79 +14,150 @@ import dayjs from 'dayjs'
|
|||
import clsx from 'clsx'
|
||||
import Textarea from 'react-expanding-textarea'
|
||||
|
||||
import { OutcomeLabel } from './outcome-label'
|
||||
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'
|
||||
import { FreeResponse, FullContract } from '../../common/contract'
|
||||
import { Answer } from '../../common/answer'
|
||||
} from '../../lib/firebase/contracts'
|
||||
import { useUser } from '../../hooks/use-user'
|
||||
import { Linkify } from '../linkify'
|
||||
import { Row } from '../layout/row'
|
||||
import {
|
||||
canAddComment,
|
||||
createComment,
|
||||
MAX_COMMENT_LENGTH,
|
||||
} from '../../lib/firebase/comments'
|
||||
import { formatMoney } from '../../../common/util/format'
|
||||
import { Comment } from '../../../common/comment'
|
||||
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 { Bet } from '../../lib/firebase/bets'
|
||||
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'
|
||||
import { Answer } from '../../../common/answer'
|
||||
import { ActivityItem } from './activity-items'
|
||||
import { FreeResponse, FullContract } from '../../../common/contract'
|
||||
|
||||
const canAddComment = (createdTime: number, isSelf: boolean) => {
|
||||
return isSelf && Date.now() - createdTime < 60 * 60 * 1000
|
||||
export function FeedItems(props: {
|
||||
contract: Contract
|
||||
items: ActivityItem[]
|
||||
betRowClassName?: string
|
||||
}) {
|
||||
const { contract, items, betRowClassName } = props
|
||||
const { outcomeType } = contract
|
||||
|
||||
return (
|
||||
<div className="flow-root pr-2 md:pr-0">
|
||||
<div className={clsx(tradingAllowed(contract) ? '' : '-mb-6')}>
|
||||
{items.map((item, activityItemIdx) => (
|
||||
<div key={item.id} className="relative pb-6">
|
||||
{activityItemIdx !== items.length - 1 ||
|
||||
item.type === 'answergroup' ? (
|
||||
<span
|
||||
className="absolute top-5 left-5 -ml-px h-[calc(100%-2rem)] w-0.5 bg-gray-200"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
<div className="relative flex items-start space-x-3">
|
||||
<FeedItem item={item} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{outcomeType === 'BINARY' && tradingAllowed(contract) && (
|
||||
<BetRow contract={contract} className={clsx('mb-2', betRowClassName)} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FeedItem(props: { item: ActivityItem }) {
|
||||
const { item } = props
|
||||
|
||||
switch (item.type) {
|
||||
case 'question':
|
||||
return <FeedQuestion {...item} />
|
||||
case 'description':
|
||||
return <FeedDescription {...item} />
|
||||
case 'comment':
|
||||
return <FeedComment {...item} />
|
||||
case 'bet':
|
||||
return <FeedBet {...item} />
|
||||
case 'createanswer':
|
||||
return <FeedCreateAnswer {...item} />
|
||||
case 'betgroup':
|
||||
return <FeedBetGroup {...item} />
|
||||
case 'answergroup':
|
||||
return <FeedAnswerGroup {...item} />
|
||||
case 'close':
|
||||
return <FeedClose {...item} />
|
||||
case 'resolve':
|
||||
return <FeedResolve {...item} />
|
||||
}
|
||||
}
|
||||
|
||||
function FeedComment(props: {
|
||||
activityItem: any
|
||||
moreHref: string
|
||||
feedType: FeedType
|
||||
contract: Contract
|
||||
comment: Comment
|
||||
bet: Bet
|
||||
hideOutcome: boolean
|
||||
truncate: boolean
|
||||
smallAvatar: boolean
|
||||
}) {
|
||||
const { activityItem, moreHref, feedType } = props
|
||||
const { person, text, amount, outcome, createdTime } = activityItem
|
||||
const { contract, comment, bet, hideOutcome, truncate, smallAvatar } = props
|
||||
const { amount, outcome } = bet
|
||||
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
|
||||
|
||||
const bought = amount >= 0 ? 'bought' : 'sold'
|
||||
const money = formatMoney(Math.abs(amount))
|
||||
|
||||
return (
|
||||
<>
|
||||
<Avatar username={person.username} avatarUrl={person.avatarUrl} />
|
||||
<Avatar
|
||||
className={clsx(smallAvatar && 'ml-1')}
|
||||
size={smallAvatar ? 'sm' : undefined}
|
||||
username={userUsername}
|
||||
avatarUrl={userAvatarUrl}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div>
|
||||
<p className="mt-0.5 text-sm text-gray-500">
|
||||
<UserLink
|
||||
className="text-gray-500"
|
||||
username={person.username}
|
||||
name={person.name}
|
||||
username={userUsername}
|
||||
name={userName}
|
||||
/>{' '}
|
||||
{bought} {money}
|
||||
<MaybeOutcomeLabel outcome={outcome} feedType={feedType} />
|
||||
<Timestamp time={createdTime} />
|
||||
{!hideOutcome && (
|
||||
<>
|
||||
{' '}
|
||||
of <OutcomeLabel outcome={outcome} />
|
||||
</>
|
||||
)}
|
||||
<RelativeTimestamp time={createdTime} />
|
||||
</p>
|
||||
</div>
|
||||
<TruncatedComment
|
||||
comment={text}
|
||||
moreHref={moreHref}
|
||||
shouldTruncate={feedType == 'activity'}
|
||||
moreHref={contractPath(contract)}
|
||||
shouldTruncate={truncate}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Timestamp(props: { time: number }) {
|
||||
function RelativeTimestamp(props: { time: number }) {
|
||||
const { time } = props
|
||||
return (
|
||||
<DateTimeTooltip time={time}>
|
||||
|
@ -97,38 +168,47 @@ function Timestamp(props: { time: number }) {
|
|||
)
|
||||
}
|
||||
|
||||
function FeedBet(props: { activityItem: any; feedType: FeedType }) {
|
||||
const { activityItem, feedType } = props
|
||||
const { id, contractId, amount, outcome, createdTime, contract } =
|
||||
activityItem
|
||||
function FeedBet(props: {
|
||||
contract: Contract
|
||||
bet: Bet
|
||||
hideOutcome: boolean
|
||||
smallAvatar: boolean
|
||||
}) {
|
||||
const { contract, bet, hideOutcome, smallAvatar } = props
|
||||
const { id, amount, outcome, createdTime, userId } = bet
|
||||
const user = useUser()
|
||||
const isSelf = user?.id == activityItem.userId
|
||||
const isCreator = contract.creatorId == activityItem.userId
|
||||
const isSelf = user?.id === userId
|
||||
const isCreator = contract.creatorId === userId
|
||||
|
||||
// You can comment if your bet was posted in the last hour
|
||||
const canComment = canAddComment(createdTime, isSelf)
|
||||
|
||||
const [comment, setComment] = useState('')
|
||||
async function submitComment() {
|
||||
if (!user || !comment) return
|
||||
await createComment(contractId, id, comment, user)
|
||||
await createComment(contract.id, id, comment, user)
|
||||
}
|
||||
|
||||
const bought = amount >= 0 ? 'bought' : 'sold'
|
||||
const money = formatMoney(Math.abs(amount))
|
||||
|
||||
const answer =
|
||||
feedType !== 'multi' &&
|
||||
(contract.answers?.find((answer: Answer) => answer?.id === outcome) as
|
||||
| Answer
|
||||
| undefined)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
{isSelf ? (
|
||||
<Avatar avatarUrl={user?.avatarUrl} />
|
||||
<Avatar
|
||||
className={clsx(smallAvatar && 'ml-1')}
|
||||
size={smallAvatar ? 'sm' : undefined}
|
||||
avatarUrl={user.avatarUrl}
|
||||
username={user.username}
|
||||
/>
|
||||
) : isCreator ? (
|
||||
<Avatar avatarUrl={contract.creatorAvatarUrl} />
|
||||
<Avatar
|
||||
className={clsx(smallAvatar && 'ml-1')}
|
||||
size={smallAvatar ? 'sm' : undefined}
|
||||
avatarUrl={contract.creatorAvatarUrl}
|
||||
username={contract.creatorUsername}
|
||||
/>
|
||||
) : (
|
||||
<div className="relative px-1">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
|
||||
|
@ -137,21 +217,19 @@ function FeedBet(props: { activityItem: any; feedType: FeedType }) {
|
|||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={clsx('min-w-0 flex-1 pb-1.5', !answer && 'pt-1.5')}>
|
||||
{answer && (
|
||||
<div className="text-neutral mb-2" style={{ fontSize: 15 }}>
|
||||
{answer.text}
|
||||
</div>
|
||||
)}
|
||||
<div className={'min-w-0 flex-1 pb-1.5'}>
|
||||
<div className="text-sm text-gray-500">
|
||||
<span>
|
||||
{isSelf ? 'You' : isCreator ? contract.creatorName : 'A trader'}
|
||||
</span>{' '}
|
||||
{bought} {money}
|
||||
{!answer && (
|
||||
<MaybeOutcomeLabel outcome={outcome} feedType={feedType} />
|
||||
{!hideOutcome && (
|
||||
<>
|
||||
{' '}
|
||||
of <OutcomeLabel outcome={outcome} />
|
||||
</>
|
||||
)}
|
||||
<Timestamp time={createdTime} />
|
||||
<RelativeTimestamp time={createdTime} />
|
||||
{canComment && (
|
||||
// Allow user to comment in an textarea if they are the creator
|
||||
<div className="mt-2">
|
||||
|
@ -330,7 +408,7 @@ function TruncatedComment(props: {
|
|||
)
|
||||
}
|
||||
|
||||
function FeedQuestion(props: {
|
||||
export function FeedQuestion(props: {
|
||||
contract: Contract
|
||||
showDescription?: boolean
|
||||
}) {
|
||||
|
@ -345,7 +423,7 @@ function FeedQuestion(props: {
|
|||
<>
|
||||
<span className="mx-2">•</span>
|
||||
{contract.closeTime > Date.now() ? 'Closes' : 'Closed'}
|
||||
<Timestamp time={contract.closeTime || 0} />
|
||||
<RelativeTimestamp time={contract.closeTime || 0} />
|
||||
</>
|
||||
)
|
||||
|
||||
|
@ -421,7 +499,7 @@ function FeedDescription(props: { contract: Contract }) {
|
|||
name={creatorName}
|
||||
username={creatorUsername}
|
||||
/>{' '}
|
||||
created this market <Timestamp time={contract.createdTime} />
|
||||
created this market <RelativeTimestamp time={contract.createdTime} />
|
||||
</div>
|
||||
<ContractDescription contract={contract} isCreator={isCreator} />
|
||||
</div>
|
||||
|
@ -429,17 +507,20 @@ function FeedDescription(props: { contract: Contract }) {
|
|||
)
|
||||
}
|
||||
|
||||
function FeedAnswer(props: {
|
||||
function FeedCreateAnswer(props: {
|
||||
contract: FullContract<any, FreeResponse>
|
||||
outcome: string
|
||||
answer: Answer
|
||||
}) {
|
||||
const { contract, outcome } = props
|
||||
const answer = contract?.answers?.[Number(outcome) - 1]
|
||||
if (!answer) return null
|
||||
const { answer } = props
|
||||
|
||||
return (
|
||||
<>
|
||||
<Avatar username={answer.username} avatarUrl={answer.avatarUrl} />
|
||||
<Avatar
|
||||
className="ml-1"
|
||||
size="sm"
|
||||
username={answer.username}
|
||||
avatarUrl={answer.avatarUrl}
|
||||
/>
|
||||
<div className="min-w-0 flex-1 py-1.5">
|
||||
<div className="text-sm text-gray-500">
|
||||
<UserLink
|
||||
|
@ -447,8 +528,7 @@ function FeedAnswer(props: {
|
|||
name={answer.name}
|
||||
username={answer.username}
|
||||
/>{' '}
|
||||
submitted answer <OutcomeLabel outcome={outcome} />{' '}
|
||||
<Timestamp time={contract.createdTime} />
|
||||
submitted this answer <RelativeTimestamp time={answer.createdTime} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
@ -491,7 +571,7 @@ function FeedResolve(props: { contract: Contract }) {
|
|||
username={creatorUsername}
|
||||
/>{' '}
|
||||
resolved this market to <OutcomeLabel outcome={resolution} />{' '}
|
||||
<Timestamp time={contract.resolutionTime || 0} />
|
||||
<RelativeTimestamp time={contract.resolutionTime || 0} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
@ -516,111 +596,15 @@ function FeedClose(props: { contract: Contract }) {
|
|||
<div className="min-w-0 flex-1 py-1.5">
|
||||
<div className="text-sm text-gray-500">
|
||||
Trading closed in this market{' '}
|
||||
<Timestamp time={contract.closeTime || 0} />
|
||||
<RelativeTimestamp time={contract.closeTime || 0} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
function BetGroupSpan(props: { bets: Bet[]; outcome?: string }) {
|
||||
const { bets, outcome } = props
|
||||
|
||||
const numberTraders = _.uniqBy(bets, (b) => b.userId).length
|
||||
|
||||
|
@ -635,15 +619,22 @@ function BetGroupSpan(props: {
|
|||
{buyTotal > 0 && <>bought {formatMoney(buyTotal)} </>}
|
||||
{sellTotal > 0 && <>sold {formatMoney(sellTotal)} </>}
|
||||
</JoinSpans>
|
||||
<MaybeOutcomeLabel outcome={outcome} feedType={feedType} />{' '}
|
||||
{outcome && (
|
||||
<>
|
||||
{' '}
|
||||
of <OutcomeLabel outcome={outcome} />
|
||||
</>
|
||||
)}{' '}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// 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
|
||||
function FeedBetGroup(props: {
|
||||
contract: Contract
|
||||
bets: Bet[]
|
||||
hideOutcome: boolean
|
||||
}) {
|
||||
const { bets, hideOutcome } = props
|
||||
|
||||
const betGroups = _.groupBy(bets, (bet) => bet.outcome)
|
||||
const outcomes = Object.keys(betGroups)
|
||||
|
@ -660,25 +651,71 @@ function FeedBetGroup(props: { activityItem: any; feedType: FeedType }) {
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<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
|
||||
outcome={outcome}
|
||||
outcome={hideOutcome ? undefined : outcome}
|
||||
bets={betGroups[outcome]}
|
||||
feedType={feedType}
|
||||
/>
|
||||
{index !== outcomes.length - 1 && <br />}
|
||||
</Fragment>
|
||||
))}
|
||||
<Timestamp time={createdTime} />
|
||||
<RelativeTimestamp time={createdTime} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function FeedAnswerGroup(props: {
|
||||
contract: FullContract<any, FreeResponse>
|
||||
answer: Answer
|
||||
items: ActivityItem[]
|
||||
}) {
|
||||
const { answer, items } = props
|
||||
const { username, avatarUrl, userId, name, text } = answer
|
||||
|
||||
return (
|
||||
<Col className="gap-2 flex-1">
|
||||
<Row className="gap-3 mb-4">
|
||||
<div className="px-1">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
|
||||
<Avatar username={username} avatarUrl={avatarUrl} />
|
||||
</div>
|
||||
</div>
|
||||
<Col className="min-w-0 flex-1 gap-2">
|
||||
<div className="text-sm text-gray-500">
|
||||
<UserLink username={userId} name={name} /> answered
|
||||
</div>
|
||||
<Linkify text={text} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={clsx(
|
||||
'relative ml-8',
|
||||
index !== items.length - 1 && 'pb-4'
|
||||
)}
|
||||
>
|
||||
{index !== items.length - 1 ? (
|
||||
<span
|
||||
className="absolute top-5 left-5 -ml-px h-[calc(100%-1rem)] w-0.5 bg-gray-200"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
<div className="relative flex items-start space-x-3">
|
||||
<FeedItem item={item} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</Col>
|
||||
)
|
||||
}
|
||||
|
||||
// TODO: Should highlight the entire Feed segment
|
||||
function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) {
|
||||
const { setExpanded } = props
|
||||
|
@ -705,255 +742,3 @@ function FeedExpand(props: { setExpanded: (expanded: boolean) => void }) {
|
|||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 : (
|
||||
<span>
|
||||
{' '}
|
||||
of <OutcomeLabel outcome={outcome} />
|
||||
{/* TODO: Link to the correct e.g. #23 */}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// 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'
|
||||
|
||||
return (
|
||||
<div className="flow-root pr-2 md:pr-0">
|
||||
<div className={clsx(tradingAllowed(contract) ? '' : '-mb-6')}>
|
||||
{items.map((activityItem, activityItemIdx) => (
|
||||
<div key={activityItem.id} className="relative pb-6">
|
||||
{activityItemIdx !== items.length - 1 ? (
|
||||
<span
|
||||
className="absolute top-5 left-5 -ml-px h-[calc(100%-2rem)] w-0.5 bg-gray-200"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
<div className="relative flex items-start space-x-3">
|
||||
{activityItem.type === 'start' ? (
|
||||
feedType === 'activity' ? (
|
||||
<FeedQuestion contract={contract} />
|
||||
) : feedType === 'market' ? (
|
||||
<FeedDescription contract={contract} />
|
||||
) : feedType === 'multi' ? (
|
||||
<FeedAnswer contract={contract} outcome={outcome || '0'} />
|
||||
) : null
|
||||
) : activityItem.type === 'comment' ? (
|
||||
<FeedComment
|
||||
activityItem={activityItem}
|
||||
moreHref={contractPath(contract)}
|
||||
feedType={feedType}
|
||||
/>
|
||||
) : activityItem.type === 'bet' ? (
|
||||
<FeedBet activityItem={activityItem} feedType={feedType} />
|
||||
) : activityItem.type === 'betgroup' ? (
|
||||
<FeedBetGroup activityItem={activityItem} feedType={feedType} />
|
||||
) : activityItem.type === 'close' ? (
|
||||
<FeedClose contract={contract} />
|
||||
) : activityItem.type === 'resolve' ? (
|
||||
<FeedResolve contract={contract} />
|
||||
) : activityItem.type === 'expand' ? (
|
||||
<FeedExpand setExpanded={setExpanded} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{isBinary && tradingAllowed(contract) && (
|
||||
<BetRow contract={contract} className={clsx('mb-2', betRowClassName)} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
const comments = useComments(id) ?? props.comments
|
||||
|
||||
let bets = useBets(contract.id) ?? props.bets
|
||||
bets = isBinary
|
||||
? bets.filter((bet) => !bet.isAnte && !bet.isRedemption)
|
||||
: bets.filter((bet) => !(bet.isAnte && (bet.outcome as string) === '0'))
|
||||
|
||||
if (feedType === 'multi') {
|
||||
bets = bets.filter((bet) => bet.outcome === outcome)
|
||||
} else if (outcomeType === 'FREE_RESPONSE') {
|
||||
// Keep bets on comments or your bets where you can comment.
|
||||
const commentBetIds = new Set(comments.map((comment) => comment.betId))
|
||||
bets = bets.filter(
|
||||
(bet) =>
|
||||
commentBetIds.has(bet.id) ||
|
||||
canAddComment(bet.createdTime, user?.id === bet.userId)
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<FeedItems
|
||||
contract={contract}
|
||||
items={items}
|
||||
feedType={feedType}
|
||||
setExpanded={setExpanded}
|
||||
betRowClassName={betRowClassName}
|
||||
outcome={outcome}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function ContractActivityFeed(props: {
|
||||
contract: Contract
|
||||
bets: Bet[]
|
||||
comments: Comment[]
|
||||
betRowClassName?: string
|
||||
}) {
|
||||
const { contract, betRowClassName, comments } = props
|
||||
|
||||
const user = useUser()
|
||||
|
||||
let bets = props.bets
|
||||
.filter((bet) => !bet.isAnte && !bet.isRedemption)
|
||||
.sort((b1, b2) => b1.createdTime - b2.createdTime)
|
||||
comments.sort((c1, c2) => c1.createdTime - c2.createdTime)
|
||||
|
||||
if (contract.outcomeType === 'FREE_RESPONSE') {
|
||||
// Keep bets on comments, and the last non-comment bet.
|
||||
const commentBetIds = new Set(comments.map((comment) => comment.betId))
|
||||
const [commentBets, nonCommentBets] = _.partition(bets, (bet) =>
|
||||
commentBetIds.has(bet.id)
|
||||
)
|
||||
bets = [...commentBets, ...nonCommentBets.slice(-1)].sort(
|
||||
(b1, b2) => b1.createdTime - b2.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 (
|
||||
<FeedItems
|
||||
contract={contract}
|
||||
items={items}
|
||||
feedType="activity"
|
||||
setExpanded={() => {}}
|
||||
betRowClassName={betRowClassName}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function ContractSummaryFeed(props: {
|
||||
contract: Contract
|
||||
betRowClassName?: string
|
||||
}) {
|
||||
const { contract, betRowClassName } = props
|
||||
const { outcomeType } = contract
|
||||
const isBinary = outcomeType === 'BINARY'
|
||||
|
||||
return (
|
||||
<div className="flow-root pr-2 md:pr-0">
|
||||
<div className={clsx(tradingAllowed(contract) ? '' : '-mb-8')}>
|
||||
<div className="relative pb-8">
|
||||
<div className="relative flex items-start space-x-3">
|
||||
<FeedQuestion contract={contract} showDescription />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isBinary && tradingAllowed(contract) && (
|
||||
<BetRow contract={contract} className={clsx('mb-2', betRowClassName)} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
68
web/components/feed/find-active-contracts.ts
Normal file
68
web/components/feed/find-active-contracts.ts
Normal file
|
@ -0,0 +1,68 @@
|
|||
import _ from 'lodash'
|
||||
import { Contract } from '../../lib/firebase/contracts'
|
||||
import { Comment } from '../../lib/firebase/comments'
|
||||
import { Bet } from '../../../common/bet'
|
||||
|
||||
const MAX_ACTIVE_CONTRACTS = 75
|
||||
|
||||
// This does NOT include comment times, since those aren't part of the contract atm.
|
||||
// TODO: Maybe store last activity time directly in the contract?
|
||||
// Pros: simplifies this code; cons: harder to tweak "activity" definition later
|
||||
function lastActivityTime(contract: Contract) {
|
||||
return Math.max(
|
||||
contract.resolutionTime || 0,
|
||||
contract.lastUpdatedTime,
|
||||
contract.createdTime
|
||||
)
|
||||
}
|
||||
|
||||
// Types of activity to surface:
|
||||
// - Comment on a market
|
||||
// - New market created
|
||||
// - Market resolved
|
||||
// - Bet on market
|
||||
export function findActiveContracts(
|
||||
allContracts: Contract[],
|
||||
recentComments: Comment[],
|
||||
recentBets: Bet[]
|
||||
) {
|
||||
const idToActivityTime = new Map<string, number>()
|
||||
function record(contractId: string, time: number) {
|
||||
// Only record if the time is newer
|
||||
const oldTime = idToActivityTime.get(contractId)
|
||||
idToActivityTime.set(contractId, Math.max(oldTime ?? 0, time))
|
||||
}
|
||||
|
||||
const contractsById = new Map(allContracts.map((c) => [c.id, c]))
|
||||
|
||||
// Record contract activity.
|
||||
for (const contract of allContracts) {
|
||||
record(contract.id, lastActivityTime(contract))
|
||||
}
|
||||
|
||||
// Add every contract that had a recent comment, too
|
||||
for (const comment of recentComments) {
|
||||
const contract = contractsById.get(comment.contractId)
|
||||
if (contract) record(contract.id, comment.createdTime)
|
||||
}
|
||||
|
||||
// Add contracts by last bet time.
|
||||
const contractBets = _.groupBy(recentBets, (bet) => bet.contractId)
|
||||
const contractMostRecentBet = _.mapValues(
|
||||
contractBets,
|
||||
(bets) => _.maxBy(bets, (bet) => bet.createdTime) as Bet
|
||||
)
|
||||
for (const bet of Object.values(contractMostRecentBet)) {
|
||||
const contract = contractsById.get(bet.contractId)
|
||||
if (contract) record(contract.id, bet.createdTime)
|
||||
}
|
||||
|
||||
let activeContracts = allContracts.filter(
|
||||
(contract) => contract.visibility === 'public' && !contract.isResolved
|
||||
)
|
||||
activeContracts = _.sortBy(
|
||||
activeContracts,
|
||||
(c) => -(idToActivityTime.get(c.id) ?? 0)
|
||||
)
|
||||
return activeContracts.slice(0, MAX_ACTIVE_CONTRACTS)
|
||||
}
|
|
@ -4,11 +4,11 @@ import { useMemo, useRef } from 'react'
|
|||
import { Fold } from '../../common/fold'
|
||||
import { User } from '../../common/user'
|
||||
import { filterDefined } from '../../common/util/array'
|
||||
import { findActiveContracts } from '../components/feed/find-active-contracts'
|
||||
import { Bet } from '../lib/firebase/bets'
|
||||
import { Comment, getRecentComments } from '../lib/firebase/comments'
|
||||
import { Contract, getActiveContracts } from '../lib/firebase/contracts'
|
||||
import { listAllFolds } from '../lib/firebase/folds'
|
||||
import { findActiveContracts } from '../components/activity-feed'
|
||||
import { useInactiveContracts } from './use-contracts'
|
||||
import { useFollowedFolds } from './use-fold'
|
||||
import { useUserBetContracts } from './use-user-bets'
|
||||
|
@ -25,7 +25,7 @@ export const getAllContractInfo = async () => {
|
|||
return { contracts, recentComments, folds }
|
||||
}
|
||||
|
||||
const defaultSkippedTags = [
|
||||
const defaultExcludedTags = [
|
||||
'meta',
|
||||
'test',
|
||||
'trolling',
|
||||
|
@ -34,10 +34,11 @@ const defaultSkippedTags = [
|
|||
'personal',
|
||||
]
|
||||
const includedWithDefaultFeed = (contract: Contract) => {
|
||||
const { tags } = contract
|
||||
const { lowercaseTags } = contract
|
||||
|
||||
if (tags.length === 0) return false
|
||||
if (tags.some((tag) => defaultSkippedTags.includes(tag))) return false
|
||||
if (lowercaseTags.length === 0) return false
|
||||
if (lowercaseTags.some((tag) => defaultExcludedTags.includes(tag)))
|
||||
return false
|
||||
return true
|
||||
}
|
||||
|
||||
|
|
|
@ -49,6 +49,7 @@ export const useFollowingFold = (fold: Fold, user: User | null | undefined) => {
|
|||
return following
|
||||
}
|
||||
|
||||
// Note: We cache FollowedFolds in localstorage to speed up the initial load
|
||||
export const useFollowedFolds = (user: User | null | undefined) => {
|
||||
const [followedFoldIds, setFollowedFoldIds] = useState<string[] | undefined>(
|
||||
undefined
|
||||
|
|
|
@ -2,6 +2,8 @@ import _ from 'lodash'
|
|||
import { useRouter } from 'next/router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
|
||||
const MARKETS_SORT = 'markets_sort'
|
||||
|
||||
export type Sort =
|
||||
| 'creator'
|
||||
| 'tag'
|
||||
|
@ -14,7 +16,13 @@ export type Sort =
|
|||
| 'resolved'
|
||||
| 'all'
|
||||
|
||||
export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
|
||||
export function useQueryAndSortParams(options?: {
|
||||
defaultSort: Sort
|
||||
shouldLoadFromStorage?: boolean
|
||||
}) {
|
||||
const { defaultSort, shouldLoadFromStorage } = _.defaults(options, {
|
||||
shouldLoadFromStorage: true,
|
||||
})
|
||||
const router = useRouter()
|
||||
|
||||
const { s: sort, q: query } = router.query as {
|
||||
|
@ -25,6 +33,9 @@ export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
|
|||
const setSort = (sort: Sort | undefined) => {
|
||||
router.query.s = sort
|
||||
router.push(router, undefined, { shallow: true })
|
||||
if (shouldLoadFromStorage) {
|
||||
localStorage.setItem(MARKETS_SORT, sort || '')
|
||||
}
|
||||
}
|
||||
|
||||
const [queryState, setQueryState] = useState(query)
|
||||
|
@ -52,8 +63,18 @@ export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
|
|||
pushQuery(query)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// If there's no sort option, then set the one from localstorage
|
||||
if (!sort && shouldLoadFromStorage) {
|
||||
const localSort = localStorage.getItem(MARKETS_SORT) as Sort
|
||||
if (localSort) {
|
||||
setSort(localSort)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
sort: sort ?? options?.defaultSort ?? '24-hour-vol',
|
||||
sort: sort ?? defaultSort ?? '24-hour-vol',
|
||||
query: queryState ?? '',
|
||||
setSort,
|
||||
setQuery,
|
||||
|
|
|
@ -40,6 +40,10 @@ export async function createComment(
|
|||
return await setDoc(ref, comment)
|
||||
}
|
||||
|
||||
export const canAddComment = (createdTime: number, isSelf: boolean) => {
|
||||
return isSelf && Date.now() - createdTime < 60 * 60 * 1000
|
||||
}
|
||||
|
||||
function getCommentsCollection(contractId: string) {
|
||||
return collection(db, 'contracts', contractId, 'comments')
|
||||
}
|
||||
|
|
|
@ -12,10 +12,7 @@ import {
|
|||
getFoldBySlug,
|
||||
getFoldContracts,
|
||||
} from '../../../lib/firebase/folds'
|
||||
import {
|
||||
ActivityFeed,
|
||||
findActiveContracts,
|
||||
} from '../../../components/activity-feed'
|
||||
import { ActivityFeed } from '../../../components/feed/activity-feed'
|
||||
import { TagsList } from '../../../components/tags-list'
|
||||
import { Row } from '../../../components/layout/row'
|
||||
import { UserLink } from '../../../components/user-page'
|
||||
|
@ -43,6 +40,7 @@ import { filterDefined } from '../../../../common/util/array'
|
|||
import { useRecentBets } from '../../../hooks/use-bets'
|
||||
import { useRecentComments } from '../../../hooks/use-comments'
|
||||
import { LoadingIndicator } from '../../../components/loading-indicator'
|
||||
import { findActiveContracts } from '../../../components/feed/find-active-contracts'
|
||||
|
||||
export const getStaticProps = fromPropz(getStaticPropz)
|
||||
export async function getStaticPropz(props: { params: { slugs: string[] } }) {
|
||||
|
@ -248,7 +246,7 @@ export default function FoldPage(props: {
|
|||
contracts={activeContracts}
|
||||
recentBets={recentBets ?? []}
|
||||
recentComments={recentComments ?? []}
|
||||
loadBetAndCommentHistory
|
||||
mode="abbreviated"
|
||||
/>
|
||||
{activeContracts.length === 0 && (
|
||||
<div className="mx-2 mt-4 text-gray-500 lg:mx-0">
|
||||
|
|
|
@ -11,7 +11,7 @@ import { SiteLink } from '../components/site-link'
|
|||
import { TagsList } from '../components/tags-list'
|
||||
import { Title } from '../components/title'
|
||||
import { UserLink } from '../components/user-page'
|
||||
import { useFolds } from '../hooks/use-fold'
|
||||
import { useFolds, useFollowedFolds } from '../hooks/use-fold'
|
||||
import { useUser } from '../hooks/use-user'
|
||||
import { foldPath, listAllFolds } from '../lib/firebase/folds'
|
||||
import { getUser, User } from '../lib/firebase/users'
|
||||
|
@ -43,8 +43,11 @@ export default function Folds(props: {
|
|||
const [curatorsDict, setCuratorsDict] = useState(props.curatorsDict)
|
||||
|
||||
let folds = useFolds() ?? props.folds
|
||||
folds = _.sortBy(folds, (fold) => -1 * fold.followCount)
|
||||
const user = useUser()
|
||||
const followedFoldIds = useFollowedFolds(user) || []
|
||||
// First sort by follower count, then list followed folds first
|
||||
folds = _.sortBy(folds, (fold) => -1 * fold.followCount)
|
||||
folds = _.sortBy(folds, (fold) => !followedFoldIds.includes(fold.id))
|
||||
|
||||
useEffect(() => {
|
||||
// Load User object for curator of new Folds.
|
||||
|
|
|
@ -6,7 +6,10 @@ import _ from 'lodash'
|
|||
|
||||
import { Contract } from '../lib/firebase/contracts'
|
||||
import { Page } from '../components/page'
|
||||
import { ActivityFeed, SummaryActivityFeed } from '../components/activity-feed'
|
||||
import {
|
||||
ActivityFeed,
|
||||
SummaryActivityFeed,
|
||||
} from '../components/feed/activity-feed'
|
||||
import { Comment } from '../lib/firebase/comments'
|
||||
import FeedCreate from '../components/feed-create'
|
||||
import { Spacer } from '../components/layout/spacer'
|
||||
|
@ -128,6 +131,7 @@ const Home = (props: {
|
|||
contracts={activeContracts}
|
||||
recentBets={recentBets}
|
||||
recentComments={recentComments}
|
||||
mode="only-recent"
|
||||
/>
|
||||
) : (
|
||||
<LoadingIndicator className="mt-4" />
|
||||
|
|
Loading…
Reference in New Issue
Block a user