fix: update PLP UI

This commit is contained in:
Chloe 2024-06-21 11:53:50 +07:00
parent cc3982288a
commit 441126c4b5
No known key found for this signature in database
GPG Key ID: CFD53CE570D42DF5
11 changed files with 178 additions and 118 deletions

View File

@ -6,7 +6,6 @@ import Breadcrumb from 'components/breadcrumb';
import BreadcrumbHome from 'components/breadcrumb/breadcrumb-home'; import BreadcrumbHome from 'components/breadcrumb/breadcrumb-home';
import FAQ from 'components/faq'; import FAQ from 'components/faq';
import YMMFilters, { YMMFiltersPlaceholder } from 'components/filters'; import YMMFilters, { YMMFiltersPlaceholder } from 'components/filters';
import Grid from 'components/grid';
import Manufacturers from 'components/home-page/manufacturers'; import Manufacturers from 'components/home-page/manufacturers';
import ProductsList from 'components/layout/products-list'; import ProductsList from 'components/layout/products-list';
import { getProductsInCollection } from 'components/layout/products-list/actions'; import { getProductsInCollection } from 'components/layout/products-list/actions';
@ -61,19 +60,18 @@ async function CategoryPage({
<MobileFilters filters={filters} menu={<SubMenu collection={params.collection} />} /> <MobileFilters filters={filters} menu={<SubMenu collection={params.collection} />} />
<SortingMenu /> <SortingMenu />
</div> </div>
<Grid className="hide-scrollbar max-h-[1000px] grid-cols-1 overflow-y-auto sm:grid-cols-2 sm:gap-x-8 lg:grid-cols-3">
{products.length === 0 ? ( {products.length === 0 ? (
<p className="py-3 text-lg">{`No products found in this collection`}</p> <p className="py-3 text-lg">{`No products found in this collection`}</p>
) : ( ) : (
<ProductsList <ProductsList
initialProducts={products} initialProducts={products}
pageInfo={pageInfo} pageInfo={pageInfo}
page="collection" page="collection"
searchParams={searchParams} searchParams={searchParams}
key={JSON.stringify(searchParams)} key={JSON.stringify(searchParams)}
/> />
)} )}
</Grid>
</> </>
); );
} }

View File

@ -43,10 +43,11 @@ const FiltersList = ({ years, makes, models, menu, autoFocusField }: FiltersList
null null
); );
const [model, setModel] = useState<Metaobject | null>( const [model, setModel] = useState<Metaobject | null>(
(make && models.find((model) => model.id === searchParams.get(MODEL_FILTER_ID))) || null models.find((model) => model.id === searchParams.get(MODEL_FILTER_ID)) || null
); );
const [year, setYear] = useState<Metaobject | null>( const [year, setYear] = useState<Metaobject | null>(
(model && years.find((y) => y.id === searchParams.get(YEAR_FILTER_ID))) || null years.find((y) => y.id === searchParams.get(YEAR_FILTER_ID)) || null
); );
const modelOptions = make ? models.filter((m) => get(m, 'make') === make.id) : models; const modelOptions = make ? models.filter((m) => get(m, 'make') === make.id) : models;
@ -63,9 +64,13 @@ const FiltersList = ({ years, makes, models, menu, autoFocusField }: FiltersList
); );
if (_make) { if (_make) {
setMake(_make); setMake((currentMake) => {
setModel(null); if (currentMake?.id !== _make.id) {
setYear(null); setModel(null);
setYear(null);
}
return _make;
});
} }
} }
}, [makeIdFromSearchParams, makes, params.collection, partType]); }, [makeIdFromSearchParams, makes, params.collection, partType]);

View File

