import {Commentable} from '@common/comments/commentable'; import {Comment} from '@common/comments/comment'; import {useTrans} from '@common/i18n/use-trans'; import {useAuth} from '@common/auth/use-auth'; import {useCreateComment} from '@common/comments/requests/use-create-comment'; import {RefObject, useState} from 'react'; import clsx from 'clsx'; import {TextField} from '@common/ui/forms/input-field/text-field/text-field'; import {Avatar} from '@common/ui/images/avatar'; import {message} from '@common/i18n/message'; import {Trans} from '@common/i18n/trans'; import {useObjectRef} from '@react-aria/utils'; import {Button} from '@common/ui/buttons/button'; export interface NewCommentFormProps { commentable: Commentable; inReplyTo?: Comment; onSuccess?: () => void; className?: string; autoFocus?: boolean; inputRef?: RefObject; // additional data that should be sent to backend when creating comments payload?: Record; } export function NewCommentForm({ commentable, inReplyTo, onSuccess, className, autoFocus, payload, ...props }: NewCommentFormProps) { const {trans} = useTrans(); const {user} = useAuth(); const createComment = useCreateComment(); const inputRef = useObjectRef(props.inputRef); const [inputIsExpanded, setInputIsExpanded] = useState(false); const [inputValue, setInputValue] = useState(''); const clearInput = () => { setInputIsExpanded(false); if (inputRef.current) { inputRef.current.blur(); setInputValue(''); } }; return (
{ e.preventDefault(); if (inputValue && !createComment.isPending) { createComment.mutate( { ...payload, commentable, content: inputValue, inReplyTo, }, { onSuccess: () => { clearInput(); onSuccess?.(); }, }, ); } }} >
{user?.display_name} ), }} />
setInputValue(e.target.value)} onFocus={() => setInputIsExpanded(true)} onBlur={() => { if (!inputValue) { setInputIsExpanded(false); } }} minLength={3} rows={inputIsExpanded ? 3 : 1} placeholder={ inReplyTo ? trans(message('Write a reply')) : trans(message('Leave a comment')) } /> {inputIsExpanded && (
)}
); }