663 lines
20 KiB
TypeScript
663 lines
20 KiB
TypeScript
import type * as StorefrontAPI from '@shopify/hydrogen/storefront-api-types';
|
||
import type {SanityContext} from 'hydrogen-sanity';
|
||
import {unwrapSanityQueryResult} from '~/lib/abiirProductDetail';
|
||
import type {PdpProductReviewStats} from '~/lib/productReviewTypes';
|
||
import bundleFallbackSrc from '~/assets/spring-glow-bundle.png';
|
||
|
||
/** GraphQL: batch-fetch products by Storefront search query (`handle:a OR handle:b`). */
|
||
const FEATURED_PRODUCT_MONEY = `#graphql
|
||
fragment MoneyFeaturedProduct on MoneyV2 {
|
||
amount
|
||
currencyCode
|
||
}
|
||
` as const;
|
||
|
||
const FEATURED_PRODUCT_NODE = `#graphql
|
||
fragment FeaturedProductNode on Product {
|
||
id
|
||
handle
|
||
title
|
||
vendor
|
||
tags
|
||
variants(first: 1) {
|
||
nodes {
|
||
id
|
||
availableForSale
|
||
}
|
||
}
|
||
featuredImage {
|
||
id
|
||
altText
|
||
url
|
||
width
|
||
height
|
||
}
|
||
priceRange {
|
||
minVariantPrice {
|
||
...MoneyFeaturedProduct
|
||
}
|
||
}
|
||
compareAtPriceRange {
|
||
minVariantPrice {
|
||
...MoneyFeaturedProduct
|
||
}
|
||
}
|
||
}
|
||
${FEATURED_PRODUCT_MONEY}
|
||
` as const;
|
||
|
||
export const FEATURED_PRODUCTS_STOREFRONT_QUERY = `#graphql
|
||
query FeaturedProductsCatalog(
|
||
$country: CountryCode
|
||
$language: LanguageCode
|
||
$query: String!
|
||
) @inContext(country: $country, language: $language) {
|
||
products(first: 10, query: $query) {
|
||
nodes {
|
||
...FeaturedProductNode
|
||
}
|
||
}
|
||
}
|
||
${FEATURED_PRODUCT_NODE}
|
||
` as const;
|
||
|
||
/** Wishlist page: batch fetch by handle search (max 50). */
|
||
export const WISHLIST_PRODUCTS_STOREFRONT_QUERY = `#graphql
|
||
query WishlistProductsCatalog(
|
||
$country: CountryCode
|
||
$language: LanguageCode
|
||
$query: String!
|
||
) @inContext(country: $country, language: $language) {
|
||
products(first: 50, query: $query) {
|
||
nodes {
|
||
...FeaturedProductNode
|
||
}
|
||
}
|
||
}
|
||
${FEATURED_PRODUCT_NODE}
|
||
` as const;
|
||
|
||
/** Storefront collection that powers the homepage “Most Loved” product strip (merchandising order in Admin). */
|
||
export const FRONTPAGE_FEATURED_COLLECTION_HANDLE = 'frontpage' as const;
|
||
|
||
const FRONTPAGE_FEATURED_COLLECTION_QUERY = `#graphql
|
||
query FrontpageFeaturedCollection(
|
||
$country: CountryCode
|
||
$language: LanguageCode
|
||
$handle: String!
|
||
$first: Int!
|
||
) @inContext(country: $country, language: $language) {
|
||
collection(handle: $handle) {
|
||
id
|
||
handle
|
||
products(first: $first) {
|
||
nodes {
|
||
...FeaturedProductNode
|
||
}
|
||
}
|
||
}
|
||
}
|
||
${FEATURED_PRODUCT_NODE}
|
||
` as const;
|
||
|
||
export type FeaturedProductSlotCms = {
|
||
productHandle: string;
|
||
hideBadge?: boolean;
|
||
cardTitle?: string | null;
|
||
subtitle?: string | null;
|
||
benefitChips?: string[] | null;
|
||
rating?: number | null;
|
||
reviewCount?: number | null;
|
||
};
|
||
|
||
export type FeaturedProductsCms = {
|
||
eyebrow: string;
|
||
title: string;
|
||
filterPills: {label: string; href: string}[];
|
||
viewAllLabel: string;
|
||
viewAllHref: string;
|
||
items: FeaturedProductSlotCms[];
|
||
};
|
||
|
||
export type AbiirProductListItemMoney = Pick<
|
||
StorefrontAPI.MoneyV2,
|
||
'amount' | 'currencyCode'
|
||
>;
|
||
|
||
export type AbiirProductListItemImage = {
|
||
id?: string;
|
||
url: string;
|
||
altText?: string;
|
||
width?: number;
|
||
height?: number;
|
||
};
|
||
|
||
/**
|
||
* Normalized row for `AbiirProductListItem` (Shopify + Sanity overrides + shared card image).
|
||
*/
|
||
export type AbiirProductListItemData = {
|
||
handle: string;
|
||
productTitle: string;
|
||
displayTitle: string;
|
||
subtitle: string;
|
||
imageForCard: AbiirProductListItemImage | null;
|
||
/** First sellable variant — used for quick add overlays on cards. */
|
||
firstVariantId?: string | null;
|
||
availableForSale?: boolean;
|
||
price: AbiirProductListItemMoney;
|
||
compareAtPrice: AbiirProductListItemMoney | null;
|
||
tags: string[];
|
||
benefits: string[];
|
||
rating: number;
|
||
reviewCount: number;
|
||
hideBadge: boolean;
|
||
};
|
||
|
||
export type StorefrontProductNode = {
|
||
id?: string;
|
||
handle?: string | null;
|
||
title?: string | null;
|
||
vendor?: string | null;
|
||
tags?: string[];
|
||
variants?: {
|
||
nodes?: Array<{id?: string | null; availableForSale?: boolean | null} | null> | null;
|
||
} | null;
|
||
featuredImage?: AbiirProductListItemImage | null;
|
||
priceRange?: {
|
||
minVariantPrice?: AbiirProductListItemMoney | null;
|
||
} | null;
|
||
compareAtPriceRange?: {
|
||
minVariantPrice?: AbiirProductListItemMoney | null;
|
||
} | null;
|
||
};
|
||
|
||
type SanityFeaturedPayload = {
|
||
eyebrow?: string | null;
|
||
title?: string | null;
|
||
filterPills?: Array<{label?: string | null; href?: string | null} | null> | null;
|
||
viewAllLabel?: string | null;
|
||
viewAllHref?: string | null;
|
||
items?: Array<{
|
||
productHandle?: string | null;
|
||
hideBadge?: boolean | null;
|
||
cardTitle?: string | null;
|
||
subtitle?: string | null;
|
||
benefitChips?: Array<string | null> | null;
|
||
rating?: number | null;
|
||
reviewCount?: number | null;
|
||
} | null> | null;
|
||
} | null;
|
||
|
||
export const MOCK_MONEY = (amount: string): AbiirProductListItemMoney => ({
|
||
amount,
|
||
currencyCode: 'USD' as StorefrontAPI.CurrencyCode,
|
||
});
|
||
|
||
export const MOCK_FEATURED_IMAGE: AbiirProductListItemImage = {
|
||
id: 'mock-featured-shared',
|
||
url: bundleFallbackSrc,
|
||
altText: 'ABiiR skincare product',
|
||
width: 846,
|
||
height: 1127,
|
||
};
|
||
|
||
/** Homepage featured strip filter chips (overridden in the loader; kept for mocks / Storybook). */
|
||
export const DEFAULT_FEATURED_FILTER_PILLS: {label: string; href: string}[] = [
|
||
{label: 'BESTSELLERS', href: '/collections/bestsellers'},
|
||
{label: 'Face', href: '/collections/face'},
|
||
{label: 'Ritual', href: '/collections/ritual'},
|
||
];
|
||
|
||
/** Strip New Arrivals pill when the collection is not merchandised yet. */
|
||
export function omitNewArrivalsFilterPills<T extends {label: string; href: string}>(
|
||
pills: T[],
|
||
): T[] {
|
||
return pills.filter((p) => {
|
||
const href = p.href.trim().toLowerCase();
|
||
const label = p.label.trim().toLowerCase().replace(/\s+/g, ' ');
|
||
if (href.includes('new-arrivals')) return false;
|
||
if (label === 'new arrivals' || label === 'new arrival') return false;
|
||
return true;
|
||
});
|
||
}
|
||
|
||
/** Defaults from `React/src/app/components/FeaturedProducts.tsx` + product data. */
|
||
export const MOCK_FEATURED_PRODUCTS_CMS: FeaturedProductsCms = {
|
||
eyebrow: 'Curated Picks',
|
||
title: 'Most Loved',
|
||
filterPills: DEFAULT_FEATURED_FILTER_PILLS,
|
||
viewAllLabel: 'View All Products',
|
||
viewAllHref: '/collections/all',
|
||
items: [
|
||
{productHandle: 'face-mask'},
|
||
{productHandle: 'face-scrub'},
|
||
{
|
||
productHandle: 'experience-kit',
|
||
hideBadge: true,
|
||
subtitle: 'Ayurvedic Ritual Starter Set',
|
||
benefitChips: ['Cleanses', 'Hydrates', 'Glows'],
|
||
rating: 4.9,
|
||
reviewCount: 289,
|
||
},
|
||
{
|
||
productHandle: 'glow-with-love-bundle',
|
||
cardTitle: 'Glow Bundle',
|
||
subtitle: 'Complete Ritual Collection',
|
||
benefitChips: ['Hydrates', 'Sculpts', 'Glows'],
|
||
rating: 5,
|
||
reviewCount: 167,
|
||
},
|
||
],
|
||
};
|
||
|
||
/** Full mock rows when Storefront is unavailable (visual parity with React reference). */
|
||
export const MOCK_FEATURED_PRODUCT_ROWS: AbiirProductListItemData[] = [
|
||
{
|
||
handle: 'face-mask',
|
||
productTitle: 'Brightening Face Mask',
|
||
displayTitle: 'Brightening Face Mask',
|
||
subtitle: 'Radiance Ritual Mask',
|
||
imageForCard: MOCK_FEATURED_IMAGE,
|
||
price: MOCK_MONEY('40'),
|
||
compareAtPrice: null,
|
||
tags: ['Bestseller'],
|
||
benefits: ['Brightens', 'Purifies', 'Glows'],
|
||
rating: 4.9,
|
||
reviewCount: 334,
|
||
hideBadge: false,
|
||
},
|
||
{
|
||
handle: 'face-scrub',
|
||
productTitle: 'Brightening Face Scrub',
|
||
displayTitle: 'Brightening Face Scrub',
|
||
subtitle: 'Skincare Rooted in Ayurveda',
|
||
imageForCard: MOCK_FEATURED_IMAGE,
|
||
price: MOCK_MONEY('35'),
|
||
compareAtPrice: null,
|
||
tags: ['New'],
|
||
benefits: ['Exfoliates', 'Brightens', 'Smooths'],
|
||
rating: 4.8,
|
||
reviewCount: 156,
|
||
hideBadge: false,
|
||
},
|
||
{
|
||
handle: 'experience-kit',
|
||
productTitle: 'Experience Kit',
|
||
displayTitle: 'Experience Kit',
|
||
subtitle: 'Ayurvedic Ritual Starter Set',
|
||
imageForCard: MOCK_FEATURED_IMAGE,
|
||
price: MOCK_MONEY('35'),
|
||
compareAtPrice: null,
|
||
tags: ['Bestseller'],
|
||
benefits: ['Cleanses', 'Hydrates', 'Glows'],
|
||
rating: 4.9,
|
||
reviewCount: 289,
|
||
hideBadge: true,
|
||
},
|
||
{
|
||
handle: 'glow-with-love-bundle',
|
||
productTitle: 'Glow With Love Bundle',
|
||
displayTitle: 'Glow Bundle',
|
||
subtitle: 'Complete Ritual Collection',
|
||
imageForCard: MOCK_FEATURED_IMAGE,
|
||
price: MOCK_MONEY('99.9'),
|
||
compareAtPrice: MOCK_MONEY('130'),
|
||
tags: ['Bestseller', 'Sale'],
|
||
benefits: ['Hydrates', 'Sculpts', 'Glows'],
|
||
rating: 5,
|
||
reviewCount: 167,
|
||
hideBadge: false,
|
||
},
|
||
];
|
||
|
||
function parseMoneyAmount(m: AbiirProductListItemMoney | null | undefined): number {
|
||
if (!m?.amount) return 0;
|
||
const n = parseFloat(m.amount);
|
||
return Number.isFinite(n) ? n : 0;
|
||
}
|
||
|
||
function pickCompareAt(
|
||
price: AbiirProductListItemMoney,
|
||
compareAt: AbiirProductListItemMoney | null | undefined,
|
||
): AbiirProductListItemMoney | null {
|
||
if (!compareAt) return null;
|
||
if (parseMoneyAmount(compareAt) > parseMoneyAmount(price)) return compareAt;
|
||
return null;
|
||
}
|
||
|
||
function toImageData(
|
||
img: AbiirProductListItemImage | null | undefined,
|
||
): AbiirProductListItemImage | null {
|
||
if (!img?.url) return null;
|
||
return {
|
||
id: img.id,
|
||
url: img.url,
|
||
altText: img.altText,
|
||
width: img.width ?? undefined,
|
||
height: img.height ?? undefined,
|
||
};
|
||
}
|
||
|
||
/** Map a Storefront `Product` (e.g. collection / catalog query) to the homepage featured card shape. */
|
||
export function mapStorefrontProductToAbiirProductListItemData(
|
||
product: StorefrontProductNode,
|
||
): AbiirProductListItemData {
|
||
const title = product.title?.trim() || product.handle || '';
|
||
const price = product.priceRange?.minVariantPrice ?? MOCK_MONEY('0');
|
||
const compareRaw = product.compareAtPriceRange?.minVariantPrice;
|
||
const compareAt = pickCompareAt(price, compareRaw);
|
||
const firstVariant = product.variants?.nodes?.find(Boolean) ?? null;
|
||
|
||
return {
|
||
handle: product.handle?.trim() || '',
|
||
productTitle: title,
|
||
displayTitle: title,
|
||
subtitle: product.vendor?.trim() || '',
|
||
imageForCard: toImageData(product.featuredImage ?? null),
|
||
firstVariantId: firstVariant?.id ?? null,
|
||
availableForSale: Boolean(firstVariant?.availableForSale),
|
||
price,
|
||
compareAtPrice: compareAt,
|
||
tags: product.tags ?? [],
|
||
benefits: [],
|
||
rating: 0,
|
||
reviewCount: 0,
|
||
hideBadge: false,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* When Sanity UGC exists for a handle, prefer it over static CMS / mock values on the card.
|
||
*/
|
||
export function applyProductReviewStatsToListItemData(
|
||
item: AbiirProductListItemData,
|
||
stats: PdpProductReviewStats | undefined,
|
||
): AbiirProductListItemData {
|
||
if (!stats || stats.count < 1) return item;
|
||
return {
|
||
...item,
|
||
rating: stats.averageRating,
|
||
reviewCount: stats.count,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Manual/display rating + count from Sanity. If missing, we intentionally keep
|
||
* `rating`/`reviewCount` as-is (typically 0) so the UI hides the rating line.
|
||
*/
|
||
export function applyDisplayRatingsToListItemData(
|
||
item: AbiirProductListItemData,
|
||
stats: {rating: number; reviewCount: number} | undefined,
|
||
): AbiirProductListItemData {
|
||
if (!stats) return item;
|
||
return {
|
||
...item,
|
||
rating: stats.rating,
|
||
reviewCount: stats.reviewCount,
|
||
};
|
||
}
|
||
|
||
/** Batch map Storefront `Product` nodes to `AbiirProductListItem` rows (PDP “You may also love”). */
|
||
export function buildRelatedListFromStorefront(
|
||
nodes: StorefrontProductNode[],
|
||
): AbiirProductListItemData[] {
|
||
return nodes.map((n) => mapStorefrontProductToAbiirProductListItemData(n));
|
||
}
|
||
|
||
export function normalizeFeaturedProductsSanityPayload(
|
||
raw: unknown,
|
||
): FeaturedProductsCms | null {
|
||
if (raw == null || typeof raw !== 'object') return null;
|
||
const b = raw as SanityFeaturedPayload;
|
||
if (!b?.eyebrow || !b?.items?.length) return null;
|
||
|
||
const filterPills: {label: string; href: string}[] = [];
|
||
for (const row of b.filterPills ?? []) {
|
||
if (row?.label && row?.href) {
|
||
filterPills.push({label: row.label, href: row.href});
|
||
}
|
||
}
|
||
|
||
const items: FeaturedProductSlotCms[] = [];
|
||
for (const row of b.items) {
|
||
if (!row?.productHandle?.trim()) continue;
|
||
const chips =
|
||
row.benefitChips?.filter((c): c is string => typeof c === 'string' && c.length > 0) ??
|
||
[];
|
||
items.push({
|
||
productHandle: row.productHandle.trim(),
|
||
hideBadge: Boolean(row.hideBadge),
|
||
cardTitle: row.cardTitle ?? undefined,
|
||
subtitle: row.subtitle ?? undefined,
|
||
benefitChips: chips.length ? chips : undefined,
|
||
rating: row.rating ?? undefined,
|
||
reviewCount: row.reviewCount ?? undefined,
|
||
});
|
||
}
|
||
if (!items.length) return null;
|
||
|
||
return {
|
||
eyebrow: b.eyebrow,
|
||
title: b.title ?? 'Most Loved',
|
||
filterPills: omitNewArrivalsFilterPills(
|
||
filterPills.length ? filterPills : DEFAULT_FEATURED_FILTER_PILLS,
|
||
),
|
||
viewAllLabel: b.viewAllLabel ?? 'View All Products',
|
||
viewAllHref: b.viewAllHref ?? '/collections/all',
|
||
items,
|
||
};
|
||
}
|
||
|
||
function mockRowForHandle(handle: string): AbiirProductListItemData | undefined {
|
||
return MOCK_FEATURED_PRODUCT_ROWS.find((r) => r.handle === handle);
|
||
}
|
||
|
||
function mergeSlotWithShopify(
|
||
slot: FeaturedProductSlotCms,
|
||
product: StorefrontProductNode,
|
||
/** Used only when this product has no `featuredImage` (e.g. first slot’s image as batch fallback). */
|
||
sharedImageFallback: AbiirProductListItemImage | null,
|
||
): AbiirProductListItemData {
|
||
const title = product.title ?? slot.productHandle;
|
||
const price = product.priceRange?.minVariantPrice ?? MOCK_MONEY('0');
|
||
const compareRaw = product.compareAtPriceRange?.minVariantPrice;
|
||
const compareAt = pickCompareAt(price, compareRaw);
|
||
|
||
const chips =
|
||
slot.benefitChips != null
|
||
? slot.benefitChips.filter((c) => c.length > 0)
|
||
: (mockRowForHandle(slot.productHandle)?.benefits ?? []);
|
||
|
||
const mockMeta = mockRowForHandle(slot.productHandle);
|
||
const fromStorefront = toImageData(product.featuredImage ?? null);
|
||
const imageForCard =
|
||
fromStorefront
|
||
?? sharedImageFallback
|
||
?? mockMeta?.imageForCard
|
||
?? MOCK_FEATURED_IMAGE;
|
||
|
||
return {
|
||
handle: product.handle ?? slot.productHandle,
|
||
productTitle: title,
|
||
displayTitle: slot.cardTitle?.trim() || title,
|
||
subtitle: slot.subtitle?.trim() || product.vendor?.trim() || mockMeta?.subtitle || '',
|
||
imageForCard,
|
||
price,
|
||
compareAtPrice: compareAt,
|
||
tags: product.tags ?? [],
|
||
benefits: chips,
|
||
rating: slot.rating ?? mockMeta?.rating ?? 0,
|
||
reviewCount: slot.reviewCount ?? mockMeta?.reviewCount ?? 0,
|
||
hideBadge: Boolean(slot.hideBadge),
|
||
};
|
||
}
|
||
|
||
function mergeSlotFallback(slot: FeaturedProductSlotCms): AbiirProductListItemData {
|
||
const mock = mockRowForHandle(slot.productHandle);
|
||
if (mock) {
|
||
return {
|
||
...mock,
|
||
displayTitle: slot.cardTitle?.trim() || mock.displayTitle,
|
||
subtitle: slot.subtitle?.trim() || mock.subtitle,
|
||
benefits:
|
||
slot.benefitChips?.filter((c) => c.length > 0) ?? mock.benefits,
|
||
rating: slot.rating ?? mock.rating,
|
||
reviewCount: slot.reviewCount ?? mock.reviewCount,
|
||
hideBadge: Boolean(slot.hideBadge),
|
||
};
|
||
}
|
||
return {
|
||
handle: slot.productHandle,
|
||
productTitle: slot.productHandle,
|
||
displayTitle: slot.cardTitle?.trim() || slot.productHandle,
|
||
subtitle: slot.subtitle?.trim() || '',
|
||
imageForCard: MOCK_FEATURED_IMAGE,
|
||
price: MOCK_MONEY('0'),
|
||
compareAtPrice: null,
|
||
tags: [],
|
||
benefits: slot.benefitChips?.filter((c) => c.length > 0) ?? [],
|
||
rating: slot.rating ?? 0,
|
||
reviewCount: slot.reviewCount ?? 0,
|
||
hideBadge: Boolean(slot.hideBadge),
|
||
};
|
||
}
|
||
|
||
/** Storefront `products` search query: `handle:a OR handle:b` (up to `first` cap). */
|
||
export function buildHandleSearchQuery(handles: string[]): string {
|
||
return handles.map((h) => `handle:${h}`).join(' OR ');
|
||
}
|
||
|
||
export type StorefrontLike = {
|
||
i18n: {country: string; language: string};
|
||
query: (
|
||
query: string,
|
||
opts?: {variables?: Record<string, unknown>},
|
||
) => Promise<{
|
||
products?: {nodes?: Array<StorefrontProductNode | null | undefined> | null} | null;
|
||
}>;
|
||
};
|
||
|
||
/**
|
||
* Featured “Most loved” strip (Storefront + Sanity slots). Use
|
||
* `loadFeaturedProductsSection` from `~/lib/featuredProducts.server` to merge UGC review stats.
|
||
*/
|
||
export async function loadFeaturedProductsSectionCore(args: {
|
||
sanity: SanityContext;
|
||
storefront: StorefrontLike;
|
||
groq: string;
|
||
}): Promise<{cms: FeaturedProductsCms; rows: AbiirProductListItemData[]}> {
|
||
const initial = await args.sanity
|
||
.query<SanityFeaturedPayload | null>(args.groq)
|
||
.catch((): SanityFeaturedPayload | null => null);
|
||
|
||
const normalized = normalizeFeaturedProductsSanityPayload(
|
||
unwrapSanityQueryResult(initial),
|
||
);
|
||
const cmsBase = normalized ?? MOCK_FEATURED_PRODUCTS_CMS;
|
||
const cms: FeaturedProductsCms = {
|
||
...cmsBase,
|
||
filterPills: omitNewArrivalsFilterPills(cmsBase.filterPills),
|
||
};
|
||
|
||
const country = args.storefront.i18n.country;
|
||
const language = args.storefront.i18n.language;
|
||
const maxFromCollection = 8;
|
||
|
||
let collectionNodes: StorefrontProductNode[] = [];
|
||
try {
|
||
const {collection} = await args.storefront.query(
|
||
FRONTPAGE_FEATURED_COLLECTION_QUERY,
|
||
{
|
||
variables: {
|
||
country,
|
||
language,
|
||
handle: FRONTPAGE_FEATURED_COLLECTION_HANDLE,
|
||
first: maxFromCollection,
|
||
},
|
||
},
|
||
);
|
||
collectionNodes = (collection?.products?.nodes ?? []).filter(
|
||
(n): n is StorefrontProductNode => Boolean(n && n.handle),
|
||
);
|
||
} catch {
|
||
collectionNodes = [];
|
||
}
|
||
|
||
if (collectionNodes.length > 0) {
|
||
const slotsByHandle = new Map(
|
||
cms.items.map((s) => [s.productHandle.trim(), s] as const),
|
||
);
|
||
const firstNode = collectionNodes[0];
|
||
const batchImageFallback = toImageData(firstNode?.featuredImage ?? null);
|
||
/**
|
||
* Never pair by index (cms.items[i]) — collection merchandising order can differ
|
||
* from CMS row order, which caused wrong title / subtitle / chips / rating per card.
|
||
* Only use the slot that matches this product’s handle, else Storefront + handle only.
|
||
*/
|
||
const rows: AbiirProductListItemData[] = collectionNodes.map((node) => {
|
||
const h = node.handle?.trim() ?? '';
|
||
const slot: FeaturedProductSlotCms = h
|
||
? (slotsByHandle.get(h) ?? {productHandle: h})
|
||
: {productHandle: String(node.handle ?? '')};
|
||
return mergeSlotWithShopify(slot, node, batchImageFallback);
|
||
});
|
||
return {cms, rows};
|
||
}
|
||
|
||
const handles = cms.items.map((i) => i.productHandle.trim()).filter(Boolean);
|
||
const productByHandle = new Map<string, StorefrontProductNode>();
|
||
|
||
if (handles.length) {
|
||
try {
|
||
const {products} = await args.storefront.query(
|
||
FEATURED_PRODUCTS_STOREFRONT_QUERY,
|
||
{
|
||
variables: {
|
||
country,
|
||
language,
|
||
query: buildHandleSearchQuery(handles),
|
||
},
|
||
},
|
||
);
|
||
for (const node of products?.nodes ?? []) {
|
||
if (node?.handle) {
|
||
productByHandle.set(node.handle, node);
|
||
}
|
||
}
|
||
} catch {
|
||
/* use mock merge */
|
||
}
|
||
}
|
||
|
||
/** Batch fallback if a product is missing a featured image (each card still prefers that product’s image). */
|
||
const firstHandle = cms.items[0]?.productHandle;
|
||
let batchImageFallback: AbiirProductListItemImage | null = null;
|
||
if (firstHandle) {
|
||
const firstProduct = productByHandle.get(firstHandle);
|
||
batchImageFallback = toImageData(firstProduct?.featuredImage ?? null);
|
||
}
|
||
if (!batchImageFallback) {
|
||
for (const slot of cms.items) {
|
||
const p = productByHandle.get(slot.productHandle);
|
||
const img = toImageData(p?.featuredImage ?? null);
|
||
if (img) {
|
||
batchImageFallback = img;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (!batchImageFallback) {
|
||
batchImageFallback = MOCK_FEATURED_IMAGE;
|
||
}
|
||
|
||
const rows: AbiirProductListItemData[] = cms.items.map((slot) => {
|
||
const p = productByHandle.get(slot.productHandle);
|
||
if (p) {
|
||
return mergeSlotWithShopify(slot, p, batchImageFallback);
|
||
}
|
||
return mergeSlotFallback(slot);
|
||
});
|
||
|
||
return {cms, rows};
|
||
}
|