Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wishlist Sheet on Product Card #1474

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-impalas-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bigcommerce/catalyst-core": patch
---

wishlist sheet added to product card on plp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { bodl } from '~/lib/bodl';

import { getCategoryPageData } from '../page-data';

type Category = Awaited<ReturnType<typeof getCategoryPageData>>['category'];
type Category = Awaited<ReturnType<typeof getCategoryPageData>>['data']['category'];
type productSearchItem = FragmentOf<typeof ProductCardFragment>;

interface Props {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client';
import { cache } from 'react';

import { getSessionCustomerId } from '~/auth';
import { client } from '~/client';
import { graphql, VariablesOf } from '~/client/graphql';
import { revalidate } from '~/client/revalidate-target';
import { BreadcrumbsFragment } from '~/components/breadcrumbs/fragment';
import { WishlistSheetFragment } from '~/components/wishlist-sheet/fragment';

import { CategoryTreeFragment } from './_components/sub-categories';

Expand All @@ -23,9 +25,14 @@ const CategoryPageQuery = graphql(
}
...CategoryTreeFragment
}
customer {
wishlists(first: 50) {
...WishlistSheetFragment
}
}
}
`,
[BreadcrumbsFragment, CategoryTreeFragment],
[BreadcrumbsFragment, CategoryTreeFragment, WishlistSheetFragment],
);

type Variables = VariablesOf<typeof CategoryPageQuery>;
Expand All @@ -40,5 +47,14 @@ export const getCategoryPageData = cache(async (variables: Variables) => {
fetchOptions: customerId ? { cache: 'no-store' } : { next: { revalidate } },
});

return response.data.site;
const wishlists = response.data.customer?.wishlists
? removeEdgesAndNodes(response.data.customer.wishlists).map((wishlist) => {
return {
...wishlist,
items: removeEdgesAndNodes(wishlist.items),
};
})
: [];

return { data: response.data.site, wishlists };
});
15 changes: 13 additions & 2 deletions core/app/[locale]/(default)/(faceted)/category/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getTranslations, unstable_setRequestLocale } from 'next-intl/server';

import { auth } from '~/auth';
import { Breadcrumbs } from '~/components/breadcrumbs';
import { ProductCard } from '~/components/product-card';
import { Pagination } from '~/components/ui/pagination';
Expand All @@ -27,7 +28,7 @@ interface Props {
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const categoryId = Number(params.slug);

const data = await getCategoryPageData({
const { data } = await getCategoryPageData({
categoryId,
});

Expand All @@ -53,7 +54,15 @@ export default async function Category({ params: { locale, slug }, searchParams

const categoryId = Number(slug);

const [{ category, categoryTree }, search] = await Promise.all([
const session = await auth();

const [
{
data: { category, categoryTree },
wishlists,
},
search,
] = await Promise.all([
getCategoryPageData({ categoryId }),
fetchFacetedSearch({ ...searchParams, category: categoryId }),
]);
Expand Down Expand Up @@ -116,6 +125,8 @@ export default async function Category({ params: { locale, slug }, searchParams
imageSize="wide"
key={product.entityId}
product={product}
showWishlistSheet={Boolean(session)}
wishlistsList={wishlists}
/>
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use server';

import { revalidatePath } from 'next/cache';
import { z } from 'zod';

import { createWishlist as createWishlistMutation } from '~/client/mutations/create-wishlist';
Expand All @@ -22,8 +21,6 @@ export const createWishlist = async (formData: FormData) => {
try {
const newWishlist = await createWishlistMutation({ input });

revalidatePath('/account/wishlists', 'page');

if (newWishlist) {
return {
status: 'success' as const,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
FormSubmit,
Input,
} from '~/components/ui/form';
import { useRouter } from '~/i18n/routing';

import { useAccountStatusContext } from '../../../_components/account-status-provider';

Expand Down Expand Up @@ -47,6 +48,8 @@ export const CreateWishlistForm = ({ onWishlistCreated }: CreateWishlistFormProp

const t = useTranslations('Account.Wishlist');

const router = useRouter();

const handleInputValidation = (e: ChangeEvent<HTMLInputElement>) => {
const validationStatus = e.target.validity.valueMissing;

Expand All @@ -62,6 +65,7 @@ export const CreateWishlistForm = ({ onWishlistCreated }: CreateWishlistFormProp
status: submit.status,
message: t('messages.created', { name: submit.data.name }),
});
router.refresh();
}

if (submit.status === 'error') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import { useTranslations } from 'next-intl';
import { FormProvider, useFormContext } from 'react-hook-form';
import { toast } from 'react-hot-toast';

import { WishlistSheet } from '~/app/[locale]/(default)/account/(tabs)/wishlists/_components/wishlist-sheet';
import { Wishlists } from '~/app/[locale]/(default)/product/[slug]/_components/details';
import { ProductItemFragment } from '~/client/fragments/product-item';
import { AddToCartButton } from '~/components/add-to-cart-button';
import { Link } from '~/components/link';
import { Button } from '~/components/ui/button';
import { WishlistSheet } from '~/components/wishlist-sheet';
import { bodl } from '~/lib/bodl';

import { handleAddToCart } from './_actions/add-to-cart';
Expand Down Expand Up @@ -158,7 +158,7 @@ export const ProductForm = ({ data: product, isLogged, wishlists }: ProductFormP
<div className="mt-4 flex flex-col gap-4 @md:flex-row">
<Submit data={product} />
{isLogged && wishlists ? (
<WishlistSheet productId={product.entityId} wishlistsData={wishlists} />
<WishlistSheet productId={product.entityId} wishlistsList={wishlists} />
) : (
<Button asChild type="button" variant="secondary">
<Link href="/login">
Expand Down
3 changes: 1 addition & 2 deletions core/app/[locale]/(default)/product/[slug]/page-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import { ProductItemFragment } from '~/client/fragments/product-item';
import { graphql, VariablesOf } from '~/client/graphql';
import { revalidate } from '~/client/revalidate-target';
import { BreadcrumbsFragment } from '~/components/breadcrumbs/fragment';

import { WishlistSheetFragment } from '../../account/(tabs)/wishlists/_components/wishlist-sheet/fragment';
import { WishlistSheetFragment } from '~/components/wishlist-sheet/fragment';

import { DescriptionFragment } from './_components/description';
import { DetailsFragment } from './_components/details';
Expand Down
15 changes: 15 additions & 0 deletions core/components/product-card/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useFormatter } from 'next-intl';

import { ResultOf } from '~/client/graphql';
import { ProductCard as ComponentProductCard } from '~/components/ui/product-card';
import { Wishlist, WishlistSheet } from '~/components/wishlist-sheet';
import { pricesTransformer } from '~/data-transformers/prices-transformer';

import { AddToCart } from './add-to-cart';
Expand All @@ -15,7 +16,9 @@ interface Props {
showCompare?: boolean;
showCart?: boolean;
showWishlist?: boolean;
showWishlistSheet?: boolean;
wishlistData?: DeleteWishlistItemFormProps;
wishlistsList?: Wishlist[];
}

export const ProductCard = ({
Expand All @@ -25,7 +28,9 @@ export const ProductCard = ({
showCart = true,
showCompare = true,
showWishlist = false,
showWishlistSheet = false,
wishlistData,
wishlistsList,
}: Props) => {
const format = useFormatter();

Expand All @@ -48,6 +53,16 @@ export const ProductCard = ({
price={price}
showCompare={showCompare}
subtitle={brand?.name}
wishlistSheet={
showWishlistSheet &&
wishlistsList && (
bc-alexsaiannyi marked this conversation as resolved.
Show resolved Hide resolved
<WishlistSheet
productId={product.entityId}
trigger="icon"
wishlistsList={wishlistsList}
/>
)
}
/>
);
};
3 changes: 3 additions & 0 deletions core/components/ui/product-card/product-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ interface Props extends Product {
imagePriority?: boolean;
imageSize?: 'square' | 'tall' | 'wide';
deleteFromWishlist?: ReactNode;
wishlistSheet?: ReactNode;
showCompare?: boolean;
}

Expand All @@ -53,6 +54,7 @@ const ProductCard = ({
price,
id,
deleteFromWishlist,
wishlistSheet,
showCompare = true,
subtitle,
name,
Expand Down Expand Up @@ -119,6 +121,7 @@ const ProductCard = ({
</div>
</div>
{deleteFromWishlist ? <div className="absolute right-0 top-0">{deleteFromWishlist}</div> : null}
{wishlistSheet ? <div className="absolute right-0 top-0">{wishlistSheet}</div> : null}
{addToCart}
</div>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use client';

import { Heart } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { PropsWithChildren, useEffect, useState } from 'react';
Expand All @@ -6,7 +8,7 @@ import { ExistingResultType } from '~/client/util';
import { Button } from '~/components/ui/button';
import { Sheet } from '~/components/ui/sheet';

import { AccountStatusProvider } from '../../../_components/account-status-provider';
import { AccountStatusProvider } from '../../app/[locale]/(default)/account/(tabs)/_components/account-status-provider';

import { addWishlistItems } from './update-wishlists-form/_actions/add-wishlist-items';
import { WishlistSheetContent } from './wishlist-sheet-content';
Expand All @@ -15,26 +17,29 @@ export type Wishlist = NonNullable<ExistingResultType<typeof addWishlistItems>['

interface WishlistSheetProps extends PropsWithChildren {
productId: number;
wishlistsData: Wishlist[];
trigger?: 'button' | 'icon';
wishlistsList: Wishlist[];
}

export const WishlistSheet = ({ productId, wishlistsData }: WishlistSheetProps) => {
export const WishlistSheet = ({
productId,
trigger = 'button',
wishlistsList,
}: WishlistSheetProps) => {
const t = useTranslations('Account.Wishlist.Sheet');

const [wishlists, setWishlists] = useState(() => {
if (wishlistsData.length === 0) {
return [{ items: [], entityId: 0, name: t('favorites') }];
}
const [wishlists, setWishlists] = useState(wishlistsList);

return wishlistsData;
});
useEffect(() => {
setWishlists(wishlistsList);
}, [wishlistsList]);

const [saved, setSaved] = useState(() => {
if (wishlistsData.length === 0) {
if (wishlistsList.length === 0) {
return false;
}

return wishlistsData.some(({ items }) => {
return wishlistsList.some(({ items }) => {
return items.some(({ product }) => product.entityId === productId);
});
});
Expand All @@ -52,14 +57,26 @@ export const WishlistSheet = ({ productId, wishlistsData }: WishlistSheetProps)
side="right"
title={t('title')}
trigger={
<Button type="button" variant="secondary">
<Heart
aria-hidden="true"
className="mx-2"
fill={saved ? 'currentColor' : 'transparent'}
/>
<span>{t(saved ? 'saved' : 'saveToWishlist')}</span>
</Button>
trigger === 'button' ? (
<Button type="button" variant="secondary">
<Heart
aria-hidden="true"
className="mx-2"
fill={saved ? 'currentColor' : 'transparent'}
/>
<span>{t(saved ? 'saved' : 'saveToWishlist')}</span>
</Button>
) : (
<Button
aria-label={t('open')}
className="p-3 text-black hover:bg-transparent hover:text-black"
title={t('open')}
type="button"
variant="subtle"
>
<Heart fill="currentColor" />
</Button>
)
}
>
<AccountStatusProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { createWishlist } from '~/client/mutations/create-wishlist';
import { Button } from '~/components/ui/button';
import { Message } from '~/components/ui/message';

import { useAccountStatusContext } from '../../../_components/account-status-provider';
import { Modal } from '../../../_components/modal';
import { CreateWishlistForm } from '../create-wishlist-form';
import { useAccountStatusContext } from '../../app/[locale]/(default)/account/(tabs)/_components/account-status-provider';
import { Modal } from '../../app/[locale]/(default)/account/(tabs)/_components/modal';
import { CreateWishlistForm } from '../../app/[locale]/(default)/account/(tabs)/wishlists/_components/create-wishlist-form';

import { UpdateWishlistsForm } from './update-wishlists-form';

Expand Down
3 changes: 2 additions & 1 deletion core/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@
"saved": "Saved",
"createTitle": "New wishlist",
"selectCta": "Select from available lists:",
"favorites": "Favorites"
"favorites": "Favorites",
"open": "Open wishlist sheet"
},
"Errors": {
"error": "Something went wrong. Please try again later."
Expand Down
Loading