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.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { createContext, useContext } from 'react';
  2. import type { ShopInfo, 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. storeName: string;
  13. shop: ShopInfo;
  14. };
  15. const StorefrontContext = createContext<Storefront>({
  16. baseUrl: '',
  17. isHome: true,
  18. language: 'en',
  19. products: [],
  20. cart: { count: 0, subtotal: 0, adjusted: false, lines: [] },
  21. storeName: '',
  22. shop: { whatsapp: null, free_shipping_over: null },
  23. });
  24. export const StorefrontProvider = StorefrontContext.Provider;
  25. export function useStorefront(): Storefront {
  26. return useContext(StorefrontContext);
  27. }
  28. /**
  29. * Turn a link from the store plan into a real address.
  30. *
  31. * - "#faq" scrolls on the home page, and goes to the home page first from anywhere else.
  32. * - "/shop" becomes an address inside this store.
  33. * - Anything else (https, mailto, tel) is left alone.
  34. */
  35. export function resolveHref(
  36. href: string,
  37. baseUrl: string,
  38. isHome: boolean,
  39. ): string {
  40. // A live store's home page is "/"; in the owner's preview it is the preview address.
  41. const home = baseUrl || '/';
  42. if (href.startsWith('#')) {
  43. if (isHome) {
  44. return href;
  45. }
  46. return href === '#' ? home : home + href;
  47. }
  48. if (href.startsWith('/')) {
  49. return href === '/' ? home : baseUrl + href;
  50. }
  51. return href;
  52. }
  53. export function useHref(href: string): string {
  54. const { baseUrl, isHome } = useStorefront();
  55. return resolveHref(href, baseUrl, isHome);
  56. }