import { ButtonSubmit } from '@components/Buttons'; import { Field, Form, FormItem, Label } from '@components/FormElements'; 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 { useEffect, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; import styles from './CommentForm.module.scss'; const CommentForm = ({ articleId, parentId = 0, }: { articleId: number; parentId?: number; }) => { 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 nameFieldRef = useRef(null); useEffect(() => { if (parentId === 0) return; nameFieldRef.current && nameFieldRef.current.focus(); }); 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', id: 'AVUUgG', }) ); } else { setNotice( intl.formatMessage({ defaultMessage: 'Thanks for your comment! It is now awaiting moderation.', description: 'CommentForm: success notice but awaiting moderation', id: 'Ul2NIl', }) ); } setTimeout(() => { setNotice(undefined); }, 10000); } else { setNoticeType('error'); setNotice( intl.formatMessage({ defaultMessage: 'An unexpected error happened. Comment cannot be submitted.', description: 'CommentForm: error notice', id: 'cjK9Ad', }) ); } }; 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', id: 'Rle+UK', }) ); } }; const isReply = parentId !== 0; const wrapperClasses = `${styles.wrapper} ${ isReply ? styles['wrapper--reply'] : '' }`; const getLabel = ( body: string, htmlFor: string, required: boolean = false ) => { return