import { ButtonSubmit } from '@components/Buttons'; import { Form, FormItem, Input, TextArea } from '@components/Form'; import Notice from '@components/Notice/Notice'; import Spinner from '@components/Spinner/Spinner'; import { createComment } from '@services/graphql/mutations'; import { NoticeType } from '@ts/types/app'; import { ForwardedRef, forwardRef, useState } from 'react'; import { useIntl } from 'react-intl'; import styles from './CommentForm.module.scss'; const CommentForm = ( { articleId, parentId = 0 }: { articleId: number; parentId?: number }, ref: ForwardedRef ) => { const intl = useIntl(); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [website, setWebsite] = useState(''); const [comment, setComment] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); const [notice, setNotice] = useState(); const [noticeType, setNoticeType] = useState('success'); const resetForm = () => { setName(''); setEmail(''); setWebsite(''); setComment(''); setIsSubmitting(false); }; const isEmptyString = (value: string): boolean => value.trim() === ''; const areRequiredFieldsSet = (): boolean => !isEmptyString(name) && !isEmptyString(email) && !isEmptyString(comment); const sendComment = async () => { const data = { author: name, authorEmail: email, authorUrl: website, content: comment, parent: parentId, commentOn: articleId, mutationId: 'createComment', }; const createdComment = await createComment(data); if (createdComment.success) { resetForm(); setNoticeType('success'); if (createdComment.comment?.approved) { setNotice( intl.formatMessage({ defaultMessage: 'Thanks for your comment!', description: 'CommentForm: success notice', }) ); } else { setNotice( intl.formatMessage({ defaultMessage: 'Thanks for your comment! It is now awaiting moderation.', description: 'CommentForm: success notice but awaiting moderation', }) ); } setTimeout(() => { setNotice(undefined); }, 10000); } else { setNoticeType('error'); setNotice( intl.formatMessage({ defaultMessage: 'An unexpected error happened. Comment cannot be submitted.', description: 'CommentForm: error notice', }) ); } }; const submitHandler = async (e: SubmitEvent) => { e.preventDefault(); setNotice(undefined); setIsSubmitting(true); if (areRequiredFieldsSet()) { sendComment(); } else { setIsSubmitting(false); setNoticeType('warning'); setNotice( intl.formatMessage({ defaultMessage: 'Some required fields are empty. Comment cannot be submitted.', description: 'CommentForm: missing required fields', }) ); } }; const isReply = parentId !== 0; const wrapperClasses = `${styles.wrapper} ${ isReply ? styles['wrapper--reply'] : '' }`; return (

{intl.formatMessage({ defaultMessage: 'Leave a comment', description: 'CommentForm: Form title', })}