import Button from '@components/atoms/buttons/button'; import Form from '@components/atoms/forms/form'; import Heading, { type HeadingLevel } from '@components/atoms/headings/heading'; import Spinner from '@components/atoms/loaders/spinner'; import LabelledField from '@components/molecules/forms/labelled-field'; import { FC, ReactNode, useState } from 'react'; import { useIntl } from 'react-intl'; import styles from './comment-form.module.scss'; export type CommentFormData = { comment: string; email: string; name: string; parentId?: number; website?: string; }; export type CommentFormProps = { /** * Set additional classnames to the form wrapper. */ className?: string; /** * Pass a component to print a success/error message. */ Notice?: ReactNode; /** * The comment parent id. */ parentId?: number; /** * A callback function to save comment. It takes a function as parameter to * reset the form. */ saveComment: (data: CommentFormData, reset: () => void) => Promise; /** * The form title. */ title?: string; /** * The title level. */ titleLevel?: HeadingLevel; }; const CommentForm: FC = ({ className = '', Notice, parentId, saveComment, title, titleLevel = 2, }) => { const intl = useIntl(); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [website, setWebsite] = useState(''); const [comment, setComment] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); /** * Reset all the form fields. */ const resetForm = () => { setName(''); setEmail(''); setWebsite(''); setComment(''); setIsSubmitting(false); }; const nameLabel = intl.formatMessage({ defaultMessage: 'Name:', description: 'CommentForm: name label', id: 'ZIrTee', }); const emailLabel = intl.formatMessage({ defaultMessage: 'Email:', description: 'CommentForm: email label', id: 'Bh7z5v', }); const websiteLabel = intl.formatMessage({ defaultMessage: 'Website:', description: 'CommentForm: website label', id: 'u41qSk', }); const commentLabel = intl.formatMessage({ defaultMessage: 'Comment:', description: 'CommentForm: comment label', id: 'A8hGaK', }); const formTitle = intl.formatMessage({ defaultMessage: 'Comment form', description: 'CommentForm: aria label', id: 'dz2kDV', }); const formAriaLabel = title ? undefined : formTitle; const formId = 'comment-form-title'; const formLabelledBy = title ? formId : undefined; /** * Handle form submit. */ const submitHandler = () => { setIsSubmitting(true); saveComment({ comment, email, name, parentId, website }, resetForm).then( () => setIsSubmitting(false) ); }; return (
{title && ( {title} )} {isSubmitting && ( )} {Notice} ); }; export default CommentForm;