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 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { createContext, useContext } from 'react';
  2. import type { HeroImageSet, 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. /** Real products that featured product sections point to, by web-address name. */
  15. featuredProducts: Record<string, StoreProduct>;
  16. heroImages: HeroImageSet;
  17. };
  18. const StorefrontContext = createContext<Storefront>({
  19. baseUrl: '',
  20. isHome: true,
  21. language: 'en',
  22. products: [],
  23. cart: {
  24. count: 0,
  25. subtotal: 0,
  26. discount: null,
  27. applied: null,
  28. offer_hint: null,
  29. total: 0,
  30. adjusted: false,
  31. lines: [],
  32. },
  33. storeName: '',
  34. shop: { whatsapp: null, free_shipping_over: null, offers: [] },
  35. featuredProducts: {},
  36. heroImages: { refs: {}, fallback: [] },
  37. });
  38. export const StorefrontProvider = StorefrontContext.Provider;
  39. export function useStorefront(): Storefront {
  40. return useContext(StorefrontContext);
  41. }
  42. /**
  43. * Turn a link from the store plan into a real address.
  44. *
  45. * - "#faq" scrolls on the home page, and goes to the home page first from anywhere else.
  46. * - "/shop" becomes an address inside this store.
  47. * - Anything else (https, mailto, tel) is left alone.
  48. */
  49. export function resolveHref(
  50. href: string,
  51. baseUrl: string,
  52. isHome: boolean,
  53. ): string {
  54. // A live store's home page is "/"; in the owner's preview it is the preview address.
  55. const home = baseUrl || '/';
  56. if (href.startsWith('#')) {
  57. if (isHome) {
  58. return href;
  59. }
  60. return href === '#' ? home : home + href;
  61. }
  62. if (href.startsWith('/')) {
  63. return href === '/' ? home : baseUrl + href;
  64. }
  65. return href;
  66. }
  67. export function useHref(href: string): string {
  68. const { baseUrl, isHome } = useStorefront();
  69. return resolveHref(href, baseUrl, isHome);
  70. }