| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import { createContext, useContext } from 'react';
- import type { HeroImageSet, ShopInfo, 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;
- storeName: string;
- shop: ShopInfo;
- /** Real products that featured product sections point to, by web-address name. */
- featuredProducts: Record<string, StoreProduct>;
- heroImages: HeroImageSet;
- };
-
- const StorefrontContext = createContext<Storefront>({
- baseUrl: '',
- isHome: true,
- language: 'en',
- products: [],
- cart: {
- count: 0,
- subtotal: 0,
- discount: null,
- applied: null,
- offer_hint: null,
- total: 0,
- adjusted: false,
- lines: [],
- },
- storeName: '',
- shop: {
- whatsapp: null,
- free_shipping_over: null,
- announcements: [],
- shipping_from: 0,
- offers: [],
- },
- featuredProducts: {},
- heroImages: { refs: {}, fallback: [] },
- });
-
- 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 {
- // A live store's home page is "/"; in the owner's preview it is the preview address.
- const home = baseUrl || '/';
-
- if (href.startsWith('#')) {
- if (isHome) {
- return href;
- }
-
- return href === '#' ? home : home + href;
- }
-
- if (href.startsWith('/')) {
- return href === '/' ? home : baseUrl + href;
- }
-
- return href;
- }
-
- export function useHref(href: string): string {
- const { baseUrl, isHome } = useStorefront();
-
- return resolveHref(href, baseUrl, isHome);
- }
|