import React, { useState, useRef, useEffect } from 'react' import { Paperclip, ArrowUp, X, Loader2, FileText, Image as ImageIcon } from 'lucide-react' import { useMutation } from '@tanstack/react-query' import { client } from '@/ui/api/client' import { m } from '@/ui/paraglide/messages.js' import { toast } from 'sonner' import { Button } from '@/ui/components/ui/button' import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { formatSize } from '@/ui/lib/format' import { useMemberStore, type MemberInfo } from '@/ui/stores/members' import type { KanbanAttachmentPayload, PostAttachmentRequest, PostKanbanAttachmentResponse, } from '@shumai/dtos' interface UploadingFile { id: string file: File isUploading: boolean payload?: KanbanAttachmentPayload error?: string } interface TaskCommentInputProps { teamId: string onSendMessage: (text: string, attachments?: KanbanAttachmentPayload[]) => Promise | void isSubmitting?: boolean } export function TaskCommentInput({ teamId, onSendMessage, isSubmitting }: TaskCommentInputProps) { const [text, setText] = useState('') const [uploadingFiles, setUploadingFiles] = useState([]) const [showMentionList, setShowMentionList] = useState(false) const [mentionQuery, setMentionQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(0) const textareaRef = useRef(null) const fileInputRef = useRef(null) const mentionListRef = useRef(null) const { members, fetchMembers } = useMemberStore() useEffect(() => { if (teamId) { fetchMembers(teamId, true, true) } }, [teamId, fetchMembers]) const { mutateAsync: getUploadUrl } = useMutation({ mutationFn: async (data: PostAttachmentRequest) => { const res = await client.api.teams[':teamId'].kanban.attachments.$post({ param: { teamId }, json: data, }) if (!res.ok) throw new Error('Failed to get attachment upload url') return (await res.json()) as PostKanbanAttachmentResponse }, }) // Auto-resize textarea const handleTextChange = (e: React.ChangeEvent) => { const val = e.target.value setText(val) if (textareaRef.current) { textareaRef.current.style.height = 'auto' textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px` } // Mention detection const cursorPos = e.target.selectionStart || 0 const textBeforeCursor = val.slice(0, cursorPos) 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) return } } } setShowMentionList(false) } const filteredMembers = members.filter((m) => m.name?.toLowerCase().includes(mentionQuery.toLowerCase()), ) useEffect(() => { setHighlightedIndex(0) }, [mentionQuery, showMentionList]) const handleSelectMention = (member: MemberInfo) => { if (!textareaRef.current) return const cursorPos = textareaRef.current.selectionStart || 0 const textBeforeCursor = text.slice(0, cursorPos) const textAfterCursor = text.slice(cursorPos) const lastAtPos = textBeforeCursor.lastIndexOf('@') if (lastAtPos !== -1) { const newText = `${text.slice(0, lastAtPos)}@${member.name} ${textAfterCursor}` setText(newText) setShowMentionList(false) setTimeout(() => { if (textareaRef.current) { textareaRef.current.focus() const newCursorPos = lastAtPos + member.name.length + 2 textareaRef.current.setSelectionRange(newCursorPos, newCursorPos) } }, 0) } } const handleFileSelect = async (e: React.ChangeEvent) => { const files = Array.from(e.target.files || []) if (files.length === 0) return const newUploading: UploadingFile[] = files.map((file) => ({ id: `${Date.now()}-${file.name}-${Math.random()}`, file, isUploading: true, })) setUploadingFiles((prev) => [...prev, ...newUploading]) for (const uf of newUploading) { try { const res = await getUploadUrl({ fileName: uf.file.name, size: uf.file.size, contentType: uf.file.type || 'application/octet-stream', }) // Direct upload to S3 const uploadRes = await fetch(res.uploadUrl, { method: 'PUT', body: uf.file, headers: { 'Content-Type': uf.file.type || 'application/octet-stream', }, }) if (!uploadRes.ok) { throw new Error('Failed to upload file to storage') } setUploadingFiles((prev) => prev.map((item) => item.id === uf.id ? { ...item, isUploading: false, payload: { id: res.id, name: res.name, key: res.key, sizeByte: res.sizeByte, contentType: res.contentType, proxyType: res.proxyType, }, } : item, ), ) } catch (err: unknown) { const message = err instanceof Error ? err.message : 'Upload failed' toast.error(`${uf.file.name}: ${message}`) setUploadingFiles((prev) => prev.map((item) => item.id === uf.id ? { ...item, isUploading: false, error: message } : item, ), ) } } if (fileInputRef.current) { fileInputRef.current.value = '' } } const removeFile = (id: string) => { setUploadingFiles((prev) => prev.filter((f) => f.id !== id)) } const isUploadingAny = uploadingFiles.some((f) => f.isUploading) const successfulAttachments = uploadingFiles .map((f) => f.payload) .filter((p): p is KanbanAttachmentPayload => !!p) const canSend = (text.trim().length > 0 || successfulAttachments.length > 0) && !isUploadingAny const handleSend = async () => { if (!canSend || isSubmitting) return try { await onSendMessage( text.trim(), successfulAttachments.length > 0 ? successfulAttachments : undefined, ) setText('') setUploadingFiles([]) if (textareaRef.current) { textareaRef.current.style.height = 'auto' } } catch { // Error handled by parent } } const handleKeyDown = (e: React.KeyboardEvent) => { if (showMentionList && filteredMembers.length > 0) { if (e.key === 'ArrowDown') { e.preventDefault() setHighlightedIndex((prev) => (prev + 1) % filteredMembers.length) return } if (e.key === 'ArrowUp') { e.preventDefault() setHighlightedIndex((prev) => (prev - 1 + filteredMembers.length) % filteredMembers.length) return } if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault() const selected = filteredMembers[highlightedIndex] if (selected) handleSelectMention(selected) return } if (e.key === 'Escape') { setShowMentionList(false) return } } if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault() handleSend() } } return (
{/* Mention Popup */} {showMentionList && filteredMembers.length > 0 && (
{filteredMembers.map((member, idx) => ( ))}
)} {/* Uploading / Attached Files Preview */} {uploadingFiles.length > 0 && (
{uploadingFiles.map((uf) => { const isImage = uf.file.type.startsWith('image/') return (
{uf.isUploading ? ( ) : isImage ? ( ) : ( )}
{uf.file.name} {formatSize(uf.file.size)}
) })}
)} {/* Text Area */}