Revert "Switch comments/chat to rich text editor (#703)"

This reverts commit f52da72115.
This commit is contained in:
James Grugett 2022-08-04 16:49:59 -07:00
parent f52da72115
commit 33906adfe4
12 changed files with 266 additions and 196 deletions

View File

@ -1,5 +1,3 @@
import type { JSONContent } from '@tiptap/core'
// Currently, comments are created after the bet, not atomically with the bet.
// They're uniquely identified by the pair contractId/betId.
export type Comment = {
@ -11,9 +9,7 @@ export type Comment = {
replyToCommentId?: string
userId: string
/** @deprecated - content now stored as JSON in content*/
text?: string
content: JSONContent
text: string
createdTime: number
// Denormalized, for rendering comments

View File

@ -7,7 +7,7 @@ import {
} from '../../common/notification'
import { User } from '../../common/user'
import { Contract } from '../../common/contract'
import { getValues } from './utils'
import { getUserByUsername, getValues } from './utils'
import { Comment } from '../../common/comment'
import { uniq } from 'lodash'
import { Bet, LimitBet } from '../../common/bet'
@ -17,7 +17,6 @@ import { removeUndefinedProps } from '../../common/util/object'
import { TipTxn } from '../../common/txn'
import { Group, GROUP_CHAT_SLUG } from '../../common/group'
import { Challenge } from '../../common/challenge'
import { richTextToString } from 'common/util/parse'
const firestore = admin.firestore()
type user_to_reason_texts = {
@ -156,6 +155,17 @@ export const createNotification = async (
}
}
/** @deprecated parse from rich text instead */
const parseMentions = async (source: string) => {
const mentions = source.match(/@\w+/g)
if (!mentions) return []
return Promise.all(
mentions.map(
async (username) => (await getUserByUsername(username.slice(1)))?.id
)
)
}
const notifyTaggedUsers = (
userToReasonTexts: user_to_reason_texts,
userIds: (string | undefined)[]
@ -291,7 +301,8 @@ export const createNotification = async (
if (sourceType === 'comment') {
if (recipients?.[0] && relatedSourceType)
notifyRepliedUser(userToReasonTexts, recipients[0], relatedSourceType)
if (sourceText) notifyTaggedUsers(userToReasonTexts, recipients ?? [])
if (sourceText)
notifyTaggedUsers(userToReasonTexts, await parseMentions(sourceText))
}
await notifyContractCreator(userToReasonTexts, sourceContract)
await notifyOtherAnswerersOnContract(userToReasonTexts, sourceContract)
@ -416,7 +427,7 @@ export const createGroupCommentNotification = async (
sourceUserName: fromUser.name,
sourceUserUsername: fromUser.username,
sourceUserAvatarUrl: fromUser.avatarUrl,
sourceText: richTextToString(comment.content),
sourceText: comment.text,
sourceSlug,
sourceTitle: `${group.name}`,
isSeenOnHref: sourceSlug,

View File

@ -17,7 +17,6 @@ import { formatNumericProbability } from '../../common/pseudo-numeric'
import { sendTemplateEmail } from './send-email'
import { getPrivateUser, getUser } from './utils'
import { getFunctionUrl } from '../../common/api'
import { richTextToString } from 'common/util/parse'
const UNSUBSCRIBE_ENDPOINT = getFunctionUrl('unsubscribe')
@ -292,8 +291,7 @@ export const sendNewCommentEmail = async (
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
const { name: commentorName, avatarUrl: commentorAvatarUrl } = commentCreator
const { content } = comment
const text = richTextToString(content)
const { text } = comment
let betDescription = ''
if (bet) {

View File

@ -1,13 +1,13 @@
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import { compact, uniq } from 'lodash'
import { uniq } from 'lodash'
import { getContract, getUser, getValues } from './utils'
import { Comment } from '../../common/comment'
import { sendNewCommentEmail } from './emails'
import { Bet } from '../../common/bet'
import { Answer } from '../../common/answer'
import { createNotification } from './create-notification'
import { parseMentions, richTextToString } from 'common/util/parse'
const firestore = admin.firestore()
@ -71,10 +71,7 @@ export const onCreateCommentOnContract = functions
const repliedUserId = comment.replyToCommentId
? comments.find((c) => c.id === comment.replyToCommentId)?.userId
: answer?.userId
const recipients = uniq(
compact([...parseMentions(comment.content), repliedUserId])
)
const recipients = repliedUserId ? [repliedUserId] : []
await createNotification(
comment.id,
@ -82,7 +79,7 @@ export const onCreateCommentOnContract = functions
'created',
commentCreator,
eventId,
richTextToString(comment.content),
comment.text,
{ contract, relatedSourceType, recipients }
)

View File

@ -8,8 +8,8 @@ import { RelativeTimestamp } from './relative-timestamp'
import { UserLink } from './user-page'
import { User } from 'common/user'
import { Col } from './layout/col'
import { Linkify } from './linkify'
import { groupBy } from 'lodash'
import { Content } from './editor'
export function UserCommentsList(props: {
user: User
@ -50,8 +50,7 @@ export function UserCommentsList(props: {
function ProfileComment(props: { comment: Comment; className?: string }) {
const { comment, className } = props
const { text, content, userUsername, userName, userAvatarUrl, createdTime } =
comment
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
// TODO: find and attach relevant bets by comment betId at some point
return (
<Row className={className}>
@ -65,7 +64,7 @@ function ProfileComment(props: { comment: Comment; className?: string }) {
/>{' '}
<RelativeTimestamp time={createdTime} />
</p>
<Content content={content || text} />
<Linkify text={text} />
</div>
</Row>
)

View File

@ -107,6 +107,7 @@ export function ContractTopTrades(props: {
comment={commentsById[topCommentId]}
tips={tips[topCommentId]}
betsBySameUser={[betsById[topCommentId]]}
truncate={false}
smallAvatar={false}
/>
</div>

View File

@ -41,16 +41,14 @@ export function useTextEditor(props: {
max?: number
defaultValue?: Content
disabled?: boolean
simple?: boolean
}) {
const { placeholder, max, defaultValue = '', disabled, simple } = props
const { placeholder, max, defaultValue = '', disabled } = props
const users = useUsers()
const editorClass = clsx(
proseClass,
!simple && 'min-h-[6em]',
'outline-none pt-2 px-4'
'min-h-[6em] resize-none outline-none border-none pt-3 px-4 focus:ring-0'
)
const editor = useEditor(
@ -58,8 +56,7 @@ export function useTextEditor(props: {
editorProps: { attributes: { class: editorClass } },
extensions: [
StarterKit.configure({
heading: simple ? false : { levels: [1, 2, 3] },
horizontalRule: simple ? false : {},
heading: { levels: [1, 2, 3] },
}),
Placeholder.configure({
placeholder,
@ -123,9 +120,8 @@ function isValidIframe(text: string) {
export function TextEditor(props: {
editor: Editor | null
upload: ReturnType<typeof useUploadMutation>
children?: React.ReactNode // additional toolbar buttons
}) {
const { editor, upload, children } = props
const { editor, upload } = props
const [iframeOpen, setIframeOpen] = useState(false)
return (
@ -147,10 +143,20 @@ export function TextEditor(props: {
images!
</FloatingMenu>
)}
<div className="rounded-lg border border-gray-300 shadow-sm focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500">
<div className="overflow-hidden rounded-lg border border-gray-300 shadow-sm focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500">
<EditorContent editor={editor} />
{/* Toolbar, with buttons for images and embeds */}
<div className="flex h-9 items-center gap-5 pl-4 pr-1">
{/* Spacer element to match the height of the toolbar */}
<div className="py-2" aria-hidden="true">
{/* Matches height of button in toolbar (1px border + 36px content height) */}
<div className="py-px">
<div className="h-9" />
</div>
</div>
</div>
{/* Toolbar, with buttons for image and embeds */}
<div className="absolute inset-x-0 bottom-0 flex justify-between py-2 pl-3 pr-2">
<div className="flex items-center space-x-5">
<div className="flex items-center">
<FileUploadButton
onFiles={upload.mutate}
@ -175,8 +181,6 @@ export function TextEditor(props: {
<span className="sr-only">Embed an iframe</span>
</button>
</div>
<div className="ml-auto" />
{children}
</div>
</div>
</div>

View File

@ -31,9 +31,9 @@ export function FeedAnswerCommentGroup(props: {
const { answer, contract, comments, tips, bets, user } = props
const { username, avatarUrl, name, text } = answer
const [replyToUser, setReplyToUser] =
useState<Pick<User, 'id' | 'username'>>()
const [replyToUsername, setReplyToUsername] = useState('')
const [showReply, setShowReply] = useState(false)
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
const [highlighted, setHighlighted] = useState(false)
const router = useRouter()
@ -70,14 +70,9 @@ export function FeedAnswerCommentGroup(props: {
const scrollAndOpenReplyInput = useEvent(
(comment?: Comment, answer?: Answer) => {
setReplyToUser(
comment
? { id: comment.userId, username: comment.userUsername }
: answer
? { id: answer.userId, username: answer.username }
: undefined
)
setReplyToUsername(comment?.userUsername ?? answer?.username ?? '')
setShowReply(true)
inputRef?.focus()
}
)
@ -85,7 +80,7 @@ export function FeedAnswerCommentGroup(props: {
// Only show one comment input for a bet at a time
if (
betsByCurrentUser.length > 1 &&
// inputRef?.textContent?.length === 0 && //TODO: editor.isEmpty
inputRef?.textContent?.length === 0 &&
betsByCurrentUser.sort((a, b) => b.createdTime - a.createdTime)[0]
?.outcome !== answer.number.toString()
)
@ -94,6 +89,10 @@ export function FeedAnswerCommentGroup(props: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [betsByCurrentUser.length, user, answer.number])
useEffect(() => {
if (showReply && inputRef) inputRef.focus()
}, [inputRef, showReply])
useEffect(() => {
if (router.asPath.endsWith(`#${answerElementId}`)) {
setHighlighted(true)
@ -155,6 +154,7 @@ export function FeedAnswerCommentGroup(props: {
commentsList={commentsList}
betsByUserId={betsByUserId}
smallAvatar={true}
truncate={false}
bets={bets}
tips={tips}
scrollAndOpenReplyInput={scrollAndOpenReplyInput}
@ -172,8 +172,12 @@ export function FeedAnswerCommentGroup(props: {
betsByCurrentUser={betsByCurrentUser}
commentsByCurrentUser={commentsByCurrentUser}
parentAnswerOutcome={answer.number.toString()}
replyToUser={replyToUser}
onSubmitComment={() => setShowReply(false)}
replyToUsername={replyToUsername}
setRef={setInputRef}
onSubmitComment={() => {
setShowReply(false)
setReplyToUsername('')
}}
/>
</div>
)}

View File

@ -13,22 +13,25 @@ import { Avatar } from 'web/components/avatar'
import { UserLink } from 'web/components/user-page'
import { OutcomeLabel } from 'web/components/outcome-label'
import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time'
import { contractPath } from 'web/lib/firebase/contracts'
import { firebaseLogin } from 'web/lib/firebase/users'
import {
createCommentOnContract,
MAX_COMMENT_LENGTH,
} from 'web/lib/firebase/comments'
import Textarea from 'react-expanding-textarea'
import { Linkify } from 'web/components/linkify'
import { SiteLink } from 'web/components/site-link'
import { BetStatusText } from 'web/components/feed/feed-bets'
import { Col } from 'web/components/layout/col'
import { getProbability } from 'common/calculate'
import { LoadingIndicator } from 'web/components/loading-indicator'
import { PaperAirplaneIcon } from '@heroicons/react/outline'
import { track } from 'web/lib/service/analytics'
import { useEvent } from 'web/hooks/use-event'
import { Tipper } from '../tipper'
import { CommentTipMap, CommentTips } from 'web/hooks/use-tip-txns'
import { useWindowSize } from 'web/hooks/use-window-size'
import { Content, TextEditor, useTextEditor } from '../editor'
import { Editor } from '@tiptap/react'
export function FeedCommentThread(props: {
contract: Contract
@ -36,12 +39,20 @@ export function FeedCommentThread(props: {
tips: CommentTipMap
parentComment: Comment
bets: Bet[]
truncate?: boolean
smallAvatar?: boolean
}) {
const { contract, comments, bets, tips, smallAvatar, parentComment } = props
const {
contract,
comments,
bets,
tips,
truncate,
smallAvatar,
parentComment,
} = props
const [showReply, setShowReply] = useState(false)
const [replyToUser, setReplyToUser] =
useState<{ id: string; username: string }>()
const [replyToUsername, setReplyToUsername] = useState('')
const betsByUserId = groupBy(bets, (bet) => bet.userId)
const user = useUser()
const commentsList = comments.filter(
@ -49,12 +60,15 @@ export function FeedCommentThread(props: {
parentComment.id && comment.replyToCommentId === parentComment.id
)
commentsList.unshift(parentComment)
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
function scrollAndOpenReplyInput(comment: Comment) {
setReplyToUser({ id: comment.userId, username: comment.userUsername })
setReplyToUsername(comment.userUsername)
setShowReply(true)
inputRef?.focus()
}
useEffect(() => {
if (showReply && inputRef) inputRef.focus()
}, [inputRef, showReply])
return (
<Col className={'w-full gap-3 pr-1'}>
<span
@ -67,6 +81,7 @@ export function FeedCommentThread(props: {
betsByUserId={betsByUserId}
tips={tips}
smallAvatar={smallAvatar}
truncate={truncate}
bets={bets}
scrollAndOpenReplyInput={scrollAndOpenReplyInput}
/>
@ -83,9 +98,13 @@ export function FeedCommentThread(props: {
(c) => c.userId === user?.id
)}
parentCommentId={parentComment.id}
replyToUser={replyToUser}
replyToUsername={replyToUsername}
parentAnswerOutcome={comments[0].answerOutcome}
onSubmitComment={() => setShowReply(false)}
setRef={setInputRef}
onSubmitComment={() => {
setShowReply(false)
setReplyToUsername('')
}}
/>
</Col>
)}
@ -102,12 +121,14 @@ export function CommentRepliesList(props: {
bets: Bet[]
treatFirstIndexEqually?: boolean
smallAvatar?: boolean
truncate?: boolean
}) {
const {
contract,
commentsList,
betsByUserId,
tips,
truncate,
smallAvatar,
bets,
scrollAndOpenReplyInput,
@ -147,6 +168,7 @@ export function CommentRepliesList(props: {
: undefined
}
smallAvatar={smallAvatar}
truncate={truncate}
/>
</div>
))}
@ -160,6 +182,7 @@ export function FeedComment(props: {
tips: CommentTips
betsBySameUser: Bet[]
probAtCreatedTime?: number
truncate?: boolean
smallAvatar?: boolean
onReplyClick?: (comment: Comment) => void
}) {
@ -169,10 +192,10 @@ export function FeedComment(props: {
tips,
betsBySameUser,
probAtCreatedTime,
truncate,
onReplyClick,
} = props
const { text, content, userUsername, userName, userAvatarUrl, createdTime } =
comment
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
let betOutcome: string | undefined,
bought: string | undefined,
money: string | undefined
@ -253,9 +276,11 @@ export function FeedComment(props: {
elementId={comment.id}
/>
</div>
<div className="mt-2 text-[15px] text-gray-700">
<Content content={content || text} />
</div>
<TruncatedComment
comment={text}
moreHref={contractPath(contract)}
shouldTruncate={truncate}
/>
<Row className="mt-2 items-center gap-6 text-xs text-gray-500">
<Tipper comment={comment} tips={tips ?? {}} />
{onReplyClick && (
@ -320,7 +345,8 @@ export function CommentInput(props: {
contract: Contract
betsByCurrentUser: Bet[]
commentsByCurrentUser: Comment[]
replyToUser?: { id: string; username: string }
replyToUsername?: string
setRef?: (ref: HTMLTextAreaElement) => void
// Reply to a free response answer
parentAnswerOutcome?: string
// Reply to another comment
@ -333,18 +359,12 @@ export function CommentInput(props: {
commentsByCurrentUser,
parentAnswerOutcome,
parentCommentId,
replyToUser,
replyToUsername,
onSubmitComment,
setRef,
} = props
const user = useUser()
const { editor, upload } = useTextEditor({
simple: true,
max: MAX_COMMENT_LENGTH,
placeholder:
!!parentCommentId || !!parentAnswerOutcome
? 'Write a reply...'
: 'Write a comment...',
})
const [comment, setComment] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const mostRecentCommentableBet = getMostRecentCommentableBet(
@ -360,17 +380,18 @@ export function CommentInput(props: {
track('sign in to comment')
return await firebaseLogin()
}
if (!editor || editor.isEmpty || isSubmitting) return
if (!comment || isSubmitting) return
setIsSubmitting(true)
await createCommentOnContract(
contract.id,
editor.getJSON(),
comment,
user,
betId,
parentAnswerOutcome,
parentCommentId
)
onSubmitComment?.()
setComment('')
setIsSubmitting(false)
}
@ -425,12 +446,14 @@ export function CommentInput(props: {
)}
</div>
<CommentInputTextArea
editor={editor}
upload={upload}
replyToUser={replyToUser}
commentText={comment}
setComment={setComment}
isReply={!!parentCommentId || !!parentAnswerOutcome}
replyToUsername={replyToUsername ?? ''}
user={user}
submitComment={submitComment}
isSubmitting={isSubmitting}
setRef={setRef}
presetId={id}
/>
</div>
@ -442,89 +465,94 @@ export function CommentInput(props: {
export function CommentInputTextArea(props: {
user: User | undefined | null
replyToUser?: { id: string; username: string }
editor: Editor | null
upload: Parameters<typeof TextEditor>[0]['upload']
isReply: boolean
replyToUsername: string
commentText: string
setComment: (text: string) => void
submitComment: (id?: string) => void
isSubmitting: boolean
submitOnEnter?: boolean
setRef?: (ref: HTMLTextAreaElement) => void
presetId?: string
enterToSubmitOnDesktop?: boolean
}) {
const {
isReply,
setRef,
user,
editor,
upload,
commentText,
setComment,
submitComment,
presetId,
isSubmitting,
submitOnEnter,
replyToUser,
replyToUsername,
enterToSubmitOnDesktop,
} = props
const isMobile = (useWindowSize().width ?? 0) < 768 // TODO: base off input device (keybord vs touch)
const { width } = useWindowSize()
const memoizedSetComment = useEvent(setComment)
useEffect(() => {
editor?.setEditable(!isSubmitting)
}, [isSubmitting, editor])
const submit = () => {
submitComment(presetId)
editor?.commands?.clearContent()
}
useEffect(() => {
if (!editor) {
return
}
// submit on Enter key
editor.setOptions({
editorProps: {
handleKeyDown: (view, event) => {
if (
submitOnEnter &&
event.key === 'Enter' &&
!event.shiftKey &&
(!isMobile || event.ctrlKey || event.metaKey) &&
// mention list is closed
!(view.state as any).mention$.active
) {
submit()
event.preventDefault()
return true
}
return false
},
},
})
// insert at mention
if (replyToUser) {
editor.commands.insertContentAt(0, {
type: 'mention',
attrs: { label: replyToUser.username, id: replyToUser.id },
})
editor.commands.focus()
}
if (!replyToUsername || !user || replyToUsername === user.username) return
const replacement = `@${replyToUsername} `
memoizedSetComment(replacement + commentText.replace(replacement, ''))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editor])
}, [user, replyToUsername, memoizedSetComment])
return (
<>
<div>
<TextEditor editor={editor} upload={upload}>
<Row className="gap-1.5 text-gray-700">
<Textarea
ref={setRef}
value={commentText}
onChange={(e) => setComment(e.target.value)}
className={clsx('textarea textarea-bordered w-full resize-none')}
// Make room for floating submit button.
style={{ paddingRight: 48 }}
placeholder={
isReply
? 'Write a reply... '
: enterToSubmitOnDesktop
? 'Send a message'
: 'Write a comment...'
}
autoFocus={false}
maxLength={MAX_COMMENT_LENGTH}
disabled={isSubmitting}
onKeyDown={(e) => {
if (
(enterToSubmitOnDesktop &&
e.key === 'Enter' &&
!e.shiftKey &&
width &&
width > 768) ||
(e.key === 'Enter' && (e.ctrlKey || e.metaKey))
) {
e.preventDefault()
submitComment(presetId)
e.currentTarget.blur()
}
}}
/>
<Col className={clsx('relative justify-end')}>
{user && !isSubmitting && (
<button
className="btn btn-ghost btn-sm px-2 disabled:bg-inherit disabled:text-gray-300"
disabled={!editor || editor.isEmpty}
onClick={submit}
className={clsx(
'btn btn-ghost btn-sm absolute right-2 bottom-2 flex-row pl-2 capitalize',
!commentText && 'pointer-events-none text-gray-500'
)}
onClick={() => {
submitComment(presetId)
}}
>
<PaperAirplaneIcon className="m-0 h-[25px] min-w-[22px] rotate-90 p-0" />
<PaperAirplaneIcon
className={'m-0 min-w-[22px] rotate-90 p-0 '}
height={25}
/>
</button>
)}
{isSubmitting && (
<LoadingIndicator spinnerClassName={'border-gray-500'} />
)}
</TextEditor>
</div>
</Col>
</Row>
<Row>
{!user && (
<button
@ -539,6 +567,38 @@ export function CommentInputTextArea(props: {
)
}
export function TruncatedComment(props: {
comment: string
moreHref: string
shouldTruncate?: boolean
}) {
const { comment, moreHref, shouldTruncate } = props
let truncated = comment
// Keep descriptions to at most 400 characters
const MAX_CHARS = 400
if (shouldTruncate && truncated.length > MAX_CHARS) {
truncated = truncated.slice(0, MAX_CHARS)
// Make sure to end on a space
const i = truncated.lastIndexOf(' ')
truncated = truncated.slice(0, i)
}
return (
<div
className="mt-2 whitespace-pre-line break-words text-gray-700"
style={{ fontSize: 15 }}
>
<Linkify text={truncated} />
{truncated != comment && (
<SiteLink href={moreHref} className="text-indigo-700">
... (show more)
</SiteLink>
)}
</div>
)
}
function getBettorsLargestPositionBeforeTime(
contract: Contract,
createdTime: number,

View File

@ -5,19 +5,24 @@ import React, { useEffect, memo, useState, useMemo } from 'react'
import { Avatar } from 'web/components/avatar'
import { Group } from 'common/group'
import { Comment, createCommentOnGroup } from 'web/lib/firebase/comments'
import { CommentInputTextArea } from 'web/components/feed/feed-comments'
import {
CommentInputTextArea,
TruncatedComment,
} from 'web/components/feed/feed-comments'
import { track } from 'web/lib/service/analytics'
import { firebaseLogin } from 'web/lib/firebase/users'
import { useRouter } from 'next/router'
import clsx from 'clsx'
import { UserLink } from 'web/components/user-page'
import { groupPath } from 'web/lib/firebase/groups'
import { CopyLinkDateTimeComponent } from 'web/components/feed/copy-link-date-time'
import { CommentTipMap, CommentTips } from 'web/hooks/use-tip-txns'
import { Tipper } from 'web/components/tipper'
import { sum } from 'lodash'
import { formatMoney } from 'common/util/format'
import { useWindowSize } from 'web/hooks/use-window-size'
import { Content, useTextEditor } from 'web/components/editor'
import { useUnseenPreferredNotifications } from 'web/hooks/use-notifications'
import { ChatIcon, ChevronDownIcon } from '@heroicons/react/outline'
import { setNotificationsAsSeen } from 'web/pages/notifications'
@ -29,18 +34,16 @@ export function GroupChat(props: {
tips: CommentTipMap
}) {
const { messages, user, group, tips } = props
const { editor, upload } = useTextEditor({
simple: true,
placeholder: 'Send a message',
})
const [messageText, setMessageText] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [scrollToBottomRef, setScrollToBottomRef] =
useState<HTMLDivElement | null>(null)
const [scrollToMessageId, setScrollToMessageId] = useState('')
const [scrollToMessageRef, setScrollToMessageRef] =
useState<HTMLDivElement | null>(null)
const [replyToUser, setReplyToUser] = useState<any>()
const [replyToUsername, setReplyToUsername] = useState('')
const [inputRef, setInputRef] = useState<HTMLTextAreaElement | null>(null)
const [groupedMessages, setGroupedMessages] = useState<Comment[]>([])
const router = useRouter()
const isMember = user && group.memberIds.includes(user?.id)
@ -51,26 +54,25 @@ export function GroupChat(props: {
const remainingHeight =
(height ?? 0) - (containerRef?.offsetTop ?? 0) - bottomBarHeight
// array of groups, where each group is an array of messages that are displayed as one
const groupedMessages = useMemo(() => {
useMemo(() => {
// Group messages with createdTime within 2 minutes of each other.
const tempGrouped: Comment[][] = []
const tempMessages = []
for (let i = 0; i < messages.length; i++) {
const message = messages[i]
if (i === 0) tempGrouped.push([message])
if (i === 0) tempMessages.push({ ...message })
else {
const prevMessage = messages[i - 1]
const diff = message.createdTime - prevMessage.createdTime
const creatorsMatch = message.userId === prevMessage.userId
if (diff < 2 * 60 * 1000 && creatorsMatch) {
tempGrouped.at(-1)?.push(message)
tempMessages[tempMessages.length - 1].text += `\n${message.text}`
} else {
tempGrouped.push([message])
tempMessages.push({ ...message })
}
}
}
return tempGrouped
setGroupedMessages(tempMessages)
}, [messages])
useEffect(() => {
@ -92,12 +94,11 @@ export function GroupChat(props: {
useEffect(() => {
// is mobile?
if (width && width > 720) focusInput()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [width])
if (inputRef && width && width > 720) inputRef.focus()
}, [inputRef, width])
function onReplyClick(comment: Comment) {
setReplyToUser({ id: comment.userId, username: comment.userUsername })
setReplyToUsername(comment.userUsername)
}
async function submitMessage() {
@ -105,16 +106,13 @@ export function GroupChat(props: {
track('sign in to comment')
return await firebaseLogin()
}
if (!editor || editor.isEmpty || isSubmitting) return
if (!messageText || isSubmitting) return
setIsSubmitting(true)
await createCommentOnGroup(group.id, editor.getJSON(), user)
editor.commands.clearContent()
await createCommentOnGroup(group.id, messageText, user)
setMessageText('')
setIsSubmitting(false)
setReplyToUser(undefined)
focusInput()
}
function focusInput() {
editor?.commands.focus()
setReplyToUsername('')
inputRef?.focus()
}
return (
@ -125,20 +123,20 @@ export function GroupChat(props: {
}
ref={setScrollToBottomRef}
>
{groupedMessages.map((messages) => (
{groupedMessages.map((message) => (
<GroupMessage
user={user}
key={`group ${messages[0].id}`}
comments={messages}
key={message.id}
comment={message}
group={group}
onReplyClick={onReplyClick}
highlight={messages[0].id === scrollToMessageId}
highlight={message.id === scrollToMessageId}
setRef={
scrollToMessageId === messages[0].id
scrollToMessageId === message.id
? setScrollToMessageRef
: undefined
}
tips={tips[messages[0].id] ?? {}}
tips={tips[message.id] ?? {}}
/>
))}
{messages.length === 0 && (
@ -146,7 +144,7 @@ export function GroupChat(props: {
No messages yet. Why not{isMember ? ` ` : ' join and '}
<button
className={'cursor-pointer font-bold text-gray-700'}
onClick={focusInput}
onClick={() => inputRef?.focus()}
>
add one?
</button>
@ -164,13 +162,15 @@ export function GroupChat(props: {
</div>
<div className={'flex-1'}>
<CommentInputTextArea
editor={editor}
upload={upload}
commentText={messageText}
setComment={setMessageText}
isReply={false}
user={user}
replyToUser={replyToUser}
replyToUsername={replyToUsername}
submitComment={submitMessage}
isSubmitting={isSubmitting}
submitOnEnter
enterToSubmitOnDesktop={true}
setRef={setInputRef}
/>
</div>
</div>
@ -292,18 +292,16 @@ function GroupChatNotificationsIcon(props: {
const GroupMessage = memo(function GroupMessage_(props: {
user: User | null | undefined
comments: Comment[]
comment: Comment
group: Group
onReplyClick?: (comment: Comment) => void
setRef?: (ref: HTMLDivElement) => void
highlight?: boolean
tips: CommentTips
}) {
const { comments, onReplyClick, group, setRef, highlight, user, tips } = props
const first = comments[0]
const { id, userUsername, userName, userAvatarUrl, createdTime } = first
const isCreatorsComment = user && first.userId === user.id
const { comment, onReplyClick, group, setRef, highlight, user, tips } = props
const { text, userUsername, userName, userAvatarUrl, createdTime } = comment
const isCreatorsComment = user && comment.userId === user.id
return (
<Col
ref={setRef}
@ -333,21 +331,23 @@ const GroupMessage = memo(function GroupMessage_(props: {
prefix={'group'}
slug={group.slug}
createdTime={createdTime}
elementId={id}
elementId={comment.id}
/>
</Row>
<Row className={'text-black'}>
<TruncatedComment
comment={text}
moreHref={groupPath(group.slug)}
shouldTruncate={false}
/>
</Row>
<div className="mt-2 text-black">
{comments.map((comment) => (
<Content content={comment.content || comment.text} />
))}
</div>
<Row>
{!isCreatorsComment && onReplyClick && (
<button
className={
'self-start py-1 text-xs font-bold text-gray-500 hover:underline'
}
onClick={() => onReplyClick(first)}
onClick={() => onReplyClick(comment)}
>
Reply
</button>
@ -357,7 +357,7 @@ const GroupMessage = memo(function GroupMessage_(props: {
{formatMoney(sum(Object.values(tips)))}
</span>
)}
{!isCreatorsComment && <Tipper comment={first} tips={tips} />}
{!isCreatorsComment && <Tipper comment={comment} tips={tips} />}
</Row>
</Col>
)

View File

@ -14,7 +14,6 @@ import { User } from 'common/user'
import { Comment } from 'common/comment'
import { removeUndefinedProps } from 'common/util/object'
import { track } from '@amplitude/analytics-browser'
import { JSONContent } from '@tiptap/react'
export type { Comment }
@ -22,7 +21,7 @@ export const MAX_COMMENT_LENGTH = 10000
export async function createCommentOnContract(
contractId: string,
content: JSONContent,
text: string,
commenter: User,
betId?: string,
answerOutcome?: string,
@ -35,7 +34,7 @@ export async function createCommentOnContract(
id: ref.id,
contractId,
userId: commenter.id,
content: content,
text: text.slice(0, MAX_COMMENT_LENGTH),
createdTime: Date.now(),
userName: commenter.name,
userUsername: commenter.username,
@ -54,7 +53,7 @@ export async function createCommentOnContract(
}
export async function createCommentOnGroup(
groupId: string,
content: JSONContent,
text: string,
user: User,
replyToCommentId?: string
) {
@ -63,7 +62,7 @@ export async function createCommentOnGroup(
id: ref.id,
groupId,
userId: user.id,
content: content,
text: text.slice(0, MAX_COMMENT_LENGTH),
createdTime: Date.now(),
userName: user.name,
userUsername: user.username,

View File

@ -354,6 +354,7 @@ function ContractTopTrades(props: {
comment={commentsById[topCommentId]}
tips={tips[topCommentId]}
betsBySameUser={[betsById[topCommentId]]}
truncate={false}
smallAvatar={false}
/>
</div>