Restructure codebase to use src directory

This commit is contained in:
Aaron William Po
2023-04-11 23:32:06 -04:00
parent 90f2cc2c0c
commit 08422fe24e
141 changed files with 6 additions and 4 deletions

View File

@@ -0,0 +1,104 @@
import sendCreateBeerCommentRequest from '@/requests/sendCreateBeerCommentRequest';
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { zodResolver } from '@hookform/resolvers/zod';
import { FunctionComponent, useState, useEffect } from 'react';
import { Rating } from 'react-daisyui';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import Button from '../ui/forms/Button';
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 BeerCommentFormProps {
beerPost: z.infer<typeof beerPostQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
}
const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
beerPost,
mutate,
}) => {
const { register, handleSubmit, formState, reset, setValue } = useForm<
z.infer<typeof BeerCommentValidationSchema>
>({
defaultValues: {
rating: 0,
},
resolver: zodResolver(BeerCommentValidationSchema),
});
const [rating, setRating] = useState(0);
useEffect(() => {
setRating(0);
reset({ rating: 0, content: '' });
}, [reset]);
const onSubmit: SubmitHandler<z.infer<typeof BeerCommentValidationSchema>> = async (
data,
) => {
setValue('rating', 0);
setRating(0);
await sendCreateBeerCommentRequest({
content: data.content,
rating: data.rating,
beerPostId: beerPost.id,
});
await mutate();
reset();
};
const { errors } = formState;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
<div>
<FormInfo>
<FormLabel htmlFor="content">Leave a comment</FormLabel>
<FormError>{errors.content?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextArea
id="content"
formValidationSchema={register('content')}
placeholder="Comment"
rows={5}
error={!!errors.content?.message}
disabled={formState.isSubmitting}
/>
</FormSegment>
<FormInfo>
<FormLabel htmlFor="rating">Rating</FormLabel>
<FormError>{errors.rating?.message}</FormError>
</FormInfo>
<Rating
value={rating}
onChange={(value) => {
setRating(value);
setValue('rating', value);
}}
>
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
</Rating>
</div>
<div>
<Button type="submit" isSubmitting={formState.isSubmitting}>
Submit
</Button>
</div>
</form>
);
};
export default BeerCommentForm;

View File

@@ -0,0 +1,100 @@
import Link from 'next/link';
import format from 'date-fns/format';
import { FC, useContext } from 'react';
import UserContext from '@/contexts/userContext';
import { FaRegEdit } from 'react-icons/fa';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { z } from 'zod';
import useGetLikeCount from '@/hooks/useGetLikeCount';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerPostLikeButton from './BeerPostLikeButton';
const BeerInfoHeader: FC<{
beerPost: z.infer<typeof beerPostQueryResult>;
}> = ({ beerPost }) => {
const createdAt = new Date(beerPost.createdAt);
const timeDistance = useTimeDistance(createdAt);
const { user } = useContext(UserContext);
const idMatches = user && beerPost.postedBy.id === user.id;
const isPostOwner = !!(user && idMatches);
const { likeCount, mutate } = useGetLikeCount(beerPost.id);
return (
<main className="card flex flex-col justify-center bg-base-300">
<article className="card-body">
<div className="flex justify-between">
<header>
<h1 className="text-4xl font-bold">{beerPost.name}</h1>
<h2 className="text-2xl font-semibold">
by{' '}
<Link
href={`/breweries/${beerPost.brewery.id}`}
className="link-hover link text-2xl font-semibold"
>
{beerPost.brewery.name}
</Link>
</h2>
</header>
{isPostOwner && (
<div className="tooltip tooltip-left" data-tip={`Edit '${beerPost.name}'`}>
<Link
href={`/beers/${beerPost.id}/edit`}
className="btn-outline btn-sm btn"
>
<FaRegEdit className="text-xl" />
</Link>
</div>
)}
</div>
<h3 className="italic">
{' posted by '}
<Link href={`/users/${beerPost.postedBy.id}`} className="link-hover link">
{`${beerPost.postedBy.username} `}
</Link>
{timeDistance && (
<span
className="tooltip tooltip-right"
data-tip={format(createdAt, 'MM/dd/yyyy')}
>
{`${timeDistance} ago`}
</span>
)}
</h3>
<p>{beerPost.description}</p>
<div className="flex justify-between">
<div className="space-y-1">
<div>
<Link
className="link-hover link text-lg font-bold"
href={`/beers/types/${beerPost.type.id}`}
>
{beerPost.type.name}
</Link>
</div>
<div>
<span className="mr-4 text-lg font-medium">{beerPost.abv}% ABV</span>
<span className="text-lg font-medium">{beerPost.ibu} IBU</span>
</div>
<div>
{(!!likeCount || likeCount === 0) && (
<span>
Liked by {likeCount} user{likeCount !== 1 && 's'}
</span>
)}
</div>
</div>
<div className="card-actions items-end">
{user && <BeerPostLikeButton beerPostId={beerPost.id} mutateCount={mutate} />}
</div>
</div>
</article>
</main>
);
};
export default BeerInfoHeader;

