AbiirSkincare/Hydrogen/web/app/routes/collections.$handle.tsx

199 lines
5.0 KiB
TypeScript

import {redirect, useLoaderData} from 'react-router';
import type {Route} from '~/lib/reactRouterRouteStubs';
import {getPaginationVariables, Analytics} from '@shopify/hydrogen';
import {AbiirProductListItem} from '~/components/AbiirProductListItem';
import {CollectionPageView} from '~/components/CollectionPageView';
import {PaginatedResourceSection} from '~/components/PaginatedResourceSection';
import {getCollectionProductCountLine} from '~/lib/collectionPageSort';
import {
applyDisplayRatingsToListItemData,
mapStorefrontProductToAbiirProductListItemData,
type StorefrontProductNode,
} from '~/lib/featuredProducts';
import {ABIIR_PRODUCT_LIST_GRID_CLASS} from '~/lib/abiirProductListGrid';
import {loadProductDisplayRatingsByHandles} from '~/lib/productDisplayRatings.server';
import {redirectIfHandleIsLocalized} from '~/lib/redirect';
import type {ProductItemFragment} from 'storefrontapi.generated';
import {pageTitleWithShopName} from '~/lib/shopSeo';
export const meta: Route.MetaFunction = ({data, matches}) => {
return [
{
title: pageTitleWithShopName(
data?.collection.title ?? 'Collection',
matches,
),
},
];
};
export async function loader(args: Route.LoaderArgs) {
const deferredData = loadDeferredData(args);
const criticalData = await loadCriticalData(args);
return {...deferredData, ...criticalData};
}
async function loadCriticalData({context, params, request}: Route.LoaderArgs) {
const {handle} = params;
const {storefront, sanity} = context;
const paginationVariables = getPaginationVariables(request, {
pageBy: 8,
});
if (!handle) {
throw redirect('/collections/all');
}
const [{collection}] = await Promise.all([
storefront.query(COLLECTION_QUERY, {
variables: {handle, ...paginationVariables},
}),
]);
if (!collection) {
throw new Response(`Collection ${handle} not found`, {
status: 404,
});
}
redirectIfHandleIsLocalized(request, {handle, data: collection});
const nodes = collection.products?.nodes ?? [];
const productHandles = nodes
.map((p) => p?.handle)
.filter((h): h is string => typeof h === 'string' && h.length > 0);
const displayRatingsByHandle = await loadProductDisplayRatingsByHandles({
sanity,
handles: productHandles,
});
return {
collection,
productCountLine: getCollectionProductCountLine(
request,
collection.products,
),
displayRatingsByHandle,
};
}
function loadDeferredData({context}: Route.LoaderArgs) {
return {};
}
export default function Collection() {
const {collection, productCountLine, displayRatingsByHandle} =
useLoaderData<typeof loader>();
return (
<>
<CollectionPageView productCountLine={productCountLine} title={collection.title}>
<PaginatedResourceSection<ProductItemFragment>
connection={collection.products}
resourcesClassName={ABIIR_PRODUCT_LIST_GRID_CLASS}
>
{({node: product, index}) => {
const h = product.handle?.trim() ?? '';
const base = mapStorefrontProductToAbiirProductListItemData(
product as StorefrontProductNode,
);
const item = applyDisplayRatingsToListItemData(
base,
h ? displayRatingsByHandle[h] : undefined,
);
return (
<AbiirProductListItem
key={product.id}
index={index}
item={item}
/>
);
}}
</PaginatedResourceSection>
</CollectionPageView>
<Analytics.CollectionView
data={{
collection: {
id: collection.id,
handle: collection.handle,
},
}}
/>
</>
);
}
const PRODUCT_ITEM_FRAGMENT = `#graphql
fragment MoneyProductItem on MoneyV2 {
amount
currencyCode
}
fragment ProductItem on Product {
id
handle
title
vendor
tags
variants(first: 1) {
nodes {
id
availableForSale
}
}
featuredImage {
id
altText
url
width
height
}
priceRange {
minVariantPrice {
...MoneyProductItem
}
maxVariantPrice {
...MoneyProductItem
}
}
compareAtPriceRange {
minVariantPrice {
...MoneyProductItem
}
}
}
` as const;
const COLLECTION_QUERY = `#graphql
${PRODUCT_ITEM_FRAGMENT}
query Collection(
$handle: String!
$country: CountryCode
$language: LanguageCode
$first: Int
$last: Int
$startCursor: String
$endCursor: String
) @inContext(country: $country, language: $language) {
collection(handle: $handle) {
id
handle
title
products(
first: $first
last: $last
before: $startCursor
after: $endCursor
) {
nodes {
...ProductItem
}
pageInfo {
hasPreviousPage
hasNextPage
endCursor
startCursor
}
}
}
}
` as const;