| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import { createContext, useContext } from 'react';
- import type { 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[];
- };
-
- const StorefrontContext = createContext<Storefront>({
- baseUrl: '',
- isHome: true,
- language: 'en',
- products: [],
- });
-
- 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);
- }
|