Refactor: create separate directory for beer/brewery comments

This commit is contained in:
Aaron William Po
2023-05-02 23:27:12 -04:00
parent 954892a5ca
commit c5b546dcf6
7 changed files with 9 additions and 9 deletions

View File

@@ -0,0 +1,30 @@
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { FC, useState } from 'react';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
import CommentContentBody from './CommentContentBody';
import EditCommentBody from './EditCommentBody';
interface CommentCardProps {
comment: z.infer<typeof CommentQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
ref?: ReturnType<typeof useInView>['ref'];
}
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
const [inEditMode, setInEditMode] = useState(false);
return !inEditMode ? (
<CommentContentBody comment={comment} ref={ref} setInEditMode={setInEditMode} />
) : (
<EditCommentBody
comment={comment}
mutate={mutate}
setInEditMode={setInEditMode}
ref={ref}
/>
);
};
export default CommentCardBody;

View File

@@ -0,0 +1,47 @@
import UserContext from '@/contexts/userContext';
import { Dispatch, SetStateAction, FC, useContext } from 'react';
import { FaEllipsisH } from 'react-icons/fa';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { z } from 'zod';
interface CommentCardDropdownProps {
comment: z.infer<typeof CommentQueryResult>;
setInEditMode: Dispatch<SetStateAction<boolean>>;
}
const CommentCardDropdown: FC<CommentCardDropdownProps> = ({
comment,
setInEditMode,
}) => {
const { user } = useContext(UserContext);
const isCommentOwner = user?.id === comment.postedBy.id;
return (
<div className="dropdown-end dropdown">
<label tabIndex={0} className="btn-ghost btn-sm btn m-1">
<FaEllipsisH />
</label>
<ul
tabIndex={0}
className="dropdown-content menu rounded-box w-52 bg-base-100 p-2 shadow"
>
<li>
{isCommentOwner ? (
<button
type="button"
onClick={() => {
setInEditMode(true);
}}
>
Edit
</button>
) : (
<button>Report</button>
)}
</li>
</ul>
</div>
);
};
export default CommentCardDropdown;

View File

@@ -0,0 +1,67 @@
import UserContext from '@/contexts/userContext';
import useTimeDistance from '@/hooks/utilities/useTimeDistance';
import { format } from 'date-fns';
import { Dispatch, FC, SetStateAction, useContext } from 'react';
import { Link, Rating } from 'react-daisyui';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
import CommentCardDropdown from './CommentCardDropdown';
interface CommentContentBodyProps {
comment: z.infer<typeof CommentQueryResult>;
ref: ReturnType<typeof useInView>['ref'] | undefined;
setInEditMode: Dispatch<SetStateAction<boolean>>;
}
const CommentContentBody: FC<CommentContentBodyProps> = ({
comment,
ref,
setInEditMode,
}) => {
const { user } = useContext(UserContext);
const timeDistance = useTimeDistance(new Date(comment.createdAt));
return (
<div className="card-body animate-in fade-in-10" ref={ref}>
<div className="flex flex-row justify-between">
<div>
<h3 className="font-semibold sm:text-2xl">
<Link href={`/users/${comment.postedBy.id}`} className="link-hover link">
{comment.postedBy.username}
</Link>
</h3>
<h4 className="italic">
posted{' '}
<time
className="tooltip tooltip-bottom"
data-tip={format(new Date(comment.createdAt), 'MM/dd/yyyy')}
>
{timeDistance}
</time>{' '}
ago
</h4>
</div>
{user && <CommentCardDropdown comment={comment} setInEditMode={setInEditMode} />}
</div>
<div className="space-y-1">
<Rating value={comment.rating}>
{Array.from({ length: 5 }).map((val, index) => (
<Rating.Item
name="rating-1"
className="mask mask-star cursor-default"
disabled
aria-disabled
key={index}
/>
))}
</Rating>
<p>{comment.content}</p>
</div>
</div>
);
};
export default CommentContentBody;

