AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.tsx 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { createContext, useContext } from 'react';
  2. import type { StoreCart, StoreProduct } from './types';
  3. export type Storefront = {
  4. /** Address of the store's home page. Every other storefront address is built on it. */
  5. baseUrl: string;
  6. /** True when the home page is showing, where "#section" links can simply scroll. */
  7. isHome: boolean;
  8. language: string;
  9. /** The merchant's real products that shoppers may see. */
  10. products: StoreProduct[];
  11. cart: StoreCart;
  12. };
  13. const StorefrontContext = createContext<Storefront>({
  14. baseUrl: '',
  15. isHome: true,
  16. language: 'en',
  17. products: [],
  18. cart: { count: 0, subtotal: 0, adjusted: false, lines: [] },
  19. });
  20. export const StorefrontProvider = StorefrontContext.Provider;
  21. export function useStorefront(): Storefront {
  22. return useContext(StorefrontContext);
  23. }
  24. /**
  25. * Turn a link from the store plan into a real address.
  26. *
  27. * - "#faq" scrolls on the home page, and goes to the home page first from anywhere else.
  28. * - "/shop" becomes an address inside this store.
  29. * - Anything else (https, mailto, tel) is left alone.
  30. */
  31. export function resolveHref(
  32. href: string,
  33. baseUrl: string,
  34. isHome: boolean,
  35. ): string {
  36. if (href.startsWith('#')) {
  37. if (isHome) {
  38. return href;
  39. }
  40. return href === '#' ? baseUrl : baseUrl + href;
  41. }
  42. if (href.startsWith('/')) {
  43. return href === '/' ? baseUrl : baseUrl + href;
  44. }
  45. return href;
  46. }
  47. export function useHref(href: string): string {
  48. const { baseUrl, isHome } = useStorefront();
  49. return resolveHref(href, baseUrl, isHome);
  50. }