chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,275 @@
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Fragment } from 'react'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createConsoleQueryClient, seedSystemFeatures } from '@/test/console/query-data'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
import { useWorkflowComment } from '../../hooks/use-workflow-comment'
import { useStore } from '../../store'
import { CommentIcon } from '../comment-icon'
import { CommentThread } from '../thread'
const mockFetchComments = vi.hoisted(() => vi.fn())
const mockFetchComment = vi.hoisted(() => vi.fn())
const mockUpdateComment = vi.hoisted(() => vi.fn())
vi.mock('@/hooks/use-format-time-from-now', () => ({
useFormatTimeFromNow: () => ({ formatTimeFromNow: () => 'just now' }),
}))
vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', () => ({
collaborationManager: {
onCommentsUpdate: () => () => {},
emitCommentsUpdate: vi.fn(),
},
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'apps.byAppId.workflow.comments.get': mockFetchComments,
'apps.byAppId.workflow.comments.byCommentId.get': mockFetchComment,
'apps.byAppId.workflow.comments.byCommentId.put': mockUpdateComment,
}),
}
})
const comment: WorkflowCommentBasic = {
id: 'comment-1',
position_x: 10,
position_y: 20,
content: 'Check this workflow',
created_by: 'user-1',
created_by_account: {
id: 'user-1',
name: 'Alice',
email: 'alice@example.com',
avatar_url: null,
},
created_at: 100,
updated_at: 100,
resolved: false,
mention_count: 0,
reply_count: 0,
participants: [],
}
function CommentCanvas() {
const showUserComments = useStore((state) => state.showUserComments)
const {
comments,
activeComment,
activeCommentLoading,
handleCommentIconClick,
handleActiveCommentClose,
handleCommentReply,
handleCommentPositionUpdate,
handleCommentNavigate,
} = useWorkflowComment()
return (
<div id="workflow-container">
{comments.map((item, index) => {
// Match Workflow's active/inactive branches: opening and closing rebuild the marker.
if (activeComment?.id === item.id) {
return (
<Fragment key={item.id}>
<CommentIcon
key={`${item.id}-icon`}
comment={item}
onClick={() => handleCommentIconClick(item)}
isActive
onPositionUpdate={(position) => handleCommentPositionUpdate(item.id, position)}
/>
<CommentThread
key={`${item.id}-thread`}
comment={activeComment}
loading={activeCommentLoading}
onClose={handleActiveCommentClose}
onReply={(content, ids) => handleCommentReply(item.id, content, ids)}
onPrev={index > 0 ? () => handleCommentNavigate('prev') : undefined}
onNext={
index < comments.length - 1 ? () => handleCommentNavigate('next') : undefined
}
canGoPrev={index > 0}
canGoNext={index < comments.length - 1}
/>
</Fragment>
)
}
return showUserComments ? (
<CommentIcon
key={item.id}
comment={item}
onClick={() => handleCommentIconClick(item)}
onPositionUpdate={(position) => handleCommentPositionUpdate(item.id, position)}
/>
) : null
})}
</div>
)
}
function renderCommentCanvas(comments = [comment]) {
mockFetchComments.mockResolvedValue({ data: comments })
mockFetchComment.mockImplementation(({ params }: { params: { comment_id: string } }) =>
Promise.resolve({
...comments.find((item) => item.id === params.comment_id),
mentions: [],
replies: [],
}),
)
const queryClient = createConsoleQueryClient()
seedAccountProfileQuery(queryClient, { id: 'user-1', name: 'Alice' })
seedSystemFeatures(queryClient, { enable_collaboration_mode: true })
return renderWorkflowFlowComponent(<CommentCanvas />, {
queryClient,
initialStoreState: {
comments,
showUserComments: true,
mentionableUsersCache: { 'app-1': [] },
},
})
}
describe('Comment keyboard focus lifecycle', () => {
beforeEach(() => {
vi.clearAllMocks()
mockUpdateComment.mockResolvedValue({})
})
it.each([
{ open: 'Enter', key: '{Enter}', close: 'Escape' },
{ open: 'Space', key: ' ', close: 'Escape' },
{ open: 'Enter', key: '{Enter}', close: 'close button' },
])(
'restores the current marker after $open and $close, so arrow keys still move it',
async ({ key, close }) => {
const user = userEvent.setup()
renderCommentCanvas()
screen.getByRole('button', { name: /keyboard.openComment/ }).focus()
expect(screen.getByRole('button', { name: /keyboard.openComment/ })).toHaveFocus()
await user.keyboard(key)
const reply = await screen.findByRole('textbox')
await waitFor(() => expect(reply).toHaveFocus())
if (close === 'Escape') {
await user.keyboard('{Escape}')
} else {
await user.tab({ shift: true })
await user.tab({ shift: true })
expect(screen.getByRole('button', { name: /comments.aria.closeComment/ })).toHaveFocus()
await user.keyboard('{Enter}')
}
await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument())
await waitFor(() => {
expect(screen.getByRole('button', { name: /keyboard.openComment/ })).toHaveFocus()
})
await user.keyboard('{ArrowRight}')
await waitFor(() => {
expect(mockUpdateComment).toHaveBeenCalledWith({
params: { app_id: 'app-1', comment_id: comment.id },
body: { content: comment.content, position_x: 15, position_y: 20 },
})
})
},
)
it.each(['actions menu', 'mention suggestions'] as const)(
'closes %s before the thread and restores its marker on the next Escape',
async (surface) => {
const user = userEvent.setup()
const { store } = renderCommentCanvas()
act(() => {
store
.getState()
.setMentionableUsersCache('app-1', [
{ id: 'user-2', name: 'Bob', email: 'bob@example.com', avatar_url: null },
])
})
screen.getByRole('button', { name: /keyboard.openComment/ }).focus()
await user.keyboard('{Enter}')
const reply = await screen.findByRole('textbox')
await waitFor(() => expect(reply).toHaveFocus())
const commentActions = screen.getByRole('button', { name: /comments.aria.commentActions/ })
if (surface === 'actions menu') {
await user.click(commentActions)
expect(await screen.findByRole('menu')).toBeInTheDocument()
} else {
await user.type(reply, '@Bo')
expect(await screen.findByText('bob@example.com')).toBeInTheDocument()
}
await user.keyboard('{Escape}')
await waitFor(() => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
expect(screen.queryByText('bob@example.com')).not.toBeInTheDocument()
})
expect(screen.getByRole('dialog')).toBeInTheDocument()
await waitFor(() => {
expect(surface === 'actions menu' ? commentActions : reply).toHaveFocus()
})
await user.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: /keyboard.openComment/ })).toHaveFocus()
},
)
it('restores the last viewed comment marker after navigating to another thread', async () => {
const user = userEvent.setup()
const otherComment: WorkflowCommentBasic = {
...comment,
id: 'comment-2',
content: 'Another comment',
created_by: 'user-2',
created_by_account: {
id: 'user-2',
name: 'Bob',
email: 'bob@example.com',
avatar_url: null,
},
}
renderCommentCanvas([comment, otherComment])
screen.getAllByRole('button', { name: /keyboard.openComment/ })[0]!.focus()
await user.keyboard('{Enter}')
await waitFor(() => expect(screen.getByRole('textbox')).toHaveFocus())
await user.tab({ shift: true })
await user.tab({ shift: true })
await user.tab({ shift: true })
expect(screen.getByRole('button', { name: /comments.aria.nextComment/ })).toHaveFocus()
await user.keyboard('{Enter}')
await waitFor(() => expect(screen.getByRole('textbox')).toHaveFocus())
expect(screen.getByText(otherComment.content)).toBeInTheDocument()
await user.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: /keyboard.openComment.*Bob/ })).toHaveFocus()
})
it('closes safely when comment markers have been hidden', async () => {
const user = userEvent.setup()
const { store } = renderCommentCanvas()
screen.getAllByRole('button', { name: /keyboard.openComment/ })[0]!.focus()
await user.keyboard('{Enter}')
const reply = await screen.findByRole('textbox')
await waitFor(() => expect(reply).toHaveFocus())
act(() => store.getState().setShowUserComments(false))
await user.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument())
expect(screen.queryByRole('button', { name: /keyboard.openComment/ })).not.toBeInTheDocument()
})
})
@@ -0,0 +1,275 @@
import type {
WorkflowCommentBasic,
WorkflowCommentDetail,
} from '@dify/contracts/api/console/apps/types.gen'
import type { UserProfile } from '../types'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
import { CommentIcon } from '../comment-icon'
import { CommentInput } from '../comment-input'
import { CommentThread } from '../thread'
let mentionableUsers: UserProfile[] = []
const renderWithAccountProfile = (ui: Parameters<typeof renderWorkflowFlowComponent>[0]) => {
const { queryClient } = createConsoleQueryWrapper({ accountProfile: { id: 'user-1' } })
return renderWorkflowFlowComponent(ui, {
queryClient,
initialStoreState: { mentionableUsersCache: { 'app-1': mentionableUsers } },
})
}
const createComment = (): WorkflowCommentDetail & WorkflowCommentBasic => ({
id: 'comment-1',
position_x: 120,
position_y: 80,
content: 'Move this comment',
created_by: 'user-1',
created_by_account: {
id: 'user-1',
name: 'Alice',
email: 'alice@example.com',
avatar_url: null,
},
created_at: 1,
updated_at: 2,
resolved: false,
mentions: [],
replies: [],
mention_count: 0,
reply_count: 0,
participants: [],
})
describe('Comment thread focus', () => {
beforeEach(() => {
vi.clearAllMocks()
mentionableUsers = []
vi.useFakeTimers({ shouldAdvanceTime: true })
})
afterEach(() => {
vi.useRealTimers()
})
it.each(['draft', 'thread'] as const)(
'dismisses mentions before closing the %s',
async (kind) => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onClose = vi.fn()
mentionableUsers = [{ id: 'user-2', name: 'Bob', email: 'bob@example.com', avatar_url: null }]
renderWithAccountProfile(
kind === 'draft' ? (
<CommentInput position={{ x: 0, y: 0 }} onSubmit={() => {}} onCancel={onClose} />
) : (
<CommentThread comment={createComment()} onClose={onClose} onReply={() => {}} />
),
)
await user.click(screen.getByRole('textbox'))
await user.type(screen.getByRole('textbox'), '@')
expect(screen.getByText('Bob')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(screen.queryByText('Bob')).not.toBeInTheDocument()
expect(onClose).not.toHaveBeenCalled()
await user.keyboard('{Escape}')
expect(onClose).toHaveBeenCalledTimes(1)
},
)
it('keeps focus on the marker after saving a keyboard move with its thread open', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onPositionUpdate = vi.fn()
function Comment() {
const [comment, setComment] = useState(createComment)
const [opened, setOpened] = useState(false)
return (
<div id="workflow-container">
<CommentIcon
comment={comment}
isActive={opened}
onClick={() => setOpened(true)}
onPositionUpdate={(position) => {
onPositionUpdate(position)
setComment((current) => ({
...current,
position_x: position.x,
position_y: position.y,
}))
}}
/>
{opened && (
<CommentThread comment={comment} onClose={() => setOpened(false)} onReply={() => {}} />
)}
</div>
)
}
renderWithAccountProfile(<Comment />)
const marker = screen.getByRole('button', { name: /workflow.keyboard.openComment/ })
act(() => marker.focus())
await user.keyboard('{Enter}')
await act(() => vi.advanceTimersByTimeAsync(100))
expect(screen.getByRole('textbox')).toHaveFocus()
expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-modal', 'true')
act(() => marker.focus())
await user.keyboard('{ArrowRight}')
expect(onPositionUpdate).toHaveBeenLastCalledWith({ x: 125, y: 80 })
await act(() => vi.advanceTimersByTimeAsync(100))
expect(marker).toHaveFocus()
await user.keyboard('{ArrowDown}')
expect(onPositionUpdate).toHaveBeenLastCalledWith({ x: 125, y: 85 })
expect(onPositionUpdate).toHaveBeenCalledTimes(2)
})
it('confirms reply deletion outside the menu and restores focus when cancelled', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onDelete = vi.fn()
const onClose = vi.fn()
const comment = createComment()
comment.replies = [
{
id: 'reply-1',
content: 'A reply',
created_at: 2,
created_by: 'user-1',
created_by_account: comment.created_by_account,
},
]
renderWithAccountProfile(
<CommentThread
comment={comment}
onClose={onClose}
onReply={() => {}}
onReplyEdit={() => {}}
onReplyDeleteDirect={onDelete}
/>,
)
await act(() => vi.advanceTimersByTimeAsync(100))
const trigger = screen.getByRole('button', {
name: 'workflowComments.comments.aria.replyActions',
})
await user.click(trigger)
const deleteItem = screen.getByRole('menuitem', {
name: 'workflowComments.comments.actions.deleteReply',
})
await user.click(deleteItem)
const confirm = await screen.findByRole('alertdialog', {
name: 'workflowComments.comments.actions.deleteReply',
})
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
expect(onDelete).not.toHaveBeenCalled()
await user.click(within(confirm).getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(trigger).toHaveFocus())
expect(onClose).not.toHaveBeenCalled()
await user.click(trigger)
await user.click(
await screen.findByRole('menuitem', {
name: 'workflowComments.comments.actions.deleteReply',
}),
)
const reopened = await screen.findByRole('alertdialog')
await user.click(within(reopened).getByRole('button', { name: 'common.operation.delete' }))
expect(onDelete).toHaveBeenCalledExactlyOnceWith('reply-1')
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(onClose).not.toHaveBeenCalled()
})
it('keeps reply deletion pending until the reply disappears, then focuses the reply input', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onDelete = vi.fn()
let finishDeletion!: () => void
const deletion = new Promise<void>((resolve) => {
finishDeletion = resolve
})
const initial = createComment()
initial.replies = [
{
id: 'reply-1',
content: 'A reply',
created_at: 2,
created_by: 'user-1',
created_by_account: initial.created_by_account,
},
]
function Thread() {
const [comment, setComment] = useState(initial)
const [loading, setLoading] = useState(false)
return (
<CommentThread
comment={comment}
loading={loading}
onClose={() => {}}
onReply={() => {}}
onReplyEdit={() => {}}
onReplyDeleteDirect={async (id) => {
setLoading(true)
onDelete(id)
await deletion
setComment({ ...initial, replies: [] })
setLoading(false)
}}
/>
)
}
renderWithAccountProfile(<Thread />)
await act(() => vi.advanceTimersByTimeAsync(100))
await user.click(
screen.getByRole('button', { name: 'workflowComments.comments.aria.replyActions' }),
)
await user.click(
screen.getByRole('menuitem', { name: 'workflowComments.comments.actions.deleteReply' }),
)
const dialog = await screen.findByRole('alertdialog')
const confirm = within(dialog).getByRole('button', { name: 'common.operation.delete' })
await user.click(confirm)
await waitFor(() => expect(confirm).toHaveAttribute('aria-disabled', 'true'))
expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
await user.click(confirm)
await user.keyboard('{Escape}')
expect(dialog).toBeInTheDocument()
expect(onDelete).toHaveBeenCalledExactlyOnceWith('reply-1')
await act(async () => finishDeletion())
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(
screen.queryByRole('button', { name: 'workflowComments.comments.aria.replyActions' }),
).not.toBeInTheDocument()
await waitFor(() => expect(screen.getByRole('textbox')).toHaveFocus())
})
it('focuses the reply input when navigating to another comment', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onReply = vi.fn()
function Comments() {
const [comment, setComment] = useState(createComment)
return (
<CommentThread
comment={comment}
onClose={() => {}}
onReply={onReply}
canGoNext
onNext={() => setComment((current) => ({ ...current, id: 'comment-2' }))}
/>
)
}
renderWithAccountProfile(<Comments />)
await act(() => vi.advanceTimersByTimeAsync(100))
const replyInput = screen.getByRole('textbox')
expect(replyInput).toHaveFocus()
await user.click(
screen.getByRole('button', { name: 'workflowComments.comments.aria.nextComment' }),
)
await act(() => vi.advanceTimersByTimeAsync(100))
expect(replyInput).toHaveFocus()
})
})
@@ -0,0 +1,151 @@
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import type { ReactElement } from 'react'
import { fireEvent, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { describe, expect, it, vi } from 'vite-plus/test'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { CommentIcon } from './comment-icon'
const render = (ui: ReactElement, userId = 'user-1') => {
const { queryClient } = createConsoleQueryWrapper({
accountProfile: { id: userId, name: 'User', avatar_url: 'avatar' },
})
return renderWorkflowFlowComponent(ui, {
queryClient,
reactFlowProps: {
proOptions: { hideAttribution: true },
fitView: false,
defaultViewport: { x: 50, y: 30, zoom: 2 },
},
})
}
const createComment = (overrides: Partial<WorkflowCommentBasic> = {}): WorkflowCommentBasic => ({
id: 'comment-1',
position_x: 0,
position_y: 0,
content: 'Hello',
created_by: 'user-1',
created_by_account: {
id: 'user-1',
name: 'Alice',
email: 'alice@example.com',
avatar_url: null,
},
created_at: 1,
updated_at: 2,
resolved: false,
mention_count: 0,
reply_count: 0,
participants: [],
...overrides,
})
describe('CommentIcon', () => {
it('opens with the keyboard and moves an authored comment in canvas coordinates', async () => {
const user = userEvent.setup()
const onClick = vi.fn()
const onPositionUpdate = vi.fn()
function Comment() {
const [comment, setComment] = useState(() => createComment())
return (
<CommentIcon
comment={comment}
onClick={onClick}
onPositionUpdate={(position) => {
onPositionUpdate(position)
setComment((current) => ({
...current,
position_x: position.x,
position_y: position.y,
}))
}}
/>
)
}
render(<Comment />)
await user.tab()
const marker = screen.getByRole('button', { name: /workflow.keyboard.openComment/ })
expect(marker).toHaveFocus()
await user.keyboard('{Enter}')
expect(onClick).toHaveBeenCalledTimes(1)
await user.keyboard('{ArrowRight}{Shift>}{ArrowDown}{/Shift}')
expect(onPositionUpdate).toHaveBeenLastCalledWith({ x: 5, y: 20 })
expect(marker).toHaveFocus()
onPositionUpdate.mockClear()
await user.keyboard('{ArrowRight>3}')
expect(onPositionUpdate).not.toHaveBeenCalled()
await user.keyboard('{/ArrowRight}')
expect(onPositionUpdate).toHaveBeenCalledExactlyOnceWith({ x: 20, y: 20 })
})
it("allows opening another author's comment but does not move it with arrow keys", async () => {
const user = userEvent.setup()
const onClick = vi.fn()
const onPositionUpdate = vi.fn()
render(
<CommentIcon
comment={createComment()}
onClick={onClick}
onPositionUpdate={onPositionUpdate}
/>,
'user-2',
)
await user.tab()
await user.keyboard('{ArrowRight}{Enter}')
expect(onPositionUpdate).not.toHaveBeenCalled()
expect(onClick).toHaveBeenCalledTimes(1)
})
it('toggles preview on hover when inactive', async () => {
const user = userEvent.setup()
const comment = createComment()
render(<CommentIcon comment={comment} onClick={vi.fn()} isActive={false} />)
const marker = screen.getByRole('button', { name: /workflow.keyboard.openComment/ })
await user.hover(within(marker).getByRole('img', { name: 'Alice' }))
expect(screen.getByText('Hello')).toBeInTheDocument()
await user.unhover(within(marker).getByRole('img', { name: 'Alice' }))
expect(screen.queryByText('Hello')).not.toBeInTheDocument()
})
it('converts pointer movement through the zoomed canvas before saving the authored position', () => {
const comment = createComment({ position_x: 0, position_y: 0 })
const onClick = vi.fn()
const onPositionUpdate = vi.fn()
render(<CommentIcon comment={comment} onClick={onClick} onPositionUpdate={onPositionUpdate} />)
const marker = screen.getByRole('button', { name: /workflow.keyboard.openComment/ })
fireEvent.pointerDown(marker, {
pointerId: 1,
button: 0,
clientX: 100,
clientY: 100,
})
fireEvent.pointerMove(marker, {
pointerId: 1,
clientX: 110,
clientY: 110,
})
fireEvent.pointerUp(marker, {
pointerId: 1,
clientX: 110,
clientY: 110,
})
expect(onPositionUpdate).toHaveBeenCalledExactlyOnceWith({ x: 5, y: 5 })
expect(onClick).not.toHaveBeenCalled()
})
it('opens another author’s comment with a click', async () => {
const user = userEvent.setup()
const onClick = vi.fn()
render(<CommentIcon comment={createComment()} onClick={onClick} isActive={false} />, 'user-2')
await user.click(screen.getByRole('button', { name: /workflow.keyboard.openComment/ }))
expect(onClick).toHaveBeenCalledExactlyOnceWith()
})
})
@@ -0,0 +1,354 @@
'use client'
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import type { FC, PointerEvent as ReactPointerEvent } from 'react'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useSuspenseQuery } from '@tanstack/react-query'
import { memo, useCallback, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useReactFlow, useViewport } from 'reactflow'
import { UserAvatarList } from '@/app/components/base/user-avatar-list'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { getKeyboardMovement } from '../utils/keyboard-movement'
import CommentPreview from './comment-preview'
type CommentIconProps = {
comment: WorkflowCommentBasic
onClick: () => void
isActive?: boolean
onPositionUpdate?: (position: { x: number; y: number }) => void
}
export const CommentIcon: FC<CommentIconProps> = memo(
({ comment, onClick, isActive = false, onPositionUpdate }) => {
const { t } = useTranslation(['workflow'])
const descriptionId = useId()
const { flowToScreenPosition, screenToFlowPosition } = useReactFlow()
const viewport = useViewport()
const { data: currentUserId } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.id,
})
const isAuthor = comment.created_by_account?.id === currentUserId
const [showPreview, setShowPreview] = useState(false)
const [dragPosition, setDragPosition] = useState<{ x: number; y: number } | null>(null)
const [isDragging, setIsDragging] = useState(false)
const keyboardPositionRef = useRef<{ x: number; y: number } | null>(null)
const finishKeyboardMove = useCallback(() => {
const position = keyboardPositionRef.current
if (!position) return
keyboardPositionRef.current = null
setDragPosition(null)
onPositionUpdate?.(position)
}, [onPositionUpdate])
const dragStateRef = useRef<{
offsetX: number
offsetY: number
startX: number
startY: number
hasMoved: boolean
} | null>(null)
const workflowContainerRect =
typeof document !== 'undefined'
? document.getElementById('workflow-container')?.getBoundingClientRect()
: null
const containerLeft = workflowContainerRect?.left ?? 0
const containerTop = workflowContainerRect?.top ?? 0
const screenPosition = useMemo(() => {
return flowToScreenPosition({
x: comment.position_x,
y: comment.position_y,
})
}, [
comment.position_x,
comment.position_y,
viewport.x,
viewport.y,
viewport.zoom,
flowToScreenPosition,
])
const effectiveScreenPosition = dragPosition ?? screenPosition
const canvasPosition = useMemo(
() => ({
x: effectiveScreenPosition.x - containerLeft,
y: effectiveScreenPosition.y - containerTop,
}),
[effectiveScreenPosition.x, effectiveScreenPosition.y, containerLeft, containerTop],
)
const cursorClass = useMemo(() => {
if (!isAuthor) return 'cursor-pointer'
if (isActive) return isDragging ? 'cursor-grabbing' : ''
return isDragging ? 'cursor-grabbing' : 'cursor-pointer'
}, [isActive, isAuthor, isDragging])
const handlePointerDown = useCallback(
(event: ReactPointerEvent<HTMLElement>) => {
if (event.button !== 0) return
event.stopPropagation()
event.preventDefault()
if (!isAuthor) {
if (event.currentTarget.dataset.role !== 'comment-preview') setShowPreview(false)
return
}
dragStateRef.current = {
offsetX: event.clientX - screenPosition.x,
offsetY: event.clientY - screenPosition.y,
startX: event.clientX,
startY: event.clientY,
hasMoved: false,
}
setDragPosition(screenPosition)
setIsDragging(false)
if (event.currentTarget.dataset.role !== 'comment-preview') setShowPreview(false)
if (event.currentTarget.setPointerCapture)
event.currentTarget.setPointerCapture(event.pointerId)
},
[isAuthor, screenPosition],
)
const handlePointerMove = useCallback((event: ReactPointerEvent<HTMLElement>) => {
const dragState = dragStateRef.current
if (!dragState) return
event.stopPropagation()
event.preventDefault()
const nextX = event.clientX - dragState.offsetX
const nextY = event.clientY - dragState.offsetY
if (!dragState.hasMoved) {
const distance = Math.hypot(
event.clientX - dragState.startX,
event.clientY - dragState.startY,
)
if (distance > 4) {
dragState.hasMoved = true
setIsDragging(true)
}
}
setDragPosition({ x: nextX, y: nextY })
}, [])
const finishDrag = useCallback((event: ReactPointerEvent<HTMLElement>) => {
const dragState = dragStateRef.current
if (!dragState) return false
if (event.currentTarget.hasPointerCapture?.(event.pointerId))
event.currentTarget.releasePointerCapture(event.pointerId)
dragStateRef.current = null
setDragPosition(null)
setIsDragging(false)
return dragState.hasMoved
}, [])
const handlePointerUp = useCallback(
(event: ReactPointerEvent<HTMLElement>) => {
event.stopPropagation()
event.preventDefault()
const finalScreenPosition = dragPosition ?? screenPosition
const didDrag = finishDrag(event)
setShowPreview(false)
if (didDrag) {
if (onPositionUpdate) {
const flowPosition = screenToFlowPosition({
x: finalScreenPosition.x,
y: finalScreenPosition.y,
})
onPositionUpdate(flowPosition)
}
} else if (!isActive) {
onClick()
}
},
[
dragPosition,
finishDrag,
isActive,
onClick,
onPositionUpdate,
screenPosition,
screenToFlowPosition,
],
)
const handlePointerCancel = useCallback(
(event: ReactPointerEvent<HTMLElement>) => {
event.stopPropagation()
event.preventDefault()
finishDrag(event)
},
[finishDrag],
)
const handleMouseEnter = useCallback(() => {
if (isActive || isDragging) return
setShowPreview(true)
}, [isActive, isDragging])
const handleMouseLeave = useCallback(() => {
setShowPreview(false)
}, [])
const participants = useMemo(() => {
const list = comment.participants ?? []
const author = comment.created_by_account
if (!author) return [...list]
const rest = list.filter((user) => user.id !== author.id)
return [author, ...rest]
}, [comment.created_by_account, comment.participants])
// Calculate dynamic width based on number of participants
const participantCount = participants.length
const maxVisible = Math.min(3, participantCount)
const showCount = participantCount > 3
const avatarSize = 24
const avatarSpacing = 4 // -space-x-1 is about 4px overlap
// Width calculation: first avatar + (additional avatars * (size - spacing)) + padding
const dynamicWidth = Math.max(
40, // minimum width
8 +
avatarSize +
Math.max(0, showCount ? 2 : maxVisible - 1) * (avatarSize - avatarSpacing) +
8,
)
const pointerEventHandlers = useMemo(
() => ({
onPointerDown: handlePointerDown,
onPointerMove: handlePointerMove,
onPointerUp: handlePointerUp,
onPointerCancel: handlePointerCancel,
}),
[handlePointerCancel, handlePointerDown, handlePointerMove, handlePointerUp],
)
return (
<>
<IconButton
aria-label={t(($) => $['keyboard.openComment'], {
name: comment.created_by_account?.name ?? '',
})}
aria-describedby={isAuthor && onPositionUpdate ? descriptionId : undefined}
className="nokey absolute z-10 h-auto w-auto border-0 bg-transparent p-0"
style={{
left: canvasPosition.x,
top: canvasPosition.y,
transform: 'translate(-50%, -50%)',
}}
data-role="comment-marker"
id={`workflow-comment-marker-${comment.id}`}
{...pointerEventHandlers}
onClick={(event) => {
if (event.detail === 0 && !isActive) {
finishKeyboardMove()
onClick()
}
}}
onBlur={finishKeyboardMove}
onKeyUp={(event) => {
if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key))
finishKeyboardMove()
}}
onKeyDown={(event) => {
const delta = getKeyboardMovement(event)
if (!delta || !isAuthor || !onPositionUpdate) return
event.preventDefault()
event.stopPropagation()
const current = keyboardPositionRef.current ?? {
x: comment.position_x,
y: comment.position_y,
}
const next = { x: current.x + delta.x, y: current.y + delta.y }
keyboardPositionRef.current = next
setDragPosition(flowToScreenPosition(next))
}}
>
<div
className={cursorClass}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<div
className="relative h-10 rounded-t-full rounded-br-full"
style={{ width: dynamicWidth }}
>
<div
className={`absolute inset-1.5 overflow-hidden rounded-tl-full rounded-tr-full rounded-br-full border bg-components-panel-bg transition-shadow ${
isActive
? 'border-primary-500 ring-1 ring-primary-500'
: 'border-components-panel-border'
}`}
>
<div className="flex size-full items-center justify-center px-1">
<UserAvatarList
users={participants}
maxVisible={3}
size="sm"
className="translate-y-[-1.5px]"
/>
</div>
</div>
</div>
</div>
</IconButton>
{isAuthor && onPositionUpdate && (
<span id={descriptionId} className="sr-only" aria-live="polite">
{t(($) => $['keyboard.moveHelp'])}{' '}
{t(($) => $['keyboard.position'], { x: comment.position_x, y: comment.position_y })}
</span>
)}
{/* Preview panel */}
{showPreview && !isActive && (
<div
className="absolute z-20"
style={{
left: effectiveScreenPosition.x - containerLeft - dynamicWidth / 2,
top: effectiveScreenPosition.y - containerTop + 20,
transform: 'translateY(-100%)',
}}
data-role="comment-preview"
{...pointerEventHandlers}
onMouseEnter={() => setShowPreview(true)}
onMouseLeave={() => setShowPreview(false)}
>
<CommentPreview
comment={comment}
onClick={() => {
setShowPreview(false)
onClick()
}}
/>
</div>
)}
</>
)
},
(prevProps, nextProps) => {
return (
prevProps.comment.id === nextProps.comment.id &&
prevProps.comment.position_x === nextProps.comment.position_x &&
prevProps.comment.position_y === nextProps.comment.position_y &&
prevProps.onClick === nextProps.onClick &&
prevProps.isActive === nextProps.isActive &&
prevProps.onPositionUpdate === nextProps.onPositionUpdate
)
},
)
CommentIcon.displayName = 'CommentIcon'
@@ -0,0 +1,108 @@
import type { ReactElement } from 'react'
import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { describe, expect, it, vi } from 'vite-plus/test'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createConsoleQueryClient } from '@/test/console/query-data'
import { renderWorkflowComponent } from '../__tests__/workflow-test-env'
import { CommentInput } from './comment-input'
const mockConsoleState = vi.hoisted(() => ({
userProfile: {
id: 'user-1',
name: 'Alice',
avatar_url: 'avatar',
},
}))
const render = (ui: ReactElement) => {
const queryClient = createConsoleQueryClient()
seedAccountProfileQuery(queryClient, mockConsoleState.userProfile)
return renderWorkflowComponent(ui, {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
queryClient,
initialStoreState: {
mentionableUsersCache: {
'app-1': [{ id: 'user-2', name: 'Bob', email: 'bob@example.com', avatar_url: '' }],
},
},
})
}
describe('CommentInput', () => {
it('moves the draft using a focused handle and finishes moving with Enter', async () => {
const user = userEvent.setup()
const onPositionChange = vi.fn()
function Draft() {
const [position, setPosition] = useState({ x: 100, y: 100 })
return (
<CommentInput
autoFocus={false}
position={position}
onCancel={vi.fn()}
onSubmit={vi.fn()}
onPositionChange={(next) => {
onPositionChange(next)
setPosition({ x: next.elementX, y: next.elementY })
}}
/>
)
}
render(<Draft />)
const handle = screen.getByRole('button', { name: 'workflow.keyboard.moveDraftComment' })
handle.focus()
await user.keyboard('{Enter}{ArrowRight}{Shift>}{ArrowDown}{/Shift}')
expect(onPositionChange).toHaveBeenLastCalledWith(
expect.objectContaining({ elementX: 105, elementY: 120 }),
)
expect(handle).toHaveAttribute('aria-pressed', 'true')
await user.keyboard('{Enter}{ArrowRight}')
expect(handle).toHaveAttribute('aria-pressed', 'false')
expect(onPositionChange).toHaveBeenCalledTimes(2)
await user.tab()
expect(screen.getByRole('textbox')).toHaveFocus()
})
it('does not offer keyboard movement while disabled', () => {
render(
<CommentInput
position={{ x: 0, y: 0 }}
onCancel={vi.fn()}
onSubmit={vi.fn()}
onPositionChange={vi.fn()}
disabled
/>,
)
expect(
screen.getByRole('button', { name: 'workflow.keyboard.moveDraftComment' }),
).toBeDisabled()
})
it('calls onCancel when Escape is pressed', () => {
const onCancel = vi.fn()
render(<CommentInput position={{ x: 0, y: 0 }} onSubmit={vi.fn()} onCancel={onCancel} />)
fireEvent.keyDown(document, { key: 'Escape' })
expect(onCancel).not.toHaveBeenCalled()
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' })
expect(onCancel).toHaveBeenCalledTimes(1)
})
it('submits the real mention and clears the draft', async () => {
const onSubmit = vi.fn()
render(<CommentInput position={{ x: 0, y: 0 }} onSubmit={onSubmit} onCancel={vi.fn()} />)
const user = userEvent.setup()
await user.type(screen.getByRole('textbox'), '@Bo')
await user.click(await screen.findByText('bob@example.com'))
await user.type(screen.getByRole('textbox'), 'Hello')
await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
expect(onSubmit).toHaveBeenCalledWith('@Bob Hello', ['user-2'])
expect(screen.getByRole('textbox')).toHaveValue('')
})
})
@@ -0,0 +1,216 @@
import type { FC, PointerEvent as ReactPointerEvent } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useSuspenseQuery } from '@tanstack/react-query'
import { memo, useCallback, useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { getAvatarInitial } from '@/utils/avatar'
import { getKeyboardMovement } from '../utils/keyboard-movement'
import { MentionInput } from './mention-input'
type CommentInputProps = {
position: { x: number; y: number }
onSubmit: (content: string, mentionedUserIds: string[]) => void
onCancel: () => void
autoFocus?: boolean
disabled?: boolean
onPositionChange?: (position: {
pageX: number
pageY: number
elementX: number
elementY: number
}) => void
}
export const CommentInput: FC<CommentInputProps> = memo(
({ position, onSubmit, onCancel, autoFocus = true, disabled = false, onPositionChange }) => {
const [content, setContent] = useState('')
const [keyboardMoving, setKeyboardMoving] = useState(false)
const moveDescriptionId = useId()
const { t } = useTranslation(['workflow', 'workflowComments'])
const { data: userProfile } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile,
})
const dragStateRef = useRef<
{
pointerId: number | null
startPointerX: number
startPointerY: number
startX: number
startY: number
active: boolean
} & {
endHandler?: (event: PointerEvent) => void
}
>({
pointerId: null,
startPointerX: 0,
startPointerY: 0,
startX: 0,
startY: 0,
active: false,
endHandler: undefined,
})
const handleMentionSubmit = useCallback(
(content: string, mentionedUserIds: string[]) => {
onSubmit(content, mentionedUserIds)
setContent('')
},
[onSubmit],
)
const handleDragPointerMove = useCallback(
(event: PointerEvent) => {
const state = dragStateRef.current
if (!state.active || (state.pointerId !== null && event.pointerId !== state.pointerId))
return
if (!onPositionChange) return
event.preventDefault()
const deltaX = event.clientX - state.startPointerX
const deltaY = event.clientY - state.startPointerY
onPositionChange({
pageX: event.clientX,
pageY: event.clientY,
elementX: state.startX + deltaX,
elementY: state.startY + deltaY,
})
},
[onPositionChange],
)
const stopDragging = useCallback(
(event?: PointerEvent) => {
const state = dragStateRef.current
if (!state.active) return
if (event && state.pointerId !== null && event.pointerId !== state.pointerId) return
state.active = false
state.pointerId = null
window.removeEventListener('pointermove', handleDragPointerMove)
if (state.endHandler) {
window.removeEventListener('pointerup', state.endHandler)
window.removeEventListener('pointercancel', state.endHandler)
state.endHandler = undefined
}
},
[handleDragPointerMove],
)
const handleDragPointerDown = useCallback(
(event: ReactPointerEvent<HTMLElement>) => {
if (event.button !== 0) return
event.stopPropagation()
event.preventDefault()
if (!onPositionChange) return
const endHandler = (pointerEvent: PointerEvent) => {
stopDragging(pointerEvent)
}
dragStateRef.current = {
pointerId: event.pointerId,
startPointerX: event.clientX,
startPointerY: event.clientY,
startX: position.x,
startY: position.y,
active: true,
endHandler,
}
window.addEventListener('pointermove', handleDragPointerMove, { passive: false })
window.addEventListener('pointerup', endHandler)
window.addEventListener('pointercancel', endHandler)
},
[handleDragPointerMove, onPositionChange, position.x, position.y, stopDragging],
)
useEffect(
() => () => {
stopDragging()
},
[stopDragging],
)
return (
// oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The comment surface handles bubbling Escape after its child editor handles mentions.
<div
className={cn('absolute z-40 w-96', disabled && 'pointer-events-none opacity-80')}
style={{
left: position.x,
top: position.y,
}}
role="group"
data-comment-input
onKeyDown={(event) => {
if (event.defaultPrevented || event.nativeEvent.isComposing || event.key !== 'Escape')
return
event.preventDefault()
event.stopPropagation()
onCancel()
}}
>
<div className="flex items-center gap-3">
<IconButton
aria-label={t(($) => $['keyboard.moveDraftComment'], { ns: 'workflow' })}
aria-describedby={moveDescriptionId}
aria-pressed={keyboardMoving}
disabled={disabled || !onPositionChange}
className="relative size-8 shrink-0 cursor-move p-0"
onPointerDown={handleDragPointerDown}
onClick={(event) => {
if (event.detail === 0) setKeyboardMoving((value) => !value)
}}
onBlur={() => setKeyboardMoving(false)}
onKeyDown={(event) => {
const delta = getKeyboardMovement(event)
if (!delta || !keyboardMoving || disabled || !onPositionChange) return
event.preventDefault()
event.stopPropagation()
const rect = event.currentTarget
.closest('[data-comment-input]')
?.getBoundingClientRect()
onPositionChange({
pageX: (rect?.left ?? position.x) + delta.x,
pageY: (rect?.top ?? position.y) + delta.y,
elementX: position.x + delta.x,
elementY: position.y + delta.y,
})
}}
>
<div className="relative aspect-square h-8 w-8 shrink-0 rounded-tl-full rounded-tr-full rounded-br-full bg-primary-500 p-0.5">
<div className="flex size-full items-center justify-center overflow-hidden rounded-tl-full rounded-tr-full rounded-br-full bg-components-panel-bg-blur p-0.5">
<Avatar size="sm" className="block size-full rounded-full" aria-hidden="true">
<AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>
<AvatarImage src={userProfile.avatar_url || undefined} alt="" />
</Avatar>
</div>
</div>
</IconButton>
<span id={moveDescriptionId} className="sr-only" aria-live="polite">
{t(($) => $['keyboard.moveDraftHelp'], { ns: 'workflow' })}{' '}
{t(($) => $['keyboard.position'], { ns: 'workflow', x: position.x, y: position.y })}
</span>
<div
className={cn(
'relative z-10 flex-1 rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur pb-1 shadow-md',
)}
>
<div className="relative pt-1 pl-2.25">
<MentionInput
value={content}
onChange={setContent}
onSubmit={handleMentionSubmit}
placeholder={t(($) => $['comments.placeholder.add'], { ns: 'workflowComments' })}
autoFocus={autoFocus}
disabled={disabled}
className="relative"
/>
</div>
</div>
</div>
</div>
)
},
)
CommentInput.displayName = 'CommentInput'
@@ -0,0 +1,123 @@
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Suspense, useState } from 'react'
import ReactFlow, { ReactFlowProvider } from 'reactflow'
import { page, userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { consoleQueryKey } from '@/test/console/operation-hooks'
import { CommentIcon } from './comment-icon'
import { CommentInput } from './comment-input'
import 'reactflow/dist/style.css'
vi.mock('@/features/account-profile/client', () => ({
userProfileQueryOptions: () => ({
queryKey: consoleQueryKey('account.profile.get'),
queryFn: async () => ({ profile: { id: 'author', name: 'Alice', avatar_url: null } }),
}),
}))
vi.mock('./comment-preview', () => ({ default: () => null }))
vi.mock('./mention-input', () => ({ MentionInput: () => <textarea aria-label="Comment text" /> }))
const comment: WorkflowCommentBasic = {
id: 'comment',
content: 'Comment',
created_by: 'author',
position_x: 100,
position_y: 100,
created_by_account: { id: 'author', name: 'Alice', email: 'alice@example.com', avatar_url: null },
created_at: 1,
updated_at: 1,
resolved: false,
mention_count: 0,
reply_count: 0,
participants: [],
}
function Fixture({ draft = false }: { draft?: boolean }) {
const [queryClient] = useState(
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
)
const [current, setCurrent] = useState(comment)
const [position, setPosition] = useState({ x: 100, y: 100 })
const [opened, setOpened] = useState(false)
return (
<QueryClientProvider client={queryClient}>
<Suspense fallback={<p>Loading profile</p>}>
<ReactFlowProvider>
<button type="button">Before canvas</button>
<div
id="workflow-container"
role="group"
aria-label="Canvas"
style={{ position: 'relative', width: 800, height: 600 }}
>
{draft ? (
<CommentInput
position={position}
onSubmit={() => {}}
onCancel={() => {}}
onPositionChange={(next) => setPosition({ x: next.elementX, y: next.elementY })}
/>
) : (
<CommentIcon
comment={current}
onClick={() => setOpened(true)}
onPositionUpdate={(next) =>
setCurrent((value) => ({ ...value, position_x: next.x, position_y: next.y }))
}
/>
)}
<ReactFlow nodes={[]} />
{opened && <p role="status">Comment opened</p>}
</div>
</ReactFlowProvider>
</Suspense>
</QueryClientProvider>
)
}
it('keeps an authored comment focusable and draggable after adding keyboard movement', async () => {
// Browser-owned: real pointer capture, marker hit testing, and native button activation.
await page.viewport(1000, 800)
const screen = await render(<Fixture />)
const marker = screen.getByRole('button', { name: /workflow.keyboard.openComment/ })
await expect.element(marker).toBeVisible()
await screen.getByRole('button', { name: 'Before canvas' }).click()
await userEvent.tab()
await expect.element(marker).toHaveFocus()
const initial = marker.element().getBoundingClientRect()
await userEvent.keyboard('{ArrowRight}')
await expect.poll(() => marker.element().getBoundingClientRect().x).toBe(initial.x + 5)
await userEvent.dragAndDrop(marker, screen.getByRole('group', { name: 'Canvas' }), {
targetPosition: { x: 300, y: 250 },
})
expect(marker.element().getBoundingClientRect().x).toBeGreaterThan(initial.x + 5)
await expect.element(screen.getByRole('status')).not.toBeInTheDocument()
await marker.click()
await expect.element(screen.getByRole('status')).toHaveTextContent('Comment opened')
})
it('preserves draft mouse dragging and lets keyboard users move the same handle', async () => {
// Browser-owned: native document pointer events and geometry of the positioned draft.
await page.viewport(1000, 800)
const screen = await render(<Fixture draft />)
const handle = screen.getByRole('button', { name: 'workflow.keyboard.moveDraftComment' })
await expect.element(handle).toBeVisible()
const initial = handle.element().getBoundingClientRect()
await userEvent.dragAndDrop(handle, screen.getByRole('group', { name: 'Canvas' }), {
targetPosition: { x: 300, y: 250 },
})
expect(handle.element().getBoundingClientRect().x).toBeGreaterThan(initial.x)
await screen.getByRole('button', { name: 'Before canvas' }).click()
await userEvent.tab()
await expect.element(handle).toHaveFocus()
const dragged = handle.element().getBoundingClientRect()
await userEvent.keyboard('{Enter}')
await expect.element(handle).toHaveAttribute('aria-pressed', 'true')
await userEvent.keyboard('{ArrowRight}')
await expect.poll(() => handle.element().getBoundingClientRect().x).toBe(dragged.x + 5)
await userEvent.keyboard('{Shift>}{ArrowDown}{/Shift}')
await expect.poll(() => handle.element().getBoundingClientRect().y).toBe(dragged.y + 20)
await userEvent.keyboard('{Enter}')
await expect.element(handle).toHaveAttribute('aria-pressed', 'false')
})
@@ -0,0 +1,62 @@
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vite-plus/test'
import { renderWorkflowComponent as render } from '../__tests__/workflow-test-env'
import CommentPreview from './comment-preview'
vi.mock('@/hooks/use-format-time-from-now', () => ({
useFormatTimeFromNow: () => ({
formatTimeFromNow: (value: number) => `time:${value}`,
}),
}))
const createComment = (overrides: Partial<WorkflowCommentBasic> = {}): WorkflowCommentBasic => {
const author = { id: 'user-1', name: 'Alice', email: 'alice@example.com', avatar_url: null }
const participant = { id: 'user-2', name: 'Bob', email: 'bob@example.com', avatar_url: null }
return {
id: 'comment-1',
position_x: 0,
position_y: 0,
content: 'Hello',
created_by: author.id,
created_by_account: author,
created_at: 1,
updated_at: 10,
resolved: false,
mention_count: 0,
reply_count: 0,
participants: [participant, author],
...overrides,
}
}
describe('CommentPreview', () => {
it('orders participants with author first and formats time', () => {
const comment = createComment()
render(<CommentPreview comment={comment} />)
expect(screen.getAllByRole('img').map((avatar) => avatar.getAttribute('aria-label'))).toEqual([
'Alice',
'Bob',
])
expect(screen.getByText('Hello')).toBeInTheDocument()
expect(screen.getByText('time:10000')).toBeInTheDocument()
})
it('tracks hovering and releases the preview on leave or unmount', async () => {
const user = userEvent.setup()
const { store, unmount } = render(<CommentPreview comment={createComment()} />)
const content = screen.getByText('Hello')
await user.hover(content)
expect(store.getState().isCommentPreviewHovering).toBe(true)
await user.unhover(content)
expect(store.getState().isCommentPreviewHovering).toBe(false)
await user.hover(content)
expect(store.getState().isCommentPreviewHovering).toBe(true)
unmount()
expect(store.getState().isCommentPreviewHovering).toBe(false)
})
})
@@ -0,0 +1,58 @@
'use client'
import type { WorkflowCommentBasic } from '@dify/contracts/api/console/apps/types.gen'
import type { FC } from 'react'
import { memo, useEffect, useMemo } from 'react'
import { UserAvatarList } from '@/app/components/base/user-avatar-list'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { useStore } from '../store'
type CommentPreviewProps = {
comment: WorkflowCommentBasic
onClick?: () => void
}
const CommentPreview: FC<CommentPreviewProps> = ({ comment, onClick }) => {
const { formatTimeFromNow } = useFormatTimeFromNow()
const setCommentPreviewHovering = useStore((s) => s.setCommentPreviewHovering)
const authorName = comment.created_by_account?.name ?? ''
const participants = useMemo(() => {
const list = comment.participants ?? []
const author = comment.created_by_account
if (!author) return [...list]
const rest = list.filter((user) => user.id !== author.id)
return [author, ...rest]
}, [comment.created_by_account, comment.participants])
useEffect(
() => () => {
setCommentPreviewHovering(false)
},
[setCommentPreviewHovering],
)
return (
<div
className="w-80 cursor-pointer rounded-3xl rounded-bl-[3px] border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-4 shadow-lg backdrop-blur-[10px] transition-colors hover:bg-components-panel-on-panel-item-bg-hover"
onClick={onClick}
onMouseEnter={() => setCommentPreviewHovering(true)}
onMouseLeave={() => setCommentPreviewHovering(false)}
>
<div className="mb-3 flex items-center justify-between">
<UserAvatarList users={participants} maxVisible={3} size="sm" />
</div>
<div className="mb-2 flex items-start">
<div className="flex min-w-0 items-center gap-2">
<div className="truncate system-sm-medium text-text-primary">{authorName}</div>
<div className="shrink-0 system-2xs-regular text-text-tertiary">
{formatTimeFromNow((comment.updated_at ?? comment.created_at ?? 0) * 1000)}
</div>
</div>
</div>
<div className="system-sm-regular wrap-break-word text-text-secondary">{comment.content}</div>
</div>
)
}
export default memo(CommentPreview)
@@ -0,0 +1,55 @@
import { render } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { ControlMode } from '../types'
import { CommentCursor } from './cursor'
const mockState: {
controlMode: ControlMode
isCommentPlacing: boolean
mousePosition: { elementX: number; elementY: number }
} = {
controlMode: ControlMode.Pointer,
isCommentPlacing: false,
mousePosition: {
elementX: 10,
elementY: 20,
},
}
vi.mock('../store', () => ({
useStore: (selector: (state: typeof mockState) => unknown) => selector(mockState),
}))
describe('CommentCursor', () => {
beforeEach(() => {
mockState.controlMode = ControlMode.Pointer
mockState.isCommentPlacing = false
mockState.mousePosition = { elementX: 10, elementY: 20 }
})
it('renders nothing when not in comment mode', () => {
mockState.controlMode = ControlMode.Pointer
const { container } = render(<CommentCursor />)
expect(container).toBeEmptyDOMElement()
})
it('renders at current mouse position when in comment mode', () => {
mockState.controlMode = ControlMode.Comment
mockState.isCommentPlacing = false
const { container } = render(<CommentCursor />)
expect(container.firstElementChild).toHaveStyle({ left: '10px', top: '20px' })
})
it('renders nothing when comment is in placing mode', () => {
mockState.controlMode = ControlMode.Comment
mockState.isCommentPlacing = true
const { container } = render(<CommentCursor />)
expect(container).toBeEmptyDOMElement()
})
})
@@ -0,0 +1,27 @@
import type { FC } from 'react'
import { memo } from 'react'
import { useStore } from '../store'
import { ControlMode } from '../types'
export const CommentCursor: FC = memo(() => {
const controlMode = useStore((s) => s.controlMode)
const mousePosition = useStore((s) => s.mousePosition)
const isCommentPlacing = useStore((s) => s.isCommentPlacing)
if (controlMode !== ControlMode.Comment || isCommentPlacing) return null
return (
<div
className="pointer-events-none absolute z-30 flex size-6 items-center justify-center"
style={{
left: mousePosition.elementX,
top: mousePosition.elementY,
transform: 'translate(-50%, -50%)',
}}
>
<span aria-hidden className="i-custom-public-other-comment h-3 w-3.5 text-text-primary" />
</div>
)
})
CommentCursor.displayName = 'CommentCursor'
@@ -0,0 +1,147 @@
import type { ReactElement } from 'react'
import type { UserProfile } from '@/app/components/workflow/comment/types'
import { act, render as renderComponent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { WorkflowContext } from '../context'
import { EditorResourceScope } from '../editor-resource/provider'
import { createWorkflowStore } from '../store'
import { MentionInput } from './mention-input'
const render = (ui: ReactElement, cachedUsers?: UserProfile[]) => {
const store = createWorkflowStore({})
if (cachedUsers) store.getState().setMentionableUsersCache('app-1', cachedUsers)
return renderComponent(
<EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>
<WorkflowContext value={store}>{ui}</WorkflowContext>
</EditorResourceScope>,
)
}
const mockFetchMentionableUsers = vi.hoisted(() => vi.fn())
vi.mock('@/service/console', () => ({
consoleClient: {
apps: {
byAppId: {
workflow: {
comments: {
mentionUsers: {
get: (...args: unknown[]) => mockFetchMentionableUsers(...args),
},
},
},
},
},
},
}))
const mentionUsers: UserProfile[] = [
{
id: 'user-2',
name: 'Alice',
email: 'alice@example.com',
avatar_url: 'alice.png',
},
{
id: 'user-3',
name: 'Bob',
email: 'bob@example.com',
avatar_url: 'bob.png',
},
]
function ControlledMentionInput({
onSubmit,
}: {
onSubmit: (content: string, mentionedUserIds: string[]) => void
}) {
const [value, setValue] = useState('')
return <MentionInput value={value} onChange={setValue} onSubmit={onSubmit} />
}
describe('MentionInput', () => {
beforeEach(() => {
vi.clearAllMocks()
mockFetchMentionableUsers.mockResolvedValue({ users: mentionUsers })
})
it('loads users, selects a mention and submits its user id through the real store', async () => {
const user = userEvent.setup()
const onSubmit = vi.fn()
render(<ControlledMentionInput onSubmit={onSubmit} />)
const textarea = screen.getByPlaceholderText(
'workflowComments.comments.placeholder.add',
) as HTMLTextAreaElement
await user.type(textarea, '@Ali')
await waitFor(() => {
expect(screen.getByText('alice@example.com')).toBeInTheDocument()
})
expect(mockFetchMentionableUsers).toHaveBeenCalledExactlyOnceWith({
params: { app_id: 'app-1' },
})
await user.click(screen.getByText('alice@example.com'))
await waitFor(() => expect(textarea).toHaveFocus())
await user.type(textarea, 'hi')
await user.keyboard('{Enter}')
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith('@Alice hi', ['user-2'])
})
})
it('uses cached users and trims the saved reply in editing mode', async () => {
const user = userEvent.setup()
const onSubmit = vi.fn()
const onCancel = vi.fn()
render(
<MentionInput
value=" updated reply "
onChange={vi.fn()}
onSubmit={onSubmit}
onCancel={onCancel}
isEditing
/>,
mentionUsers,
)
expect(mockFetchMentionableUsers).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
expect(onCancel).toHaveBeenCalledTimes(1)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith('updated reply', [])
})
})
it('focuses the textarea at the end when autoFocus is enabled', () => {
vi.useFakeTimers()
try {
const { unmount } = render(
<MentionInput value="draft" onChange={vi.fn()} onSubmit={vi.fn()} autoFocus />,
mentionUsers,
)
const textarea = screen.getByPlaceholderText(
'workflowComments.comments.placeholder.add',
) as HTMLTextAreaElement
act(() => {
vi.runOnlyPendingTimers()
})
expect(document.activeElement).toBe(textarea)
expect(textarea.selectionStart).toBe(5)
expect(textarea.selectionEnd).toBe(5)
unmount()
} finally {
vi.useRealTimers()
}
})
})
@@ -0,0 +1,686 @@
'use client'
import type { ReactNode } from 'react'
import type { UserProfile } from '@/app/components/workflow/comment/types'
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useAtomValue } from 'jotai'
import {
forwardRef,
memo,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import Textarea from 'react-textarea-autosize'
import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'
import { consoleClient } from '@/service/console'
import { getAvatarInitial } from '@/utils/avatar'
import { useStore, useWorkflowStore } from '../store'
type MentionInputProps = {
value: string
onChange: (value: string) => void
onSubmit: (content: string, mentionedUserIds: string[]) => void
onCancel?: () => void
placeholder?: string
disabled?: boolean
loading?: boolean
className?: string
isEditing?: boolean
autoFocus?: boolean
}
const EMPTY_USERS: UserProfile[] = []
const MentionInputInner = forwardRef<HTMLTextAreaElement, MentionInputProps>(
(
{
value,
onChange,
onSubmit,
onCancel,
placeholder,
disabled = false,
loading = false,
className,
isEditing = false,
autoFocus = false,
},
forwardedRef,
) => {
const { t } = useTranslation(['common', 'workflowComments', 'workflowAgent'])
const appId = useAtomValue(editorAppIdAtom)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const highlightContentRef = useRef<HTMLDivElement>(null)
const actionContainerRef = useRef<HTMLDivElement | null>(null)
const actionRightRef = useRef<HTMLDivElement | null>(null)
const baseTextareaHeightRef = useRef<number | null>(null)
// Expose textarea ref to parent component
useImperativeHandle(forwardedRef, () => textareaRef.current!, [])
const workflowStore = useWorkflowStore()
const mentionUsersFromStore = useStore((state) =>
appId ? state.mentionableUsersCache[appId] : undefined,
)
const mentionUsers = useMemo(
() => mentionUsersFromStore ?? EMPTY_USERS,
[mentionUsersFromStore],
)
const [showMentionDropdown, setShowMentionDropdown] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [mentionPosition, setMentionPosition] = useState(0)
const [selectedMentionIndex, setSelectedMentionIndex] = useState(0)
const [mentionedUserIds, setMentionedUserIds] = useState<string[]>([])
const resolvedPlaceholder =
placeholder ?? t(($) => $['comments.placeholder.add'], { ns: 'workflowComments' })
const BASE_PADDING = 4
const [shouldReserveButtonGap, setShouldReserveButtonGap] = useState(isEditing)
const [shouldReserveHorizontalSpace, setShouldReserveHorizontalSpace] = useState(
() => !isEditing,
)
const [paddingRight, setPaddingRight] = useState(() => BASE_PADDING + (isEditing ? 0 : 48))
const [paddingBottom, setPaddingBottom] = useState(() => BASE_PADDING + (isEditing ? 32 : 0))
const mentionNameList = useMemo(() => {
const names = mentionUsers
.map((user) => user.name?.trim())
.filter((name): name is string => Boolean(name))
const uniqueNames = Array.from(new Set(names))
uniqueNames.sort((a, b) => b.length - a.length)
return uniqueNames
}, [mentionUsers])
const highlightedValue = useMemo<ReactNode>(() => {
if (!value) return ''
if (mentionNameList.length === 0) return value
const segments: ReactNode[] = []
let cursor = 0
let hasMention = false
while (cursor < value.length) {
let nextMatchStart = -1
let matchedName = ''
for (const name of mentionNameList) {
const searchStart = value.indexOf(`@${name}`, cursor)
if (searchStart === -1) continue
const previousChar = searchStart > 0 ? value[searchStart - 1] : ''
if (searchStart > 0 && !/\s/.test(previousChar!)) continue
if (
nextMatchStart === -1 ||
searchStart < nextMatchStart ||
(searchStart === nextMatchStart && name.length > matchedName.length)
) {
nextMatchStart = searchStart
matchedName = name
}
}
if (nextMatchStart === -1) break
if (nextMatchStart > cursor)
segments.push(<span key={`text-${cursor}`}>{value.slice(cursor, nextMatchStart)}</span>)
const mentionEnd = nextMatchStart + matchedName.length + 1
segments.push(
<span key={`mention-${nextMatchStart}`} className="text-primary-600">
{value.slice(nextMatchStart, mentionEnd)}
</span>,
)
hasMention = true
cursor = mentionEnd
}
if (!hasMention) return value
if (cursor < value.length)
segments.push(<span key={`text-${cursor}`}>{value.slice(cursor)}</span>)
return segments
}, [value, mentionNameList])
const loadMentionableUsers = useCallback(async () => {
if (!appId) return
const state = workflowStore.getState()
if (state.mentionableUsersCache[appId] !== undefined) return
if (state.mentionableUsersLoading[appId]) return
state.setMentionableUsersLoading(appId, true)
try {
const response = await consoleClient.apps.byAppId.workflow.comments.mentionUsers.get({
params: { app_id: appId },
})
workflowStore.getState().setMentionableUsersCache(appId, response.users)
} catch (error) {
console.error('Failed to load mentionable users:', error)
} finally {
workflowStore.getState().setMentionableUsersLoading(appId, false)
}
}, [appId, workflowStore])
useEffect(() => {
loadMentionableUsers()
}, [loadMentionableUsers])
const syncHighlightScroll = useCallback(() => {
const textarea = textareaRef.current
const highlightContent = highlightContentRef.current
if (!textarea || !highlightContent) return
const { scrollTop, scrollLeft } = textarea
highlightContent.style.transform = `translate(${-scrollLeft}px, ${-scrollTop}px)`
}, [])
const evaluateContentLayout = useCallback(() => {
const textarea = textareaRef.current
if (!textarea) return
const extraBottom = Math.max(0, paddingBottom - BASE_PADDING)
const effectiveClientHeight = textarea.clientHeight - extraBottom
if (baseTextareaHeightRef.current === null)
baseTextareaHeightRef.current = effectiveClientHeight
const baseHeight = baseTextareaHeightRef.current ?? effectiveClientHeight
const hasMultiline = effectiveClientHeight > baseHeight + 1
const shouldReserveVertical = isEditing ? true : hasMultiline
setShouldReserveButtonGap(shouldReserveVertical)
setShouldReserveHorizontalSpace(!hasMultiline)
}, [isEditing, paddingBottom])
const updateLayoutPadding = useCallback(() => {
const actionEl = actionContainerRef.current
const rect = actionEl?.getBoundingClientRect()
const rightRect = actionRightRef.current?.getBoundingClientRect()
let actionWidth = 0
if (rightRect) actionWidth = Math.ceil(rightRect.width)
else if (rect) actionWidth = Math.ceil(rect.width)
const actionHeight = rect ? Math.ceil(rect.height) : 0
const fallbackWidth = Math.max(0, paddingRight - BASE_PADDING)
const fallbackHeight = Math.max(0, paddingBottom - BASE_PADDING)
const effectiveWidth = actionWidth > 0 ? actionWidth : fallbackWidth
const effectiveHeight = actionHeight > 0 ? actionHeight : fallbackHeight
const nextRight = BASE_PADDING + (shouldReserveHorizontalSpace ? effectiveWidth : 0)
const nextBottom = BASE_PADDING + (shouldReserveButtonGap ? effectiveHeight : 0)
setPaddingRight((prev) => (prev === nextRight ? prev : nextRight))
setPaddingBottom((prev) => (prev === nextBottom ? prev : nextBottom))
}, [shouldReserveButtonGap, shouldReserveHorizontalSpace, paddingRight, paddingBottom])
const setActionContainerRef = useCallback(
(node: HTMLDivElement | null) => {
actionContainerRef.current = node
if (!isEditing) actionRightRef.current = node
else if (!node) actionRightRef.current = null
if (node && typeof window !== 'undefined')
window.requestAnimationFrame(() => updateLayoutPadding())
},
[isEditing, updateLayoutPadding],
)
const setActionRightRef = useCallback(
(node: HTMLDivElement | null) => {
actionRightRef.current = node
if (node && typeof window !== 'undefined')
window.requestAnimationFrame(() => updateLayoutPadding())
},
[updateLayoutPadding],
)
useLayoutEffect(() => {
syncHighlightScroll()
}, [value, syncHighlightScroll])
useLayoutEffect(() => {
Promise.resolve().then(() => {
evaluateContentLayout()
})
}, [value, evaluateContentLayout])
useLayoutEffect(() => {
Promise.resolve().then(() => {
updateLayoutPadding()
})
}, [updateLayoutPadding, isEditing, shouldReserveButtonGap])
useEffect(() => {
const handleResize = () => {
evaluateContentLayout()
updateLayoutPadding()
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [evaluateContentLayout, updateLayoutPadding])
useEffect(() => {
Promise.resolve().then(() => {
baseTextareaHeightRef.current = null
evaluateContentLayout()
setShouldReserveHorizontalSpace(!isEditing)
})
}, [isEditing, evaluateContentLayout])
const filteredMentionUsers = useMemo(() => {
if (!mentionQuery) return mentionUsers
return mentionUsers.filter(
(user) =>
user.name.toLowerCase().includes(mentionQuery.toLowerCase()) ||
user.email.toLowerCase().includes(mentionQuery.toLowerCase()),
)
}, [mentionUsers, mentionQuery])
const shouldDisableMentionButton = useMemo(() => {
if (showMentionDropdown) return true
const textarea = textareaRef.current
if (!textarea) return false
const cursorPosition = textarea.selectionStart || 0
const textBeforeCursor = value.slice(0, cursorPosition)
return /@\w*$/.test(textBeforeCursor)
}, [showMentionDropdown, value])
const dropdownPosition = useMemo(() => {
if (!showMentionDropdown || !textareaRef.current)
return { x: 0, y: 0, placement: 'bottom' as const }
const textareaRect = textareaRef.current.getBoundingClientRect()
const dropdownHeight = 160 // max-h-40 = 10rem = 160px
const viewportHeight = window.innerHeight
const spaceBelow = viewportHeight - textareaRect.bottom
const spaceAbove = textareaRect.top
const shouldPlaceAbove = spaceBelow < dropdownHeight && spaceAbove > spaceBelow
return {
x: textareaRect.left,
y: shouldPlaceAbove ? textareaRect.top - 4 : textareaRect.bottom + 4,
placement: shouldPlaceAbove ? ('top' as const) : ('bottom' as const),
}
}, [showMentionDropdown])
const handleContentChange = useCallback(
(newValue: string) => {
onChange(newValue)
setTimeout(() => {
const cursorPosition = textareaRef.current?.selectionStart || 0
const textBeforeCursor = newValue.slice(0, cursorPosition)
const mentionMatch = textBeforeCursor.match(/@(\w*)$/)
if (mentionMatch) {
setMentionQuery(mentionMatch[1]!)
setMentionPosition(cursorPosition - mentionMatch[0].length)
setShowMentionDropdown(true)
setSelectedMentionIndex(0)
} else {
setShowMentionDropdown(false)
}
if (typeof window !== 'undefined') {
window.requestAnimationFrame(() => {
evaluateContentLayout()
syncHighlightScroll()
})
}
}, 0)
},
[onChange, evaluateContentLayout, syncHighlightScroll],
)
const handleMentionButtonClick = useCallback(
(e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
const textarea = textareaRef.current
if (!textarea) return
const cursorPosition = textarea.selectionStart || 0
const textBeforeCursor = value.slice(0, cursorPosition)
if (showMentionDropdown) return
if (/@\w*$/.test(textBeforeCursor)) return
const newContent = `${value.slice(0, cursorPosition)}@${value.slice(cursorPosition)}`
onChange(newContent)
setTimeout(() => {
const newCursorPos = cursorPosition + 1
textarea.setSelectionRange(newCursorPos, newCursorPos)
textarea.focus()
setMentionQuery('')
setMentionPosition(cursorPosition)
setShowMentionDropdown(true)
setSelectedMentionIndex(0)
if (typeof window !== 'undefined') {
window.requestAnimationFrame(() => {
evaluateContentLayout()
syncHighlightScroll()
})
}
}, 0)
},
[value, onChange, evaluateContentLayout, syncHighlightScroll, showMentionDropdown],
)
const insertMention = useCallback(
(user: UserProfile) => {
const textarea = textareaRef.current
if (!textarea) return
const beforeMention = value.slice(0, mentionPosition)
const afterMention = value.slice(textarea.selectionStart || 0)
const needsSpaceBefore = mentionPosition > 0 && !/\s/.test(value[mentionPosition - 1]!)
const prefix = needsSpaceBefore ? ' ' : ''
const newContent = `${beforeMention}${prefix}@${user.name} ${afterMention}`
onChange(newContent)
setShowMentionDropdown(false)
const newMentionedUserIds = [...mentionedUserIds, user.id]
setMentionedUserIds(newMentionedUserIds)
setTimeout(() => {
const extraSpace = needsSpaceBefore ? 1 : 0
const newCursorPos = mentionPosition + extraSpace + user.name.length + 2 // (space) + @ + name + space
textarea.setSelectionRange(newCursorPos, newCursorPos)
textarea.focus()
if (typeof window !== 'undefined') {
window.requestAnimationFrame(() => {
evaluateContentLayout()
syncHighlightScroll()
})
}
}, 0)
},
[
value,
mentionPosition,
onChange,
mentionedUserIds,
evaluateContentLayout,
syncHighlightScroll,
],
)
const handleSubmit = useCallback(
async (e?: React.MouseEvent) => {
if (e) {
e.preventDefault()
e.stopPropagation()
}
if (value.trim()) {
try {
await onSubmit(value.trim(), mentionedUserIds)
setMentionedUserIds([])
setShowMentionDropdown(false)
} catch (error) {
console.error('Failed to submit', error)
}
}
},
[value, mentionedUserIds, onSubmit],
)
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
// Ignore key events during IME composition (e.g., Chinese, Japanese input)
if (e.nativeEvent.isComposing) return
if (showMentionDropdown) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedMentionIndex((prev) =>
prev < filteredMentionUsers.length - 1 ? prev + 1 : 0,
)
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedMentionIndex((prev) =>
prev > 0 ? prev - 1 : filteredMentionUsers.length - 1,
)
} else if (e.key === 'Enter') {
e.preventDefault()
if (filteredMentionUsers[selectedMentionIndex])
insertMention(filteredMentionUsers[selectedMentionIndex])
return
} else if (e.key === 'Escape') {
e.preventDefault()
setShowMentionDropdown(false)
return
}
}
if (e.key === 'Enter' && !e.shiftKey && !showMentionDropdown) {
e.preventDefault()
handleSubmit()
}
},
[
showMentionDropdown,
filteredMentionUsers,
selectedMentionIndex,
insertMention,
handleSubmit,
],
)
const resetMentionState = useCallback(() => {
setMentionedUserIds([])
setShowMentionDropdown(false)
setMentionQuery('')
setMentionPosition(0)
setSelectedMentionIndex(0)
}, [])
useEffect(() => {
if (!value) {
Promise.resolve().then(() => {
resetMentionState()
})
}
}, [value, resetMentionState])
useEffect(() => {
if (!autoFocus || !textareaRef.current) return
const textarea = textareaRef.current
const timeout = window.setTimeout(() => {
textarea.focus()
const length = textarea.value.length
textarea.setSelectionRange(length, length)
}, 0)
return () => window.clearTimeout(timeout)
}, [autoFocus])
return (
<>
<div className={cn('relative flex items-center', className)}>
<div
aria-hidden
className={cn(
'pointer-events-none absolute inset-0 z-0 overflow-hidden p-1 leading-6 wrap-break-word whitespace-pre-wrap',
'body-lg-regular text-text-primary',
)}
style={{ paddingRight, paddingBottom }}
>
<div
ref={highlightContentRef}
className="min-h-full"
style={{ willChange: 'transform' }}
>
{highlightedValue}
</div>
</div>
<Textarea
ref={textareaRef}
className={cn(
'relative z-10 w-full resize-none bg-transparent p-1 body-lg-regular leading-6 text-transparent caret-primary-500 outline-hidden',
'placeholder:text-text-tertiary',
)}
style={{ paddingRight, paddingBottom }}
placeholder={resolvedPlaceholder}
autoFocus={autoFocus}
minRows={isEditing ? 4 : 1}
maxRows={4}
value={value}
disabled={disabled || loading}
onChange={(e) => handleContentChange(e.target.value)}
onKeyDown={handleKeyDown}
onScroll={syncHighlightScroll}
/>
{!isEditing && (
<div
ref={setActionContainerRef}
className="absolute right-1 bottom-0 z-20 flex items-end gap-1"
>
<IconButton
aria-label={t(($) => $['nodes.agent.task.mention'], { ns: 'workflowAgent' })}
size="lg"
disabled={shouldDisableMentionButton}
className="z-20 transition-opacity data-disabled:opacity-40"
onClick={handleMentionButtonClick}
>
<span aria-hidden className="i-ri-at-line size-4 text-text-tertiary" />
</IconButton>
<IconButton
aria-label={t(($) => $['operation.send'], { ns: 'common' })}
className="z-20 ml-2"
size="lg"
variant="primary"
disabled={!value.trim() || disabled || loading}
onClick={handleSubmit}
>
{loading ? (
<span
aria-hidden
className="i-ri-loader-2-line size-4 animate-spin text-components-button-primary-text"
/>
) : (
<span
aria-hidden
className="i-ri-arrow-up-line size-4 text-components-button-primary-text"
/>
)}
</IconButton>
</div>
)}
{isEditing && (
<div
ref={setActionContainerRef}
className="absolute inset-x-1 bottom-0 z-20 flex items-end justify-between"
>
<IconButton
aria-label={t(($) => $['nodes.agent.task.mention'], { ns: 'workflowAgent' })}
size="lg"
disabled={shouldDisableMentionButton}
className="z-20 transition-opacity data-disabled:opacity-40"
onClick={handleMentionButtonClick}
>
<span aria-hidden className="i-ri-at-line size-4 text-text-tertiary" />
</IconButton>
<div ref={setActionRightRef} className="flex items-center gap-2">
<Button variant="secondary" size="small" onClick={onCancel} disabled={loading}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
<Button
variant="primary"
size="small"
disabled={loading || !value.trim()}
onClick={() => handleSubmit()}
>
{loading && (
<span aria-hidden className="i-ri-loader-2-line size-3.5 animate-spin" />
)}
<span>{t(($) => $['operation.save'], { ns: 'common' })}</span>
{!loading && (
<span aria-hidden className="i-custom-public-common-enter-key size-4" />
)}
</Button>
</div>
</div>
)}
</div>
{showMentionDropdown &&
filteredMentionUsers.length > 0 &&
typeof document !== 'undefined' &&
createPortal(
<div
className="fixed max-h-62 w-70 overflow-y-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg/95 shadow-lg backdrop-blur-[10px]"
style={{
left: dropdownPosition.x,
[dropdownPosition.placement === 'top' ? 'bottom' : 'top']:
dropdownPosition.placement === 'top'
? window.innerHeight - dropdownPosition.y
: dropdownPosition.y,
}}
data-mention-dropdown
>
{filteredMentionUsers.map((user, index) => (
<div
key={user.id}
className={cn(
'flex cursor-pointer items-center gap-2 rounded-md py-1 pr-3 pl-2 hover:bg-state-base-hover',
index === selectedMentionIndex && 'bg-state-base-hover',
)}
onClick={() => insertMention(user)}
>
<Avatar size="sm" className="shrink-0" aria-hidden="true">
<AvatarFallback>{getAvatarInitial(user.name)}</AvatarFallback>
<AvatarImage src={user.avatar_url || undefined} alt="" />
</Avatar>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-text-primary">
{user.name}
</div>
<div className="truncate text-xs text-text-tertiary">{user.email}</div>
</div>
</div>
))}
</div>,
document.body,
)}
</>
)
},
)
MentionInputInner.displayName = 'MentionInputInner'
export const MentionInput = memo(MentionInputInner)
@@ -0,0 +1,66 @@
import { HotkeysProvider } from '@tanstack/react-hotkeys'
import { act, fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowComponent } from '../__tests__/workflow-test-env'
import { CommentPlacementPreview } from './placement-preview'
function renderPlacement(placing = true) {
const onCancel = vi.fn()
const result = renderWorkflowComponent(
<HotkeysProvider>
<button>Canvas action</button>
<button onKeyDown={(event) => event.preventDefault()}>Local escape owner</button>
<input aria-label="Node input" />
<CommentPlacementPreview onSubmit={vi.fn()} onCancel={onCancel} />
</HotkeysProvider>,
{ initialStoreState: { isCommentPlacing: placing, mentionableUsersCache: { 'app-1': [] } } },
)
return { ...result, onCancel }
}
it('cancels pending placement from the canvas without focusing the disabled preview', async () => {
const user = userEvent.setup()
const { onCancel } = renderPlacement()
await user.click(screen.getByRole('button', { name: 'Canvas action' }))
const owner = screen.getByRole('button', { name: 'Canvas action' })
for (const repeat of [false, true, true]) {
const event = new KeyboardEvent('keydown', {
key: 'Escape',
repeat,
bubbles: true,
cancelable: true,
})
fireEvent(owner, event)
expect(event.defaultPrevented).toBe(true)
}
fireEvent.keyUp(owner, { key: 'Escape' })
expect(onCancel).toHaveBeenCalledTimes(1)
})
it('leaves claimed, composing, and input Escape with their local owner', async () => {
const user = userEvent.setup()
const { onCancel } = renderPlacement()
await user.click(screen.getByRole('button', { name: 'Local escape owner' }))
await user.keyboard('{Escape}')
await user.click(screen.getByRole('textbox', { name: 'Node input' }))
await user.keyboard('{Escape}')
const canvasAction = screen.getByRole('button', { name: 'Canvas action' })
fireEvent.keyDown(canvasAction, { key: 'Escape', isComposing: true })
fireEvent.keyUp(canvasAction, { key: 'Escape' })
expect(onCancel).not.toHaveBeenCalled()
})
it('stops owning Escape when inactive or once the editable draft is placed', async () => {
const user = userEvent.setup()
const { store, onCancel } = renderPlacement(false)
await user.click(screen.getByRole('button', { name: 'Canvas action' }))
await user.keyboard('{Escape}')
act(() =>
store.setState({
isCommentPlacing: true,
pendingComment: { pageX: 0, pageY: 0, elementX: 0, elementY: 0 },
}),
)
await user.keyboard('{Escape}')
expect(onCancel).not.toHaveBeenCalled()
})
@@ -0,0 +1,45 @@
import { useHotkey } from '@tanstack/react-hotkeys'
import { useStore } from '../store/workflow'
import { CommentInput } from './comment-input'
export function CommentPlacementPreview({
onSubmit,
onCancel,
}: {
onSubmit: (content: string, mentionedUserIds: string[]) => void
onCancel: () => void
}) {
const isCommentPlacing = useStore((state) => state.isCommentPlacing)
const pendingComment = useStore((state) => state.pendingComment)
const mousePosition = useStore((state) => state.mousePosition)
const placing = isCommentPlacing && !pendingComment
useHotkey(
'Escape',
(event) => {
if (event.defaultPrevented || event.isComposing) return
event.preventDefault()
event.stopPropagation()
if (event.repeat) return
onCancel()
},
{
enabled: placing,
ignoreInputs: true,
preventDefault: false,
stopPropagation: false,
},
)
if (!placing) return null
return (
<CommentInput
position={{ x: mousePosition.elementX, y: mousePosition.elementY }}
onSubmit={onSubmit}
onCancel={onCancel}
autoFocus={false}
disabled
/>
)
}
@@ -0,0 +1,108 @@
import type { WorkflowCommentDetail } from '@dify/contracts/api/console/apps/types.gen'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Suspense, useState } from 'react'
import { page, userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { consoleQueryKey } from '@/test/console/operation-hooks'
import { EditorResourceScope } from '../editor-resource/provider'
import { CommentThread } from './thread'
vi.mock('reactflow', () => ({
useReactFlow: () => ({ flowToScreenPosition: (position: { x: number; y: number }) => position }),
useViewport: () => ({ x: 0, y: 0, zoom: 1 }),
}))
const store = vi.hoisted(() => ({
mentionableUsersCache: { 'app-1': [] },
setCommentPreviewHovering: () => {},
}))
vi.mock('../store', () => ({
useStore: (selector: (state: typeof store) => unknown) => selector(store),
useWorkflowStore: () => ({ getState: () => store }),
}))
vi.mock('@/features/account-profile/client', () => ({
userProfileQueryOptions: () => ({
queryKey: consoleQueryKey('account.profile.get'),
queryFn: async () => ({ profile: { id: 'author', name: 'Alice', avatar_url: null } }),
}),
}))
const author = { id: 'author', name: 'Alice', email: 'alice@example.com', avatar_url: null }
const comment: WorkflowCommentDetail = {
id: 'comment',
content: 'Review this node',
created_by: 'author',
created_by_account: author,
position_x: 100,
position_y: 100,
created_at: 1,
updated_at: 1,
resolved: false,
mentions: [],
replies: [
{
id: 'reply',
content: 'A reply',
created_by: 'author',
created_by_account: author,
created_at: 2,
},
],
}
function Fixture({ onDelete }: { onDelete: (id: string) => void }) {
const [queryClient] = useState(
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
)
return (
<QueryClientProvider client={queryClient}>
<EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>
<Suspense fallback={<p>Loading profile</p>}>
<button type="button">Outside thread</button>
<div id="workflow-container" style={{ position: 'relative', width: 1000, height: 650 }}>
<CommentThread
comment={comment}
onClose={() => {}}
onReply={() => {}}
onReplyEdit={() => {}}
onReplyDeleteDirect={onDelete}
/>
</div>
</Suspense>
</EditorResourceScope>
</QueryClientProvider>
)
}
it('lets keyboard users request reply deletion and returns focus to reply actions when cancelled', async () => {
// Native Tab and CSS visibility expose regressions hidden by DOM-only tests.
await page.viewport(1200, 800)
const onDelete = vi.fn()
const screen = await render(<Fixture onDelete={onDelete} />)
const replyInput = screen.getByRole('textbox')
await expect.element(replyInput).toHaveFocus()
await userEvent.tab({ shift: true })
const trigger = screen.getByRole('button', {
name: 'workflowComments.comments.aria.replyActions',
})
await expect.element(trigger).toHaveFocus()
expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true)
await userEvent.keyboard('{ArrowDown}')
const edit = screen.getByRole('menuitem', { name: 'workflowComments.comments.actions.editReply' })
await expect.element(edit).toHaveFocus()
await userEvent.keyboard('{End}')
const deleteItem = screen.getByRole('menuitem', {
name: 'workflowComments.comments.actions.deleteReply',
})
await expect.element(deleteItem).toHaveFocus()
await userEvent.keyboard('{Enter}')
const confirmation = screen.getByRole('alertdialog', {
name: 'workflowComments.comments.actions.deleteReply',
})
await expect.element(confirmation).toBeVisible()
await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
expect(onDelete).not.toHaveBeenCalled()
await confirmation.getByRole('button', { name: 'common.operation.cancel' }).click()
await expect.element(confirmation).not.toBeInTheDocument()
await expect.element(trigger).toHaveFocus()
expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true)
})
@@ -0,0 +1,179 @@
import type { WorkflowCommentDetail } from '@dify/contracts/api/console/apps/types.gen'
import type { ReactElement } from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { renderWorkflowFlowComponent } from '../__tests__/workflow-test-env'
import { CommentThread } from './thread'
const render = (ui: ReactElement) => {
const { queryClient } = createConsoleQueryWrapper({
accountProfile: { id: 'user-1', name: 'Alice', avatar_url: 'alice.png' },
})
return renderWorkflowFlowComponent(<div id="workflow-container">{ui}</div>, {
queryClient,
initialStoreState: {
mentionableUsersCache: {
'app-1': [
{ id: 'user-1', name: 'Alice', email: 'alice@example.com', avatar_url: 'alice.png' },
{ id: 'user-2', name: 'Bob', email: 'bob@example.com', avatar_url: 'bob.png' },
],
},
},
})
}
const createComment = (): WorkflowCommentDetail => ({
id: 'comment-1',
position_x: 120,
position_y: 80,
content: '@Alice original comment',
created_by: 'user-1',
created_by_account: {
id: 'user-1',
name: 'Alice',
email: 'alice@example.com',
avatar_url: 'alice.png',
},
created_at: 1,
updated_at: 2,
resolved: false,
mentions: [],
replies: [
{
id: 'reply-1',
content: 'first reply',
created_by: 'user-1',
created_by_account: {
id: 'user-1',
name: 'Alice',
email: 'alice@example.com',
avatar_url: 'alice.png',
},
created_at: 2,
},
],
})
describe('CommentThread', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('triggers header actions and closes on Escape', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const onDelete = vi.fn()
const onResolve = vi.fn()
const onPrev = vi.fn()
const onNext = vi.fn()
render(
<CommentThread
comment={createComment()}
onClose={onClose}
onDelete={onDelete}
onResolve={onResolve}
onPrev={onPrev}
onNext={onNext}
canGoPrev
canGoNext
/>,
)
await user.click(screen.getByLabelText('workflowComments.comments.aria.deleteComment'))
await user.click(screen.getByLabelText('workflowComments.comments.aria.resolveComment'))
await user.click(screen.getByLabelText('workflowComments.comments.aria.previousComment'))
await user.click(screen.getByLabelText('workflowComments.comments.aria.nextComment'))
await user.click(screen.getByLabelText('workflowComments.comments.aria.closeComment'))
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(1)
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
expect(onDelete).toHaveBeenCalledTimes(1)
expect(onResolve).toHaveBeenCalledTimes(1)
expect(onPrev).toHaveBeenCalledTimes(1)
expect(onNext).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(2)
})
it('supports editing the root comment when the current user owns the thread', async () => {
const user = userEvent.setup()
const onCommentEdit = vi.fn()
render(
<CommentThread comment={createComment()} onClose={vi.fn()} onCommentEdit={onCommentEdit} />,
)
await user.click(screen.getByLabelText('workflowComments.comments.aria.commentActions'))
await user.click(screen.getByText('workflowComments.comments.actions.editComment'))
const editor = screen.getByPlaceholderText('workflowComments.comments.placeholder.editComment')
await user.clear(editor)
await user.type(editor, 'Updated root comment')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(onCommentEdit).toHaveBeenCalledWith('Updated root comment', [])
})
})
it('submits reply and updates preview hovering state on mouse enter/leave', async () => {
const user = userEvent.setup()
const onReply = vi.fn()
const { store } = render(
<CommentThread comment={createComment()} onClose={vi.fn()} onReply={onReply} />,
)
const dialog = screen.getByRole('dialog')
fireEvent.mouseEnter(dialog)
expect(store.getState().isCommentPreviewHovering).toBe(true)
fireEvent.mouseLeave(dialog)
expect(store.getState().isCommentPreviewHovering).toBe(false)
const input = screen.getByPlaceholderText('workflowComments.comments.placeholder.reply')
await user.type(input, '@Bo')
await user.keyboard('{Enter}')
await waitFor(() => expect(input).toHaveValue('@Bob '))
await user.type(input, 'please review')
await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
await waitFor(() => expect(onReply).toHaveBeenCalledWith('@Bob please review', ['user-2']))
})
it('supports editing and direct deleting an existing reply', async () => {
const user = userEvent.setup()
const onReplyEdit = vi.fn()
const onReplyDeleteDirect = vi.fn()
render(
<CommentThread
comment={createComment()}
onClose={vi.fn()}
onReplyEdit={onReplyEdit}
onReplyDeleteDirect={onReplyDeleteDirect}
/>,
)
await user.click(screen.getByLabelText('workflowComments.comments.aria.replyActions'))
await user.click(await screen.findByText('workflowComments.comments.actions.editReply'))
const editor = screen.getByPlaceholderText('workflowComments.comments.placeholder.editReply')
await user.clear(editor)
await user.type(editor, 'Updated reply')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(onReplyEdit).toHaveBeenCalledWith('reply-1', 'Updated reply', [])
})
await waitFor(() => {
expect(
screen.getByLabelText('workflowComments.comments.aria.replyActions'),
).toBeInTheDocument()
})
await user.click(screen.getByLabelText('workflowComments.comments.aria.replyActions'))
await user.click(await screen.findByText('workflowComments.comments.actions.deleteReply'))
await user.click(await screen.findByRole('button', { name: 'common.operation.delete' }))
expect(onReplyDeleteDirect).toHaveBeenCalledWith('reply-1')
})
})
@@ -0,0 +1,842 @@
'use client'
import type {
WorkflowCommentDetail,
WorkflowCommentReply,
} from '@dify/contracts/api/console/apps/types.gen'
import type { ReactNode } from 'react'
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
import { Menu, MenuContent, MenuItem, MenuTrigger } from '@langgenius/dify-ui/menu'
import { Separator } from '@langgenius/dify-ui/separator'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import {
RiArrowDownSLine,
RiArrowUpSLine,
RiCheckboxCircleFill,
RiCheckboxCircleLine,
RiCloseLine,
RiDeleteBinLine,
RiMoreFill,
} from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useReactFlow, useViewport } from 'reactflow'
import { getUserColor } from '@/app/components/workflow/collaboration/utils/user-color'
import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { getAvatarInitial } from '@/utils/avatar'
import { useStore } from '../store'
import { MentionInput } from './mention-input'
type CommentThreadProps = {
comment: WorkflowCommentDetail
loading?: boolean
replySubmitting?: boolean
replyUpdating?: boolean
onClose: () => void
onDelete?: () => void
onResolve?: () => void
onPrev?: () => void
onNext?: () => void
canGoPrev?: boolean
canGoNext?: boolean
onCommentEdit?: (content: string, mentionedUserIds?: string[]) => Promise<void> | void
onReply?: (content: string, mentionedUserIds?: string[]) => Promise<void> | void
onReplyEdit?: (
replyId: string,
content: string,
mentionedUserIds?: string[],
) => Promise<void> | void
onReplyDelete?: (replyId: string) => void
onReplyDeleteDirect?: (replyId: string) => Promise<void> | void
}
type ThreadMessageProps = {
authorId: string
authorName: string
avatarUrl?: string | null
createdAt: number
content: string
mentionableNames: string[]
className?: string
}
function ThreadMessage({
authorId,
authorName,
avatarUrl,
createdAt,
content,
mentionableNames,
className,
}: ThreadMessageProps) {
const { formatTimeFromNow } = useFormatTimeFromNow()
const { data: currentUserId } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.id,
})
const isCurrentUser = authorId === currentUserId
const userColor = isCurrentUser ? undefined : getUserColor(authorId)
const highlightedContent = useMemo<ReactNode>(() => {
if (!content) return ''
// Extract valid user names from mentionableNames, sorted by length (longest first)
const normalizedNames = Array.from(
new Set(mentionableNames.map((name) => name.trim()).filter(Boolean)),
)
normalizedNames.sort((a, b) => b.length - a.length)
if (normalizedNames.length === 0) return content
const segments: ReactNode[] = []
let hasMention = false
let cursor = 0
while (cursor < content.length) {
let nextMatchStart = -1
let matchedName = ''
for (const name of normalizedNames) {
const searchStart = content.indexOf(`@${name}`, cursor)
if (searchStart === -1) continue
const previousChar = searchStart > 0 ? content[searchStart - 1] : ''
if (searchStart > 0 && !/\s/.test(previousChar!)) continue
if (
nextMatchStart === -1 ||
searchStart < nextMatchStart ||
(searchStart === nextMatchStart && name.length > matchedName.length)
) {
nextMatchStart = searchStart
matchedName = name
}
}
if (nextMatchStart === -1) break
if (nextMatchStart > cursor)
segments.push(<span key={`text-${cursor}`}>{content.slice(cursor, nextMatchStart)}</span>)
const mentionEnd = nextMatchStart + matchedName.length + 1
segments.push(
<span key={`mention-${nextMatchStart}`} className="text-primary-600">
{content.slice(nextMatchStart, mentionEnd)}
</span>,
)
hasMention = true
cursor = mentionEnd
}
if (!hasMention) return content
if (cursor < content.length)
segments.push(<span key={`text-${cursor}`}>{content.slice(cursor)}</span>)
return segments
}, [content, mentionableNames])
return (
<div className={cn('flex gap-3 pt-1', className)}>
<div className="shrink-0">
<Avatar size="md" aria-hidden="true">
<AvatarFallback style={userColor ? { backgroundColor: userColor } : undefined}>
{getAvatarInitial(authorName)}
</AvatarFallback>
<AvatarImage src={avatarUrl || undefined} alt="" />
</Avatar>
</div>
<div className="min-w-0 flex-1 pb-4 text-text-primary last:pb-0">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="system-sm-medium text-text-primary">{authorName}</span>
<span className="system-2xs-regular text-text-tertiary">
{formatTimeFromNow(createdAt * 1000)}
</span>
</div>
<div className="mt-1 system-sm-regular wrap-break-word whitespace-pre-wrap text-text-secondary">
{highlightedContent}
</div>
</div>
</div>
)
}
function CommentThreadComponent({
comment,
loading = false,
replySubmitting = false,
replyUpdating = false,
onClose,
onDelete,
onResolve,
onPrev,
onNext,
canGoPrev,
canGoNext,
onCommentEdit,
onReply,
onReplyEdit,
onReplyDelete,
onReplyDeleteDirect,
}: CommentThreadProps) {
const appId = useAtomValue(editorAppIdAtom)
const { flowToScreenPosition } = useReactFlow()
const viewport = useViewport()
const { data: userProfile } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile,
})
const currentUserId = userProfile.id
const { t } = useTranslation(['common', 'workflowComments'])
const [replyContent, setReplyContent] = useState('')
const [editingCommentContent, setEditingCommentContent] = useState('')
const [activeReplyMenuId, setActiveReplyMenuId] = useState<string | null>(null)
const [editingReply, setEditingReply] = useState<{ id: string; content: string }>({
id: '',
content: '',
})
const [deletingReplyId, setDeletingReplyId] = useState<string | null>(null)
const [isCommentEditing, setIsCommentEditing] = useState(false)
const [isSubmittingEdit, setIsSubmittingEdit] = useState(false)
// Focus management refs
const replyInputRef = useRef<HTMLTextAreaElement>(null)
const replyMenuTriggersRef = useRef(new Map<string, HTMLButtonElement>())
const deleteReplyTriggerRef = useRef<HTMLButtonElement | null>(null)
// Get mentionable users from store
const mentionUsersFromStore = useStore((state) =>
appId ? state.mentionableUsersCache[appId] : undefined,
)
const mentionUsers = mentionUsersFromStore ?? []
const setCommentPreviewHovering = useStore((state) => state.setCommentPreviewHovering)
// Extract all mentionable names for highlighting
const mentionableNames = useMemo(() => {
const names = mentionUsers
.map((user) => user.name?.trim())
.filter((name): name is string => Boolean(name))
return Array.from(new Set(names))
}, [mentionUsers])
useEffect(() => {
Promise.resolve().then(() => {
setReplyContent('')
setEditingCommentContent('')
setIsCommentEditing(false)
setEditingReply({ id: '', content: '' })
setActiveReplyMenuId(null)
setDeletingReplyId(null)
})
}, [comment.id])
useEffect(
() => () => {
setCommentPreviewHovering(false)
},
[setCommentPreviewHovering],
)
const canReply = Boolean(onReply)
// Focus on thread transitions, not callback changes after position updates.
useEffect(() => {
const timer = setTimeout(() => {
if (replyInputRef.current && !editingReply.id && !isCommentEditing && canReply)
replyInputRef.current.focus()
}, 100)
return () => clearTimeout(timer)
}, [comment.id, editingReply.id, isCommentEditing, canReply])
const handleReplySubmit = useCallback(
async (content: string, mentionedUserIds: string[]) => {
if (!onReply || replySubmitting) return
setReplyContent('')
try {
await onReply(content, mentionedUserIds)
// P0: Restore focus to reply input after successful submission
setTimeout(() => {
replyInputRef.current?.focus()
}, 0)
} catch (error) {
console.error('Failed to send reply', error)
setReplyContent(content)
}
},
[onReply, replySubmitting],
)
const screenPosition = useMemo(() => {
return flowToScreenPosition({
x: comment.position_x,
y: comment.position_y,
})
}, [
comment.position_x,
comment.position_y,
viewport.x,
viewport.y,
viewport.zoom,
flowToScreenPosition,
])
const workflowContainerRect =
typeof document !== 'undefined'
? document.getElementById('workflow-container')?.getBoundingClientRect()
: null
const containerLeft = workflowContainerRect?.left ?? 0
const containerTop = workflowContainerRect?.top ?? 0
const canvasPosition = useMemo(
() => ({
x: screenPosition.x - containerLeft,
y: screenPosition.y - containerTop,
}),
[screenPosition.x, screenPosition.y, containerLeft, containerTop],
)
const handleStartEdit = useCallback((reply: WorkflowCommentReply) => {
setEditingReply({ id: reply.id, content: reply.content })
setIsCommentEditing(false)
setActiveReplyMenuId(null)
}, [])
const handleStartCommentEdit = useCallback(() => {
setEditingCommentContent(comment.content)
setEditingReply({ id: '', content: '' })
setIsCommentEditing(true)
setActiveReplyMenuId(null)
}, [comment.content])
const handleCancelEdit = useCallback(() => {
setEditingReply({ id: '', content: '' })
// P1: Restore focus to reply input after canceling edit
setTimeout(() => {
replyInputRef.current?.focus()
}, 0)
}, [])
const handleCancelCommentEdit = useCallback(() => {
setEditingCommentContent('')
setIsCommentEditing(false)
setTimeout(() => {
replyInputRef.current?.focus()
}, 0)
}, [])
const handleCommentEditSubmit = useCallback(
async (content: string, mentionedUserIds: string[]) => {
if (!onCommentEdit) return
const trimmed = content.trim()
if (!trimmed) return
setIsSubmittingEdit(true)
try {
await onCommentEdit(trimmed, mentionedUserIds)
setEditingCommentContent('')
setIsCommentEditing(false)
setTimeout(() => {
replyInputRef.current?.focus()
}, 0)
} catch (error) {
console.error('Failed to edit comment', error)
} finally {
setIsSubmittingEdit(false)
}
},
[onCommentEdit],
)
const handleEditSubmit = useCallback(
async (content: string, mentionedUserIds: string[]) => {
if (!onReplyEdit || !editingReply) return
const trimmed = content.trim()
if (!trimmed) return
setIsSubmittingEdit(true)
try {
await onReplyEdit(editingReply.id, trimmed, mentionedUserIds)
setEditingReply({ id: '', content: '' })
// P1: Restore focus to reply input after saving edit
setTimeout(() => {
replyInputRef.current?.focus()
}, 0)
} catch (error) {
console.error('Failed to edit reply', error)
} finally {
setIsSubmittingEdit(false)
}
},
[editingReply, onReplyEdit],
)
const replies = comment.replies || []
const isOwnComment = comment.created_by_account?.id === currentUserId
const messageListRef = useRef<HTMLDivElement>(null)
const previousReplyCountRef = useRef<number | undefined>(undefined)
const previousCommentIdRef = useRef<string | undefined>(undefined)
// Close menu when scrolling
useEffect(() => {
const container = messageListRef.current
if (!container || !activeReplyMenuId) return
const handleScroll = () => {
setActiveReplyMenuId(null)
}
container.addEventListener('scroll', handleScroll)
return () => container.removeEventListener('scroll', handleScroll)
}, [activeReplyMenuId])
// Auto-scroll to bottom on new messages
useEffect(() => {
const container = messageListRef.current
if (!container) return
const isFirstRender = previousCommentIdRef.current === undefined
const isNewComment = comment.id !== previousCommentIdRef.current
const hasNewReply =
previousReplyCountRef.current !== undefined && replies.length > previousReplyCountRef.current
// Scroll on first render, new comment, or new reply
if (isFirstRender || isNewComment || hasNewReply) {
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth',
})
}
previousCommentIdRef.current = comment.id
previousReplyCountRef.current = replies.length
}, [comment.id, replies.length])
return (
<div
className="absolute z-30 w-90 max-w-90"
style={{
left: canvasPosition.x + 40,
top: canvasPosition.y,
transform: 'translateY(-20%)',
}}
onMouseEnter={() => setCommentPreviewHovering(true)}
onMouseLeave={() => setCommentPreviewHovering(false)}
>
{/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The thread handles bubbling Escape after its child editor and menus have handled it. */}
<div
onKeyDown={(event) => {
if (event.defaultPrevented || event.nativeEvent.isComposing || event.key !== 'Escape')
return
if (editingReply.id || isCommentEditing) return
event.preventDefault()
event.stopPropagation()
onClose()
}}
className="relative flex h-90 flex-col overflow-hidden rounded-2xl border border-components-panel-border bg-components-panel-bg shadow-xl"
role="dialog"
aria-labelledby="comment-thread-title"
>
<div className="flex items-center justify-between rounded-t-2xl border-b border-components-panel-border bg-components-panel-bg-blur px-4 py-3">
<div id="comment-thread-title" className="font-semibold text-text-primary uppercase">
{t(($) => $['comments.panelTitle'], { ns: 'workflowComments' })}
</div>
<div className="flex items-center gap-1">
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={loading}
className={cn(
'flex size-6 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent disabled:hover:text-text-disabled',
)}
onClick={onDelete}
aria-label={t(($) => $['comments.aria.deleteComment'], {
ns: 'workflowComments',
})}
>
<RiDeleteBinLine className="size-4" />
</button>
}
/>
<TooltipContent>
{t(($) => $['comments.aria.deleteComment'], { ns: 'workflowComments' })}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={comment.resolved || loading}
className={cn(
'flex size-6 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent disabled:hover:text-text-disabled',
)}
onClick={onResolve}
aria-label={t(($) => $['comments.aria.resolveComment'], {
ns: 'workflowComments',
})}
>
{comment.resolved ? (
<RiCheckboxCircleFill className="size-4" />
) : (
<RiCheckboxCircleLine className="size-4" />
)}
</button>
}
/>
<TooltipContent>
{t(($) => $['comments.aria.resolveComment'], { ns: 'workflowComments' })}
</TooltipContent>
</Tooltip>
<Separator orientation="vertical" className="mx-2 h-3.5" />
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={!canGoPrev || loading}
className={cn(
'flex size-6 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent disabled:hover:text-text-disabled',
)}
onClick={onPrev}
aria-label={t(($) => $['comments.aria.previousComment'], {
ns: 'workflowComments',
})}
>
<RiArrowUpSLine className="size-4" />
</button>
}
/>
<TooltipContent>
{t(($) => $['comments.aria.previousComment'], { ns: 'workflowComments' })}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={!canGoNext || loading}
className={cn(
'flex size-6 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent disabled:hover:text-text-disabled',
)}
onClick={onNext}
aria-label={t(($) => $['comments.aria.nextComment'], {
ns: 'workflowComments',
})}
>
<RiArrowDownSLine className="size-4" />
</button>
}
/>
<TooltipContent>
{t(($) => $['comments.aria.nextComment'], { ns: 'workflowComments' })}
</TooltipContent>
</Tooltip>
<button
type="button"
className="flex size-6 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary"
onClick={onClose}
aria-label={t(($) => $['comments.aria.closeComment'], { ns: 'workflowComments' })}
>
<RiCloseLine className="size-4" />
</button>
</div>
</div>
<div ref={messageListRef} className="relative mt-2 flex-1 overflow-y-auto px-4 pb-4">
<div className="group relative -mx-4 rounded-lg px-4 py-2 transition-colors hover:bg-components-panel-on-panel-item-bg-hover">
{isOwnComment && !isCommentEditing && (
<Menu
open={activeReplyMenuId === comment.id}
onOpenChange={(open) => setActiveReplyMenuId(open ? comment.id : null)}
>
<MenuTrigger
className="absolute top-1 right-1 flex size-6 items-center justify-center rounded-md text-text-tertiary opacity-0 group-hover:opacity-100 hover:bg-state-base-hover hover:text-text-secondary focus:opacity-100 data-popup-open:opacity-100 [@media(hover:none)]:opacity-100"
aria-label={t(($) => $['comments.aria.commentActions'], {
ns: 'workflowComments',
})}
>
<RiMoreFill className="size-4" />
</MenuTrigger>
<MenuContent align="end" className="w-36 backdrop-blur-[10px]">
<MenuItem
className="px-3"
onClick={(e) => {
e.stopPropagation()
handleStartCommentEdit()
}}
>
{t(($) => $['comments.actions.editComment'], { ns: 'workflowComments' })}
</MenuItem>
</MenuContent>
</Menu>
)}
{isCommentEditing ? (
<div className="flex gap-3 pt-1">
<div className="shrink-0">
<Avatar size="md" aria-hidden="true">
<AvatarFallback>
{getAvatarInitial(
comment.created_by_account?.name ||
t(($) => $['comments.fallback.user'], { ns: 'workflowComments' }),
)}
</AvatarFallback>
<AvatarImage src={comment.created_by_account?.avatar_url || undefined} alt="" />
</Avatar>
</div>
<div className="min-w-0 flex-1">
<div className="rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-1 shadow-md backdrop-blur-[10px]">
<MentionInput
value={editingCommentContent}
onChange={setEditingCommentContent}
onSubmit={handleCommentEditSubmit}
onCancel={handleCancelCommentEdit}
placeholder={t(($) => $['comments.placeholder.editComment'], {
ns: 'workflowComments',
})}
disabled={loading}
loading={isSubmittingEdit}
isEditing={true}
className="system-sm-regular"
autoFocus
/>
</div>
</div>
</div>
) : (
<ThreadMessage
authorId={comment.created_by_account?.id || ''}
authorName={
comment.created_by_account?.name ||
t(($) => $['comments.fallback.user'], { ns: 'workflowComments' })
}
avatarUrl={comment.created_by_account?.avatar_url || null}
createdAt={comment.created_at ?? comment.updated_at ?? 0}
content={comment.content}
mentionableNames={mentionableNames}
/>
)}
</div>
{replies.length > 0 && (
<div className="mt-2 space-y-3 pt-3">
{replies.map((reply) => {
const isReplyEditing = editingReply?.id === reply.id
const isOwnReply = reply.created_by_account?.id === currentUserId
return (
<div
key={reply.id}
className="group relative -mx-4 rounded-lg px-4 py-2 transition-colors hover:bg-components-panel-on-panel-item-bg-hover"
>
{isOwnReply && !isReplyEditing && (
<Menu
open={activeReplyMenuId === reply.id}
onOpenChange={(open) => {
setActiveReplyMenuId(open ? reply.id : null)
}}
>
<MenuTrigger
ref={(element: HTMLButtonElement | null) => {
if (element) replyMenuTriggersRef.current.set(reply.id, element)
else replyMenuTriggersRef.current.delete(reply.id)
}}
className="absolute top-1 right-1 flex size-6 items-center justify-center rounded-md text-text-tertiary opacity-0 group-hover:opacity-100 hover:bg-state-base-hover hover:text-text-secondary focus:opacity-100 data-popup-open:opacity-100 [@media(hover:none)]:opacity-100"
data-reply-menu
aria-label={t(($) => $['comments.aria.replyActions'], {
ns: 'workflowComments',
})}
>
<RiMoreFill className="size-4" />
</MenuTrigger>
<MenuContent
align="end"
className="w-36 backdrop-blur-[10px]"
data-reply-menu
>
<MenuItem
onClick={(event) => {
event.stopPropagation()
handleStartEdit(reply)
}}
>
{t(($) => $['comments.actions.editReply'], {
ns: 'workflowComments',
})}
</MenuItem>
<MenuItem
variant="destructive"
onClick={(event) => {
event.stopPropagation()
setActiveReplyMenuId(null)
if (onReplyDeleteDirect) {
deleteReplyTriggerRef.current =
replyMenuTriggersRef.current.get(reply.id) ?? null
queueMicrotask(() => setDeletingReplyId(reply.id))
} else onReplyDelete?.(reply.id)
}}
>
{t(($) => $['comments.actions.deleteReply'], {
ns: 'workflowComments',
})}
</MenuItem>
</MenuContent>
</Menu>
)}
{isReplyEditing ? (
<div className="flex gap-3 pt-1">
<div className="shrink-0">
<Avatar size="md" aria-hidden="true">
<AvatarFallback>
{getAvatarInitial(
reply.created_by_account?.name ||
t(($) => $['comments.fallback.user'], { ns: 'workflowComments' }),
)}
</AvatarFallback>
<AvatarImage
src={reply.created_by_account?.avatar_url || undefined}
alt=""
/>
</Avatar>
</div>
<div className="min-w-0 flex-1">
<div className="rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-1 shadow-md backdrop-blur-[10px]">
<MentionInput
value={editingReply?.content ?? ''}
onChange={(newContent) =>
setEditingReply((prev) =>
prev ? { ...prev, content: newContent } : prev,
)
}
onSubmit={handleEditSubmit}
onCancel={handleCancelEdit}
placeholder={t(($) => $['comments.placeholder.editReply'], {
ns: 'workflowComments',
})}
disabled={loading}
loading={replyUpdating || isSubmittingEdit}
isEditing={true}
className="system-sm-regular"
autoFocus
/>
</div>
</div>
</div>
) : (
<ThreadMessage
authorId={reply.created_by_account?.id || ''}
authorName={
reply.created_by_account?.name ||
t(($) => $['comments.fallback.user'], { ns: 'workflowComments' })
}
avatarUrl={reply.created_by_account?.avatar_url || null}
createdAt={reply.created_at ?? 0}
content={reply.content}
mentionableNames={mentionableNames}
/>
)}
</div>
)
})}
</div>
)}
</div>
{loading && (
<div className="absolute inset-0 z-30 flex items-center justify-center bg-components-panel-bg/70 text-sm text-text-tertiary">
{t(($) => $['comments.loading'], { ns: 'workflowComments' })}
</div>
)}
{onReply && (
<div className="border-t border-components-panel-border px-4 py-3">
<div className="flex items-center gap-3">
<Avatar size="md" aria-hidden="true">
<AvatarFallback>
{getAvatarInitial(userProfile?.name || t(($) => $.you, { ns: 'common' }))}
</AvatarFallback>
<AvatarImage src={userProfile?.avatar_url || undefined} alt="" />
</Avatar>
<div className="flex-1 rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-0.5 shadow-sm">
<MentionInput
ref={replyInputRef}
value={replyContent}
onChange={setReplyContent}
onSubmit={handleReplySubmit}
placeholder={t(($) => $['comments.placeholder.reply'], {
ns: 'workflowComments',
})}
disabled={loading}
loading={replySubmitting}
/>
</div>
</div>
</div>
)}
</div>
<AlertDialog
open={deletingReplyId !== null}
onOpenChange={(open, eventDetails) => {
if (!open && loading) {
eventDetails.cancel()
return
}
if (!open) setDeletingReplyId(null)
}}
>
<AlertDialogContent
finalFocus={() =>
deleteReplyTriggerRef.current?.isConnected
? deleteReplyTriggerRef.current
: (replyInputRef.current ?? true)
}
>
<AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $['comments.actions.deleteReply'], { ns: 'workflowComments' })}
</AlertDialogTitle>
<AlertDialogDescription>
{t(($) => $['operation.confirmAction'], { ns: 'common' })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancelButton disabled={loading}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</AlertDialogCancelButton>
<AlertDialogConfirmButton
loading={loading}
onClick={async () => {
if (deletingReplyId) await onReplyDeleteDirect?.(deletingReplyId)
setDeletingReplyId(null)
}}
>
{t(($) => $['operation.delete'], { ns: 'common' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export const CommentThread = memo(CommentThreadComponent)
CommentThread.displayName = 'CommentThread'
@@ -0,0 +1,5 @@
import type { AccountWithRoleResponse } from '@dify/contracts/api/console/apps/types.gen'
export type UserProfile = Pick<AccountWithRoleResponse, 'id' | 'name' | 'email' | 'avatar_url'> & {
avatar_url?: string | null
}