manifold/web/pages/group/[...slugs]/index.tsx

490 lines
14 KiB
TypeScript
Raw Normal View History

2022-08-28 21:26:29 +00:00
import React, { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { toast } from 'react-hot-toast'
import { Group, GROUP_CHAT_SLUG } from 'common/group'
import { Page } from 'web/components/page'
import { Contract, listContractsByGroupSlug } from 'web/lib/firebase/contracts'
import {
addContractToGroup,
getGroupBySlug,
groupPath,
2022-07-14 17:09:28 +00:00
joinGroup,
listMemberIds,
updateGroup,
} from 'web/lib/firebase/groups'
import { Row } from 'web/components/layout/row'
import { firebaseLogin, getUser, User } from 'web/lib/firebase/users'
import { Col } from 'web/components/layout/col'
2022-08-10 17:27:59 +00:00
import { useUser } from 'web/hooks/use-user'
import {
useGroup,
useGroupContractIds,
useMemberIds,
} from 'web/hooks/use-group'
import { Leaderboard } from 'web/components/leaderboard'
import { formatMoney } from 'common/util/format'
import { EditGroupButton } from 'web/components/groups/edit-group-button'
import Custom404 from '../../404'
import { SEO } from 'web/components/SEO'
import { Linkify } from 'web/components/linkify'
import { fromPropz, usePropz } from 'web/hooks/use-propz'
import { Tabs } from 'web/components/layout/tabs'
import { ChoicesToggleGroup } from 'web/components/choices-toggle-group'
import { ContractSearch } from 'web/components/contract-search'
import { JoinOrLeaveGroupButton } from 'web/components/groups/groups-button'
2022-07-20 16:45:53 +00:00
import { CopyLinkButton } from 'web/components/copy-link-button'
import { ENV_CONFIG } from 'common/envs/constants'
import { useSaveReferral } from 'web/hooks/use-save-referral'
import { Button } from 'web/components/button'
import { listAllCommentsOnGroup } from 'web/lib/firebase/comments'
import { GroupComment } from 'common/comment'
import { REFERRAL_AMOUNT } from 'common/economy'
import { UserLink } from 'web/components/user-link'
import { GroupAboutPost } from 'web/components/groups/group-about-post'
import { getPost } from 'web/lib/firebase/posts'
import { Post } from 'common/post'
import { Spacer } from 'web/components/layout/spacer'
import { usePost } from 'web/hooks/use-post'
import { useAdmin } from 'web/hooks/use-admin'
2022-09-05 21:51:09 +00:00
import { track } from '@amplitude/analytics-browser'
import { SelectMarketsModal } from 'web/components/contract-select-modal'
2022-09-15 15:12:56 +00:00
import { BETTORS } from 'common/user'
export const getStaticProps = fromPropz(getStaticPropz)
export async function getStaticPropz(props: { params: { slugs: string[] } }) {
const { slugs } = props.params
const group = await getGroupBySlug(slugs[0])
const memberIds = group && (await listMemberIds(group))
const creatorPromise = group ? getUser(group.creatorId) : null
const contracts =
(group && (await listContractsByGroupSlug(group.slug))) ?? []
const now = Date.now()
const suggestedFilter =
contracts.filter((c) => (c.closeTime ?? 0) > now).length < 5
? 'all'
: 'open'
const aboutPost =
group && group.aboutPostId != null && (await getPost(group.aboutPostId))
const messages = group && (await listAllCommentsOnGroup(group.id))
const cachedTopTraderIds =
(group && group.cachedLeaderboard?.topTraders) ?? []
const cachedTopCreatorIds =
(group && group.cachedLeaderboard?.topCreators) ?? []
const topTraders = await toTopUsers(cachedTopTraderIds)
const topCreators = await toTopUsers(cachedTopCreatorIds)
const creator = await creatorPromise
return {
props: {
group,
memberIds,
creator,
topTraders,
topCreators,
messages,
aboutPost,
suggestedFilter,
},
revalidate: 60, // regenerate after a minute
}
}
export async function getStaticPaths() {
return { paths: [], fallback: 'blocking' }
}
2022-07-06 23:24:53 +00:00
const groupSubpages = [
undefined,
GROUP_CHAT_SLUG,
'markets',
'leaderboards',
2022-07-06 23:24:53 +00:00
'about',
] as const
export default function GroupPage(props: {
group: Group | null
memberIds: string[]
creator: User
topTraders: { user: User; score: number }[]
topCreators: { user: User; score: number }[]
messages: GroupComment[]
aboutPost: Post
suggestedFilter: 'open' | 'all'
}) {
props = usePropz(props, getStaticPropz) ?? {
group: null,
memberIds: [],
creator: null,
topTraders: [],
topCreators: [],
messages: [],
suggestedFilter: 'open',
}
const { creator, topTraders, topCreators, suggestedFilter } = props
const router = useRouter()
const { slugs } = router.query as { slugs: string[] }
const page = slugs?.[1] as typeof groupSubpages[number]
const group = useGroup(props.group?.id) ?? props.group
const aboutPost = usePost(props.aboutPost?.id) ?? props.aboutPost
const user = useUser()
const isAdmin = useAdmin()
const memberIds = useMemberIds(group?.id ?? null) ?? props.memberIds
useSaveReferral(user, {
Challenge Bets (#679) * Challenge bets * Store avatar url * Fix before and after probs * Check balance before creation * Calculate winning shares * pretty * Change winning value * Set shares to equal each other * Fix share challenge link * pretty * remove lib refs * Probability of bet is set to market * Remove peer pill * Cleanup * Button on contract page * don't show challenge if not binary or if resolved * challenge button (WIP) * fix accept challenge: don't change pool/probability * Opengraph preview [WIP] * elim lib * Edit og card props * Change challenge text * New card gen attempt * Get challenge on server * challenge button styling * Use env domain * Remove other window ref * Use challenge creator as avatar * Remove user name * Remove s from property, replace prob with outcome * challenge form * share text * Add in challenge parts to template and url * Challenge url params optional * Add challenge params to parse request * Parse please * Don't remove prob * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Add to readme about how to dev og-image * Add emojis * button: gradient background, 2xl size * beautify accept bet screen * update question button * Add separate challenge template * Accepted challenge sharing card, fix accept bet call * accept challenge button * challenge winner page * create challenge screen * Your outcome/cost=> acceptorOutcome/cost * New create challenge panel * Fix main merge * Add challenge slug to bet and filter by it * Center title * Add helper text * Add FAQ section * Lint * Columnize the user areas in preview link too * Absolutely position * Spacing * Orientation * Restyle challenges list, cache contract name * Make copying easy on mobile * Link spacing * Fix spacing * qr codes! * put your challenges first * eslint * Changes to contract buttons and create challenge modal * Change titles around for current bet * Add back in contract title after winning * Cleanup * Add challenge enabled flag * Spacing of switch button * Put sharing qr code in modal Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-08-04 21:27:02 +00:00
defaultReferrerUsername: creator.username,
groupId: group?.id,
})
if (group === null || !groupSubpages.includes(page) || slugs[2]) {
return <Custom404 />
}
const isCreator = user && group && user.id === group.creatorId
const isMember = user && memberIds.includes(user.id)
const maxLeaderboardSize = 50
2022-07-06 23:24:53 +00:00
const leaderboard = (
<Col>
<div className="mt-4 flex flex-col gap-8 px-4 md:flex-row">
<GroupLeaderboard
topUsers={topTraders}
2022-09-15 15:12:56 +00:00
title={`🏅 Top ${BETTORS}`}
header="Profit"
maxToShow={maxLeaderboardSize}
/>
<GroupLeaderboard
topUsers={topCreators}
title="🏅 Top creators"
header="Market volume"
maxToShow={maxLeaderboardSize}
/>
</div>
</Col>
)
2022-07-06 23:24:53 +00:00
const aboutTab = (
<Col>
{(group.aboutPostId != null || isCreator || isAdmin) && (
<GroupAboutPost
group={group}
isEditable={!!isCreator || isAdmin}
post={aboutPost}
/>
)}
<Spacer h={3} />
2022-07-06 23:24:53 +00:00
<GroupOverview
group={group}
creator={creator}
isCreator={!!isCreator}
user={user}
memberIds={memberIds}
2022-07-06 23:24:53 +00:00
/>
</Col>
)
const questionsTab = (
<ContractSearch
user={user}
defaultSort={'newest'}
defaultFilter={suggestedFilter}
additionalFilter={{ groupSlug: group.slug }}
persistPrefix={`group-${group.slug}`}
/>
)
const tabs = [
{
title: 'Markets',
content: questionsTab,
href: groupPath(group.slug, 'markets'),
},
{
title: 'Leaderboards',
content: leaderboard,
href: groupPath(group.slug, 'leaderboards'),
},
{
title: 'About',
content: aboutTab,
href: groupPath(group.slug, 'about'),
},
]
2022-08-10 17:27:59 +00:00
const tabIndex = tabs
.map((t) => t.title.toLowerCase())
.indexOf(page ?? 'markets')
2022-07-17 20:56:39 +00:00
return (
<Page>
<SEO
title={group.name}
description={`Created by ${creator.name}. ${group.about}`}
url={groupPath(group.slug)}
/>
<Col className="relative px-3">
<Row className={'items-center justify-between gap-4'}>
2022-07-07 12:53:14 +00:00
<div className={'sm:mb-1'}>
<div
2022-07-19 23:15:55 +00:00
className={'line-clamp-1 my-2 text-2xl text-indigo-700 sm:my-3'}
2022-07-07 12:53:14 +00:00
>
{group.name}
</div>
<div className={'hidden sm:block'}>
<Linkify text={group.about} />
</div>
</div>
2022-07-19 23:15:55 +00:00
<div className="mt-2">
2022-07-15 14:45:52 +00:00
<JoinOrAddQuestionsButtons
group={group}
user={user}
isMember={!!isMember}
/>
</div>
</Row>
</Col>
<Tabs
2022-07-07 21:24:13 +00:00
currentPageForAnalytics={groupPath(group.slug)}
2022-08-13 18:50:26 +00:00
className={'mx-2 mb-0 sm:mb-2'}
defaultIndex={tabIndex > 0 ? tabIndex : 0}
tabs={tabs}
/>
</Page>
)
}
2022-07-15 14:45:52 +00:00
function JoinOrAddQuestionsButtons(props: {
group: Group
user: User | null | undefined
isMember: boolean
}) {
const { group, user, isMember } = props
2022-07-06 23:24:53 +00:00
return user && isMember ? (
2022-07-19 23:15:55 +00:00
<Row className={'mt-0 justify-end'}>
2022-07-06 23:24:53 +00:00
<AddContractButton group={group} user={user} />
</Row>
) : group.anyoneCanJoin ? (
<JoinGroupButton group={group} user={user} />
) : null
}
function GroupOverview(props: {
group: Group
creator: User
user: User | null | undefined
isCreator: boolean
memberIds: string[]
}) {
const { group, creator, isCreator, user, memberIds } = props
const anyoneCanJoinChoices: { [key: string]: string } = {
Closed: 'false',
Open: 'true',
}
const [anyoneCanJoin, setAnyoneCanJoin] = useState(group.anyoneCanJoin)
function updateAnyoneCanJoin(newVal: boolean) {
if (group.anyoneCanJoin == newVal || !isCreator) return
setAnyoneCanJoin(newVal)
toast.promise(updateGroup(group, { ...group, anyoneCanJoin: newVal }), {
loading: 'Updating group...',
success: 'Updated group!',
error: "Couldn't update group",
})
}
2022-07-20 16:45:53 +00:00
const postFix = user ? '?referrer=' + user.username : ''
const shareUrl = `https://${ENV_CONFIG.domain}${groupPath(
group.slug
)}${postFix}`
const isMember = user ? memberIds.includes(user.id) : false
2022-07-20 16:45:53 +00:00
return (
2022-07-07 12:53:14 +00:00
<>
<Col className="gap-2 rounded-b bg-white p-2">
<Row className={'flex-wrap justify-between'}>
<div className={'inline-flex items-center'}>
<div className="mr-1 text-gray-500">Created by</div>
<UserLink
className="text-neutral"
name={creator.name}
username={creator.username}
/>
</div>
{isCreator ? (
<EditGroupButton className={'ml-1'} group={group} />
) : (
user && (
<Row>
2022-09-03 01:36:49 +00:00
<JoinOrLeaveGroupButton
group={group}
user={user}
isMember={isMember}
/>
</Row>
)
)}
</Row>
2022-07-07 12:53:14 +00:00
<div className={'block sm:hidden'}>
<Linkify text={group.about} />
</div>
<Row className={'items-center gap-1'}>
<span className={'text-gray-500'}>Membership</span>
{user && user.id === creator.id ? (
<ChoicesToggleGroup
currentChoice={anyoneCanJoin.toString()}
choicesMap={anyoneCanJoinChoices}
setChoice={(choice) =>
updateAnyoneCanJoin(choice.toString() === 'true')
}
toggleClassName={'h-10'}
className={'ml-2'}
/>
) : (
<span className={'text-gray-700'}>
2022-08-30 23:28:49 +00:00
{anyoneCanJoin ? 'Open to all' : 'Closed (by invite only)'}
</span>
)}
</Row>
2022-07-20 16:45:53 +00:00
{anyoneCanJoin && user && (
2022-07-20 16:45:53 +00:00
<Col className="my-4 px-2">
<div className="text-lg">Invite</div>
<div className={'mb-2 text-gray-500'}>
Invite a friend to this group and get M${REFERRAL_AMOUNT} if they
sign up!
</div>
<CopyLinkButton
url={shareUrl}
tracking="copy group share link"
buttonClassName="btn-md rounded-l-none"
toastClassName={'-left-28 mt-1'}
/>
</Col>
)}
</Col>
2022-07-07 12:53:14 +00:00
</>
)
}
function GroupLeaderboard(props: {
topUsers: { user: User; score: number }[]
title: string
maxToShow: number
header: string
}) {
const { topUsers, title, maxToShow, header } = props
const scoresByUser = topUsers.reduce((acc, { user, score }) => {
acc[user.id] = score
return acc
}, {} as { [key: string]: number })
return (
<Leaderboard
className="max-w-xl"
users={topUsers.map((t) => t.user)}
title={title}
columns={[
{ header, renderCell: (user) => formatMoney(scoresByUser[user.id]) },
]}
maxToShow={maxToShow}
/>
)
}
function AddContractButton(props: { group: Group; user: User }) {
2022-07-19 23:15:55 +00:00
const { group, user } = props
const [open, setOpen] = useState(false)
const groupContractIds = useGroupContractIds(group.id)
async function onSubmit(contracts: Contract[]) {
await Promise.all(
contracts.map((contract) => addContractToGroup(group, contract, user.id))
)
}
return (
<>
2022-07-19 23:15:55 +00:00
<div className={'flex justify-center'}>
2022-08-20 20:19:04 +00:00
<Button
className="whitespace-nowrap"
2022-08-28 21:26:29 +00:00
size="md"
color="indigo"
2022-08-20 20:19:04 +00:00
onClick={() => setOpen(true)}
>
2022-08-13 18:49:25 +00:00
Add market
</Button>
2022-07-19 23:15:55 +00:00
</div>
<SelectMarketsModal
2022-08-26 23:17:15 +00:00
open={open}
setOpen={setOpen}
title="Add markets"
description={
<div className={'text-md my-4 text-gray-600'}>
Add pre-existing markets to this group, or{' '}
<Link href={`/create?groupId=${group.id}`}>
<span className="cursor-pointer font-semibold underline">
create a new one
</span>
</Link>
.
</div>
}
submitLabel={(len) => `Add ${len} question${len !== 1 ? 's' : ''}`}
onSubmit={onSubmit}
contractSearchOptions={{
additionalFilter: { excludeContractIds: groupContractIds },
}}
/>
</>
)
}
function JoinGroupButton(props: {
group: Group
user: User | null | undefined
}) {
const { group, user } = props
2022-09-05 21:51:09 +00:00
const follow = async () => {
track('join group')
const userId = user ? user.id : (await firebaseLogin()).user.uid
toast.promise(joinGroup(group, userId), {
loading: 'Following group...',
success: 'Followed',
error: "Couldn't follow group, try again?",
})
}
2022-09-05 21:51:09 +00:00
return (
<div>
2022-06-23 17:40:32 +00:00
<button
2022-09-05 21:51:09 +00:00
onClick={follow}
2022-06-23 17:40:32 +00:00
className={'btn-md btn-outline btn whitespace-nowrap normal-case'}
>
2022-09-05 21:51:09 +00:00
Follow
</button>
</div>
)
}
const toTopUsers = async (
cachedUserIds: { userId: string; score: number }[]
): Promise<{ user: User; score: number }[]> =>
(
await Promise.all(
cachedUserIds.map(async (e) => {
const user = await getUser(e.userId)
return { user, score: e.score ?? 0 }
})
)
).filter((e) => e.user != null)