Groups chat ux (#713)

* Add in group chat bubble

* Show chat bubble on nav with unseen notifs

* Spacing

* More spacing

* Remove chat tab

* Show chat on help/welcome/updates/features groups

* Cleanup

* Scroll with updated height
This commit is contained in:
Ian Philips 2022-08-03 15:38:35 -06:00 committed by GitHub
parent a7d80d62cb
commit 82419d0b92
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 184 additions and 78 deletions

View File

@ -1,6 +1,6 @@
import { Row } from 'web/components/layout/row' import { Row } from 'web/components/layout/row'
import { Col } from 'web/components/layout/col' import { Col } from 'web/components/layout/col'
import { User } from 'common/user' import { PrivateUser, User } from 'common/user'
import React, { useEffect, memo, useState, useMemo } from 'react' import React, { useEffect, memo, useState, useMemo } from 'react'
import { Avatar } from 'web/components/avatar' import { Avatar } from 'web/components/avatar'
import { Group } from 'common/group' import { Group } from 'common/group'
@ -23,6 +23,9 @@ import { Tipper } from 'web/components/tipper'
import { sum } from 'lodash' import { sum } from 'lodash'
import { formatMoney } from 'common/util/format' import { formatMoney } from 'common/util/format'
import { useWindowSize } from 'web/hooks/use-window-size' import { useWindowSize } from 'web/hooks/use-window-size'
import { useUnseenPreferredNotifications } from 'web/hooks/use-notifications'
import { ChatIcon, ChevronDownIcon } from '@heroicons/react/outline'
import { setNotificationsAsSeen } from 'web/pages/notifications'
export function GroupChat(props: { export function GroupChat(props: {
messages: Comment[] messages: Comment[]
@ -70,9 +73,10 @@ export function GroupChat(props: {
}, [scrollToMessageRef]) }, [scrollToMessageRef])
useEffect(() => { useEffect(() => {
if (!isSubmitting) if (scrollToBottomRef)
scrollToBottomRef?.scrollTo({ top: scrollToBottomRef?.scrollHeight || 0 }) scrollToBottomRef.scrollTo({ top: scrollToBottomRef.scrollHeight || 0 })
}, [scrollToBottomRef, isSubmitting]) // Must also listen to groupedMessages as they update the height of the messaging window
}, [scrollToBottomRef, groupedMessages])
useEffect(() => { useEffect(() => {
const elementInUrl = router.asPath.split('#')[1] const elementInUrl = router.asPath.split('#')[1]
@ -81,6 +85,10 @@ export function GroupChat(props: {
} }
}, [messages, router.asPath]) }, [messages, router.asPath])
useEffect(() => {
if (inputRef) inputRef.focus()
}, [inputRef])
function onReplyClick(comment: Comment) { function onReplyClick(comment: Comment) {
setReplyToUsername(comment.userUsername) setReplyToUsername(comment.userUsername)
} }
@ -98,18 +106,13 @@ export function GroupChat(props: {
setReplyToUsername('') setReplyToUsername('')
inputRef?.focus() inputRef?.focus()
} }
function focusInput() {
inputRef?.focus()
}
const { width, height } = useWindowSize() const { width, height } = useWindowSize()
const [containerRef, setContainerRef] = useState<HTMLDivElement | null>(null) const [containerRef, setContainerRef] = useState<HTMLDivElement | null>(null)
// Subtract bottom bar when it's showing (less than lg screen) // Subtract bottom bar when it's showing (less than lg screen)
const bottomBarHeight = (width ?? 0) < 1024 ? 58 : 0 const bottomBarHeight = (width ?? 0) < 1024 ? 58 : 0
const remainingHeight = const remainingHeight =
(height ?? window.innerHeight) - (height ?? 0) - (containerRef?.offsetTop ?? 0) - bottomBarHeight
(containerRef?.offsetTop ?? 0) -
bottomBarHeight
return ( return (
<Col ref={setContainerRef} style={{ height: remainingHeight }}> <Col ref={setContainerRef} style={{ height: remainingHeight }}>
@ -140,7 +143,7 @@ export function GroupChat(props: {
No messages yet. Why not{isMember ? ` ` : ' join and '} No messages yet. Why not{isMember ? ` ` : ' join and '}
<button <button
className={'cursor-pointer font-bold text-gray-700'} className={'cursor-pointer font-bold text-gray-700'}
onClick={() => focusInput()} onClick={() => inputRef?.focus()}
> >
add one? add one?
</button> </button>
@ -175,6 +178,117 @@ export function GroupChat(props: {
) )
} }
export function GroupChatInBubble(props: {
messages: Comment[]
user: User | null | undefined
privateUser: PrivateUser | null | undefined
group: Group
tips: CommentTipMap
}) {
const { messages, user, group, tips, privateUser } = props
const [shouldShowChat, setShouldShowChat] = useState(false)
const router = useRouter()
useEffect(() => {
const groupsWithChatEmphasis = [
'welcome',
'bugs',
'manifold-features-25bad7c7792e',
'updates',
]
if (
router.asPath.includes('/chat') ||
groupsWithChatEmphasis.includes(
router.asPath.split('/group/')[1].split('/')[0]
)
) {
setShouldShowChat(true)
}
// Leave chat open between groups if user is using chat?
else {
setShouldShowChat(false)
}
}, [router.asPath])
return (
<Col
className={clsx(
'fixed right-0 bottom-[20px] h-screen w-full sm:bottom-[20px] sm:right-20 sm:w-2/3 md:w-1/2 lg:right-24 lg:w-1/3 xl:right-32 xl:w-1/4',
shouldShowChat ? 'z-10 bg-white p-2' : ''
)}
>
{shouldShowChat && (
<GroupChat messages={messages} user={user} group={group} tips={tips} />
)}
<button
type="button"
className={clsx(
'fixed right-1 inline-flex items-center rounded-full border md:right-2 lg:right-5 xl:right-10' +
' border-transparent p-3 text-white shadow-sm lg:p-4' +
' focus:outline-none focus:ring-2 focus:ring-offset-2 ' +
' bottom-[70px] ',
shouldShowChat
? 'bottom-auto top-2 bg-gray-600 hover:bg-gray-400 focus:ring-gray-500 sm:bottom-[70px] sm:top-auto '
: ' bg-indigo-600 hover:bg-indigo-700 focus:ring-indigo-500'
)}
onClick={() => {
// router.push('/chat')
setShouldShowChat(!shouldShowChat)
track('mobile group chat button')
}}
>
{!shouldShowChat ? (
<ChatIcon className="h-10 w-10" aria-hidden="true" />
) : (
<ChevronDownIcon className={'h-10 w-10'} aria-hidden={'true'} />
)}
{privateUser && (
<GroupChatNotificationsIcon
group={group}
privateUser={privateUser}
shouldSetAsSeen={shouldShowChat}
/>
)}
</button>
</Col>
)
}
function GroupChatNotificationsIcon(props: {
group: Group
privateUser: PrivateUser
shouldSetAsSeen: boolean
}) {
const { privateUser, group, shouldSetAsSeen } = props
const preferredNotificationsForThisGroup = useUnseenPreferredNotifications(
privateUser,
{
customHref: `/group/${group.slug}`,
}
)
useEffect(() => {
preferredNotificationsForThisGroup.forEach((notification) => {
if (
(shouldSetAsSeen && notification.isSeenOnHref?.includes('chat')) ||
// old style chat notif that simply ended with the group slug
notification.isSeenOnHref?.endsWith(group.slug)
) {
setNotificationsAsSeen([notification])
}
})
}, [group.slug, preferredNotificationsForThisGroup, shouldSetAsSeen])
return (
<div
className={
preferredNotificationsForThisGroup.length > 0 && !shouldSetAsSeen
? 'absolute right-4 top-4 h-3 w-3 rounded-full border-2 border-white bg-red-500'
: 'hidden'
}
></div>
)
}
const GroupMessage = memo(function GroupMessage_(props: { const GroupMessage = memo(function GroupMessage_(props: {
user: User | null | undefined user: User | null | undefined
comment: Comment comment: Comment

View File

@ -18,7 +18,7 @@ import { ManifoldLogo } from './manifold-logo'
import { MenuButton } from './menu' import { MenuButton } from './menu'
import { ProfileSummary } from './profile-menu' import { ProfileSummary } from './profile-menu'
import NotificationsIcon from 'web/components/notifications-icon' import NotificationsIcon from 'web/components/notifications-icon'
import React, { useEffect, useState } from 'react' import React, { useMemo, useState } from 'react'
import { IS_PRIVATE_MANIFOLD } from 'common/envs/constants' import { IS_PRIVATE_MANIFOLD } from 'common/envs/constants'
import { CreateQuestionButton } from 'web/components/create-question-button' import { CreateQuestionButton } from 'web/components/create-question-button'
import { useMemberGroups } from 'web/hooks/use-group' import { useMemberGroups } from 'web/hooks/use-group'
@ -27,7 +27,6 @@ import { trackCallback, withTracking } from 'web/lib/service/analytics'
import { Group, GROUP_CHAT_SLUG } from 'common/group' import { Group, GROUP_CHAT_SLUG } from 'common/group'
import { Spacer } from '../layout/spacer' import { Spacer } from '../layout/spacer'
import { useUnseenPreferredNotifications } from 'web/hooks/use-notifications' import { useUnseenPreferredNotifications } from 'web/hooks/use-notifications'
import { setNotificationsAsSeen } from 'web/pages/notifications'
import { PrivateUser } from 'common/user' import { PrivateUser } from 'common/user'
import { useWindowSize } from 'web/hooks/use-window-size' import { useWindowSize } from 'web/hooks/use-window-size'
@ -216,7 +215,7 @@ export default function Sidebar(props: { className?: string }) {
) ?? [] ) ?? []
).map((group: Group) => ({ ).map((group: Group) => ({
name: group.name, name: group.name,
href: `${groupPath(group.slug)}/${GROUP_CHAT_SLUG}`, href: `${groupPath(group.slug)}`,
})) }))
return ( return (
@ -294,30 +293,22 @@ function GroupsList(props: {
memberItems.length > 0 ? memberItems.length : undefined memberItems.length > 0 ? memberItems.length : undefined
) )
// Set notification as seen if our current page is equal to the isSeenOnHref property
useEffect(() => {
const currentPageWithoutQuery = currentPage.split('?')[0]
const currentPageGroupSlug = currentPageWithoutQuery.split('/')[2]
preferredNotifications.forEach((notification) => {
if (
notification.isSeenOnHref === currentPage ||
// Old chat style group chat notif was just /group/slug
(notification.isSeenOnHref &&
currentPageWithoutQuery.includes(notification.isSeenOnHref)) ||
// They're on the home page, so if they've a chat notif, they're seeing the chat
(notification.isSeenOnHref?.endsWith(GROUP_CHAT_SLUG) &&
currentPageWithoutQuery.endsWith(currentPageGroupSlug))
) {
setNotificationsAsSeen([notification])
}
})
}, [currentPage, preferredNotifications])
const { height } = useWindowSize() const { height } = useWindowSize()
const [containerRef, setContainerRef] = useState<HTMLDivElement | null>(null) const [containerRef, setContainerRef] = useState<HTMLDivElement | null>(null)
const remainingHeight = const remainingHeight =
(height ?? window.innerHeight) - (containerRef?.offsetTop ?? 0) (height ?? window.innerHeight) - (containerRef?.offsetTop ?? 0)
const notifIsForThisItem = useMemo(
() => (itemHref: string) =>
preferredNotifications.some(
(n) =>
!n.isSeen &&
(n.isSeenOnHref === itemHref ||
n.isSeenOnHref?.replace('/chat', '') === itemHref)
),
[preferredNotifications]
)
return ( return (
<> <>
<SidebarItem <SidebarItem
@ -331,21 +322,23 @@ function GroupsList(props: {
ref={setContainerRef} ref={setContainerRef}
> >
{memberItems.map((item) => ( {memberItems.map((item) => (
<a <Link
href={
item.href +
(notifIsForThisItem(item.href) ? '/' + GROUP_CHAT_SLUG : '')
}
key={item.href} key={item.href}
href={item.href} >
<span
className={clsx( className={clsx(
'cursor-pointer truncate',
'group flex items-center rounded-md px-3 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-900', 'group flex items-center rounded-md px-3 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-900',
preferredNotifications.some( notifIsForThisItem(item.href) && 'font-bold'
(n) =>
!n.isSeen &&
(n.isSeenOnHref === item.href ||
n.isSeenOnHref === item.href.replace('/chat', ''))
) && 'font-bold'
)} )}
> >
<span className="truncate">{item.name}</span> {item.name}
</a> </span>
</Link>
))} ))}
</div> </div>
</> </>

View File

@ -81,6 +81,7 @@ export async function createCommentOnGroup(
function getCommentsCollection(contractId: string) { function getCommentsCollection(contractId: string) {
return collection(db, 'contracts', contractId, 'comments') return collection(db, 'contracts', contractId, 'comments')
} }
function getCommentsOnGroupCollection(groupId: string) { function getCommentsOnGroupCollection(groupId: string) {
return collection(db, 'groups', groupId, 'comments') return collection(db, 'groups', groupId, 'comments')
} }
@ -91,6 +92,14 @@ export async function listAllComments(contractId: string) {
return comments return comments
} }
export async function listAllCommentsOnGroup(groupId: string) {
const comments = await getValues<Comment>(
getCommentsOnGroupCollection(groupId)
)
comments.sort((c1, c2) => c1.createdTime - c2.createdTime)
return comments
}
export function listenForCommentsOnContract( export function listenForCommentsOnContract(
contractId: string, contractId: string,
setComments: (comments: Comment[]) => void setComments: (comments: Comment[]) => void

View File

@ -16,7 +16,7 @@ import { Row } from 'web/components/layout/row'
import { UserLink } from 'web/components/user-page' import { UserLink } from 'web/components/user-page'
import { firebaseLogin, getUser, User } from 'web/lib/firebase/users' import { firebaseLogin, getUser, User } from 'web/lib/firebase/users'
import { Col } from 'web/components/layout/col' import { Col } from 'web/components/layout/col'
import { useUser } from 'web/hooks/use-user' import { usePrivateUser, useUser } from 'web/hooks/use-user'
import { listMembers, useGroup, useMembers } from 'web/hooks/use-group' import { listMembers, useGroup, useMembers } from 'web/hooks/use-group'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { scoreCreators, scoreTraders } from 'common/scoring' import { scoreCreators, scoreTraders } from 'common/scoring'
@ -30,7 +30,7 @@ import { fromPropz, usePropz } from 'web/hooks/use-propz'
import { Tabs } from 'web/components/layout/tabs' import { Tabs } from 'web/components/layout/tabs'
import { CreateQuestionButton } from 'web/components/create-question-button' import { CreateQuestionButton } from 'web/components/create-question-button'
import React, { useState } from 'react' import React, { useState } from 'react'
import { GroupChat } from 'web/components/groups/group-chat' import { GroupChatInBubble } from 'web/components/groups/group-chat'
import { LoadingIndicator } from 'web/components/loading-indicator' import { LoadingIndicator } from 'web/components/loading-indicator'
import { Modal } from 'web/components/layout/modal' import { Modal } from 'web/components/layout/modal'
import { getSavedSort } from 'web/hooks/use-sort-and-query-params' import { getSavedSort } from 'web/hooks/use-sort-and-query-params'
@ -45,11 +45,12 @@ import { SearchIcon } from '@heroicons/react/outline'
import { useTipTxns } from 'web/hooks/use-tip-txns' import { useTipTxns } from 'web/hooks/use-tip-txns'
import { JoinOrLeaveGroupButton } from 'web/components/groups/groups-button' import { JoinOrLeaveGroupButton } from 'web/components/groups/groups-button'
import { searchInAny } from 'common/util/parse' import { searchInAny } from 'common/util/parse'
import { useWindowSize } from 'web/hooks/use-window-size'
import { CopyLinkButton } from 'web/components/copy-link-button' import { CopyLinkButton } from 'web/components/copy-link-button'
import { ENV_CONFIG } from 'common/envs/constants' import { ENV_CONFIG } from 'common/envs/constants'
import { useSaveReferral } from 'web/hooks/use-save-referral' import { useSaveReferral } from 'web/hooks/use-save-referral'
import { Button } from 'web/components/button' import { Button } from 'web/components/button'
import { listAllCommentsOnGroup } from 'web/lib/firebase/comments'
import { Comment } from 'common/comment'
export const getStaticProps = fromPropz(getStaticPropz) export const getStaticProps = fromPropz(getStaticPropz)
export async function getStaticPropz(props: { params: { slugs: string[] } }) { export async function getStaticPropz(props: { params: { slugs: string[] } }) {
@ -65,6 +66,7 @@ export async function getStaticPropz(props: { params: { slugs: string[] } }) {
const bets = await Promise.all( const bets = await Promise.all(
contracts.map((contract: Contract) => listAllBets(contract.id)) contracts.map((contract: Contract) => listAllBets(contract.id))
) )
const messages = group && (await listAllCommentsOnGroup(group.id))
const creatorScores = scoreCreators(contracts) const creatorScores = scoreCreators(contracts)
const traderScores = scoreTraders(contracts, bets) const traderScores = scoreTraders(contracts, bets)
@ -86,6 +88,7 @@ export async function getStaticPropz(props: { params: { slugs: string[] } }) {
topTraders, topTraders,
creatorScores, creatorScores,
topCreators, topCreators,
messages,
}, },
revalidate: 60, // regenerate after a minute revalidate: 60, // regenerate after a minute
@ -123,6 +126,7 @@ export default function GroupPage(props: {
topTraders: User[] topTraders: User[]
creatorScores: { [userId: string]: number } creatorScores: { [userId: string]: number }
topCreators: User[] topCreators: User[]
messages: Comment[]
}) { }) {
props = usePropz(props, getStaticPropz) ?? { props = usePropz(props, getStaticPropz) ?? {
group: null, group: null,
@ -132,6 +136,7 @@ export default function GroupPage(props: {
topTraders: [], topTraders: [],
creatorScores: {}, creatorScores: {},
topCreators: [], topCreators: [],
messages: [],
} }
const { const {
creator, creator,
@ -149,19 +154,18 @@ export default function GroupPage(props: {
const group = useGroup(props.group?.id) ?? props.group const group = useGroup(props.group?.id) ?? props.group
const tips = useTipTxns({ groupId: group?.id }) const tips = useTipTxns({ groupId: group?.id })
const messages = useCommentsOnGroup(group?.id) const messages = useCommentsOnGroup(group?.id) ?? props.messages
const user = useUser() const user = useUser()
const privateUser = usePrivateUser(user?.id)
useSaveReferral(user, { useSaveReferral(user, {
defaultReferrer: creator.username, defaultReferrer: creator.username,
groupId: group?.id, groupId: group?.id,
}) })
const { width } = useWindowSize()
const chatDisabled = !group || group.chatDisabled const chatDisabled = !group || group.chatDisabled
const showChatSidebar = !chatDisabled && (width ?? 1280) >= 1280 const showChatBubble = !chatDisabled
const showChatTab = !chatDisabled && !showChatSidebar
if (group === null || !groupSubpages.includes(page) || slugs[2]) { if (group === null || !groupSubpages.includes(page) || slugs[2]) {
return <Custom404 /> return <Custom404 />
@ -195,16 +199,6 @@ export default function GroupPage(props: {
</Col> </Col>
) )
const chatTab = (
<Col className="">
{messages ? (
<GroupChat messages={messages} user={user} group={group} tips={tips} />
) : (
<LoadingIndicator />
)}
</Col>
)
const questionsTab = ( const questionsTab = (
<ContractSearch <ContractSearch
querySortOptions={{ querySortOptions={{
@ -217,15 +211,6 @@ export default function GroupPage(props: {
) )
const tabs = [ const tabs = [
...(!showChatTab
? []
: [
{
title: 'Chat',
content: chatTab,
href: groupPath(group.slug, GROUP_CHAT_SLUG),
},
]),
{ {
title: 'Markets', title: 'Markets',
content: questionsTab, content: questionsTab,
@ -246,17 +231,13 @@ export default function GroupPage(props: {
const tabIndex = tabs.map((t) => t.title).indexOf(page ?? GROUP_CHAT_SLUG) const tabIndex = tabs.map((t) => t.title).indexOf(page ?? GROUP_CHAT_SLUG)
return ( return (
<Page <Page>
rightSidebar={showChatSidebar ? chatTab : undefined}
rightSidebarClassName={showChatSidebar ? '!top-0' : ''}
className={showChatSidebar ? '!max-w-7xl !pb-0' : ''}
>
<SEO <SEO
title={group.name} title={group.name}
description={`Created by ${creator.name}. ${group.about}`} description={`Created by ${creator.name}. ${group.about}`}
url={groupPath(group.slug)} url={groupPath(group.slug)}
/> />
<Col className="px-3"> <Col className="relative px-3">
<Row className={'items-center justify-between gap-4'}> <Row className={'items-center justify-between gap-4'}>
<div className={'sm:mb-1'}> <div className={'sm:mb-1'}>
<div <div
@ -283,6 +264,15 @@ export default function GroupPage(props: {
defaultIndex={tabIndex > 0 ? tabIndex : 0} defaultIndex={tabIndex > 0 ? tabIndex : 0}
tabs={tabs} tabs={tabs}
/> />
{showChatBubble && (
<GroupChatInBubble
group={group}
user={user}
privateUser={privateUser}
tips={tips}
messages={messages}
/>
)}
</Page> </Page>
) )
} }