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 FAQ from 'components/faq';
import YMMFilters, { YMMFiltersPlaceholder } from 'components/filters';
import Grid from 'components/grid';
import Manufacturers from 'components/home-page/manufacturers';
import ProductsList from 'components/layout/products-list';
import { getProductsInCollection } from 'components/layout/products-list/actions';
@ -61,19 +60,18 @@ async function CategoryPage({
<MobileFilters filters={filters} menu={<SubMenu collection={params.collection} />} />
<SortingMenu />
</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 ? (
<p className="py-3 text-lg">{`No products found in this collection`}</p>
) : (
<ProductsList
initialProducts={products}
pageInfo={pageInfo}
page="collection"
searchParams={searchParams}
key={JSON.stringify(searchParams)}
/>
)}
</Grid>
{products.length === 0 ? (
<p className="py-3 text-lg">{`No products found in this collection`}</p>
) : (
<ProductsList
initialProducts={products}
pageInfo={pageInfo}
page="collection"
searchParams={searchParams}
key={JSON.stringify(searchParams)}
/>
)}
</>
);
}

View File

@ -43,10 +43,11 @@ const FiltersList = ({ years, makes, models, menu, autoFocusField }: FiltersList
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>(
(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;
@ -63,9 +64,13 @@ const FiltersList = ({ years, makes, models, menu, autoFocusField }: FiltersList
);
if (_make) {
setMake(_make);
setModel(null);
setYear(null);
setMake((currentMake) => {
if (currentMake?.id !== _make.id) {
setModel(null);
setYear(null);
}
return _make;
});
}
}
}, [makeIdFromSearchParams, makes, params.collection, partType]);

View File

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

View File

@ -1,9 +1,12 @@
'use client';
import { Button } from '@headlessui/react';
import clsx from 'clsx';
import Grid from 'components/grid';
import { GridTileImage } from 'components/grid/tile';
import LoadingDots from 'components/loading-dots';
import { Product } from 'lib/shopify/types';
import { useEffect, useRef, useState } from 'react';
import { useState } from 'react';
import { getProductsInCollection, searchProducts } from './actions';
const ProductsList = ({
@ -22,16 +25,15 @@ const ProductsList = ({
}) => {
const [products, setProducts] = useState(initialProducts);
const [_pageInfo, setPageInfo] = useState(pageInfo);
const lastElement = useRef(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const lastElementRef = lastElement.current;
const loadMoreProducts = async () => {
const handleClickLoadMore = async () => {
try {
const params = {
searchParams,
afterCursor: _pageInfo.endCursor
};
setIsLoading(true);
const { products, pageInfo } =
page === 'collection'
? await getProductsInCollection(params)
@ -42,42 +44,45 @@ const ProductsList = ({
hasNextPage: pageInfo.hasNextPage,
endCursor: pageInfo.endCursor
});
};
const observer = new IntersectionObserver(
(entries) => {
if (entries[0]?.isIntersecting) {
loadMoreProducts();
}
},
{ threshold: 1 }
);
lastElementRef && observer.observe(lastElementRef);
return () => {
if (lastElementRef) {
observer.unobserve(lastElementRef);
}
};
}, [_pageInfo.endCursor, page, searchParams]);
} catch (error) {
console.log('Failed to fetch products', error);
} finally {
setIsLoading(false);
}
};
return (
<>
{products.map((product, index) => (
<Grid.Item
key={product.handle}
className="animate-fadeIn"
ref={index === products.length - 1 && _pageInfo.hasNextPage ? lastElement : undefined}
>
<GridTileImage
alt={product.title}
product={product}
src={product.featuredImage?.url}
fill
sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw"
href={`/product/${product.handle}`}
/>
</Grid.Item>
))}
<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">
{products.map((product) => (
<Grid.Item key={product.handle} className="animate-fadeIn">
<GridTileImage
alt={product.title}
product={product}
src={product.featuredImage?.url}
fill
sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw"
href={`/product/${product.handle}`}
/>
</Grid.Item>
))}
</Grid>
{_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 collectionData = await getCollection({ handle: collection });
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>
<p className="mt-2 text-base text-gray-500">{collectionData.description}</p>
</div>
<>
<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>
<p className="mt-2 text-base text-gray-500">{collectionData.description}</p>
</div>
<Suspense fallback={<HelpfulLinksPlaceholder />}>
<HelpfulLinks ids={collectionData.helpfulLinksTop} />
</Suspense>
</>
) : null;
};
@ -18,4 +54,5 @@ export const HeaderPlaceholder = () => {
</div>
);
};
export default Header;

View File

@ -1,23 +1,6 @@
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 collectionData = await getCollection({ handle: collection });
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">
{helpfulLinks.map((link) => (
<LinkItem
<CollectionLink
key={link.id}
collectionLinkId={link.collection_link!}
anchorText={link.anchor_text!}

View File

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

View File

@ -175,6 +175,7 @@ const reshapeCollection = (collection: ShopifyCollection): Collection | undefine
return {
...collection,
helpfulLinks: parseMetaFieldValue<string[]>(collection.helpfulLinks),
helpfulLinksTop: parseMetaFieldValue<string[]>(collection.helpfulLinksTop),
path: `/search/${collection.handle}`
};
};
@ -530,7 +531,8 @@ export async function getCollections(): Promise<Collection[]> {
},
path: '/search',
updatedAt: new Date().toISOString(),
helpfulLinks: null
helpfulLinks: null,
helpfulLinksTop: null
},
// Filter out the `hidden` collections.
// 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") {
value
}
helpfulLinksTop: metafield(namespace: "custom", key: "helpful_links_top") {
value
}
updatedAt
}
${seoFragment}

View File

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