AbiirSkincare/Hydrogen/web/app/lib/collectionPageSort.ts

87 lines
2.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export type CollectionSortParam =
| 'featured'
| 'price-asc'
| 'price-desc'
| 'alphabetical'
| 'newest';
const DEFAULT: CollectionSortParam = 'featured';
export function getCollectionSortParam(
searchParams: URLSearchParams,
): CollectionSortParam {
const s = searchParams.get('sort');
if (
s === 'price-asc' ||
s === 'price-desc' ||
s === 'alphabetical' ||
s === 'newest' ||
s === 'featured'
) {
return s;
}
return DEFAULT;
}
/** Collection handle pages — `collection { products(sortKey, reverse) }`. */
export function getStorefrontCollectionProductSort(
searchParams: URLSearchParams,
): {sortKey: string; reverse: boolean} {
const s = getCollectionSortParam(searchParams);
switch (s) {
case 'price-asc':
return {sortKey: 'PRICE', reverse: false};
case 'price-desc':
return {sortKey: 'PRICE', reverse: true};
case 'alphabetical':
return {sortKey: 'TITLE', reverse: false};
case 'newest':
return {sortKey: 'CREATED', reverse: true};
default:
return {sortKey: 'BEST_SELLING', reverse: false};
}
}
/** `/collections/all` — Skincare collection `products(sortKey, reverse)`. */
export function getStorefrontCatalogProductSort(
searchParams: URLSearchParams,
): {sortKey: string; reverse: boolean} {
const s = getCollectionSortParam(searchParams);
switch (s) {
case 'price-asc':
return {sortKey: 'PRICE', reverse: false};
case 'price-desc':
return {sortKey: 'PRICE', reverse: true};
case 'alphabetical':
return {sortKey: 'TITLE', reverse: false};
case 'newest':
return {sortKey: 'CREATED', reverse: true};
default:
return {sortKey: 'COLLECTION_DEFAULT', reverse: false};
}
}
/** First page only: “8 products” / “8+ products”; hidden when paginated with cursors. */
export function getCollectionProductCountLine(
request: Request,
connection: {nodes: unknown[]; pageInfo: {hasNextPage: boolean}},
): string | null {
const u = new URL(request.url);
if (u.searchParams.get('cursor')) return null;
const n = connection.nodes.length;
if (n === 0) return '0 products';
if (connection.pageInfo.hasNextPage) return `${n}+ products`;
return `${n} ${n === 1 ? 'product' : 'products'}`;
}
export const COLLECTION_PAGE_SORT_OPTIONS: {
value: CollectionSortParam;
label: string;
}[] = [
{value: 'featured', label: 'Featured'},
{value: 'newest', label: 'Newest'},
{value: 'price-asc', label: 'Price, low to high'},
{value: 'price-desc', label: 'Price, high to low'},
{value: 'alphabetical', label: 'Alphabetically, A–Z'},
];