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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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: {
  35. whatsapp: null,
  36. free_shipping_over: null,
  37. announcements: [],
  38. shipping_from: 0,
  39. shipping_west: 0,
  40. shipping_east: 0,
  41. offers: [],
  42. },
  43. featuredProducts: {},
  44. heroImages: { refs: {}, fallback: [] },
  45. });
  46. export const StorefrontProvider = StorefrontContext.Provider;
  47. export function useStorefront(): Storefront {
  48. return useContext(StorefrontContext);
  49. }
  50. /**
  51. * Turn a link from the store plan into a real address.
  52. *
  53. * - "#faq" scrolls on the home page, and goes to the home page first from anywhere else.
  54. * - "/shop" becomes an address inside this store.
  55. * - Anything else (https, mailto, tel) is left alone.
  56. */
  57. export function resolveHref(
  58. href: string,
  59. baseUrl: string,
  60. isHome: boolean,
  61. ): string {
  62. // A live store's home page is "/"; in the owner's preview it is the preview address.
  63. const home = baseUrl || '/';
  64. if (href.startsWith('#')) {
  65. if (isHome) {
  66. return href;
  67. }
  68. return href === '#' ? home : home + href;
  69. }
  70. if (href.startsWith('/')) {
  71. return href === '/' ? home : baseUrl + href;
  72. }
  73. return href;
  74. }
  75. export function useHref(href: string): string {
  76. const { baseUrl, isHome } = useStorefront();
  77. return resolveHref(href, baseUrl, isHome);
  78. }