From 2771de88f40a5f4ed7480bd8614532dda72deeda Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Sat, 4 Nov 2023 19:26:16 +0100 Subject: refactor(components): rewrite CommentForm component * remove `Notice` prop to handle it directly in the form * replace `saveComment` prop with `onSubmit` * use `useForm` hook to handle the form --- .../organisms/forms/comment-form/comment-form.tsx | 350 +++++++++------------ 1 file changed, 144 insertions(+), 206 deletions(-) (limited to 'src/components/organisms/forms/comment-form/comment-form.tsx') diff --git a/src/components/organisms/forms/comment-form/comment-form.tsx b/src/components/organisms/forms/comment-form/comment-form.tsx index 9059cbc..336e85a 100644 --- a/src/components/organisms/forms/comment-form/comment-form.tsx +++ b/src/components/organisms/forms/comment-form/comment-form.tsx @@ -1,26 +1,21 @@ -/* eslint-disable max-statements */ -import { - type ChangeEvent, - type FC, - type FormEvent, - type ReactNode, - useCallback, - useMemo, - useState, - useId, -} from 'react'; +import { type FC, useCallback, useId } from 'react'; import { useIntl } from 'react-intl'; -import { useBoolean } from '../../../../utils/hooks'; +import type { Nullable } from '../../../../types'; +import { + type FormSubmitHandler, + useForm, + type FormSubmitStatus, + type FormSubmitMessages, +} from '../../../../utils/hooks'; import { Button, Form, type FormProps, - Heading, - type HeadingLevel, Spinner, Input, TextArea, Label, + Notice, } from '../../../atoms'; import { LabelledField } from '../../../molecules'; import styles from './comment-form.module.scss'; @@ -33,93 +28,114 @@ export type CommentFormData = { website?: string; }; -export type CommentFormProps = Pick & { +export type CommentFormSubmit = FormSubmitHandler; + +export type CommentFormProps = Omit & { /** - * Pass a component to print a success/error message. + * A callback function to handle form submit. */ - Notice?: ReactNode; + onSubmit?: CommentFormSubmit; /** * 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. Default: 2. - */ - titleLevel?: HeadingLevel; }; export const CommentForm: FC = ({ className = '', - Notice, + onSubmit, parentId, - saveComment, - title, - titleLevel = 2, ...props }) => { + const formId = useId(); const formClass = `${styles.form} ${className}`; const intl = useIntl(); - const emptyForm: CommentFormData = useMemo(() => { - return { - author: '', - comment: '', - email: '', - parentId, - website: '', - }; - }, [parentId]); - const [data, setData] = useState(emptyForm); - const { - activate: activateNotice, - deactivate: deactivateNotice, - state: isSubmitting, - } = useBoolean(false); + const { messages, submit, submitStatus, update, values } = + useForm({ + initialValues: + /* The order matter: it will be reused to generate the fields in the right + * order. */ + { + parentId, + author: '', + email: '', + website: '', + comment: '', + }, + submitHandler: onSubmit, + }); - /** - * Reset all the form fields. - */ - const resetForm = useCallback(() => { - setData(emptyForm); - deactivateNotice(); - }, [deactivateNotice, emptyForm]); + const renderFields = useCallback(() => { + const entries = Object.entries(values) as [ + keyof CommentFormData, + CommentFormData[keyof CommentFormData], + ][]; + const labels: Record, string> = { + author: intl.formatMessage({ + defaultMessage: 'Name:', + description: 'CommentForm: name label', + id: 'ZIrTee', + }), + comment: intl.formatMessage({ + defaultMessage: 'Comment:', + description: 'CommentForm: comment label', + id: 'A8hGaK', + }), + email: intl.formatMessage({ + defaultMessage: 'Email:', + description: 'CommentForm: email label', + id: 'Bh7z5v', + }), + website: intl.formatMessage({ + defaultMessage: 'Website:', + description: 'CommentForm: website label', + id: 'u41qSk', + }), + }; - const nameLabel = intl.formatMessage({ - defaultMessage: 'Name:', - description: 'CommentForm: name label', - id: 'ZIrTee', - }); + return entries.map(([field, value]) => { + const isRequired = field !== 'website'; + const inputType = field === 'email' ? 'email' : 'text'; + const fieldId = `${formId}-${field}`; - const emailLabel = intl.formatMessage({ - defaultMessage: 'Email:', - description: 'CommentForm: email label', - id: 'Bh7z5v', - }); + return field === 'parentId' ? null : ( + + ) : ( + + ) + } + key={field} + label={ + + } + /> + ); + }); + }, [values, formId, intl, update]); - 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 btnLabel = intl.formatMessage({ + defaultMessage: 'Publish', + description: 'CommentForm: submit button', + id: 'OL0Yzx', }); const loadingMsg = intl.formatMessage({ @@ -128,137 +144,59 @@ export const CommentForm: FC = ({ id: 'IY5ew6', }); - const formAriaLabel = title ? undefined : formTitle; - const formId = useId(); - const formLabelledBy = title ? formId : undefined; - - const updateForm = useCallback( - (e: ChangeEvent) => { - switch (e.target.name) { - case 'author': - setData((prevData) => { - return { ...prevData, author: e.target.value }; - }); - break; - case 'comment': - setData((prevData) => { - return { ...prevData, comment: e.target.value }; - }); - break; - case 'email': - setData((prevData) => { - return { ...prevData, email: e.target.value }; - }); - break; - case 'website': - setData((prevData) => { - return { ...prevData, website: e.target.value }; - }); - break; + const renderNotice = useCallback( + ( + currentStatus: FormSubmitStatus, + msg: Nullable> + ) => { + switch (currentStatus) { + case 'FAILED': + return msg?.error ? ( + + {msg.error} + + ) : null; + case 'PENDING': + return ( + + {loadingMsg} + + ); + case 'SUCCEEDED': + return msg?.success ? ( + + {msg.success} + + ) : null; default: - break; + return null; } }, - [] - ); - - const sendForm = useCallback( - (e: FormEvent) => { - e.preventDefault(); - activateNotice(); - saveComment(data, resetForm).then(() => deactivateNotice()); - }, - [activateNotice, data, deactivateNotice, resetForm, saveComment] + [loadingMsg] ); return ( -
- {title ? ( - - {title} - - ) : null} - - } - label={ - - } - /> - - } - label={ - - } - /> - - } - label={} - /> - - } - label={ - - } - /> - - {isSubmitting ? {loadingMsg} : null} - {Notice} + {renderNotice(submitStatus, messages)} ); }; -- cgit v1.2.3