View File

@@ -0,0 +1,140 @@
/* eslint-disable no-nested-ternary */
import UserContext from '@/contexts/userContext';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { FC, MutableRefObject, useContext, useRef } from 'react';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import { useRouter } from 'next/router';
import { useInView } from 'react-intersection-observer';
import { FaArrowUp } from 'react-icons/fa';
import BeerCommentForm from './BeerCommentForm';
import CommentCardBody from './CommentCardBody';
import NoCommentsCard from './NoCommentsCard';
import LoadingComponent from './LoadingComponent';
interface BeerPostCommentsSectionProps {
beerPost: z.infer<typeof beerPostQueryResult>;
}
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
const { user } = useContext(UserContext);
const router = useRouter();
const { id } = beerPost;
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
const PAGE_SIZE = 4;
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
useBeerPostComments({
id,
pageNum,
pageSize: PAGE_SIZE,
});
const { ref: lastCommentRef } = useInView({
/**
* When the last comment comes into view, call setSize from useBeerPostComments to
* load more comments.
*/
onChange: (visible) => {
if (!visible || isAtEnd) return;
setSize(size + 1);
},
});
const sectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
return (
<div className="w-full space-y-3">
<div className="card h-96 bg-base-300">
<div className="card-body h-full" ref={sectionRef}>
{user ? (
<BeerCommentForm beerPost={beerPost} mutate={mutate} />
) : (
<div className="flex h-full flex-col items-center justify-center">
<span className="text-lg font-bold">Log in to leave a comment.</span>
</div>
)}
</div>
</div>
{
/**
* If the comments are loading, show a loading component. Otherwise, show the
* comments.
*/
isLoading ? (
<div className="card bg-base-300 pb-6">
<LoadingComponent length={PAGE_SIZE} />
</div>
) : (
<>
{!!comments.length && (
<div className="card bg-base-300 pb-6">
{comments.map((comment, index) => {
const isLastComment = index === comments.length - 1;
/**
* Attach a ref to the last comment in the list. When it comes into
* view, the component will call setSize to load more comments.
*/
return (
<div
ref={isLastComment ? lastCommentRef : undefined}
key={comment.id}
>
<CommentCardBody comment={comment} mutate={mutate} />
</div>
);
})}
{
/**
* If there are more comments to load, show a loading component with a
* skeleton loader and a loading spinner.
*/
!!isLoadingMore && (
<LoadingComponent length={Math.floor(PAGE_SIZE / 2)} />
)
}
{
/**
* If the user has scrolled to the end of the comments, show a button
* that will scroll them back to the top of the comments section.
*/
!!isAtEnd && (
<div className="flex h-20 items-center justify-center text-center">
<div
className="tooltip tooltip-bottom"
data-tip="Scroll back to top of comments."
>
<button
type="button"
className="btn-ghost btn-sm btn"
aria-label="Scroll back to top of comments"
onClick={() => {
sectionRef.current?.scrollIntoView({
behavior: 'smooth',
});
}}
>
<FaArrowUp />
</button>
</div>
</div>
)
}
</div>
)}
{!comments.length && <NoCommentsCard />}
</>
)
}
</div>
);
};
export default BeerPostCommentsSection;

View File