View File

@@ -0,0 +1,19 @@
const CommentLoadingCardBody = () => {
return (
<div className="animate card-body h-52 fade-in-10">
<div className="flex animate-pulse space-x-4 slide-in-from-top">
<div className="flex-1 space-y-4 py-1">
<div className="h-4 w-3/4 rounded bg-base-100" />
<div className="space-y-2">
<div className="h-4 rounded bg-base-100" />
<div className="h-4 w-11/12 rounded bg-base-100" />
<div className="h-4 w-10/12 rounded bg-base-100" />
<div className="h-4 w-11/12 rounded bg-base-100" />
</div>
</div>
</div>
</div>
);
};
export default CommentLoadingCardBody;

View File

@@ -0,0 +1,158 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { FC, useState, useEffect, Dispatch, SetStateAction } from 'react';
import { Rating } from 'react-daisyui';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { useInView } from 'react-intersection-observer';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel';
import FormSegment from '../ui/forms/FormSegment';
import FormTextArea from '../ui/forms/FormTextArea';
interface CommentCardDropdownProps {
comment: z.infer<typeof CommentQueryResult>;
setInEditMode: Dispatch<SetStateAction<boolean>>;
ref: ReturnType<typeof useInView>['ref'] | undefined;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
}
const EditCommentBody: FC<CommentCardDropdownProps> = ({
comment,
setInEditMode,
ref,
mutate,
}) => {
const { register, handleSubmit, formState, setValue, watch } = useForm<
z.infer<typeof CreateCommentValidationSchema>
>({
defaultValues: {
content: comment.content,
rating: comment.rating,
},
resolver: zodResolver(CreateCommentValidationSchema),
});
const { errors } = formState;
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
return () => {
setIsDeleting(false);
};
}, []);
const handleDelete = async () => {
setIsDeleting(true);
const response = await fetch(`/api/beer-comments/${comment.id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete comment');
}
await mutate();
};
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data,
) => {
const response = await fetch(`/api/beer-comments/${comment.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: data.content,
rating: data.rating,
}),
});
if (!response.ok) {
throw new Error('Failed to update comment');
}
await mutate();
setInEditMode(false);
};
return (
<div className="card-body animate-in fade-in-10" ref={ref}>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div>
<FormInfo>
<FormLabel htmlFor="content">Edit your comment</FormLabel>
<FormError>{errors.content?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextArea
id="content"
formValidationSchema={register('content')}
placeholder="Comment"
rows={2}
error={!!errors.content?.message}
disabled={formState.isSubmitting || isDeleting}
/>
</FormSegment>
<div className="flex flex-row items-center justify-between">
<div>
<FormInfo>
<FormLabel htmlFor="rating">Change your rating</FormLabel>
<FormError>{errors.rating?.message}</FormError>
</FormInfo>
<Rating
value={watch('rating')}
onChange={(value) => {
setValue('rating', value);
}}
>
{Array.from({ length: 5 }).map((val, index) => (
<Rating.Item
name="rating-1"
className="mask mask-star cursor-default"
disabled={formState.isSubmitting || isDeleting}
aria-disabled={formState.isSubmitting || isDeleting}
key={index}
/>
))}
</Rating>
</div>
<div className="btn-group btn-group-horizontal">
<button
type="button"
className="btn-xs btn lg:btn-sm"
disabled={formState.isSubmitting || isDeleting}
onClick={() => {
setInEditMode(false);
}}
>
Cancel
</button>
<button
type="submit"
disabled={formState.isSubmitting || isDeleting}
className="btn-xs btn lg:btn-sm"
>
Save
</button>
<button
type="button"
className="btn-xs btn lg:btn-sm"
onClick={handleDelete}
disabled={isDeleting || formState.isSubmitting}
>
Delete
</button>
</div>
</div>
</div>
</form>
</div>
);
};
export default EditCommentBody;