@ -38,48 +38,48 @@ const Hero = async () => {
</div> </div>
</nav> </nav>
<div className="bg-white"> <div className="relative bg-gray-900">
<div className="relative bg-gray-900"> {/* Decorative image and overlay */}
{/* Decorative image and overlay */} <div aria-hidden="true" className="absolute inset-0 overflow-hidden">
<div aria-hidden="true" className="absolute inset-0 overflow-hidden"> {heroImage ? (
{heroImage ? ( <Suspense fallback={<div className="h-[626px] w-full" />}>
<Suspense fallback={<div className="h-[626px] w-full" />}> <ImageDisplay
<ImageDisplay fileId={heroImage.file as string}
fileId={heroImage.file as string} title="Hero Image"
title="Hero Image"
priority
className="h-full w-full object-cover object-center"
sizes="100vw"
width={1103}
height={626}
/>
</Suspense>
) : (
<Image
src="/hero-image.jpeg"
alt="Hero Image"
width={1103}
height={626}
priority priority
className="h-full w-full object-cover object-center" className="h-full w-full object-cover object-center"
sizes="100vw" sizes="100vw"
width={1103}
height={626}
/> />
)} </Suspense>
</div> ) : (
<div aria-hidden="true" className="absolute inset-0 bg-dark opacity-80" /> <Image
<div className="flex flex-col gap-10 px-6 py-32 text-center sm:py-56 lg:px-0"> src="/hero-image.jpeg"
<div className="relative mx-auto hidden flex-col items-center justify-center text-white md:flex"> alt="Hero Image"
<Image src="/best-price.svg" alt="Best Price" width={100} height={90} /> width={1103}
height={626}
priority
className="h-full w-full object-cover object-center"
sizes="100vw"
/>
)}
</div>
<div aria-hidden="true" className="absolute inset-0 bg-dark opacity-80" />
<div className="flex flex-col gap-10 px-6 py-20 text-center sm:pb-56 sm:pt-32 lg:px-0">
<div className="relative mx-auto hidden items-center justify-center gap-4 text-white md:flex">
<Image src="/best-price.svg" alt="Best Price" width={100} height={90} />
<div className="flex w-1/2 flex-col items-start gap-0.5 text-left">
<p className="tracking-wide">Best Price Guarantee</p> <p className="tracking-wide">Best Price Guarantee</p>
<p className="text-sm tracking-wide"> <p className="text-sm tracking-wide">
We will match or beat any competitor&apos;s pricing. We will match or beat any competitor&apos;s pricing.
</p> </p>
</div> </div>
<div className="relative mx-auto flex w-3/4 max-w-4xl flex-col items-center @container"> </div>
<Suspense fallback={<HomePageFiltersPlaceholder />}> <div className="relative mx-auto flex w-3/4 max-w-4xl flex-col items-center @container">
<HomePageFilters /> <Suspense fallback={<HomePageFiltersPlaceholder />}>
</Suspense> <HomePageFilters />
</div> </Suspense>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,9 +1,12 @@
'use client'; 'use client';
import { Button } from '@headlessui/react';
import clsx from 'clsx';
import Grid from 'components/grid'; import Grid from 'components/grid';
import { GridTileImage } from 'components/grid/tile'; import { GridTileImage } from 'components/grid/tile';
import LoadingDots from 'components/loading-dots';
import { Product } from 'lib/shopify/types'; import { Product } from 'lib/shopify/types';
import { useEffect, useRef, useState } from 'react'; import { useState } from 'react';
import { getProductsInCollection, searchProducts } from './actions'; import { getProductsInCollection, searchProducts } from './actions';
const ProductsList = ({ const ProductsList = ({
@ -22,16 +25,15 @@ const ProductsList = ({
}) => { }) => {
const [products, setProducts] = useState(initialProducts); const [products, setProducts] = useState(initialProducts);
const [_pageInfo, setPageInfo] = useState(pageInfo); const [_pageInfo, setPageInfo] = useState(pageInfo);
const lastElement = useRef(null); const [isLoading, setIsLoading] = useState(false);
useEffect(() => { const handleClickLoadMore = async () => {
const lastElementRef = lastElement.current; try {
const loadMoreProducts = async () => {
const params = { const params = {
searchParams, searchParams,
afterCursor: _pageInfo.endCursor afterCursor: _pageInfo.endCursor
}; };
setIsLoading(true);
const { products, pageInfo } = const { products, pageInfo } =
page === 'collection' page === 'collection'
? await getProductsInCollection(params) ? await getProductsInCollection(params)
@ -42,42 +44,45 @@ const ProductsList = ({
hasNextPage: pageInfo.hasNextPage, hasNextPage: pageInfo.hasNextPage,
endCursor: pageInfo.endCursor endCursor: pageInfo.endCursor
}); });
}; } catch (error) {
const observer = new IntersectionObserver( console.log('Failed to fetch products', error);
(entries) => { } finally {
if (entries[0]?.isIntersecting) { setIsLoading(false);
loadMoreProducts(); }
} };
},
{ threshold: 1 }
);
lastElementRef && observer.observe(lastElementRef);
return () => {
if (lastElementRef) {
observer.unobserve(lastElementRef);
}
};
}, [_pageInfo.endCursor, page, searchParams]);
return ( return (
<> <>
{products.map((product, index) => ( <Grid className="hide-scrollbar max-h-[1000px] grid-cols-1 overflow-y-auto border-b border-gray-100 pb-4 sm:grid-cols-2 sm:gap-x-8 lg:grid-cols-3">
<Grid.Item {products.map((product) => (
key={product.handle} <Grid.Item key={product.handle} className="animate-fadeIn">
className="animate-fadeIn" <GridTileImage
ref={index === products.length - 1 && _pageInfo.hasNextPage ? lastElement : undefined} alt={product.title}
> product={product}
<GridTileImage src={product.featuredImage?.url}
alt={product.title} fill
product={product} sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw"
src={product.featuredImage?.url} href={`/product/${product.handle}`}
fill />
sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw" </Grid.Item>
href={`/product/${product.handle}`} ))}
/> </Grid>
</Grid.Item> {_pageInfo.hasNextPage && (
))} <div className="mt-4 w-full">
<Button
className={clsx(
'mx-auto flex items-center gap-2 rounded border border-gray-600 px-2 py-1',
{ 'opacity-50': isLoading },
{ 'opacity-100': !isLoading }
)}
onClick={handleClickLoadMore}
disabled={isLoading}
>
{isLoading && <LoadingDots className="bg-black" />}
Load more products
</Button>
</div>
)}
</> </>
); );
}; };

View File

@ -0,0 +1,25 @@
import { getCollection } from 'lib/shopify';
import { cn } from 'lib/utils';
import Link from 'next/link';
const CollectionLink = async ({
collectionLinkId,
anchorText,
className
}: {
collectionLinkId: string;
anchorText: string;
className?: string;
}) => {
const collection = await getCollection({ id: collectionLinkId });
if (!collection) return null;
return (
<Link href={collection.path} className={cn('border p-2 text-sm text-gray-600', className)}>
{anchorText}
</Link>
);
};
export default CollectionLink;

View File

@ -1,13 +1,49 @@
import { getCollection } from 'lib/shopify'; import { getCollection, getMetaobjectsByIds } from 'lib/shopify';
import { Suspense } from 'react';
import CollectionLink from './collection-link';
const HelpfulLinks = async ({ ids }: { ids: string[] | null }) => {
if (!ids?.length) return null;
const links = await getMetaobjectsByIds(ids);
return (
<div className="flex w-full flex-wrap items-center gap-3 py-2">
{links.map((link) => (
<CollectionLink
key={link.id}
collectionLinkId={link.collection_link!}
anchorText={link.anchor_text!}
className="rounded border border-gray-600 px-3 py-1 text-sm"
/>
))}
</div>
);
};
const HelpfulLinksPlaceholder = () => {
return (
<div className="flex w-full animate-pulse items-center gap-3 py-2">
<div className="h-[30px] w-[150px] rounded bg-gray-200" />
<div className="h-[30px] w-[150px] rounded bg-gray-200" />
<div className="h-[30px] w-[150px] rounded bg-gray-200" />
</div>
);
};
const Header = async ({ collection }: { collection: string }) => { const Header = async ({ collection }: { collection: string }) => {
const collectionData = await getCollection({ handle: collection }); const collectionData = await getCollection({ handle: collection });
return collectionData ? ( return collectionData ? (
<div className="mb-3 mt-3 max-w-5xl lg:mb-1"> <>
<h1 className="text-4xl font-bold tracking-tight text-gray-900">{collectionData.title}</h1> <div className="mb-3 mt-3 max-w-5xl lg:mb-1">
<p className="mt-2 text-base text-gray-500">{collectionData.description}</p> <h1 className="text-4xl font-bold tracking-tight text-gray-900">{collectionData.title}</h1>
</div> <p className="mt-2 text-base text-gray-500">{collectionData.description}</p>
</div>
<Suspense fallback={<HelpfulLinksPlaceholder />}>
<HelpfulLinks ids={collectionData.helpfulLinksTop} />
</Suspense>
</>
) : null; ) : null;
}; };
@ -18,4 +54,5 @@ export const HeaderPlaceholder = () => {
</div> </div>
); );
}; };
export default Header; export default Header;

