import React, { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react' import { useMutation, useQueryClient } from '@tanstack/react-query' import type { AttachmentInfo, CommentInfo, PostAttachmentRequest, PostAttachmentResponse, UserInfo, } from '@shumai/dtos' import { FileIcon, FileText, Paperclip, XIcon } from 'lucide-react' import { toast } from 'sonner' import { client } from '@/ui/api/client' import { isImageFileName } from '@/ui/lib/media' import { m } from '@/ui/paraglide/messages.js' import { useMemberStore, type MemberInfo } from '@/ui/stores/members' import { useTeamContextStore } from '@/ui/stores/team-context' import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar' import { Button } from '../ui/button' import { DrawAnnotation } from '../ui/icons' import { ProgressCircle } from '../ui/progress-circle' import { Skeleton } from '../ui/skeleton' import { CommentVisibilitySelector } from './comment-visibility-selector' import { createMentionNode, hydrateEditableWithMentions, serializeEditableContent, } from './mention-utils' import type { UploadingFile } from './message-input' export interface MessageEditFormProps { projectId?: string teamId?: string message: CommentInfo parentIsInternal?: boolean getUser: (id: string) => MemberInfo | UserInfo displayTime: string hasDrawInfo: boolean onCancel: () => void onSaved: () => void } type MentionEntity = { type: 'user'; data: MemberInfo } export const MessageEditForm: React.FC = ({ projectId, teamId: propTeamId, message, parentIsInternal = false, getUser, displayTime, hasDrawInfo, onCancel, onSaved, }) => { const queryClient = useQueryClient() const editorRef = useRef(null) const fileInputRef = useRef(null) const mentionRangeRef = useRef(null) const mentionListRef = useRef(null) const [editedIsInternal, setEditedIsInternal] = useState( parentIsInternal ? true : Boolean(message.isInternal), ) const [editedSecond, setEditedSecond] = useState(message.second ?? null) const [keptAttachments, setKeptAttachments] = useState( () => message.attachments ?? [], ) const [uploadingFiles, setUploadingFiles] = useState([]) const [hasText, setHasText] = useState(() => Boolean((message.message ?? '').trim())) const [showMentionList, setShowMentionList] = useState(false) const [mentionQuery, setMentionQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(0) const { teamId: storeTeamId, ensureTeamIdForProject } = useTeamContextStore() const effectiveTeamId = propTeamId || storeTeamId const { members: storeMembers, loading: membersLoading, fetchMembers, fetchProjectMembers, } = useMemberStore() useEffect(() => { if (projectId && !effectiveTeamId) { ensureTeamIdForProject(projectId) } }, [projectId, effectiveTeamId, ensureTeamIdForProject]) // Hydrate editor once on mount so background comment polling never overwrites draft edits. useEffect(() => { const editor = editorRef.current if (!editor) return const resolveUserName = (userId: string) => { const fromMentions = message.mentions?.find((u) => u.id === userId) if (fromMentions?.name) return fromMentions.name const fromStore = getUser(userId) return fromStore?.name || 'Unknown' } hydrateEditableWithMentions(editor, message.message ?? '', resolveUserName) setHasText(Boolean(serializeEditableContent(editor))) editor.focus() const range = document.createRange() const sel = window.getSelection() range.selectNodeContents(editor) range.collapse(false) sel?.removeAllRanges() sel?.addRange(range) }, []) const { mutateAsync: uploadAttachment } = useMutation({ mutationFn: async ({ targetProjectId, data, }: { targetProjectId: string data: PostAttachmentRequest }) => { const res = await client.api.projects[':projectId'].attachments.$post({ param: { projectId: targetProjectId }, json: data, }) if (!res.ok) throw new Error('Failed to create attachment') return (await res.json()) as PostAttachmentResponse }, }) const { mutate: updateComment, isPending: isSaving } = useMutation({ mutationFn: async (payload: { message: string isInternal: boolean second: number | null attachmentIds: string[] }) => { const res = await client.api.comments[':commentId'].$patch({ param: { commentId: message.id }, json: payload, }) if (!res.ok) throw new Error('Failed to update comment') return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ predicate: (query) => query.queryKey.includes('comments'), }) onSaved() }, onError: () => { toast.error(m.failed_to_update_comment()) }, }) const filteredEntities: MentionEntity[] = storeMembers .filter((u) => u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase())) .map((u) => ({ type: 'user' as const, data: u })) useEffect(() => { setHighlightedIndex(0) }, [mentionQuery, showMentionList]) useEffect(() => { mentionListRef.current ?.querySelector(`[data-index="${highlightedIndex}"]`) ?.scrollIntoView({ block: 'nearest' }) }, [highlightedIndex]) const getInitials = (name: string) => name .split(' ') .map((n) => n[0]) .slice(0, 2) .join('') .toUpperCase() const handleInput = () => { if (!editorRef.current) return setHasText(Boolean(serializeEditableContent(editorRef.current))) const sel = window.getSelection() if (!sel || sel.rangeCount === 0) return const range = sel.getRangeAt(0) const node = range.startContainer const offset = range.startOffset if (node.nodeType === Node.TEXT_NODE) { const textContent = node.textContent || '' const textBeforeCursor = textContent.slice(0, offset) const lastAtPos = textBeforeCursor.lastIndexOf('@') if (lastAtPos !== -1) { const isStartOfLine = lastAtPos === 0 const charBeforeAt = textBeforeCursor[lastAtPos - 1] const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt) if (hasSpaceBefore) { const query = textBeforeCursor.slice(lastAtPos + 1) if (!/\s/.test(query)) { setMentionQuery(query) setShowMentionList(true) if (projectId) { fetchProjectMembers(projectId, true, true) } else if (effectiveTeamId) { fetchMembers(effectiveTeamId, true, true) } const mentionRange = document.createRange() mentionRange.setStart(node, lastAtPos) mentionRange.setEnd(node, offset) mentionRangeRef.current = mentionRange return } } } } setShowMentionList(false) mentionRangeRef.current = null } const handleSelectEntity = (entity: MentionEntity) => { if (!mentionRangeRef.current || !editorRef.current) return const range = mentionRangeRef.current range.deleteContents() const mentionNode = createMentionNode({ id: entity.data.id, name: entity.data.name }) range.insertNode(mentionNode) const spaceNode = document.createTextNode('\u00A0') mentionNode.after(spaceNode) const newRange = document.createRange() const sel = window.getSelection() newRange.setStartAfter(spaceNode) newRange.collapse(true) sel?.removeAllRanges() sel?.addRange(newRange) setShowMentionList(false) mentionRangeRef.current = null setHasText(true) editorRef.current.focus() } const handlePaste = (e: React.ClipboardEvent) => { e.preventDefault() const text = e.clipboardData.getData('text/plain') if (!text) return const success = typeof document.execCommand === 'function' && document.queryCommandSupported?.('insertText') && document.execCommand('insertText', false, text) if (!success) { const sel = window.getSelection() if (sel && sel.rangeCount > 0) { const range = sel.getRangeAt(0) range.deleteContents() const textNode = document.createTextNode(text) range.insertNode(textNode) range.setStartAfter(textNode) range.collapse(true) sel.removeAllRanges() sel.addRange(range) } else if (editorRef.current) { editorRef.current.innerText += text } } handleInput() } const handleFileSelect = useCallback( async (e: ChangeEvent) => { if (!e.target.files || !projectId) return const newFiles = Array.from(e.target.files) for (const file of newFiles) { const tempId = `${Date.now()}-${Math.random()}-${file.name}` setUploadingFiles((prev) => [...prev, { id: tempId, file, progress: 0 }]) try { const data = await uploadAttachment({ targetProjectId: projectId, data: { fileName: file.name, contentType: file.type, size: file.size, }, }) if (data.uploadUrl && data.id) { await fetch(data.uploadUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type, }, }) setUploadingFiles((prev) => prev.map((uf) => uf.id === tempId ? { ...uf, progress: 100, attachmentId: data.id } : uf, ), ) } } catch (error) { setUploadingFiles((prev) => prev.map((uf) => uf.id === tempId ? { ...uf, error: error instanceof Error ? error.message : 'Upload failed', } : uf, ), ) } } if (fileInputRef.current) { fileInputRef.current.value = '' } }, [projectId, uploadAttachment], ) const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error) const uploadedAttachmentIds = uploadingFiles .map((f) => f.attachmentId) .filter((id): id is string => Boolean(id)) const effectiveIsInternal = parentIsInternal ? true : editedIsInternal const canSave = !isSaving && !isUploading && (hasText || keptAttachments.length > 0 || uploadedAttachmentIds.length > 0 || hasDrawInfo) const handleSave = () => { if (!editorRef.current || !canSave) return const serialized = serializeEditableContent(editorRef.current) const attachmentIds = [...keptAttachments.map((att) => att.assetId), ...uploadedAttachmentIds] if (!serialized && attachmentIds.length === 0 && !hasDrawInfo) return updateComment({ message: serialized, isInternal: effectiveIsInternal, second: editedSecond, attachmentIds, }) } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.nativeEvent.isComposing) return if (showMentionList && filteredEntities.length > 0) { if (e.key === 'ArrowUp') { e.preventDefault() setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1)) return } if (e.key === 'ArrowDown') { e.preventDefault() setHighlightedIndex((prev) => (prev < filteredEntities.length - 1 ? prev + 1 : 0)) return } if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault() handleSelectEntity(filteredEntities[highlightedIndex]) return } if (e.key === 'Escape') { e.preventDefault() setShowMentionList(false) return } } if (e.key === 'Escape') { e.preventDefault() onCancel() return } if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleSave() } } return (
e.stopPropagation()} > {/* Mention dropdown */} {showMentionList && (membersLoading || filteredEntities.length > 0) && (
e.preventDefault()} className="absolute bottom-full left-0 mb-2 w-60 rounded-xl shadow-lg border border-border overflow-hidden z-30 bg-popover text-popover-foreground" >
{membersLoading ? (
) : ( filteredEntities.map((item, index) => ( )) )}
)} {/* Timestamp & Draw badges */} {((editedSecond !== null && displayTime) || hasDrawInfo) && (
{editedSecond !== null && displayTime && (
{displayTime}
)} {hasDrawInfo && (
)}
)} {/* Editable text box */}
{/* Existing & Newly Uploaded Attachments */} {(keptAttachments.length > 0 || uploadingFiles.length > 0) && (
{keptAttachments.map((att) => { const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file' const name = decodeURIComponent(rawName) const isImage = isImageFileName(name) return (
{isImage ? ( {name} ) : ( )} {name}
) })} {uploadingFiles.map((upload) => (
{upload.file.type.startsWith('image/') ? (
{upload.file.name} {!upload.attachmentId && !upload.error && (
)}
) : ( )}
{upload.file.name} {upload.error && ( {upload.error} )}
))}
)} {/* Action bar: attach + visibility on left, cancel + save on right */}
{projectId && ( <> )}
) }