feat(comment): add emoji reaction support for comments (#405)

* feat(comment): add emoji reaction support for comments

* fix(webui): adjust emoji picker trigger icon size to match mark-done icon

* fix(webui): prevent search icon and placeholder overlap in emoji picker

* fix(webui): use normal text color for reaction count

* feat(db): limit comment reaction code column to VarChar(32)
This commit is contained in:
Yiling-J
2026-09-14 15:01:36 +08:00
committed by GitHub
parent ede52e5009
commit def42cd000
29 changed files with 3084 additions and 41 deletions
@@ -1,11 +1,54 @@
// @vitest-environment happy-dom
import React from 'react'
import { cleanup, render, screen, fireEvent } from '@testing-library/react'
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { CommentInfo } from '@shumai/dtos'
import { MessageCard } from './message-card'
import { client } from '@/ui/api/client'
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
me: {
$get: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ id: 'u-1', name: 'Bob Reviewer', role: 'member' }),
}),
},
},
},
comments: {
':commentId': {
complete: {
$post: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ isCompleted: true }),
}),
},
reactions: {
$post: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
}),
$delete: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
}),
},
$delete: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
}),
},
},
},
},
}))
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -56,6 +99,7 @@ describe('MessageCard component', () => {
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [],
}
const onReply = vi.fn()
@@ -98,4 +142,124 @@ describe('MessageCard component', () => {
)
windowOpenSpy.mockRestore()
})
it('renders reaction badges with active and inactive styling and toggles on click', async () => {
const mockMessage: CommentInfo = {
id: 'msg-reactions',
assetId: 'asset-1',
message: 'Great work!',
annotations: null,
second: null,
creator: { id: 'u-2', name: 'Alice' },
replies: [],
attachments: [],
mentions: [],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [
{
code: '👍',
count: 2,
requestingUserReacted: true,
creatorNames: ['Bob'],
},
{
code: '❤️',
count: 1,
requestingUserReacted: false,
creatorNames: ['Charlie'],
},
],
}
const onReply = vi.fn()
const getUser = vi.fn().mockReturnValue({ id: 'u-2', name: 'Alice' })
render(<MessageCard message={mockMessage} getUser={getUser} onReply={onReply} />, {
wrapper: createWrapper(),
})
// Both emoji badges are rendered with their counts
const thumbsUpBadge = screen.getByText('👍').closest('button')
const heartBadge = screen.getByText('❤️').closest('button')
expect(thumbsUpBadge).toBeDefined()
expect(heartBadge).toBeDefined()
// Active badge (requestingUserReacted = true) has primary border/bg style
expect(thumbsUpBadge?.className).toContain('border-primary/40')
expect(thumbsUpBadge?.className).toContain('bg-primary/10')
// Inactive badge (requestingUserReacted = false) has border-border/60 style
expect(heartBadge?.className).toContain('border-border/60')
// Both badges display count with normal text color (text-foreground)
expect(screen.getByText('2').className).toContain('text-foreground')
expect(screen.getByText('1').className).toContain('text-foreground')
// Clicking thumbsUp badge (already reacted) calls DELETE reaction
fireEvent.click(thumbsUpBadge!)
await waitFor(() => {
expect(client.api.comments[':commentId'].reactions.$delete).toHaveBeenCalledWith({
param: { commentId: 'msg-reactions' },
json: { code: '👍' },
})
})
// Clicking heart badge (not yet reacted) calls POST reaction
fireEvent.click(heartBadge!)
await waitFor(() => {
expect(client.api.comments[':commentId'].reactions.$post).toHaveBeenCalledWith({
param: { commentId: 'msg-reactions' },
json: { code: '❤️' },
})
})
})
it('hides reaction picker and disables badges when readOnly is true', () => {
const mockMessage: CommentInfo = {
id: 'msg-readonly',
assetId: 'asset-1',
message: 'Read only message',
annotations: null,
second: null,
creator: { id: 'u-2', name: 'Alice' },
replies: [],
attachments: [],
mentions: [],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [
{
code: '🎉',
count: 1,
requestingUserReacted: false,
creatorNames: ['Bob'],
},
],
}
const onReply = vi.fn()
const getUser = vi.fn().mockReturnValue({ id: 'u-2', name: 'Alice' })
render(
<MessageCard message={mockMessage} getUser={getUser} onReply={onReply} readOnly={true} />,
{
wrapper: createWrapper(),
},
)
const partyBadge = screen.getByText('🎉').closest('button')
expect(partyBadge?.getAttribute('disabled')).not.toBeNull()
// Clicking does not call API
fireEvent.click(partyBadge!)
expect(client.api.comments[':commentId'].reactions.$post).not.toHaveBeenCalled()
})
})
+280 -25
View File
@@ -17,10 +17,10 @@ import {
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import type { CommentInfo, UserInfo } from '@shumai/dtos'
import type { CommentInfo, CommentReactionCount, UserInfo } from '@shumai/dtos'
import type { MemberInfo } from '@/ui/stores/members'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Download, FileText, MoreHorizontal, Trash2 } from 'lucide-react'
import { Download, FileText, MoreHorizontal, Smile, Trash2 } from 'lucide-react'
import React from 'react'
import Markdown from 'react-markdown'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
@@ -32,6 +32,7 @@ import { useUiStore } from '@/ui/stores/ui'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
import { AgentSessionLogsDialog } from '../agent/agent-session-logs-dialog'
import { isImageFileName } from '@/ui/lib/media'
import { EmojiPickerPopover } from '../ui/emoji-picker'
interface MessageCardProps {
teamId?: string
@@ -47,6 +48,8 @@ interface MessageCardProps {
startTimecode?: string
formatTimestamp?: (second: number) => string
rootParentId?: string
readOnly?: boolean
isPublic?: boolean
}
const UnfilledCircleCheck: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
@@ -93,6 +96,94 @@ const AI_PLACEHOLDERS: Record<string, string> = {
__RUNNING__: 'Generating...',
}
function formatReactionOthers(names: string[]): string {
if (names.length <= 3) return names.join(', ')
return `${names.slice(0, 3).join(', ')} and ${names.length - 3} more`
}
function getReactionTooltip(reaction: CommentReactionCount): string {
const hasOthers = reaction.creatorNames && reaction.creatorNames.length > 0
if (reaction.requestingUserReacted) {
if (!hasOthers) {
return m.reaction_you({ emoji: reaction.code })
}
return m.reaction_you_and_others({
others: formatReactionOthers(reaction.creatorNames),
emoji: reaction.code,
})
}
if (hasOthers) {
return m.reaction_others({
others: formatReactionOthers(reaction.creatorNames),
emoji: reaction.code,
})
}
return reaction.code
}
function updateCommentTreeReactions(
comments: CommentInfo[],
targetCommentId: string,
code: string,
isAdd: boolean,
): CommentInfo[] {
return comments.map((comment) => {
if (comment.id === targetCommentId) {
const existingReactions = comment.reactionCounts ? [...comment.reactionCounts] : []
const existingIndex = existingReactions.findIndex((r) => r.code === code)
if (isAdd) {
if (existingIndex >= 0) {
const existing = existingReactions[existingIndex]
if (!existing.requestingUserReacted) {
existingReactions[existingIndex] = {
...existing,
count: existing.count + 1,
requestingUserReacted: true,
}
}
} else {
existingReactions.push({
code,
count: 1,
requestingUserReacted: true,
creatorNames: [],
})
}
} else {
if (existingIndex >= 0) {
const existing = existingReactions[existingIndex]
if (existing.requestingUserReacted) {
if (existing.count <= 1) {
existingReactions.splice(existingIndex, 1)
} else {
existingReactions[existingIndex] = {
...existing,
count: existing.count - 1,
requestingUserReacted: false,
}
}
}
}
}
return {
...comment,
reactionCounts: existingReactions,
}
}
if (comment.replies && comment.replies.length > 0) {
return {
...comment,
replies: updateCommentTreeReactions(comment.replies, targetCommentId, code, isAdd),
}
}
return comment
})
}
export const MessageCard: React.FC<MessageCardProps> = ({
teamId,
message: initialMessage,
@@ -106,8 +197,11 @@ export const MessageCard: React.FC<MessageCardProps> = ({
frameRate,
startTimecode,
formatTimestamp,
readOnly,
isPublic,
}) => {
const message = initialMessage
const isReadOnly = Boolean(readOnly || isPublic)
const hasDrawInfo =
!!message.annotations && Array.isArray(message.annotations) && message.annotations.length > 0
const creator = message.creator
@@ -161,6 +255,110 @@ export const MessageCard: React.FC<MessageCardProps> = ({
},
})
const { mutate: addReaction } = useMutation({
mutationFn: async (code: string) => {
const res = await client.api.comments[':commentId'].reactions.$post({
param: { commentId: message.id },
json: { code },
})
if (!res.ok) throw new Error('Failed to add reaction')
return await res.json()
},
onMutate: async (code: string) => {
await queryClient.cancelQueries({
predicate: (query) => query.queryKey.includes('comments'),
})
const previousData = queryClient.getQueriesData({
predicate: (query) => query.queryKey.includes('comments'),
})
queryClient.setQueriesData(
{ predicate: (query) => query.queryKey.includes('comments') },
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack Query cache structure is dynamic across infinite query pages
(old: any) => {
if (!old || !old.pages) return old
return {
...old,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack Query page object
pages: old.pages.map((page: any) => ({
...page,
data: updateCommentTreeReactions(page.data || [], message.id, code, true),
})),
}
},
)
return { previousData }
},
onError: (_err, _code, context) => {
if (context?.previousData) {
for (const [queryKey, data] of context.previousData) {
queryClient.setQueryData(queryKey, data)
}
}
},
onSettled: () => {
queryClient.invalidateQueries({
predicate: (query) => query.queryKey.includes('comments'),
})
},
})
const { mutate: removeReaction } = useMutation({
mutationFn: async (code: string) => {
const res = await client.api.comments[':commentId'].reactions.$delete({
param: { commentId: message.id },
json: { code },
})
if (!res.ok) throw new Error('Failed to remove reaction')
return await res.json()
},
onMutate: async (code: string) => {
await queryClient.cancelQueries({
predicate: (query) => query.queryKey.includes('comments'),
})
const previousData = queryClient.getQueriesData({
predicate: (query) => query.queryKey.includes('comments'),
})
queryClient.setQueriesData(
{ predicate: (query) => query.queryKey.includes('comments') },
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack Query cache structure is dynamic across infinite query pages
(old: any) => {
if (!old || !old.pages) return old
return {
...old,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack Query page object
pages: old.pages.map((page: any) => ({
...page,
data: updateCommentTreeReactions(page.data || [], message.id, code, false),
})),
}
},
)
return { previousData }
},
onError: (_err, _code, context) => {
if (context?.previousData) {
for (const [queryKey, data] of context.previousData) {
queryClient.setQueryData(queryKey, data)
}
}
},
onSettled: () => {
queryClient.invalidateQueries({
predicate: (query) => query.queryKey.includes('comments'),
})
},
})
const handleToggleReaction = (code: string) => {
if (isReadOnly) return
const existing = message.reactionCounts?.find((r) => r.code === code)
if (existing?.requestingUserReacted) {
removeReaction(code)
} else {
addReaction(code)
}
}
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = React.useState(false)
const { mutate: deleteComment, isPending: isDeleting } = useMutation({
@@ -402,6 +600,44 @@ export const MessageCard: React.FC<MessageCardProps> = ({
</div>
)}
{/* Reactions */}
{message.reactionCounts && message.reactionCounts.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 mt-2">
{message.reactionCounts.map((reaction) => {
const tooltipText = getReactionTooltip(reaction)
return (
<TooltipProvider key={reaction.code}>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
disabled={isReadOnly}
onClick={(e) => {
e.stopPropagation()
handleToggleReaction(reaction.code)
}}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors select-none ${
isReadOnly ? 'cursor-default' : 'cursor-pointer'
} ${
reaction.requestingUserReacted
? 'border-primary/40 bg-primary/10 font-medium'
: 'border-border/60 bg-muted/40 hover:bg-muted'
}`}
>
<span className="text-sm leading-none">{reaction.code}</span>
<span className="text-xs font-semibold text-foreground">
{reaction.count}
</span>
</button>
</TooltipTrigger>
<TooltipContent>{tooltipText}</TooltipContent>
</Tooltip>
</TooltipProvider>
)
})}
</div>
)}
{/* Actions */}
<div className="mt-2 flex items-center justify-between w-full">
<button
@@ -411,32 +647,51 @@ export const MessageCard: React.FC<MessageCardProps> = ({
{m.reply()}
</button>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-1">
{!isReadOnly && (
<EmojiPickerPopover
onEmojiSelect={(emoji) => handleToggleReaction(emoji)}
align="end"
side="top"
>
<button
onClick={(e) => {
e.stopPropagation()
toggleComplete()
}}
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
message.isCompleted
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
}`}
type="button"
onClick={(e) => e.stopPropagation()}
className="flex items-center justify-center p-1 rounded-full text-gray-400 hover:text-foreground hover:bg-muted/80 transition-colors cursor-pointer"
title={m.add_reaction()}
>
{message.isCompleted ? (
<FilledCircleCheck className="w-5 h-5" />
) : (
<UnfilledCircleCheck className="w-5 h-5" />
)}
<Smile className="w-5 h-5" />
</button>
</TooltipTrigger>
<TooltipContent>
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</EmojiPickerPopover>
)}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={(e) => {
e.stopPropagation()
toggleComplete()
}}
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
message.isCompleted
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
}`}
>
{message.isCompleted ? (
<FilledCircleCheck className="w-5 h-5" />
) : (
<UnfilledCircleCheck className="w-5 h-5" />
)}
</button>
</TooltipTrigger>
<TooltipContent>
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</div>
</div>
@@ -37,6 +37,7 @@ describe('ChatInput auto-mention on reply', () => {
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [],
}
const onSendMessage = vi.fn()
@@ -81,6 +82,7 @@ describe('ChatInput auto-mention on reply', () => {
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [],
}
const onSendMessage = vi.fn()
@@ -115,6 +117,7 @@ describe('ChatInput auto-mention on reply', () => {
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [],
}
const commentBob: CommentInfo = {
@@ -132,6 +135,7 @@ describe('ChatInput auto-mention on reply', () => {
sessionId: null,
isCompleted: false,
completionLastChangedBy: null,
reactionCounts: [],
}
const onSendMessage = vi.fn()
@@ -429,6 +429,8 @@ export function FileViewerRightSidebar({
onSelect={() => {
onCommentSelect?.(comment)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
{comment.replies?.map((reply, index) => (
<div key={reply.id}>
@@ -455,6 +457,8 @@ export function FileViewerRightSidebar({
onSelect={() => {
onCommentSelect?.(reply)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
</div>
))}
@@ -395,6 +395,8 @@ export function MobileFileBottomSheet({
onSelect={() => {
onCommentSelect?.(comment)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
{comment.replies?.map((reply, index) => (
<div key={reply.id}>
@@ -421,6 +423,8 @@ export function MobileFileBottomSheet({
onSelect={() => {
onCommentSelect?.(reply)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
</div>
))}
@@ -0,0 +1,80 @@
import * as React from 'react'
import { EmojiPicker } from '@ferrucc-io/emoji-picker'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { m } from '@/ui/paraglide/messages.js'
import { cn } from '@/ui/lib/utils'
export interface EmojiPickerPopoverProps {
onEmojiSelect: (emoji: string) => void
children: React.ReactNode
align?: 'start' | 'center' | 'end'
side?: 'top' | 'right' | 'bottom' | 'left'
sideOffset?: number
className?: string
open?: boolean
onOpenChange?: (open: boolean) => void
}
export function EmojiPickerPopover({
onEmojiSelect,
children,
align = 'end',
side = 'top',
sideOffset = 4,
className,
open: controlledOpen,
onOpenChange: setControlledOpen,
}: EmojiPickerPopoverProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false)
const isControlled = controlledOpen !== undefined
const open = isControlled ? controlledOpen : uncontrolledOpen
const handleOpenChange = React.useCallback(
(nextOpen: boolean) => {
if (!isControlled) {
setUncontrolledOpen(nextOpen)
}
setControlledOpen?.(nextOpen)
},
[isControlled, setControlledOpen],
)
const handleSelect = React.useCallback(
(emoji: string) => {
onEmojiSelect(emoji)
handleOpenChange(false)
},
[onEmojiSelect, handleOpenChange],
)
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>{children}</PopoverTrigger>
<PopoverContent
align={align}
side={side}
sideOffset={sideOffset}
className={cn('w-auto p-0 border-border bg-popover shadow-lg overflow-hidden', className)}
onClick={(e) => e.stopPropagation()}
>
<EmojiPicker
onEmojiSelect={handleSelect}
emojisPerRow={9}
emojiSize={28}
className="border-none w-[320px] bg-popover"
>
<EmojiPicker.Header className="p-2 pb-1">
<EmojiPicker.Input
placeholder={m.search_emoji()}
autoFocus={true}
className="h-8 w-full rounded-md border border-input bg-background pl-8 pr-7 py-1 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
/>
</EmojiPicker.Header>
<EmojiPicker.Group>
<EmojiPicker.List containerHeight={280} />
</EmojiPicker.Group>
</EmojiPicker>
</PopoverContent>
</Popover>
)
}