@@ -0,0 +1,57 @@
import useCheckIfUserLikesBeerPost from '@/hooks/useCheckIfUserLikesBeerPost';
import sendLikeRequest from '@/requests/sendLikeRequest';
import { FC, useEffect, useState } from 'react';
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
import useGetLikeCount from '@/hooks/useGetLikeCount';
const BeerPostLikeButton: FC<{
beerPostId: string;
mutateCount: ReturnType<typeof useGetLikeCount>['mutate'];
}> = ({ beerPostId, mutateCount }) => {
const { isLiked, mutate: mutateLikeStatus } = useCheckIfUserLikesBeerPost(beerPostId);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(false);
}, [isLiked]);
const handleLike = async () => {
try {
setLoading(true);
await sendLikeRequest(beerPostId);
await mutateCount();
await mutateLikeStatus();
setLoading(false);
} catch (e) {
setLoading(false);
}
};
return (
<button
type="button"
className={`btn gap-2 rounded-2xl ${
!isLiked ? 'btn-ghost outline' : 'btn-primary'
}`}
onClick={() => {
handleLike();
}}
disabled={loading}
>
{isLiked ? (
<>
<FaThumbsUp className="text-2xl" />
Liked
</>
) : (
<>
<FaRegThumbsUp className="text-2xl" />
Like
</>
)}
</button>
);
};
export default BeerPostLikeButton;

View File

@@ -0,0 +1,34 @@
import BeerRecommendationQueryResult from '@/services/BeerPost/schema/BeerRecommendationQueryResult';
import Link from 'next/link';
import { FunctionComponent } from 'react';
interface BeerRecommendationsProps {
beerRecommendations: BeerRecommendationQueryResult[];
}
const BeerRecommendations: FunctionComponent<BeerRecommendationsProps> = ({
beerRecommendations,
}) => {
return (
<div className="card sticky top-2 h-full overflow-y-scroll bg-base-300">
<div className="card-body space-y-3">
{beerRecommendations.map((beerPost) => (
<div key={beerPost.id} className="w-full">
<div>
<Link className="link-hover" href={`/beers/${beerPost.id}`} scroll={false}>
<h2 className="text-2xl font-bold">{beerPost.name}</h2>
</Link>
<Link href={`/breweries/${beerPost.brewery.id}`} className="link-hover">
<p className="text-lg font-semibold">{beerPost.brewery.name}</p>
</Link>
</div>
<p>{beerPost.abv}% ABV</p>
<p>{beerPost.ibu} IBU</p>
</div>
))}
</div>
</div>
);
};
export default BeerRecommendations;

View File

@@ -0,0 +1,105 @@
import UserContext from '@/contexts/userContext';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
import format from 'date-fns/format';
import Link from 'next/link';
import { FC, useContext } from 'react';
import { Rating } from 'react-daisyui';
import { FaEllipsisH } from 'react-icons/fa';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
interface CommentCardProps {
comment: z.infer<typeof BeerCommentQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
ref?: ReturnType<typeof useInView>['ref'];
}
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
const { user } = useContext(UserContext);
const isCommentOwner = user?.id === comment.postedBy.id;
const handleDelete = async () => {
const response = await fetch(`/api/beer-comments/${comment.id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete comment');
}
await mutate();
};
return (
<div className="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 onClick={handleDelete}>Delete</button>
) : (
<button>Report</button>
)}
</li>
</ul>
</div>
);
};
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
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-col justify-between sm:flex-row">
<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} mutate={mutate} />}
</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 CommentCardBody;

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,22 @@
import { FC } from 'react';
import Spinner from '../ui/Spinner';
import CommentLoadingCardBody from './CommentLoadingCardBody';
interface LoadingComponentProps {
length: number;
}
const LoadingComponent: FC<LoadingComponentProps> = ({ length }) => {
return (
<>
{Array.from({ length }).map((_, i) => (
<CommentLoadingCardBody key={i} />
))}
<div className="p-1">
<Spinner size="sm" />
</div>
</>
);
};
export default LoadingComponent;

View File

@@ -0,0 +1,13 @@
const NoCommentsCard = () => {
return (
<div className="card bg-base-300">
<div className="card-body h-64">
<div className="flex h-full flex-col items-center justify-center">
<span className="text-lg font-bold">No comments yet.</span>
</div>
</div>
</div>
);
};
export default NoCommentsCard;