75 lines
2.2 KiB
TypeScript
75 lines
2.2 KiB
TypeScript
import type {UIMatch} from 'react-router';
|
|
import type {MetaDescriptor} from 'react-router';
|
|
|
|
/** Shop fields used for meta tags (from `HEADER_QUERY` → `header.shop`). */
|
|
export type ShopForMeta = {
|
|
name: string;
|
|
description?: string | null;
|
|
primaryDomain?: {url: string} | null;
|
|
brand?: {
|
|
shortDescription?: string | null;
|
|
slogan?: string | null;
|
|
} | null;
|
|
};
|
|
|
|
type RootMatchData = {
|
|
header?: {
|
|
shop?: ShopForMeta | null;
|
|
} | null;
|
|
};
|
|
|
|
export function getShopForMeta(
|
|
matches: ReadonlyArray<UIMatch>,
|
|
): ShopForMeta | null {
|
|
const root = matches.find((m) => m.id === 'root');
|
|
const shop = (root?.data as RootMatchData | undefined)?.header?.shop;
|
|
if (!shop?.name?.trim()) return null;
|
|
return shop;
|
|
}
|
|
|
|
/** Meta / Open Graph description: prefers store description, then brand copy. */
|
|
export function shopMetaDescription(shop: ShopForMeta | null): string {
|
|
if (!shop) return '';
|
|
return (
|
|
shop.description?.trim() ||
|
|
shop.brand?.shortDescription?.trim() ||
|
|
shop.brand?.slogan?.trim() ||
|
|
''
|
|
);
|
|
}
|
|
|
|
/** Page title suffix: `Page | Shop name` (Shopify Online Store name). */
|
|
export function pageTitleWithShopName(
|
|
pageLabel: string,
|
|
matches: ReadonlyArray<UIMatch>,
|
|
): string {
|
|
const shop = getShopForMeta(matches);
|
|
if (!shop) return pageLabel;
|
|
return `${pageLabel} | ${shop.name}`;
|
|
}
|
|
|
|
/**
|
|
* Default document meta from Shopify Admin store name + description.
|
|
* Avoids `og:title` here so leaf routes (e.g. PDP) are not stuck with the shop title
|
|
* for social previews; use `pageTitleWithShopName` + route-specific OG in those routes.
|
|
*/
|
|
export function shopRootMetaDescriptors(
|
|
shop: ShopForMeta | null,
|
|
): MetaDescriptor[] {
|
|
if (!shop?.name?.trim()) {
|
|
return [{title: 'Store'}];
|
|
}
|
|
const title = shop.name.trim();
|
|
const description = shopMetaDescription(shop);
|
|
const out: MetaDescriptor[] = [{title}];
|
|
if (description) {
|
|
out.push({name: 'description', content: description});
|
|
out.push({property: 'og:description', content: description});
|
|
out.push({name: 'twitter:description', content: description});
|
|
}
|
|
out.push({property: 'og:type', content: 'website'});
|
|
out.push({property: 'og:site_name', content: title});
|
|
out.push({name: 'twitter:card', content: 'summary_large_image'});
|
|
return out;
|
|
}
|