| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import { createContext, useContext } from 'react';
- import type { 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>;
- };
-
- 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, offers: [] },
- featuredProducts: {},
- });
-
- 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);
- }
|