View File

@ -1,23 +1,6 @@
import { getCollection, getMetaobjectsByIds } from 'lib/shopify'; import { getCollection, getMetaobjectsByIds } from 'lib/shopify';
import Link from 'next/link'; import CollectionLink from './collection-link';
const LinkItem = async ({
collectionLinkId,
anchorText
}: {
collectionLinkId: string;
anchorText: string;
}) => {
const collection = await getCollection({ id: collectionLinkId });
if (!collection) return null;
return (
<Link href={collection.path} className="border p-2 text-sm text-gray-600">
{anchorText}
</Link>
);
};
const HelpfulLinks = async ({ collection }: { collection: string }) => { const HelpfulLinks = async ({ collection }: { collection: string }) => {
const collectionData = await getCollection({ handle: collection }); const collectionData = await getCollection({ handle: collection });
if (!collectionData || !collectionData.helpfulLinks) return null; if (!collectionData || !collectionData.helpfulLinks) return null;
@ -30,7 +13,7 @@ const HelpfulLinks = async ({ collection }: { collection: string }) => {
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
{helpfulLinks.map((link) => ( {helpfulLinks.map((link) => (
<LinkItem <CollectionLink
key={link.id} key={link.id}
collectionLinkId={link.collection_link!} collectionLinkId={link.collection_link!}
anchorText={link.anchor_text!} anchorText={link.anchor_text!}

View File

@ -21,7 +21,7 @@ const ManufacturerItem = ({
<ImageDisplay <ImageDisplay
fileId={manufacturer.logo as string} fileId={manufacturer.logo as string}
title={manufacturer.display_name || 'Logo'} title={manufacturer.display_name || 'Logo'}
className="aspect-1 h-7" className="aspect-1 w-8"
unoptimized unoptimized
/> />
</Suspense> </Suspense>

View File

@ -175,6 +175,7 @@ const reshapeCollection = (collection: ShopifyCollection): Collection | undefine
return { return {
...collection, ...collection,
helpfulLinks: parseMetaFieldValue<string[]>(collection.helpfulLinks), helpfulLinks: parseMetaFieldValue<string[]>(collection.helpfulLinks),
helpfulLinksTop: parseMetaFieldValue<string[]>(collection.helpfulLinksTop),
path: `/search/${collection.handle}` path: `/search/${collection.handle}`
}; };
}; };
@ -530,7 +531,8 @@ export async function getCollections(): Promise<Collection[]> {
}, },
path: '/search', path: '/search',
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
helpfulLinks: null helpfulLinks: null,
helpfulLinksTop: null
}, },
// Filter out the `hidden` collections. // Filter out the `hidden` collections.
// Collections that start with `hidden-*` need to be hidden on the search page. // Collections that start with `hidden-*` need to be hidden on the search page.

View File

@ -12,6 +12,9 @@ const collectionFragment = /* GraphQL */ `
helpfulLinks: metafield(namespace: "custom", key: "helpful_links") { helpfulLinks: metafield(namespace: "custom", key: "helpful_links") {
value value
} }
helpfulLinksTop: metafield(namespace: "custom", key: "helpful_links_top") {
value
}
updatedAt updatedAt
} }
${seoFragment} ${seoFragment}

View File

@ -40,9 +40,10 @@ export type CartItem = {
addOnProduct?: CartItem & { quantity: number }; addOnProduct?: CartItem & { quantity: number };
}; };
export type Collection = Omit<ShopifyCollection, 'helpfulLinks'> & { export type Collection = Omit<ShopifyCollection, 'helpfulLinks' | 'helpfulLinksTop'> & {
path: string; path: string;
helpfulLinks: string[] | null; helpfulLinks: string[] | null;
helpfulLinksTop: string[] | null;
}; };
export type Image = { export type Image = {
@ -225,6 +226,7 @@ export type ShopifyCollection = {
seo: SEO; seo: SEO;
updatedAt: string; updatedAt: string;
helpfulLinks: { value: string } | null; helpfulLinks: { value: string } | null;
helpfulLinksTop: { value: string } | null;
}; };
export type ShopifyProduct = { export type ShopifyProduct = {