import { createContext, useContext } from 'react'; import type { StoreCart, StoreProduct } from './types'; export type Storefront = { /** Address of the store's home page. Every other storefront address is built on it. */ baseUrl: string; /** True when the home page is showing, where "#section" links can simply scroll. */ isHome: boolean; language: string; /** The merchant's real products that shoppers may see. */ products: StoreProduct[]; cart: StoreCart; }; const StorefrontContext = createContext({ baseUrl: '', isHome: true, language: 'en', products: [], cart: { count: 0, subtotal: 0, adjusted: false, lines: [] }, }); export const StorefrontProvider = StorefrontContext.Provider; export function useStorefront(): Storefront { return useContext(StorefrontContext); } /** * Turn a link from the store plan into a real address. * * - "#faq" scrolls on the home page, and goes to the home page first from anywhere else. * - "/shop" becomes an address inside this store. * - Anything else (https, mailto, tel) is left alone. */ export function resolveHref( href: string, baseUrl: string, isHome: boolean, ): string { if (href.startsWith('#')) { if (isHome) { return href; } return href === '#' ? baseUrl : baseUrl + href; } if (href.startsWith('/')) { return href === '/' ? baseUrl : baseUrl + href; } return href; } export function useHref(href: string): string { const { baseUrl, isHome } = useStorefront(); return resolveHref(href, baseUrl, isHome); }