Browse Source

feat: initialize Habib Shop frontend application structure and UI components

main
sina_sajjadi 1 week ago
parent
commit
132347159c
  1. 7
      BACKEND_SPEC.md
  2. 128
      index.html
  3. 6
      public/assets/images/icon-cat-apparel-large.svg
  4. 6
      public/assets/images/icon-cat-apparel-small.svg
  5. 6
      public/assets/images/icon-cat-attar-large.svg
  6. 6
      public/assets/images/icon-cat-attar-small.svg
  7. 7
      public/assets/images/icon-cat-backpack-large.svg
  8. 7
      public/assets/images/icon-cat-backpack-small.svg
  9. 5
      public/assets/images/icon-cat-book-large.svg
  10. 5
      public/assets/images/icon-cat-book-small.svg
  11. 6
      public/assets/images/icon-cat-calligraphy-large.svg
  12. 6
      public/assets/images/icon-cat-calligraphy-small.svg
  13. 5
      public/assets/images/icon-cat-duffel-large.svg
  14. 5
      public/assets/images/icon-cat-duffel-small.svg
  15. 6
      public/assets/images/icon-cat-heritage-large.svg
  16. 6
      public/assets/images/icon-cat-heritage-small.svg
  17. 5
      public/assets/images/icon-cat-khatam-large.svg
  18. 5
      public/assets/images/icon-cat-khatam-small.svg
  19. 4
      public/assets/images/icon-cat-modest-large.svg
  20. 4
      public/assets/images/icon-cat-modest-small.svg
  21. 7
      public/assets/images/icon-cat-prayer-large.svg
  22. 7
      public/assets/images/icon-cat-prayer-small.svg
  23. 5
      public/assets/images/icon-cat-rosewater-large.svg
  24. 5
      public/assets/images/icon-cat-rosewater-small.svg
  25. 4
      public/assets/images/icon-cat-scripture-large.svg
  26. 4
      public/assets/images/icon-cat-scripture-small.svg
  27. 6
      public/assets/images/icon-cat-textiles-large.svg
  28. 6
      public/assets/images/icon-cat-textiles-small.svg
  29. 3
      public/assets/images/icon-cat-tshirt-large.svg
  30. 3
      public/assets/images/icon-cat-tshirt-small.svg
  31. 19
      src/App.tsx
  32. 48
      src/components/account/AccountMenuRow.tsx
  33. 38
      src/components/account/OrderCounterCard.tsx
  34. 68
      src/components/checkout/OrderSummaryRows.tsx
  35. 7
      src/components/common/PhoneNumberInput.tsx
  36. 839
      src/components/common/ShimmerSkeletons.tsx
  37. 69
      src/components/layout/MobileShell.tsx
  38. 92
      src/components/layout/StickyFooterBar.tsx
  39. 59
      src/components/modals/AddressFormSheet.tsx
  40. 16
      src/components/modals/PaymentMethodsSheet.tsx
  41. 54
      src/components/orders/OrderFilterTabs.tsx
  42. 127
      src/context/ShopAppContext.tsx
  43. 2
      src/data/accountData.ts
  44. 52
      src/data/catalogData.ts
  45. 65
      src/index.css
  46. 14
      src/lib/cookies.ts
  47. 4
      src/lib/mappers.ts
  48. 2
      src/lib/routes.ts
  49. 141
      src/lib/shopApi.ts
  50. 60
      src/lib/shopQueries.ts
  51. 337
      src/lib/view-paddings.ts
  52. 84
      src/lib/webview-actions.ts
  53. 319
      src/pages/account/LanguageSettingPage.tsx
  54. 67
      src/pages/account/ProviderRequestPage.tsx
  55. 118
      src/pages/account/ShopAccountPage.tsx
  56. 7
      src/pages/account/ShopAddressPage.tsx
  57. 402
      src/pages/catalog/ShopBoothPage.tsx
  58. 208
      src/pages/catalog/ShopCatItemsPage.tsx
  59. 16
      src/pages/catalog/ShopCategoryPage.tsx
  60. 701
      src/pages/catalog/ShopSinglePage.tsx
  61. 256
      src/pages/chat/ShopChatPage.tsx
  62. 17
      src/pages/checkout/ShopBuy01Page.tsx
  63. 25
      src/pages/checkout/ShopCartPage.tsx
  64. 50
      src/pages/checkout/ShopPayResultPage.tsx
  65. 34
      src/pages/checkout/ShopPaymentPage.tsx
  66. 371
      src/pages/home/ShopHomePage.tsx
  67. 240
      src/pages/orders/ShopOrderDetailPage.tsx
  68. 11
      src/pages/orders/ShopOrdersPage.tsx
  69. 180
      src/pages/orders/ShopSupportPage.tsx

7
BACKEND_SPEC.md

@ -4706,4 +4706,9 @@ The production SPA integration inside `src/` adds parameterized routing, live Ha
| `src/components/modals/PaymentMethodsSheet.tsx` | True overlay bottom sheet for `/checkout/review` payment method selection including live Habib Coins balance validation. | | `src/components/modals/PaymentMethodsSheet.tsx` | True overlay bottom sheet for `/checkout/review` payment method selection including live Habib Coins balance validation. |
| `src/components/modals/AddressFormSheet.tsx` | True overlay bottom sheet for `/checkout/shipping` and `/account/addresses` address creation/editing with optional Flutter `pick_manual_location` pin selection. | | `src/components/modals/AddressFormSheet.tsx` | True overlay bottom sheet for `/checkout/shipping` and `/account/addresses` address creation/editing with optional Flutter `pick_manual_location` pin selection. |
| `src/components/modals/ShipmentTrackingSheet.tsx` | True overlay bottom sheet for `/orders/:orderId` carrier tracking code copy and chronological shipment milestone timeline. | | `src/components/modals/ShipmentTrackingSheet.tsx` | True overlay bottom sheet for `/orders/:orderId` carrier tracking code copy and chronological shipment milestone timeline. |
| `src/components/common/ShimmerSkeletons.tsx` | Geometry-matched shimmer skeleton loaders (`HomeFeedShimmer`, `CategoryGridShimmer`, `ProductGridShimmer`, `ProductDetailBodyShimmer`, `StoreBoothBodyShimmer`, `OrdersListShimmer`, `OrderDetailShimmer`, `ChatThreadShimmer`, `CartItemsShimmer`), tactile `InlineSpinner`, and network `RetryBanner`. |
| `src/components/common/ShimmerSkeletons.tsx` | Dynamic-only shimmer skeleton loaders (`ShimmerBox`, `CompactCarouselShimmer`, `HomeFeedShimmer`, `CategoryGridShimmer`, `ProductGridShimmer`, `OrdersListShimmer`, `OrderDetailShimmer`, `ChatThreadShimmer`, `CartItemsShimmer`), tactile `InlineSpinner`, and network `RetryBanner`. |
| `src/lib/shopQueries.ts` | TanStack Query v5 query client, canonical cache keys, query hooks, and optimistic/invalidating mutation hooks for all `/api/shop/*` resources. |
| `src/lib/phone.ts` | International phone number parsing, validation, and display formatting helpers powered by `google-libphonenumber`. |
| `src/hooks/use-animated-presence.ts` | Mount/unmount animation lifecycle hook coordinating CSS exit transitions for overlay modals and bottom sheets. |
| `src/components/common/PhoneNumberInput.tsx` | Country-code selector and validated phone number input control used in address and profile forms. |
| `src/components/modals/LoginRequiredModal.tsx` | Modal prompt requesting Habib authentication via `window.FlutterChannel` or browser token sign-in before protected actions. |

128
index.html

@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta <meta
name="viewport" name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover, interactive-widget=overlays-content"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover, interactive-widget=resizes-visual"
/> />
<title>Habib Shop</title> <title>Habib Shop</title>
<style id="habib-boot-shimmer-styles"> <style id="habib-boot-shimmer-styles">
@ -22,70 +22,6 @@
background-color: #1e2229; background-color: #1e2229;
} }
} }
@keyframes habib-boot-sweep {
0% {
transform: translate3d(-100%, 0, 0);
}
100% {
transform: translate3d(100%, 0, 0);
}
}
.habib-boot-shell {
width: 100%;
min-height: 100vh;
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f3f1ef;
}
@media (min-width: 1024px) {
.habib-boot-shell {
padding: 0 16px;
background-color: #1e2229;
}
}
.habib-boot-viewport {
width: 100%;
max-width: 100%;
min-height: 100vh;
min-height: 100dvh;
background-color: #f3f1ef;
display: flex;
flex-direction: column;
justify-content: space-between;
box-sizing: border-box;
overflow: hidden;
}
@media (min-width: 1024px) {
.habib-boot-viewport {
width: 375px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.45);
}
}
.habib-boot-bone {
position: relative;
overflow: hidden;
background-color: #f8f8f8;
flex-shrink: 0;
}
.habib-boot-bone::after {
content: '';
position: absolute;
inset: 0;
transform: translate3d(-100%, 0, 0);
background-image: linear-gradient(
90deg,
rgba(248, 248, 248, 0) 0%,
rgba(229, 225, 220, 0.85) 50%,
rgba(248, 248, 248, 0) 100%
);
animation: habib-boot-sweep 1.5s cubic-bezier(0.4, 0, 0.2, 1) 1s infinite;
pointer-events: none;
}
html.is-bare-boot .habib-boot-shell {
display: none !important;
}
</style> </style>
<script> <script>
try { try {
@ -476,67 +412,7 @@
</script> </script>
</head> </head>
<body> <body>
<div id="root">
<div class="habib-boot-shell" aria-hidden="true">
<div class="habib-boot-viewport">
<div style="padding: 37px 16px 22px; display: flex; flex-direction: column; gap: 20px;">
<div style="display: flex; align-items: center; justify-content: space-between; min-height: 40px; margin-bottom: 11px;">
<div class="habib-boot-bone" style="width: 40px; height: 40px; border-radius: 15px;"></div>
<div class="habib-boot-bone" style="width: 68px; height: 22px; border-radius: 8px;"></div>
<div class="habib-boot-bone" style="width: 40px; height: 40px; border-radius: 15px;"></div>
</div>
<div style="display: flex; gap: 10px; align-items: center;">
<div class="habib-boot-bone" style="flex: 1; height: 44px; border-radius: 14px;"></div>
<div class="habib-boot-bone" style="width: 44px; height: 44px; border-radius: 14px;"></div>
</div>
<div class="habib-boot-bone" style="width: 100%; height: 164px; border-radius: 15px;"></div>
<div style="display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 2px;">
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
<div style="display: flex; flex-direction: column; align-items: center; gap: 6px;">
<div class="habib-boot-bone" style="width: 43px; height: 43px; border-radius: 50%;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 9px; border-radius: 4px;"></div>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px;">
<div style="padding: 12px; border-radius: 15px; background: #ffffff; display: flex; flex-direction: column; gap: 8px;">
<div class="habib-boot-bone" style="width: 100%; height: 112px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 62%; height: 10px; border-radius: 5px;"></div>
<div class="habib-boot-bone" style="width: 90%; height: 13px; border-radius: 6px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 15px; border-radius: 6px;"></div>
</div>
<div style="padding: 12px; border-radius: 15px; background: #ffffff; display: flex; flex-direction: column; gap: 8px;">
<div class="habib-boot-bone" style="width: 100%; height: 112px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 62%; height: 10px; border-radius: 5px;"></div>
<div class="habib-boot-bone" style="width: 90%; height: 13px; border-radius: 6px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 15px; border-radius: 6px;"></div>
</div>
</div>
</div>
<div style="height: 78px; border-radius: 17px 17px 0 0; background: #ffffff; display: flex; align-items: center; justify-content: space-around; padding: 0 16px;">
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 54px; height: 48px; border-radius: 24px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
<div class="habib-boot-bone" style="width: 36px; height: 36px; border-radius: 10px;"></div>
</div>
</div>
</div>
</div>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>

6
public/assets/images/icon-cat-apparel-large.svg

@ -0,0 +1,6 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.2 3.5C10.2 2.65 11 2 12 2C13 2 13.8 2.65 13.8 3.6C13.8 5 12 5.5 12 6.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 6.5L3.4 12.1C2.5 12.68 2.91 14.05 3.98 14.05H20.02C21.09 14.05 21.5 12.68 20.6 12.1L12 6.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7 14.05V19.5C7 20.33 7.67 21 8.5 21H15.5C16.33 21 17 20.33 17 19.5V14.05" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 14.05V21" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-apparel-small.svg

@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.2 3.5C10.2 2.65 11 2 12 2C13 2 13.8 2.65 13.8 3.6C13.8 5 12 5.5 12 6.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 6.5L3.4 12.1C2.5 12.68 2.91 14.05 3.98 14.05H20.02C21.09 14.05 21.5 12.68 20.6 12.1L12 6.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7 14.05V19.5C7 20.33 7.67 21 8.5 21H15.5C16.33 21 17 20.33 17 19.5V14.05" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 14.05V21" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-attar-large.svg

@ -0,0 +1,6 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2L14.3 4.3L12 6.6L9.7 4.3L12 2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.5 8.5H14.5M10.5 6.6V10.5M13.5 6.6V10.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.2 10.5H15.8C17.57 10.5 19 11.93 19 13.7V18.2C19 20.02 17.52 21.5 15.7 21.5H8.3C6.48 21.5 5 20.02 5 18.2V13.7C5 11.93 6.43 10.5 8.2 10.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 13.5C12 13.5 10 15.7 10 17C10 18.1 10.9 19 12 19C13.1 19 14 18.1 14 17C14 15.7 12 13.5 12 13.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-attar-small.svg

@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2L14.3 4.3L12 6.6L9.7 4.3L12 2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.5 8.5H14.5M10.5 6.6V10.5M13.5 6.6V10.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.2 10.5H15.8C17.57 10.5 19 11.93 19 13.7V18.2C19 20.02 17.52 21.5 15.7 21.5H8.3C6.48 21.5 5 20.02 5 18.2V13.7C5 11.93 6.43 10.5 8.2 10.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 13.5C12 13.5 10 15.7 10 17C10 18.1 10.9 19 12 19C13.1 19 14 18.1 14 17C14 15.7 12 13.5 12 13.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

7
public/assets/images/icon-cat-backpack-large.svg

@ -0,0 +1,7 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9 5.5V4.2C9 3 10 2 11.2 2H12.8C14 2 15 3 15 4.2V5.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 9.5C6.5 7.29 8.29 5.5 10.5 5.5H13.5C15.71 5.5 17.5 7.29 17.5 9.5V19.5C17.5 20.6 16.6 21.5 15.5 21.5H8.5C7.4 21.5 6.5 20.6 6.5 19.5V9.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 12H5C4.17 12 3.5 12.67 3.5 13.5V18.5C3.5 19.33 4.17 20 5 20H6.5M17.5 12H19C19.83 12 20.5 12.67 20.5 13.5V18.5C20.5 19.33 19.83 20 19 20H17.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.2 14H14.8C15.35 14 15.8 14.45 15.8 15V18.5H8.2V15C8.2 14.45 8.65 14 9.2 14Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10V11.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

7
public/assets/images/icon-cat-backpack-small.svg

@ -0,0 +1,7 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9 5.5V4.2C9 3 10 2 11.2 2H12.8C14 2 15 3 15 4.2V5.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 9.5C6.5 7.29 8.29 5.5 10.5 5.5H13.5C15.71 5.5 17.5 7.29 17.5 9.5V19.5C17.5 20.6 16.6 21.5 15.5 21.5H8.5C7.4 21.5 6.5 20.6 6.5 19.5V9.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 12H5C4.17 12 3.5 12.67 3.5 13.5V18.5C3.5 19.33 4.17 20 5 20H6.5M17.5 12H19C19.83 12 20.5 12.67 20.5 13.5V18.5C20.5 19.33 19.83 20 19 20H17.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.2 14H14.8C15.35 14 15.8 14.45 15.8 15V18.5H8.2V15C8.2 14.45 8.65 14 9.2 14Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10V11.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

5
public/assets/images/icon-cat-book-large.svg

@ -0,0 +1,5 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4.5C2 3.95 2.45 3.5 3 3.5H8.5C10.43 3.5 12 5.07 12 7V20.5C12 19.12 10.88 18 9.5 18H3C2.45 18 2 17.55 2 17V4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M22 4.5C22 3.95 21.55 3.5 21 3.5H15.5C13.57 3.5 12 5.07 12 7V20.5C12 19.12 13.12 18 14.5 18H21C21.55 18 22 17.55 22 17V4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 8.5H8.5M5.5 12H8.5M15.5 8.5H18.5M15.5 12H18.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

5
public/assets/images/icon-cat-book-small.svg

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4.5C2 3.95 2.45 3.5 3 3.5H8.5C10.43 3.5 12 5.07 12 7V20.5C12 19.12 10.88 18 9.5 18H3C2.45 18 2 17.55 2 17V4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M22 4.5C22 3.95 21.55 3.5 21 3.5H15.5C13.57 3.5 12 5.07 12 7V20.5C12 19.12 13.12 18 14.5 18H21C21.55 18 22 17.55 22 17V4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 8.5H8.5M5.5 12H8.5M15.5 8.5H18.5M15.5 12H18.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-calligraphy-large.svg

@ -0,0 +1,6 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 5.5L12 2.5L15.5 5.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.5 5.5H19.5C20.33 5.5 21 6.17 21 7V19.5C21 20.33 20.33 21 19.5 21H4.5C3.67 21 3 20.33 3 19.5V7C3 6.17 3.67 5.5 4.5 5.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 15.2C9 16.8 12.2 16.8 14.5 14.2C16.2 12.3 16.5 10.2 15 9.5C13.5 8.8 11.8 10.5 12.5 12.8C13.1 14.8 15.2 16.2 17 15.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="9.2" cy="10.5" r="1" fill="#D78E06"/>
</svg>

6
public/assets/images/icon-cat-calligraphy-small.svg

@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 5.5L12 2.5L15.5 5.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.5 5.5H19.5C20.33 5.5 21 6.17 21 7V19.5C21 20.33 20.33 21 19.5 21H4.5C3.67 21 3 20.33 3 19.5V7C3 6.17 3.67 5.5 4.5 5.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 15.2C9 16.8 12.2 16.8 14.5 14.2C16.2 12.3 16.5 10.2 15 9.5C13.5 8.8 11.8 10.5 12.5 12.8C13.1 14.8 15.2 16.2 17 15.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="9.2" cy="10.5" r="1" fill="#D78E06"/>
</svg>

5
public/assets/images/icon-cat-duffel-large.svg

@ -0,0 +1,5 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 8.5V6C8.5 4.34 9.84 3 11.5 3H12.5C14.16 3 15.5 4.34 15.5 6V8.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 8.5H18.5C20.43 8.5 22 10.07 22 12V17.5C22 19.43 20.43 21 18.5 21H5.5C3.57 21 2 19.43 2 17.5V12C2 10.07 3.57 8.5 5.5 8.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.5 8.5V21M15.5 8.5V21M8.5 13H15.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

5
public/assets/images/icon-cat-duffel-small.svg

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 8.5V6C8.5 4.34 9.84 3 11.5 3H12.5C14.16 3 15.5 4.34 15.5 6V8.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 8.5H18.5C20.43 8.5 22 10.07 22 12V17.5C22 19.43 20.43 21 18.5 21H5.5C3.57 21 2 19.43 2 17.5V12C2 10.07 3.57 8.5 5.5 8.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.5 8.5V21M15.5 8.5V21M8.5 13H15.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-heritage-large.svg

@ -0,0 +1,6 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 4H18.5C19.6 4 20.5 4.9 20.5 6C20.5 7.1 19.6 8 18.5 8H5.5C4.4 8 3.5 7.1 3.5 6C3.5 4.9 4.4 4 5.5 4Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 10H19.5C20.33 10 21 10.67 21 11.5V12.5C21 13.33 20.33 14 19.5 14H5.5C4.67 14 4 13.33 4 12.5V11.5C4 10.67 4.67 10 5.5 10H6.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 16H18.5C19.6 16 20.5 16.9 20.5 18C20.5 19.1 19.6 20 18.5 20H5.5C4.4 20 3.5 19.1 3.5 18C3.5 16.9 4.4 16 5.5 16Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14.5 16V22L16 21L17.5 22V16" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-heritage-small.svg

@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 4H18.5C19.6 4 20.5 4.9 20.5 6C20.5 7.1 19.6 8 18.5 8H5.5C4.4 8 3.5 7.1 3.5 6C3.5 4.9 4.4 4 5.5 4Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 10H19.5C20.33 10 21 10.67 21 11.5V12.5C21 13.33 20.33 14 19.5 14H5.5C4.67 14 4 13.33 4 12.5V11.5C4 10.67 4.67 10 5.5 10H6.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 16H18.5C19.6 16 20.5 16.9 20.5 18C20.5 19.1 19.6 20 18.5 20H5.5C4.4 20 3.5 19.1 3.5 18C3.5 16.9 4.4 16 5.5 16Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14.5 16V22L16 21L17.5 22V16" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

5
public/assets/images/icon-cat-khatam-large.svg

@ -0,0 +1,5 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6.2 6.2H17.8V17.8H6.2V6.2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 3.8L20.2 12L12 20.2L3.8 12L12 3.8Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12" cy="12" r="2.6" stroke="#D78E06" stroke-width="1.5"/>
</svg>

5
public/assets/images/icon-cat-khatam-small.svg

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6.2 6.2H17.8V17.8H6.2V6.2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 3.8L20.2 12L12 20.2L3.8 12L12 3.8Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12" cy="12" r="2.6" stroke="#D78E06" stroke-width="1.5"/>
</svg>

4
public/assets/images/icon-cat-modest-large.svg

@ -0,0 +1,4 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.5 3.5C10.1 4.4 11 5 12 5C13 5 13.9 4.4 14.5 3.5L18.5 5.2L20.8 13.2L18.2 14L16.8 9.2L18.2 21H5.8L7.2 9.2L5.8 14L3.2 13.2L5.5 5.2L9.5 3.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.1 12.2H16.9M12 5V12.2" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

4
public/assets/images/icon-cat-modest-small.svg

@ -0,0 +1,4 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.5 3.5C10.1 4.4 11 5 12 5C13 5 13.9 4.4 14.5 3.5L18.5 5.2L20.8 13.2L18.2 14L16.8 9.2L18.2 21H5.8L7.2 9.2L5.8 14L3.2 13.2L5.5 5.2L9.5 3.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.1 12.2H16.9M12 5V12.2" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

7
public/assets/images/icon-cat-prayer-large.svg

@ -0,0 +1,7 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 2.2V4M10.3 2.2V4M13.7 2.2V4M17 2.2V4M7 20V21.8M10.3 20V21.8M13.7 20V21.8M17 20V21.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 4H18.5C19.05 4 19.5 4.45 19.5 5V19C19.5 19.55 19.05 20 18.5 20H5.5C4.95 20 4.5 19.55 4.5 19V5C4.5 4.45 4.95 4 5.5 4Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 20V12.2C8 9.6 9.8 7.6 12 6.5C14.2 7.6 16 9.6 16 12.2V20" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 6.5V10.2" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12" cy="11.4" r="1.1" stroke="#D78E06" stroke-width="1.5"/>
</svg>

7
public/assets/images/icon-cat-prayer-small.svg

@ -0,0 +1,7 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 2.2V4M10.3 2.2V4M13.7 2.2V4M17 2.2V4M7 20V21.8M10.3 20V21.8M13.7 20V21.8M17 20V21.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 4H18.5C19.05 4 19.5 4.45 19.5 5V19C19.5 19.55 19.05 20 18.5 20H5.5C4.95 20 4.5 19.55 4.5 19V5C4.5 4.45 4.95 4 5.5 4Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 20V12.2C8 9.6 9.8 7.6 12 6.5C14.2 7.6 16 9.6 16 12.2V20" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 6.5V10.2" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12" cy="11.4" r="1.1" stroke="#D78E06" stroke-width="1.5"/>
</svg>

5
public/assets/images/icon-cat-rosewater-large.svg

@ -0,0 +1,5 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 3C11 3 5 9.6 5 14.2C5 17.96 7.69 21 11 21C14.31 21 17 17.96 17 14.2C17 9.6 11 3 11 3Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.2 14.5C8.2 16.1 9.3 17.5 10.8 17.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.5 8.5C17.5 6.5 20.8 6.5 21.5 6.5C21.5 7.2 21.5 10.5 19.5 12.5C18.2 13.8 16.4 13.8 15.5 12.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

5
public/assets/images/icon-cat-rosewater-small.svg

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 3C11 3 5 9.6 5 14.2C5 17.96 7.69 21 11 21C14.31 21 17 17.96 17 14.2C17 9.6 11 3 11 3Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.2 14.5C8.2 16.1 9.3 17.5 10.8 17.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.5 8.5C17.5 6.5 20.8 6.5 21.5 6.5C21.5 7.2 21.5 10.5 19.5 12.5C18.2 13.8 16.4 13.8 15.5 12.8" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

4
public/assets/images/icon-cat-scripture-large.svg

@ -0,0 +1,4 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.5 6.5L12 10.5L20.5 6.5M3.5 6.5L6.5 4.2L12 6.8L17.5 4.2L20.5 6.5M12 6.8V10.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 11.5L18.5 20.5M18.5 11.5L5.5 20.5M4 20.5H8M16 20.5H20" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

4
public/assets/images/icon-cat-scripture-small.svg

@ -0,0 +1,4 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.5 6.5L12 10.5L20.5 6.5M3.5 6.5L6.5 4.2L12 6.8L17.5 4.2L20.5 6.5M12 6.8V10.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 11.5L18.5 20.5M18.5 11.5L5.5 20.5M4 20.5H8M16 20.5H20" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-textiles-large.svg

@ -0,0 +1,6 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 4.5H19C19.83 4.5 20.5 5.17 20.5 6V17.5C20.5 18.33 19.83 19 19 19H5C4.17 19 3.5 18.33 3.5 17.5V6C3.5 5.17 4.17 4.5 5 4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3.5 8H20.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10.2L15.2 13.4L12 16.6L8.8 13.4L12 10.2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 19V21.5M10.2 19V21.5M13.8 19V21.5M17.5 19V21.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

6
public/assets/images/icon-cat-textiles-small.svg

@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 4.5H19C19.83 4.5 20.5 5.17 20.5 6V17.5C20.5 18.33 19.83 19 19 19H5C4.17 19 3.5 18.33 3.5 17.5V6C3.5 5.17 4.17 4.5 5 4.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3.5 8H20.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10.2L15.2 13.4L12 16.6L8.8 13.4L12 10.2Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.5 19V21.5M10.2 19V21.5M13.8 19V21.5M17.5 19V21.5" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

3
public/assets/images/icon-cat-tshirt-large.svg

@ -0,0 +1,3 @@
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.8 3.5C9.5 4.7 10.67 5.5 12 5.5C13.33 5.5 14.5 4.7 15.2 3.5L20.5 6.2L18.6 10.5L16.2 9.4V19.5C16.2 20.33 15.53 21 14.7 21H9.3C8.47 21 7.8 20.33 7.8 19.5V9.4L5.4 10.5L3.5 6.2L8.8 3.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

3
public/assets/images/icon-cat-tshirt-small.svg

@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.8 3.5C9.5 4.7 10.67 5.5 12 5.5C13.33 5.5 14.5 4.7 15.2 3.5L20.5 6.2L18.6 10.5L16.2 9.4V19.5C16.2 20.33 15.53 21 14.7 21H9.3C8.47 21 7.8 20.33 7.8 19.5V9.4L5.4 10.5L3.5 6.2L8.8 3.5Z" stroke="#D78E06" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

19
src/App.tsx

@ -38,7 +38,10 @@ import { ShopSupportPage } from './pages/orders/ShopSupportPage';
import { ShopAccountPage } from './pages/account/ShopAccountPage'; import { ShopAccountPage } from './pages/account/ShopAccountPage';
import { ShopAddressPage } from './pages/account/ShopAddressPage'; import { ShopAddressPage } from './pages/account/ShopAddressPage';
import { ProviderRequestPage } from './pages/account/ProviderRequestPage'; import { ProviderRequestPage } from './pages/account/ProviderRequestPage';
import { LanguageSettingPage } from './pages/account/LanguageSettingPage';
import {
LanguageSettingPage,
ShopNotesPage,
} from './pages/account/LanguageSettingPage';
// Standalone Component / Icon / Text Nodes (6 Top-Level Nodes) // Standalone Component / Icon / Text Nodes (6 Top-Level Nodes)
import { StandaloneNodesPage } from './pages/standalone/StandaloneNodesPage'; import { StandaloneNodesPage } from './pages/standalone/StandaloneNodesPage';
@ -76,16 +79,15 @@ const AppRoutes: React.FC = () => {
const activeMajorTab = isBare ? null : resolveMajorTab(location.pathname); const activeMajorTab = isBare ? null : resolveMajorTab(location.pathname);
const visibleSlots = homeBootSettled const visibleSlots = homeBootSettled
? MAJOR_PAGE_SLOTS ? MAJOR_PAGE_SLOTS
: MAJOR_PAGE_SLOTS.filter(({ tab }) => tab === 'home');
: MAJOR_PAGE_SLOTS.filter(
({ tab }) => tab === 'home' || tab === activeMajorTab
);
return ( return (
<> <>
{!isNonShellRoute && {!isNonShellRoute &&
visibleSlots.map(({ tab, element }) => { visibleSlots.map(({ tab, element }) => {
const isActive =
!homeBootSettled && activeMajorTab !== null
? tab === 'home'
: activeMajorTab === tab;
const isActive = activeMajorTab === tab;
return ( return (
<MajorTabActiveContext.Provider key={tab} value={isActive}> <MajorTabActiveContext.Provider key={tab} value={isActive}>
<div <div
@ -110,6 +112,10 @@ const AppRoutes: React.FC = () => {
path="/categories/:categorySlug" path="/categories/:categorySlug"
element={<ShopCatItemsPage mode="category" />} element={<ShopCatItemsPage mode="category" />}
/> />
<Route
path="/collections/:collectionSlug"
element={<ShopCatItemsPage mode="collection" />}
/>
<Route <Route
path="/search" path="/search"
element={<ShopCatItemsPage mode="search" />} element={<ShopCatItemsPage mode="search" />}
@ -144,6 +150,7 @@ const AppRoutes: React.FC = () => {
path="/account/bookmarks" path="/account/bookmarks"
element={<ShopCatItemsPage mode="bookmarks" />} element={<ShopCatItemsPage mode="bookmarks" />}
/> />
<Route path="/account/notes" element={<ShopNotesPage />} />
<Route path="/account/addresses" element={<ShopAddressPage />} /> <Route path="/account/addresses" element={<ShopAddressPage />} />
<Route path="/account/profile" element={<ProviderRequestPage />} /> <Route path="/account/profile" element={<ProviderRequestPage />} />
<Route path="/account/settings" element={<LanguageSettingPage />} /> <Route path="/account/settings" element={<LanguageSettingPage />} />

48
src/components/account/AccountMenuRow.tsx

@ -1,7 +1,9 @@
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useShopApp } from '../../context/ShopAppContext';
import type { AccountMenuRowItem } from '../../data/accountData'; import type { AccountMenuRowItem } from '../../data/accountData';
import { tr } from '../../lib/cookies';
import { ShimmerBox } from '../common/ShimmerSkeletons';
import { isRtlLanguage, tr } from '../../lib/cookies';
interface AccountMenuRowProps { interface AccountMenuRowProps {
row: AccountMenuRowItem; row: AccountMenuRowItem;
@ -14,6 +16,8 @@ interface AccountMenuRowProps {
*/ */
export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row, onClick }) => { export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row, onClick }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const { language } = useShopApp();
const isRtl = isRtlLanguage(language);
return ( return (
<div <div
@ -112,23 +116,32 @@ export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row, onClick })
textOverflow: 'ellipsis', textOverflow: 'ellipsis',
}} }}
> >
{tr(row.title)}
{tr(row.title, language)}
</div> </div>
{row.subtitle && (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#73889d',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{tr(row.subtitle)}
</div>
{row.loadingSubtitle ? (
<ShimmerBox
width={58}
height={11}
borderRadius={4}
style={{ marginTop: 2 }}
/>
) : (
row.subtitle && (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#73889d',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{tr(row.subtitle, language)}
</div>
)
)} )}
</div> </div>
@ -152,6 +165,7 @@ export const AccountMenuRow: React.FC<AccountMenuRowProps> = ({ row, onClick })
width: 5, width: 5,
height: 10, height: 10,
flexShrink: 0, flexShrink: 0,
transform: isRtl ? 'scaleX(-1)' : undefined,
}} }}
/> />
)} )}

38
src/components/account/OrderCounterCard.tsx

@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import type { OrderStatusCounterItem } from '../../data/accountData'; import type { OrderStatusCounterItem } from '../../data/accountData';
import { ShimmerBox } from '../common/ShimmerSkeletons';
import { tr } from '../../lib/cookies'; import { tr } from '../../lib/cookies';
import { ROUTES } from '../../lib/routes'; import { ROUTES } from '../../lib/routes';
@ -91,20 +92,29 @@ export const OrderCounterCard: React.FC<OrderCounterCardProps> = ({
> >
{tr(counter.label)} {tr(counter.label)}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(10.5px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#111111',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{tr(counter.countText)}
</div>
{counter.loadingCount ? (
<ShimmerBox
width={48}
height={14}
borderRadius={5}
style={{ marginTop: 2 }}
/>
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(10.5px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#111111',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{tr(counter.countText)}
</div>
)}
</div> </div>
</div> </div>
); );

68
src/components/checkout/OrderSummaryRows.tsx

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { ORDER_SUMMARY_ROWS } from '../../data/checkoutData'; import { ORDER_SUMMARY_ROWS } from '../../data/checkoutData';
import { ShimmerBox } from '../common/ShimmerSkeletons';
import { tr } from '../../lib/cookies'; import { tr } from '../../lib/cookies';
export interface SummaryLineRow { export interface SummaryLineRow {
@ -16,12 +17,21 @@ interface OrderSummaryRowsProps {
totalValueLeft?: number; totalValueLeft?: number;
rows?: SummaryLineRow[]; rows?: SummaryLineRow[];
totalText?: string; totalText?: string;
loading?: boolean;
} }
export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({
rows = ORDER_SUMMARY_ROWS, rows = ORDER_SUMMARY_ROWS,
totalText = '$70.50', totalText = '$70.50',
loading = false,
}) => { }) => {
const displayRows: SummaryLineRow[] = loading
? [
{ id: 'row-items', label: 'Items', value: '' },
{ id: 'row-shipping', label: 'Shipping', value: '' },
]
: rows;
return ( return (
<div <div
style={{ style={{
@ -39,7 +49,7 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({
gap: '10px', gap: '10px',
}} }}
> >
{rows.map((row) => (
{displayRows.map((row) => (
<div <div
key={row.id} key={row.id}
style={{ style={{
@ -62,18 +72,22 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({
> >
{tr(row.label)} {tr(row.label)}
</span> </span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: '14px',
lineHeight: '20px',
color: '#747474',
flexShrink: 0,
}}
>
{row.value}
</span>
{loading ? (
<ShimmerBox width={52} height={15} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: '14px',
lineHeight: '20px',
color: '#747474',
flexShrink: 0,
}}
>
{row.value}
</span>
)}
</div> </div>
))} ))}
</div> </div>
@ -107,18 +121,22 @@ export const OrderSummaryRows: React.FC<OrderSummaryRowsProps> = ({
> >
{tr('Total')} {tr('Total')}
</span> </span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '16px',
lineHeight: '20px',
color: 'var(--color-text-charcoal)',
flexShrink: 0,
}}
>
{totalText}
</span>
{loading ? (
<ShimmerBox width={64} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '16px',
lineHeight: '20px',
color: 'var(--color-text-charcoal)',
flexShrink: 0,
}}
>
{totalText}
</span>
)}
</div> </div>
</div> </div>
); );

7
src/components/common/PhoneNumberInput.tsx

@ -258,7 +258,12 @@ export const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({
) : ( ) : (
<button <button
type="button" type="button"
onClick={() => setPickerOpen(true)}
onClick={() => {
if (typeof document !== 'undefined' && document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
setPickerOpen(true);
}}
aria-label="Select country code" aria-label="Select country code"
style={{ style={{
display: 'inline-flex', display: 'inline-flex',

839
src/components/common/ShimmerSkeletons.tsx

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { tr } from '../../lib/cookies';
import { isRtlLanguage, tr } from '../../lib/cookies';
const ShimmerGate: React.FC<{ children: React.ReactNode }> = ({ children }) => ( const ShimmerGate: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<>{children}</> <>{children}</>
@ -165,86 +165,103 @@ export const CompactCarouselShimmer: React.FC<{ count?: number }> = ({
</ShimmerGate> </ShimmerGate>
); );
export const HomeFeedShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-home-feed"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
>
{/* Hero Banner Shimmer */}
export const HomeFeedShimmer: React.FC = () => {
const isRtl = isRtlLanguage();
return (
<ShimmerGate>
<div <div
className="habib-hero-banner"
style={{
width: '100%',
borderRadius: 15,
backgroundColor: '#182c1f',
padding: '16px 18px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
}}
data-testid="shimmer-home-feed"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<ShimmerBox width={68} height={10} borderRadius={5} dark />
<ShimmerBox width="72%" height={18} borderRadius={6} dark />
<ShimmerBox width="56%" height={18} borderRadius={6} dark />
<ShimmerBox width="65%" height={10} borderRadius={5} dark />
</div>
<ShimmerBox width={108} height={30} borderRadius={8} dark />
</div>
{/* 5 Quick Categories Circular Pills Shimmer */}
<div className="habib-quick-cats">
{Array.from({ length: 5 }).map((_, idx) => (
<div
key={idx}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 6,
}}
>
<ShimmerBox width={43} height={43} borderRadius="50%" />
<ShimmerBox width={36} height={9} borderRadius={4} />
</div>
))}
</div>
{/* Populars Section Shimmer */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{/* Hero Banner Shimmer */}
<div <div
className="habib-hero-banner"
style={{ style={{
width: '100%',
borderRadius: 15,
backgroundColor: '#182c1f',
padding: '16px 18px',
display: 'flex', display: 'flex',
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'space-between', justifyContent: 'space-between',
padding: '0 2px',
}} }}
> >
<ShimmerBox width={74} height={16} borderRadius={6} />
<ShimmerBox width={56} height={12} borderRadius={6} />
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<ShimmerBox width={68} height={10} borderRadius={5} dark />
<ShimmerBox width="72%" height={18} borderRadius={6} dark />
<ShimmerBox width="56%" height={18} borderRadius={6} dark />
<ShimmerBox width="65%" height={10} borderRadius={5} dark />
</div>
<ShimmerBox width={108} height={30} borderRadius={8} dark />
</div> </div>
<CompactCarouselShimmer count={3} />
</div>
{/* New Stores Section Shimmer */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<ShimmerBox width={86} height={16} borderRadius={6} />
<ShimmerBox width={56} height={12} borderRadius={6} />
{/* 5 Quick Categories Circular Pills Shimmer */}
<div className="habib-quick-cats">
{Array.from({ length: 5 }).map((_, idx) => (
<div
key={idx}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 6,
}}
>
<ShimmerBox width={43} height={43} borderRadius="50%" />
<ShimmerBox width={36} height={9} borderRadius={4} />
</div>
))}
</div> </div>
<CompactCarouselShimmer count={3} />
{/* Collection Carousels Shimmer (static "See more" renders immediately) */}
{[74, 86].map((titleWidth, idx) => (
<div key={idx} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<ShimmerBox width={titleWidth} height={16} borderRadius={6} />
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
}}
/>
</div>
</div>
<CompactCarouselShimmer count={3} />
</div>
))}
</div> </div>
</div>
</ShimmerGate>
);
</ShimmerGate>
);
};
export const CategoryGridShimmer: React.FC<{ count?: number }> = ({ export const CategoryGridShimmer: React.FC<{ count?: number }> = ({
count = 6, count = 6,
@ -315,223 +332,6 @@ export const ProductGridShimmer: React.FC<{ count?: number }> = ({
</ShimmerGate> </ShimmerGate>
); );
export const ProductDetailBodyShimmer: React.FC = () => (
<ShimmerGate>
<div data-testid="shimmer-product-detail" style={{ display: 'contents' }}>
<div
style={{
position: 'relative',
zIndex: 1,
marginTop: -38,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
backgroundColor: '#f3f1ef',
padding: '18px var(--page-px) 16px',
display: 'flex',
flexDirection: 'column',
gap: 15,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width="54%" height={11} borderRadius={5} />
<ShimmerBox width={56} height={24} borderRadius={8} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<ShimmerBox width="82%" height={22} borderRadius={7} />
<ShimmerBox width="38%" height={14} borderRadius={6} />
</div>
<div className="habib-single-attrs-grid" style={{ marginTop: 4 }}>
<ShimmerBox height={48} borderRadius={8} />
<ShimmerBox height={48} borderRadius={8} />
<ShimmerBox height={48} borderRadius={8} />
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
paddingTop: 4,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<ShimmerBox width={39} height={39} borderRadius="50%" />
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<ShimmerBox width={126} height={14} borderRadius={6} />
<ShimmerBox width={74} height={10} borderRadius={5} />
</div>
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-end',
gap: 5,
}}
>
<ShimmerBox width={42} height={13} borderRadius={5} />
<ShimmerBox width={54} height={10} borderRadius={5} />
</div>
</div>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: 16,
marginTop: 8,
paddingBottom: 6,
}}
>
<ShimmerBox height={20} borderRadius={6} />
<ShimmerBox height={20} borderRadius={6} />
</div>
</div>
<div
style={{
flex: 1,
backgroundColor: '#ebe8e5',
padding: '24px var(--page-px) 28px',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<ShimmerBox width={90} height={14} borderRadius={6} />
<ShimmerBox width="45%" height={13} borderRadius={6} />
<ShimmerBox
width={104}
height={14}
borderRadius={6}
style={{ marginTop: 8 }}
/>
<ShimmerBox width="96%" height={13} borderRadius={6} />
<ShimmerBox width="91%" height={13} borderRadius={6} />
<ShimmerBox width="78%" height={13} borderRadius={6} />
</div>
<div
style={{
position: 'sticky',
bottom: 0,
zIndex: 20,
width: '100%',
minHeight: 87,
padding: '16px var(--page-px) calc(16px + var(--safe-bottom, 0px))',
borderRadius: '17px 17px 0 0',
backgroundColor: '#ffffff',
boxShadow: '0px -7px 12px rgba(103, 110, 124, 0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<ShimmerBox width={68} height={13} borderRadius={5} />
<ShimmerBox width={88} height={24} borderRadius={7} />
</div>
<ShimmerBox width={176} height={52} borderRadius={11} />
</div>
</div>
</ShimmerGate>
);
export const StoreBoothBodyShimmer: React.FC = () => (
<ShimmerGate>
<div
data-testid="shimmer-store-booth"
style={{
position: 'relative',
zIndex: 1,
marginTop: -97,
flex: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: '0 var(--page-px) 32px',
}}
>
<ShimmerBox
width={64}
height={64}
borderRadius={32}
style={{ border: '2px solid #ffffff' }}
/>
<ShimmerBox
width={186}
height={18}
borderRadius={6}
style={{ marginTop: 12 }}
/>
<ShimmerBox
width={104}
height={13}
borderRadius={6}
style={{ marginTop: 8 }}
/>
<div
style={{
marginTop: 14,
width: '100%',
maxWidth: 340,
display: 'flex',
justifyContent: 'space-around',
gap: 10,
}}
>
<ShimmerBox width={64} height={13} borderRadius={5} />
<ShimmerBox width={92} height={13} borderRadius={5} />
<ShimmerBox width={60} height={13} borderRadius={5} />
</div>
<div className="habib-booth-metrics-grid" style={{ marginTop: 21 }}>
<ShimmerBox height={58} borderRadius={8} />
<ShimmerBox height={58} borderRadius={8} />
<ShimmerBox height={58} borderRadius={8} />
</div>
<div
style={{
marginTop: 26,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 10,
}}
>
<ShimmerBox width={62} height={16} borderRadius={6} />
<ShimmerBox width="96%" height={13} borderRadius={5} />
<ShimmerBox width="88%" height={13} borderRadius={5} />
<ShimmerBox width="70%" height={13} borderRadius={5} />
</div>
<div
style={{
marginTop: 28,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<ShimmerBox width={78} height={16} borderRadius={6} />
<ProductGridShimmer count={4} />
</div>
</div>
</ShimmerGate>
);
export const OrdersListShimmer: React.FC<{ count?: number }> = ({ export const OrdersListShimmer: React.FC<{ count?: number }> = ({
count = 2, count = 2,
}) => ( }) => (
@ -573,79 +373,52 @@ export const OrdersListShimmer: React.FC<{ count?: number }> = ({
</ShimmerGate> </ShimmerGate>
); );
export const OrderDetailShimmer: React.FC = () => (
export const OrderDetailShimmer: React.FC<{ count?: number }> = ({
count = 2,
}) => (
<ShimmerGate> <ShimmerGate>
<div
data-testid="shimmer-order-detail"
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
>
<div
style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ebe8e5',
display: 'flex',
flexDirection: 'column',
gap: 14,
}}
>
<div className="habib-orders-grid" data-testid="shimmer-order-detail">
{Array.from({ length: count }).map((_, idx) => (
<div <div
key={idx}
style={{ style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ffffff',
display: 'flex', display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexDirection: 'column',
gap: 14,
}} }}
> >
<ShimmerBox width={146} height={18} borderRadius={6} />
<ShimmerBox width={94} height={14} borderRadius={6} />
</div>
<ShimmerBox height={41} borderRadius={12} />
</div>
<div className="habib-orders-grid">
{Array.from({ length: 2 }).map((_, idx) => (
<div <div
key={idx}
style={{ style={{
width: '100%',
padding: 14,
borderRadius: 20,
backgroundColor: '#ffffff',
display: 'flex', display: 'flex',
flexDirection: 'column',
gap: 14,
alignItems: 'center',
justifyContent: 'space-between',
}} }}
> >
<ShimmerBox width={132} height={16} borderRadius={6} />
<ShimmerBox width={74} height={22} borderRadius={10} />
</div>
<div style={{ display: 'flex', gap: 10 }}>
<ShimmerBox width={58} height={58} borderRadius={10} />
<div <div
style={{ style={{
flex: 1,
display: 'flex', display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexDirection: 'column',
gap: 8,
justifyContent: 'center',
}} }}
> >
<ShimmerBox width={132} height={16} borderRadius={6} />
<ShimmerBox width={74} height={22} borderRadius={10} />
<ShimmerBox width="80%" height={14} borderRadius={6} />
<ShimmerBox width="45%" height={14} borderRadius={6} />
</div> </div>
<div style={{ display: 'flex', gap: 10 }}>
<ShimmerBox width={58} height={58} borderRadius={10} />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
gap: 8,
justifyContent: 'center',
}}
>
<ShimmerBox width="80%" height={14} borderRadius={6} />
<ShimmerBox width="45%" height={14} borderRadius={6} />
</div>
</div>
<ShimmerBox height={28} borderRadius={10} />
</div> </div>
))}
</div>
<ShimmerBox height={28} borderRadius={10} />
</div>
))}
</div> </div>
</ShimmerGate> </ShimmerGate>
); );
@ -739,388 +512,4 @@ export const CartItemsShimmer: React.FC<{ count?: number }> = ({
</ShimmerGate> </ShimmerGate>
); );
const BottomNavShimmer: React.FC = () => (
<ShimmerGate>
<div
style={{
marginTop: 'auto',
width: '100%',
minHeight: 78,
paddingBottom: 'var(--safe-bottom, 0px)',
borderRadius: '17px 17px 0 0',
backgroundColor: '#ffffff',
boxShadow: '0px -7px 12px rgba(103, 110, 124, 0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-around',
paddingLeft: 16,
paddingRight: 16,
flexShrink: 0,
}}
>
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={54} height={48} borderRadius={24} />
<ShimmerBox width={36} height={36} borderRadius={10} />
<ShimmerBox width={36} height={36} borderRadius={10} />
</div>
</ShimmerGate>
);
const TopHeaderShimmer: React.FC<{ showRightAction?: boolean }> = ({
showRightAction = false,
}) => (
<ShimmerGate>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: 40,
padding: 'calc(21px + var(--safe-top, 0px)) var(--page-px) 0',
flexShrink: 0,
}}
>
<ShimmerBox width={40} height={40} borderRadius={15} />
<ShimmerBox width={118} height={20} borderRadius={8} />
{showRightAction ? (
<ShimmerBox width={40} height={40} borderRadius={15} />
) : (
<div style={{ width: 40, height: 40 }} />
)}
</div>
</ShimmerGate>
);
export const FullPageRouteShimmer: React.FC<{ pathname: string }> = ({
pathname,
}) => {
const isHome = pathname === '/' || pathname === '/shop-home';
const isCategoryRoot =
pathname === '/categories' || pathname === '/shop-category';
const isProductGrid =
pathname.startsWith('/categories/') ||
pathname === '/search' ||
pathname === '/account/bookmarks' ||
pathname === '/shop-catitems';
const isProductSingle =
pathname.startsWith('/products/') || pathname === '/shop-single-page';
const isStoreBooth =
pathname === '/stores' ||
pathname.startsWith('/stores/') ||
pathname === '/shop-booth';
const isCart =
pathname === '/cart' ||
pathname === '/shop-cart' ||
pathname === '/shop-order-summery' ||
pathname === '/shop-payment-methods';
const isOrdersList = pathname === '/orders' || pathname === '/shop-orders';
const isOrderDetail =
(pathname.startsWith('/orders/') && !pathname.endsWith('/support')) ||
pathname === '/shop-order-detail';
const isChat =
pathname === '/chat' ||
pathname.startsWith('/chat/') ||
pathname === '/shop-chat';
const isAccount =
pathname === '/account' ||
pathname === '/shop-account' ||
pathname === '/shop-category-4214-345';
if (isProductSingle) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div className="habib-single-hero-wrap" style={{ flexShrink: 0 }}>
<ShimmerBox width="100%" height="100%" borderRadius={0} />
</div>
<ProductDetailBodyShimmer />
</div>
);
}
if (isStoreBooth) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
position: 'relative',
width: '100%',
height: 152,
overflow: 'hidden',
flexShrink: 0,
}}
>
<ShimmerBox width="100%" height="100%" borderRadius={0} />
</div>
<StoreBoothBodyShimmer />
</div>
);
}
if (isHome) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(37px + var(--safe-top, 0px)) var(--page-px) 22px',
gap: 20,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: 40,
marginBottom: 11,
}}
>
<ShimmerBox width={40} height={40} borderRadius={15} />
<ShimmerBox width={68} height={22} borderRadius={8} />
<ShimmerBox width={40} height={40} borderRadius={15} />
</div>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<ShimmerBox height={44} borderRadius={14} style={{ flex: 1 }} />
<ShimmerBox width={44} height={44} borderRadius={14} />
</div>
<HomeFeedShimmer />
</div>
<BottomNavShimmer />
</div>
);
}
if (isCategoryRoot) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(38px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 20,
}}
>
<ShimmerBox height={44} borderRadius={14} />
<CategoryGridShimmer count={6} />
</div>
<BottomNavShimmer />
</div>
);
}
if (isProductGrid) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '11px var(--page-px) 28px',
gap: 23,
}}
>
<ShimmerBox height={44} borderRadius={14} />
<ProductGridShimmer count={6} />
</div>
</div>
);
}
if (isCart) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(42px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 13,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<ShimmerBox width={120} height={14} borderRadius={5} />
<ShimmerBox width={54} height={14} borderRadius={5} />
</div>
<CartItemsShimmer count={2} />
</div>
<BottomNavShimmer />
</div>
);
}
if (isOrdersList) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '26px var(--page-px) 28px',
gap: 22,
}}
>
<ShimmerBox height={46} borderRadius={14} />
<OrdersListShimmer count={2} />
</div>
</div>
);
}
if (isOrderDetail) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '26px var(--page-px) 20px',
gap: 20,
}}
>
<OrderDetailShimmer />
</div>
</div>
);
}
if (isChat) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer showRightAction />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
padding: '24px var(--page-px) 16px',
}}
>
<ChatThreadShimmer />
</div>
<div style={{ padding: '10px var(--page-px) 20px' }}>
<ShimmerBox height={52} borderRadius={16} />
</div>
</div>
);
}
if (isAccount) {
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(21px + var(--safe-top, 0px)) var(--page-px) 24px',
gap: 24,
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 8,
}}
>
<ShimmerBox width={84} height={84} borderRadius="50%" />
<ShimmerBox width={128} height={20} borderRadius={7} />
<ShimmerBox width={96} height={12} borderRadius={5} />
</div>
<div className="habib-counters-grid">
<ShimmerBox height={78} borderRadius={15} />
<ShimmerBox height={78} borderRadius={15} />
<ShimmerBox height={78} borderRadius={15} />
</div>
<ShimmerBox height={290} borderRadius={15} />
</div>
<BottomNavShimmer />
</div>
);
}
return (
<div
className="habib-page-shimmer-overlay"
data-testid="shimmer-full-page"
aria-hidden="true"
>
<TopHeaderShimmer />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '24px var(--page-px) 24px',
gap: 18,
}}
>
<ShimmerBox height={116} borderRadius={15} />
<ShimmerBox height={148} borderRadius={15} />
<ShimmerBox height={96} borderRadius={15} />
</div>
</div>
);
};

69
src/components/layout/MobileShell.tsx

@ -10,7 +10,6 @@ import { useLocation, useNavigationType } from 'react-router-dom';
import { consumeBackNavigation } from '../../hooks/useSmartBack'; import { consumeBackNavigation } from '../../hooks/useSmartBack';
import { getToken } from '../../lib/auth-bridge'; import { getToken } from '../../lib/auth-bridge';
import { shopKeys } from '../../lib/shopQueries'; import { shopKeys } from '../../lib/shopQueries';
import { FullPageRouteShimmer } from '../common/ShimmerSkeletons';
export const MajorTabActiveContext = createContext<boolean>(true); export const MajorTabActiveContext = createContext<boolean>(true);
@ -95,6 +94,10 @@ export function useHomeBootSettled(): boolean {
); );
} }
export function isInitialBootSettled(): boolean {
return currentShellSnapshot.bootPhase === 'settled';
}
function addSettledPathname(pathname: string): void { function addSettledPathname(pathname: string): void {
settledPathnames.add(pathname); settledPathnames.add(pathname);
if (pathname === '/' || pathname === '/shop-home') { if (pathname === '/' || pathname === '/shop-home') {
@ -244,7 +247,9 @@ export const MobileShell: React.FC<MobileShellProps> = ({
const currentClearVersion = shellState.clearVersion; const currentClearVersion = shellState.clearVersion;
const isOtherTabsBackgroundSettled = shellState.otherTabsBackgroundSettled; const isOtherTabsBackgroundSettled = shellState.otherTabsBackgroundSettled;
const isPageReady = const isPageReady =
isEmbed || shellState.settledPathnames.has(location.pathname);
isEmbed ||
(currentBootPhase === 'settled' &&
shellState.settledPathnames.has(location.pathname));
useEffect(() => { useEffect(() => {
preloadSharedIcons(); preloadSharedIcons();
@ -367,11 +372,7 @@ export const MobileShell: React.FC<MobileShellProps> = ({
'.habib-shimmer, .habib-shimmer-dark, .habib-inline-spinner' '.habib-shimmer, .habib-shimmer-dark, .habib-inline-spinner'
); );
for (let i = 0; i < shimmers.length; i += 1) { for (let i = 0; i < shimmers.length; i += 1) {
if (
!shimmers[i].closest(
'.habib-page-shimmer-overlay, .habib-auth-loading-overlay'
)
) {
if (!shimmers[i].closest('.habib-auth-loading-overlay')) {
return true; return true;
} }
} }
@ -379,26 +380,14 @@ export const MobileShell: React.FC<MobileShellProps> = ({
}; };
const getUnderlyingImages = (root: HTMLElement): HTMLImageElement[] => { const getUnderlyingImages = (root: HTMLElement): HTMLImageElement[] => {
const all = root.querySelectorAll('img');
const result: HTMLImageElement[] = [];
for (let i = 0; i < all.length; i += 1) {
const img = all[i];
if (!img.closest('.habib-page-shimmer-overlay')) {
result.push(img);
}
}
return result;
return Array.from(root.querySelectorAll('img'));
}; };
const markReady = (allMajorPagesComplete: boolean) => { const markReady = (allMajorPagesComplete: boolean) => {
if (currentBootPhase === 'home') { if (currentBootPhase === 'home') {
addSettledPathname('/'); addSettledPathname('/');
addSettledPathname(targetPathname);
bootPhase = 'other-tabs'; bootPhase = 'other-tabs';
emitShellStoreChange(); emitShellStoreChange();
if (typeof window !== 'undefined') {
window.__announceHabibWebReady?.();
}
return; return;
} }
@ -416,19 +405,14 @@ export const MobileShell: React.FC<MobileShellProps> = ({
} }
}; };
// Safety fallback so no boot phase or route transition can stay stuck on shimmers forever.
// Keep initial boot splash active until all initial requests finish; only apply a fallback timer to post-boot route transitions.
const safetyTimer = const safetyTimer =
currentBootPhase === 'home' ||
currentBootPhase === 'other-tabs' ||
(currentBootPhase === 'settled' && !isPageReady)
? window.setTimeout(
() => {
if (!cancelled) {
markReady(false);
}
},
currentBootPhase === 'home' ? 3500 : 3000
)
currentBootPhase === 'settled' && !isPageReady
? window.setTimeout(() => {
if (!cancelled) {
markReady(false);
}
}, 3000)
: undefined; : undefined;
const evaluateReadiness = () => { const evaluateReadiness = () => {
@ -542,10 +526,15 @@ export const MobileShell: React.FC<MobileShellProps> = ({
'--shell-bg': backgroundColor, '--shell-bg': backgroundColor,
} as React.CSSProperties; } as React.CSSProperties;
const isChatRoute =
location.pathname === '/chat' ||
location.pathname.startsWith('/chat/') ||
location.pathname === '/shop-chat';
if (isEmbed) { if (isEmbed) {
return ( return (
<div <div
className="habib-mobile-viewport is-embed"
className={`habib-mobile-viewport is-embed${isChatRoute ? ' is-chat-route' : ''}`}
style={cssVars} style={cssVars}
> >
{children} {children}
@ -557,16 +546,15 @@ export const MobileShell: React.FC<MobileShellProps> = ({
? resolvePageTransitionClass(location.pathname, navigationType) ? resolvePageTransitionClass(location.pathname, navigationType)
: ''; : '';
const viewportClasses = [
'habib-mobile-viewport',
transitionClass,
isMajorTabActive && !isPageReady ? 'is-habib-loading' : '',
]
const viewportClasses = ['habib-mobile-viewport', transitionClass]
.filter(Boolean) .filter(Boolean)
.join(' '); .join(' ');
return ( return (
<div className="habib-shell-outer" style={cssVars}>
<div
className={`habib-shell-outer${isChatRoute ? ' is-chat-route' : ''}`}
style={cssVars}
>
{isMajorTabActive && ( {isMajorTabActive && (
<div className="habib-status-bar-scrim" aria-hidden="true" /> <div className="habib-status-bar-scrim" aria-hidden="true" />
)} )}
@ -576,9 +564,6 @@ export const MobileShell: React.FC<MobileShellProps> = ({
className={viewportClasses} className={viewportClasses}
style={cssVars} style={cssVars}
> >
{isMajorTabActive && !isPageReady && (
<FullPageRouteShimmer pathname={location.pathname} />
)}
{children} {children}
</div> </div>
</div> </div>

92
src/components/layout/StickyFooterBar.tsx

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { ShimmerBox } from '../common/ShimmerSkeletons';
import { tr } from '../../lib/cookies'; import { tr } from '../../lib/cookies';
interface StickyFooterBarProps { interface StickyFooterBarProps {
@ -13,6 +14,8 @@ interface StickyFooterBarProps {
totalItemsLabel?: string; totalItemsLabel?: string;
onTotalItemsClick?: () => void; onTotalItemsClick?: () => void;
topLabel?: string; topLabel?: string;
loadingPrice?: boolean;
loadingTopMeta?: boolean;
buttonText: string; buttonText: string;
buttonLeft?: number; buttonLeft?: number;
buttonTextLeft?: number; buttonTextLeft?: number;
@ -40,6 +43,8 @@ export const StickyFooterBar: React.FC<StickyFooterBarProps> = ({
totalItemsLabel, totalItemsLabel,
onTotalItemsClick, onTotalItemsClick,
topLabel, topLabel,
loadingPrice = false,
loadingTopMeta = false,
buttonText, buttonText,
buttonFontWeight = 700, buttonFontWeight = 700,
iconSrc, iconSrc,
@ -133,37 +138,40 @@ export const StickyFooterBar: React.FC<StickyFooterBarProps> = ({
</span> </span>
)} )}
{totalItemsLabel && (
<button
type="button"
onClick={onTotalItemsClick}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '3px',
cursor: onTotalItemsClick ? 'pointer' : 'default',
padding: 0,
}}
>
<span
{totalItemsLabel &&
(loadingTopMeta ? (
<ShimmerBox width={74} height={15} borderRadius={5} />
) : (
<button
type="button"
onClick={onTotalItemsClick}
style={{ style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '12px',
lineHeight: '17px',
color: '#111111',
whiteSpace: 'nowrap',
display: 'inline-flex',
alignItems: 'center',
gap: '3px',
cursor: onTotalItemsClick ? 'pointer' : 'default',
padding: 0,
}} }}
> >
{tr(totalItemsLabel)}
</span>
<img
src="/assets/images/icon-caret-up-gold.svg"
alt=""
style={{ width: '14px', height: '14px', flexShrink: 0 }}
/>
</button>
)}
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '12px',
lineHeight: '17px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(totalItemsLabel)}
</span>
<img
src="/assets/images/icon-caret-up-gold.svg"
alt=""
style={{ width: '14px', height: '14px', flexShrink: 0 }}
/>
</button>
))}
{topLabel && ( {topLabel && (
<span <span
@ -181,18 +189,22 @@ export const StickyFooterBar: React.FC<StickyFooterBarProps> = ({
)} )}
</div> </div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '22px',
lineHeight: '26px',
color: 'var(--color-text-charcoal)',
whiteSpace: 'nowrap',
}}
>
{price}
</span>
{loadingPrice ? (
<ShimmerBox width={82} height={24} borderRadius={6} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: '22px',
lineHeight: '26px',
color: 'var(--color-text-charcoal)',
whiteSpace: 'nowrap',
}}
>
{price}
</span>
)}
</div> </div>
{/* Primary Gold CTA Button */} {/* Primary Gold CTA Button */}

59
src/components/modals/AddressFormSheet.tsx

@ -270,6 +270,9 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
}; };
const handlePickMap = () => { const handlePickMap = () => {
if (typeof document !== 'undefined' && document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
const startLat = const startLat =
lat !== null && Number.isFinite(lat) ? lat : 36.1901; lat !== null && Number.isFinite(lat) ? lat : 36.1901;
const startLon = const startLon =
@ -570,6 +573,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
gap: '14px', gap: '14px',
maxHeight: '88dvh', maxHeight: '88dvh',
overflowY: 'auto', overflowY: 'auto',
overscrollBehavior: 'contain',
}} }}
> >
<div <div
@ -972,7 +976,7 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
)} )}
</div> </div>
{/* Anchored User GPS Location Marker (Blue Dot + Accuracy Circle + Badge on Map) */}
{/* Anchored User GPS Location Marker (Core Blue Dot on Map) */}
{gpsPointOffsetPx && ( {gpsPointOffsetPx && (
<div <div
style={{ style={{
@ -984,67 +988,16 @@ export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({
zIndex: 3, zIndex: 3,
}} }}
> >
{/* Accuracy halo */}
<div
style={{
position: 'absolute',
left: '50%',
top: '50%',
width: '64px',
height: '64px',
borderRadius: '999px',
backgroundColor: 'rgba(37, 99, 235, 0.16)',
border: '1.5px solid rgba(37, 99, 235, 0.45)',
transform: 'translate(-50%, -50%)',
}}
/>
{/* Radar pulse wave */}
<div <div
style={{ style={{
position: 'absolute',
left: '50%',
top: '50%',
width: '54px',
height: '54px',
borderRadius: '999px',
backgroundColor: 'rgba(37, 99, 235, 0.28)',
border: '2px solid rgba(37, 99, 235, 0.7)',
transform: 'translate(-50%, -50%)',
animation: 'habibGpsPulseRing 2s infinite ease-out',
}}
/>
{/* Core Blue GPS Dot */}
<div
style={{
position: 'relative',
width: '18px', width: '18px',
height: '18px', height: '18px',
borderRadius: '999px', borderRadius: '999px',
backgroundColor: '#2563eb', backgroundColor: '#2563eb',
border: '3px solid #ffffff', border: '3px solid #ffffff',
boxShadow: '0 2px 8px rgba(37, 99, 235, 0.65)',
boxShadow: '0 2px 6px rgba(0, 0, 0, 0.3)',
}} }}
/> />
{/* "Your GPS" label pill anchored to the GPS dot */}
<div
style={{
position: 'absolute',
left: '50%',
top: '16px',
transform: 'translateX(-50%)',
backgroundColor: '#1d4ed8',
color: '#ffffff',
fontSize: '9px',
fontWeight: 800,
padding: '2px 6px',
borderRadius: '999px',
whiteSpace: 'nowrap',
boxShadow: '0 2px 6px rgba(0,0,0,0.22)',
letterSpacing: '0.02em',
}}
>
{tr('Your GPS')}
</div>
</div> </div>
)} )}

16
src/components/modals/PaymentMethodsSheet.tsx

@ -2,7 +2,11 @@ import React from 'react';
import { useAnimatedPresence } from '../../hooks/use-animated-presence'; import { useAnimatedPresence } from '../../hooks/use-animated-presence';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
import { tr } from '../../lib/cookies'; import { tr } from '../../lib/cookies';
import { EmptyStateBox, InlineSpinner } from '../common/ShimmerSkeletons';
import {
EmptyStateBox,
InlineSpinner,
ShimmerBox,
} from '../common/ShimmerSkeletons';
import { PaymentMethodCard } from '../checkout/PaymentMethodCard'; import { PaymentMethodCard } from '../checkout/PaymentMethodCard';
import type { PaymentMethodItem } from '../../data/checkoutData'; import type { PaymentMethodItem } from '../../data/checkoutData';
@ -15,6 +19,7 @@ interface PaymentMethodsSheetProps {
totalPriceText: string; totalPriceText: string;
onConfirmPurchase: () => void; onConfirmPurchase: () => void;
isSubmitting?: boolean; isSubmitting?: boolean;
isLoading?: boolean;
} }
export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
@ -26,6 +31,7 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
totalPriceText, totalPriceText,
onConfirmPurchase, onConfirmPurchase,
isSubmitting = false, isSubmitting = false,
isLoading = false,
}) => { }) => {
const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200); const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200);
@ -123,7 +129,13 @@ export const PaymentMethodsSheet: React.FC<PaymentMethodsSheetProps> = ({
gap: '12px', gap: '12px',
}} }}
> >
{methods.length > 0 ? (
{isLoading && methods.length === 0 ? (
<>
<ShimmerBox height={56} borderRadius={15} />
<ShimmerBox height={56} borderRadius={15} />
<ShimmerBox height={56} borderRadius={15} />
</>
) : methods.length > 0 ? (
methods.map((method) => ( methods.map((method) => (
<PaymentMethodCard <PaymentMethodCard
key={method.id} key={method.id}

54
src/components/orders/OrderFilterTabs.tsx

@ -1,10 +1,12 @@
import React from 'react'; import React from 'react';
import type { OrderFilterTabItem } from '../../data/ordersData'; import type { OrderFilterTabItem } from '../../data/ordersData';
import { ShimmerBox } from '../common/ShimmerSkeletons';
import { isRtlLanguage, tr } from '../../lib/cookies'; import { isRtlLanguage, tr } from '../../lib/cookies';
interface OrderFilterTabsProps { interface OrderFilterTabsProps {
tabs: OrderFilterTabItem[]; tabs: OrderFilterTabItem[];
activeTabId: string; activeTabId: string;
loadingCounts?: boolean;
onSelectTab: (tabId: OrderFilterTabItem['id']) => void; onSelectTab: (tabId: OrderFilterTabItem['id']) => void;
} }
@ -16,6 +18,7 @@ interface OrderFilterTabsProps {
export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
tabs, tabs,
activeTabId, activeTabId,
loadingCounts = false,
onSelectTab, onSelectTab,
}) => { }) => {
const isRtl = isRtlLanguage(); const isRtl = isRtlLanguage();
@ -105,32 +108,41 @@ export const OrderFilterTabs: React.FC<OrderFilterTabsProps> = ({
</span> </span>
{/* Count badge pill 19×19 */} {/* Count badge pill 19×19 */}
<span
style={{
width: 19,
height: 19,
borderRadius: 10,
backgroundColor: isActive ? '#ffffff' : '#787878',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'background-color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
{loadingCounts ? (
<ShimmerBox
width={19}
height={19}
borderRadius={10}
dark={isActive}
/>
) : (
<span <span
style={{ style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: isActive ? '#d78e06' : '#ffffff',
transition: 'color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
width: 19,
height: 19,
borderRadius: 10,
backgroundColor: isActive ? '#ffffff' : '#787878',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'background-color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}} }}
> >
{tab.count}
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: isActive ? '#d78e06' : '#ffffff',
transition: 'color 220ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
{tab.count}
</span>
</span> </span>
</span>
)}
</button> </button>
); );
})} })}

127
src/context/ShopAppContext.tsx

@ -11,6 +11,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import { import {
clearSettledPathnames, clearSettledPathnames,
isInitialBootSettled,
useHomeBootSettled, useHomeBootSettled,
} from '../components/layout/MobileShell'; } from '../components/layout/MobileShell';
import { InlineSpinner } from '../components/common/ShimmerSkeletons'; import { InlineSpinner } from '../components/common/ShimmerSkeletons';
@ -70,15 +71,19 @@ interface ShopAppContextValue {
cart: ApiCart | null; cart: ApiCart | null;
cartItemsCount: number; cartItemsCount: number;
cartTotalQuantity: number; cartTotalQuantity: number;
isCartLoading: boolean;
isCartBusy: boolean; isCartBusy: boolean;
addresses: ApiAddress[]; addresses: ApiAddress[];
isAddressesLoading: boolean;
selectedAddressId: number | null; selectedAddressId: number | null;
selectedAddress: ApiAddress | null; selectedAddress: ApiAddress | null;
shippingMethods: ApiShippingMethod[]; shippingMethods: ApiShippingMethod[];
isShippingMethodsLoading: boolean;
selectedShippingMethod: ApiShippingMethod | null; selectedShippingMethod: ApiShippingMethod | null;
selectedPaymentMethod: string; selectedPaymentMethod: string;
setSelectedPaymentMethod: (code: string) => void; setSelectedPaymentMethod: (code: string) => void;
bookmarkedProducts: ApiProductCard[]; bookmarkedProducts: ApiProductCard[];
isBookmarksLoading: boolean;
isBookmarked: (productId?: number | null, slug?: string | null) => boolean; isBookmarked: (productId?: number | null, slug?: string | null) => boolean;
toggleBookmark: ( toggleBookmark: (
productRef: string | number, productRef: string | number,
@ -87,13 +92,14 @@ interface ShopAppContextValue {
) => Promise<boolean>; ) => Promise<boolean>;
profile: ApiUserProfile | null; profile: ApiUserProfile | null;
isProfileLoading: boolean; isProfileLoading: boolean;
isProfilePending: boolean;
orderCounters: ApiOrderCounters | null; orderCounters: ApiOrderCounters | null;
isOrderCountersLoading: boolean;
language: string; language: string;
changeLanguage: (lang: string) => void; changeLanguage: (lang: string) => void;
addToCart: ( addToCart: (
productRef: string | number, productRef: string | number,
quantity?: number,
variantId?: number | null
quantity?: number
) => Promise<ApiCart | null>; ) => Promise<ApiCart | null>;
updateCartItemQuantity: (itemId: number, quantity: number) => Promise<void>; updateCartItemQuantity: (itemId: number, quantity: number) => Promise<void>;
removeCartItem: (itemId: number) => Promise<void>; removeCartItem: (itemId: number) => Promise<void>;
@ -148,6 +154,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const hasAuthToken = Boolean(authToken); const hasAuthToken = Boolean(authToken);
const homeBootSettled = useHomeBootSettled(); const homeBootSettled = useHomeBootSettled();
const isHomeRoute =
location.pathname === '/' || location.pathname === '/shop-home';
const enableSecondaryQueries = !isBare && (homeBootSettled || !isHomeRoute);
const homeQuery = useQuery({ const homeQuery = useQuery({
queryKey: shopKeys.home(), queryKey: shopKeys.home(),
@ -158,7 +167,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const categoriesQuery = useQuery({ const categoriesQuery = useQuery({
queryKey: shopKeys.categories(), queryKey: shopKeys.categories(),
queryFn: () => shopApi.fetchCategories(), queryFn: () => shopApi.fetchCategories(),
enabled: !isBare && homeBootSettled,
enabled: enableSecondaryQueries,
}); });
useEffect(() => { useEffect(() => {
@ -175,38 +184,38 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const cartQuery = useQuery({ const cartQuery = useQuery({
queryKey: shopKeys.cart(), queryKey: shopKeys.cart(),
queryFn: () => shopApi.fetchCart(false), queryFn: () => shopApi.fetchCart(false),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
}); });
const profileQuery = useQuery({ const profileQuery = useQuery({
queryKey: shopKeys.profile(), queryKey: shopKeys.profile(),
queryFn: () => shopApi.fetchProfile(), queryFn: () => shopApi.fetchProfile(),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
}); });
const addressesQuery = useQuery({ const addressesQuery = useQuery({
queryKey: shopKeys.addresses(), queryKey: shopKeys.addresses(),
queryFn: () => shopApi.fetchAddresses(), queryFn: () => shopApi.fetchAddresses(),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
}); });
const shippingMethodsQuery = useQuery({ const shippingMethodsQuery = useQuery({
queryKey: shopKeys.shippingMethods(), queryKey: shopKeys.shippingMethods(),
queryFn: () => shopApi.fetchShippingMethods(), queryFn: () => shopApi.fetchShippingMethods(),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
staleTime: 5 * 60_000, staleTime: 5 * 60_000,
}); });
const bookmarksQuery = useQuery({ const bookmarksQuery = useQuery({
queryKey: shopKeys.bookmarks(), queryKey: shopKeys.bookmarks(),
queryFn: () => shopApi.fetchBookmarks(), queryFn: () => shopApi.fetchBookmarks(),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
}); });
const orderCountersQuery = useQuery({ const orderCountersQuery = useQuery({
queryKey: shopKeys.orderCounters(), queryKey: shopKeys.orderCounters(),
queryFn: () => shopApi.fetchOrderCounters(), queryFn: () => shopApi.fetchOrderCounters(),
enabled: !isBare && hasAuthToken && homeBootSettled,
enabled: enableSecondaryQueries && hasAuthToken,
}); });
const publicMajorHydrated = const publicMajorHydrated =
@ -223,9 +232,65 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const hydrated = isBare || (publicMajorHydrated && authMajorHydrated); const hydrated = isBare || (publicMajorHydrated && authMajorHydrated);
const cart = cartQuery.data ?? null; const cart = cartQuery.data ?? null;
const profile = profileQuery.data ?? null;
const bootstrapHint = useMemo(
() => (!isBare && hasAuthToken ? readBootstrapUserHint() : null),
[hasAuthToken, isBare]
);
const profile = useMemo<ApiUserProfile | null>(() => {
if (profileQuery.data) return profileQuery.data;
if (!bootstrapHint) return null;
return {
is_authenticated: true,
email: bootstrapHint.email || '',
full_name: bootstrapHint.full_name || '',
phone_number: bootstrapHint.phone_number || '',
wa_number: bootstrapHint.phone_number || '',
avatar_url: bootstrapHint.avatar_url || '',
shop_provider: null,
provider_requests: [],
};
}, [bootstrapHint, profileQuery.data]);
const orderCounters = orderCountersQuery.data ?? null; const orderCounters = orderCountersQuery.data ?? null;
const isCartLoading =
!isBare &&
hasAuthToken &&
!cart &&
(cartQuery.isPending || cartQuery.isFetching);
const isProfilePending =
!isBare &&
hasAuthToken &&
!profileQuery.data &&
(profileQuery.isPending || profileQuery.isFetching);
const isOrderCountersLoading =
!isBare &&
hasAuthToken &&
!orderCounters &&
(orderCountersQuery.isPending || orderCountersQuery.isFetching);
const isAddressesLoading =
!isBare &&
hasAuthToken &&
!addressesQuery.data &&
(addressesQuery.isPending || addressesQuery.isFetching);
const isShippingMethodsLoading =
!isBare &&
hasAuthToken &&
!shippingMethodsQuery.data &&
(shippingMethodsQuery.isPending || shippingMethodsQuery.isFetching);
const isBookmarksLoading =
!isBare &&
hasAuthToken &&
!bookmarksQuery.data &&
(bookmarksQuery.isPending || bookmarksQuery.isFetching);
const isUserAuthenticated = useMemo(() => { const isUserAuthenticated = useMemo(() => {
if (isBare) return true; if (isBare) return true;
if (profile !== null) { if (profile !== null) {
@ -234,20 +299,8 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
return Boolean(authToken || getToken()); return Boolean(authToken || getToken());
}, [authToken, isBare, profile]); }, [authToken, isBare, profile]);
const hasProfileIdentity = Boolean(
profile?.full_name?.trim() ||
profile?.avatar_url?.trim() ||
profile?.email?.trim() ||
profile?.phone_number?.trim()
);
const isProfileLoading = const isProfileLoading =
!isBare &&
isUserAuthenticated &&
(isAuthProfileSyncing ||
(!hasProfileIdentity &&
homeBootSettled &&
(profileQuery.isPending || profileQuery.isFetching)));
!isBare && isUserAuthenticated && isAuthProfileSyncing;
const addresses = useMemo( const addresses = useMemo(
() => addressesQuery.data?.results ?? [], () => addressesQuery.data?.results ?? [],
@ -358,12 +411,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
}); });
}, [queryClient]); }, [queryClient]);
useEffect(() => {
if (!isBare && hasAuthToken) {
seedProfileFromBridgeHint();
}
}, [hasAuthToken, isBare, seedProfileFromBridgeHint]);
const refreshCart = useCallback(async () => { const refreshCart = useCallback(async () => {
if (!getToken()) { if (!getToken()) {
await queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); await queryClient.invalidateQueries({ queryKey: shopKeys.cart() });
@ -408,7 +455,10 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const refreshAccountData = useCallback(async () => { const refreshAccountData = useCallback(async () => {
if (!getToken()) return; if (!getToken()) return;
seedProfileFromBridgeHint(); seedProfileFromBridgeHint();
setIsAuthProfileSyncing(true);
const shouldShowOverlaySpinner = isInitialBootSettled();
if (shouldShowOverlaySpinner) {
setIsAuthProfileSyncing(true);
}
try { try {
await Promise.allSettled([ await Promise.allSettled([
queryClient queryClient
@ -526,6 +576,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const token = await ensureToken(60000, { forceLogin: true }); const token = await ensureToken(60000, { forceLogin: true });
if (token) { if (token) {
setAuthToken(token); setAuthToken(token);
setIsAuthProfileSyncing(true);
seedProfileFromBridgeHint(); seedProfileFromBridgeHint();
const pendingCallback = loginModalState.onAuthenticated; const pendingCallback = loginModalState.onAuthenticated;
setIsLoggingIn(false); setIsLoggingIn(false);
@ -562,8 +613,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const addToCart = useCallback( const addToCart = useCallback(
async ( async (
productRef: string | number, productRef: string | number,
quantity = 1,
variantId?: number | null
quantity = 1
): Promise<ApiCart | null> => { ): Promise<ApiCart | null> => {
if (!isBare && !isUserAuthenticated) { if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({ const authed = await requireAuth({
@ -576,7 +626,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
const updated = await shopApi.addCartItem({ const updated = await shopApi.addCartItem({
product_id: productRef, product_id: productRef,
quantity, quantity,
variant_id: variantId,
}); });
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
@ -804,20 +853,26 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
cart, cart,
cartItemsCount, cartItemsCount,
cartTotalQuantity, cartTotalQuantity,
isCartLoading,
isCartBusy, isCartBusy,
addresses, addresses,
isAddressesLoading,
selectedAddressId: resolvedSelectedAddressId, selectedAddressId: resolvedSelectedAddressId,
selectedAddress, selectedAddress,
shippingMethods, shippingMethods,
isShippingMethodsLoading,
selectedShippingMethod, selectedShippingMethod,
selectedPaymentMethod, selectedPaymentMethod,
setSelectedPaymentMethod, setSelectedPaymentMethod,
bookmarkedProducts, bookmarkedProducts,
isBookmarksLoading,
isBookmarked, isBookmarked,
toggleBookmark, toggleBookmark,
profile, profile,
isProfileLoading, isProfileLoading,
isProfilePending,
orderCounters, orderCounters,
isOrderCountersLoading,
language, language,
changeLanguage, changeLanguage,
addToCart, addToCart,
@ -842,19 +897,25 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
cart, cart,
cartItemsCount, cartItemsCount,
cartTotalQuantity, cartTotalQuantity,
isCartLoading,
isCartBusy, isCartBusy,
addresses, addresses,
isAddressesLoading,
resolvedSelectedAddressId, resolvedSelectedAddressId,
selectedAddress, selectedAddress,
shippingMethods, shippingMethods,
isShippingMethodsLoading,
selectedShippingMethod, selectedShippingMethod,
selectedPaymentMethod, selectedPaymentMethod,
bookmarkedProducts, bookmarkedProducts,
isBookmarksLoading,
isBookmarked, isBookmarked,
toggleBookmark, toggleBookmark,
profile, profile,
isProfileLoading, isProfileLoading,
isProfilePending,
orderCounters, orderCounters,
isOrderCountersLoading,
language, language,
changeLanguage, changeLanguage,
addToCart, addToCart,

2
src/data/accountData.ts

@ -4,6 +4,7 @@ export interface OrderStatusCounterItem {
label: string; label: string;
labelWidth: number; labelWidth: number;
countText: string; countText: string;
loadingCount?: boolean;
bgColor: string; bgColor: string;
iconSrc: string; iconSrc: string;
} }
@ -15,6 +16,7 @@ export interface AccountMenuRowItem {
titleWidth: number; titleWidth: number;
titleColor: string; titleColor: string;
subtitle?: string; subtitle?: string;
loadingSubtitle?: boolean;
subtitleWidth?: number; subtitleWidth?: number;
iconBoxBg: string; iconBoxBg: string;
iconSrc: string; iconSrc: string;

52
src/data/catalogData.ts

@ -50,6 +50,7 @@ export interface GridProductItem {
export interface CategoryTileItem { export interface CategoryTileItem {
id: string; id: string;
slug?: string;
x: number; x: number;
y: number; y: number;
width: number; width: number;
@ -334,21 +335,48 @@ export const TWO_COLUMN_GRID_PRODUCTS: GridProductItem[] = [
export const CATEGORY_GRID_TILES: CategoryTileItem[] = [ export const CATEGORY_GRID_TILES: CategoryTileItem[] = [
// Row 1 (y = 111) // Row 1 (y = 111)
{ id: 'tile-1', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Bag', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-2', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47, iconSrc: '/assets/images/icon-cat-refrigerator-large.svg', iconLeft: 47, iconWidth: 39, iconHeight: 40 },
{ id: 'tile-1', slug: 'bags', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Bag', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-2', slug: 'home-living', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47, iconSrc: '/assets/images/icon-cat-refrigerator-large.svg', iconLeft: 47, iconWidth: 39, iconHeight: 40 },
// Row 2 (y = 243) // Row 2 (y = 243)
{ id: 'tile-3', x: 16, y: 243, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Beauty', labelRelY: 47, iconSrc: '/assets/images/icon-cat-cosmetic-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-4', x: 194, y: 243, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-3', slug: 'beauty', x: 16, y: 243, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Beauty', labelRelY: 47, iconSrc: '/assets/images/icon-cat-cosmetic-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-4', slug: 'islamic-books', x: 194, y: 243, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
// Row 3 (y = 375) // Row 3 (y = 375)
{ id: 'tile-5', x: 16, y: 375, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Art & Handicrafts', labelRelY: 47, iconSrc: '/assets/images/icon-cat-palette-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-6', x: 194, y: 375, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-5', slug: 'art-handicrafts', x: 16, y: 375, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Art & Handicrafts', labelRelY: 47, iconSrc: '/assets/images/icon-cat-palette-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-6', slug: 'apparel', x: 194, y: 375, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
// Row 4 (y = 507) // Row 4 (y = 507)
{ id: 'tile-7', x: 16, y: 507, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Bag', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-8', x: 194, y: 507, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47, iconSrc: '/assets/images/icon-cat-refrigerator-large.svg', iconLeft: 47, iconWidth: 39, iconHeight: 40 },
{ id: 'tile-7', slug: 'bags', x: 16, y: 507, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Bag', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-8', slug: 'home-living', x: 194, y: 507, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47, iconSrc: '/assets/images/icon-cat-refrigerator-large.svg', iconLeft: 47, iconWidth: 39, iconHeight: 40 },
// Row 5 (y = 639) // Row 5 (y = 639)
{ id: 'tile-9', x: 16, y: 639, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Beauty', labelRelY: 47, iconSrc: '/assets/images/icon-cat-cosmetic-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-10', x: 194, y: 639, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-9', slug: 'beauty', x: 16, y: 639, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Beauty', labelRelY: 47, iconSrc: '/assets/images/icon-cat-cosmetic-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-10', slug: 'home-living', x: 194, y: 639, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
// Row 6 (y = 771) // Row 6 (y = 771)
{ id: 'tile-11', x: 16, y: 771, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Art & Handicrafts', labelRelY: 47, iconSrc: '/assets/images/icon-cat-palette-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-12', x: 194, y: 771, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
{ id: 'tile-11', slug: 'art-handicrafts', x: 16, y: 771, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Art & Handicrafts', labelRelY: 47, iconSrc: '/assets/images/icon-cat-palette-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'tile-12', slug: 'home-living', x: 194, y: 771, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Home & Living', labelRelY: 47.26, iconSrc: '/assets/images/icon-cat-bag-large.svg', iconLeft: 46.37, iconWidth: 40.26, iconHeight: 40.26 },
]; ];
export const MOCK_SUBCATEGORY_TILES: Record<string, CategoryTileItem[]> = {
bags: [
{ id: 'sub-bag-1', slug: 'leather-backpacks', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Backpacks & Daypacks', labelRelY: 47, iconSrc: '/assets/images/icon-cat-backpack-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-bag-2', slug: 'travel-duffels', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Travel & Duffel Bags', labelRelY: 47, iconSrc: '/assets/images/icon-cat-duffel-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
'home-living': [
{ id: 'sub-home-1', slug: 'prayer-essentials', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Prayer Mats & Tasbih', labelRelY: 47, iconSrc: '/assets/images/icon-cat-prayer-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-home-2', slug: 'home-textiles', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Throws & Textiles', labelRelY: 47, iconSrc: '/assets/images/icon-cat-textiles-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
beauty: [
{ id: 'sub-beauty-1', slug: 'attar-perfumes', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Attar & Oud Oils', labelRelY: 47, iconSrc: '/assets/images/icon-cat-attar-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-beauty-2', slug: 'rosewater-care', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Rosewater & Care', labelRelY: 47, iconSrc: '/assets/images/icon-cat-rosewater-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
'art-handicrafts': [
{ id: 'sub-art-1', slug: 'calligraphy-plaques', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Calligraphy & Frames', labelRelY: 47, iconSrc: '/assets/images/icon-cat-calligraphy-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-art-2', slug: 'khatam-woodwork', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Khatam & Woodwork', labelRelY: 47, iconSrc: '/assets/images/icon-cat-khatam-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
'islamic-books': [
{ id: 'sub-book-1', slug: 'theology-scripture', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Theology & Studies', labelRelY: 47, iconSrc: '/assets/images/icon-cat-scripture-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-book-2', slug: 'classical-heritage', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Classical Texts', labelRelY: 47, iconSrc: '/assets/images/icon-cat-heritage-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
apparel: [
{ id: 'sub-apparel-1', slug: 'cotton-tees', x: 16, y: 111, width: 166, isRightCol: false, countBadgeLeft: 135, innerLeft: 16, label: 'Cotton Tees & Tops', labelRelY: 47, iconSrc: '/assets/images/icon-cat-tshirt-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
{ id: 'sub-apparel-2', slug: 'modest-everyday', x: 194, y: 111, width: 165, isRightCol: true, countBadgeLeft: 134, innerLeft: 18, label: 'Modest Everyday Wear', labelRelY: 47, iconSrc: '/assets/images/icon-cat-modest-large.svg', iconLeft: 46.5, iconWidth: 40, iconHeight: 40 },
],
};

65
src/index.css

@ -7,6 +7,7 @@
--safe-left: 0px; --safe-left: 0px;
--safe-right: 0px; --safe-right: 0px;
--kb-height: 0px; --kb-height: 0px;
--kb-offset-top: 0px;
} }
@media (max-width: 359.98px) { @media (max-width: 359.98px) {
@ -427,6 +428,43 @@ a {
animation: habib-dialog-out 180ms cubic-bezier(0.4, 0, 1, 1) forwards; animation: habib-dialog-out 180ms cubic-bezier(0.4, 0, 1, 1) forwards;
} }
/* Keep modals, bottom sheets, and page forms above the virtual keyboard */
html[data-kb-open='true'] .habib-sheet-backdrop {
padding-top: calc(var(--kb-offset-top, 0px) + var(--safe-top, 0px) + 8px);
padding-bottom: var(--kb-height, 0px);
}
html[data-kb-open='true'] .habib-bottom-sheet {
max-height: calc(
100vh - var(--kb-height, 0px) - var(--kb-offset-top, 0px) - var(--safe-top, 0px) - 8px
) !important;
max-height: calc(
100dvh - var(--kb-height, 0px) - var(--kb-offset-top, 0px) - var(--safe-top, 0px) - 8px
) !important;
padding-bottom: 18px !important;
}
html[data-kb-open='true'] .habib-dialog-card {
max-height: calc(
100vh - var(--kb-height, 0px) - var(--kb-offset-top, 0px) - var(--safe-top, 0px) - 24px
);
max-height: calc(
100dvh - var(--kb-height, 0px) - var(--kb-offset-top, 0px) - var(--safe-top, 0px) - 24px
);
overflow-y: auto;
}
html[data-kb-open='true'] .habib-shell-outer:not(.is-chat-route),
html[data-kb-open='true'] .habib-mobile-viewport.is-embed:not(.is-chat-route) {
padding-bottom: var(--kb-height, 0px);
}
html[data-kb-open='true'] nav[aria-label='Bottom Navigation'],
html[data-kb-open='true'] .habib-sticky-bottom-bar {
position: relative !important;
bottom: auto !important;
}
.habib-tab-panel { .habib-tab-panel {
animation: habib-fade-up 200ms cubic-bezier(0.22, 1, 0.36, 1); animation: habib-fade-up 200ms cubic-bezier(0.22, 1, 0.36, 1);
} }
@ -880,33 +918,6 @@ a {
border-top-color: #d78e06; border-top-color: #d78e06;
} }
.habib-mobile-viewport.is-habib-loading {
height: 100vh;
height: 100dvh;
max-height: 100dvh;
overflow: hidden !important;
}
.habib-mobile-viewport.is-habib-loading > :not(.habib-page-shimmer-overlay) {
opacity: 0 !important;
pointer-events: none !important;
user-select: none !important;
}
.habib-page-shimmer-overlay {
position: absolute;
inset: 0;
z-index: 9999;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 100vh;
min-height: 100dvh;
background-color: var(--shell-bg, var(--bg-page));
overflow: hidden;
}
/* Small Phone Refinements (<360px, e.g., 320px iPhone SE) */ /* Small Phone Refinements (<360px, e.g., 320px iPhone SE) */
@media (max-width: 359.98px) { @media (max-width: 359.98px) {
.habib-mobile-viewport:not(.is-embed) .habib-product-grid, .habib-mobile-viewport:not(.is-embed) .habib-product-grid,

14
src/lib/cookies.ts

@ -213,6 +213,7 @@ const FA_DICTIONARY: Record<string, string> = {
'تخفیف‌های ویژه روی محصولات اصیل و دست‌ساز', 'تخفیف‌های ویژه روی محصولات اصیل و دست‌ساز',
'Explore Now': 'مشاهده کنید', 'Explore Now': 'مشاهده کنید',
Populars: 'محبوب‌ترین‌ها', Populars: 'محبوب‌ترین‌ها',
'New Products': 'محصولات جدید',
'See All': 'مشاهده همه', 'See All': 'مشاهده همه',
'View All': 'مشاهده همه', 'View All': 'مشاهده همه',
'See more': 'مشاهده بیشتر', 'See more': 'مشاهده بیشتر',
@ -230,6 +231,7 @@ const FA_DICTIONARY: Record<string, string> = {
'No categories available yet.': 'هنوز دسته‌بندی‌ای موجود نیست.', 'No categories available yet.': 'هنوز دسته‌بندی‌ای موجود نیست.',
'No popular products yet.': 'هنوز محصول محبوبی ثبت نشده است.', 'No popular products yet.': 'هنوز محصول محبوبی ثبت نشده است.',
'No new store products yet.': 'هنوز محصولی در فروشگاه‌های جدید ثبت نشده است.', 'No new store products yet.': 'هنوز محصولی در فروشگاه‌های جدید ثبت نشده است.',
'No products in this collection yet.': 'هنوز محصولی در این مجموعه ثبت نشده است.',
'No products found in this category.': 'محصولی در این دسته‌بندی یافت نشد.', 'No products found in this category.': 'محصولی در این دسته‌بندی یافت نشد.',
'No products available in this booth yet.': 'هنوز محصولی در این غرفه موجود نیست.', 'No products available in this booth yet.': 'هنوز محصولی در این غرفه موجود نیست.',
'Islam in the Biblebran Transfer Book': 'کتاب انتقال اسلام در کتاب مقدس', 'Islam in the Biblebran Transfer Book': 'کتاب انتقال اسلام در کتاب مقدس',
@ -439,6 +441,11 @@ const FA_DICTIONARY: Record<string, string> = {
'About us': 'درباره ما', 'About us': 'درباره ما',
Notifications: 'اعلان‌ها', Notifications: 'اعلان‌ها',
Notes: 'یادداشت‌ها', Notes: 'یادداشت‌ها',
'No notes yet': 'هنوز یادداشتی ثبت نشده است',
'Write a note...': 'یادداشت خود را بنویسید...',
'Add Note': 'افزودن یادداشت',
'Note saved': 'یادداشت ذخیره شد',
'Note removed': 'یادداشت حذف شد',
'Program Access and Permissions': 'دسترسی‌ها و مجوزهای برنامه', 'Program Access and Permissions': 'دسترسی‌ها و مجوزهای برنامه',
'Azan Setting': 'تنظیمات اذان', 'Azan Setting': 'تنظیمات اذان',
Location: 'موقعیت مکانی', Location: 'موقعیت مکانی',
@ -772,6 +779,7 @@ const AR_DICTIONARY: Record<string, string> = {
'خصومات حصرية على المنتجات اليدوية الأصيلة', 'خصومات حصرية على المنتجات اليدوية الأصيلة',
'Explore Now': 'استكشف الآن', 'Explore Now': 'استكشف الآن',
Populars: 'الأكثر شعبية', Populars: 'الأكثر شعبية',
'New Products': 'منتجات جديدة',
'See All': 'عرض الكل', 'See All': 'عرض الكل',
'View All': 'عرض الكل', 'View All': 'عرض الكل',
'See more': 'عرض المزيد', 'See more': 'عرض المزيد',
@ -789,6 +797,7 @@ const AR_DICTIONARY: Record<string, string> = {
'No categories available yet.': 'لا توجد فئات متاحة بعد.', 'No categories available yet.': 'لا توجد فئات متاحة بعد.',
'No popular products yet.': 'لا توجد منتجات شائعة بعد.', 'No popular products yet.': 'لا توجد منتجات شائعة بعد.',
'No new store products yet.': 'لا توجد منتجات متاجر جديدة بعد.', 'No new store products yet.': 'لا توجد منتجات متاجر جديدة بعد.',
'No products in this collection yet.': 'لا توجد منتجات في هذه المجموعة بعد.',
'No products found in this category.': 'لم يتم العثور على منتجات في هذه الفئة.', 'No products found in this category.': 'لم يتم العثور على منتجات في هذه الفئة.',
'No products available in this booth yet.': 'لا توجد منتجات متاحة في هذا المتجر بعد.', 'No products available in this booth yet.': 'لا توجد منتجات متاحة في هذا المتجر بعد.',
'Islam in the Biblebran Transfer Book': 'كتاب الإسلام في الكتاب المقدس', 'Islam in the Biblebran Transfer Book': 'كتاب الإسلام في الكتاب المقدس',
@ -995,6 +1004,11 @@ const AR_DICTIONARY: Record<string, string> = {
'About us': 'من نحن', 'About us': 'من نحن',
Notifications: 'الإشعارات', Notifications: 'الإشعارات',
Notes: 'الملاحظات', Notes: 'الملاحظات',
'No notes yet': 'لا توجد ملاحظات بعد',
'Write a note...': 'اكتب ملاحظة...',
'Add Note': 'إضافة ملاحظة',
'Note saved': 'تم حفظ الملاحظة',
'Note removed': 'تم حذف الملاحظة',
'Program Access and Permissions': 'صلاحيات وأذونات البرنامج', 'Program Access and Permissions': 'صلاحيات وأذونات البرنامج',
'Azan Setting': 'إعدادات الأذان', 'Azan Setting': 'إعدادات الأذان',
Location: 'الموقع', Location: 'الموقع',

4
src/lib/mappers.ts

@ -111,9 +111,7 @@ export function mapCartItemToCard(item: ApiCartItem, index: number): CartItemDat
imageSrc: imageSrc:
resolveMediaUrl(item.image_url) || resolveMediaUrl(item.image_url) ||
'/assets/images/product-brown-leather-bag.png', '/assets/images/product-brown-leather-bag.png',
title: item.variant_title
? `${item.title} (${item.variant_title})`
: item.title,
title: item.title,
titleHeight: item.title.length > 24 ? 28 : 17, titleHeight: item.title.length > 24 ? 28 : 17,
titleLineHeight: item.title.length > 24 ? 14 : 17, titleLineHeight: item.title.length > 24 ? 14 : 17,
originRelY: item.title.length > 24 ? 34 : 19, originRelY: item.title.length > 24 ? 34 : 19,

2
src/lib/routes.ts

@ -2,6 +2,7 @@ export const ROUTES = {
home: '/', home: '/',
categories: '/categories', categories: '/categories',
category: (slug: string = 'home-living') => `/categories/${encodeURIComponent(slug)}`, category: (slug: string = 'home-living') => `/categories/${encodeURIComponent(slug)}`,
collection: (slug: string = 'popular') => `/collections/${encodeURIComponent(slug)}`,
search: (query?: string) => search: (query?: string) =>
query && query.trim() query && query.trim()
? `/search?q=${encodeURIComponent(query.trim())}` ? `/search?q=${encodeURIComponent(query.trim())}`
@ -28,6 +29,7 @@ export const ROUTES = {
support: '/support', support: '/support',
account: '/account', account: '/account',
bookmarks: '/account/bookmarks', bookmarks: '/account/bookmarks',
notes: '/account/notes',
addresses: '/account/addresses', addresses: '/account/addresses',
profile: '/account/profile', profile: '/account/profile',
settings: '/account/settings', settings: '/account/settings',

141
src/lib/shopApi.ts

@ -14,28 +14,38 @@ export interface ApiBanner {
export interface ApiCategory { export interface ApiCategory {
id: number; id: number;
parent: number | null; parent: number | null;
parent_slug?: string | null;
slug: string; slug: string;
title: string; title: string;
localized_title: string; localized_title: string;
icon_url: string; icon_url: string;
small_icon_url: string; small_icon_url: string;
accent_color: string;
display_order: number; display_order: number;
is_quick: boolean; is_quick: boolean;
products_count: number; products_count: number;
children_count?: number;
}
export interface ApiCollection {
id: number;
slug: string;
title: string;
localized_title: string;
display_order: number;
is_active?: boolean;
products_count: number;
products?: ApiProductCard[];
} }
export interface ApiStoreSummary { export interface ApiStoreSummary {
id: number; id: number;
slug: string; slug: string;
name: string; name: string;
tagline: string;
country: string; country: string;
city: string; city: string;
currency: string;
origin_label: string; origin_label: string;
logo_url: string; logo_url: string;
banner_url: string;
badge: string;
membership_label: string; membership_label: string;
sales_label: string; sales_label: string;
since_label: string; since_label: string;
@ -57,7 +67,6 @@ export interface ApiProductCard {
hero_image_url: string; hero_image_url: string;
price: string; price: string;
formatted_price: string; formatted_price: string;
compare_at_price: string | null;
formatted_old_price: string | null; formatted_old_price: string | null;
discount_badge: string; discount_badge: string;
currency: string; currency: string;
@ -71,8 +80,7 @@ export interface ApiProductCard {
category: number; category: number;
category_slug: string; category_slug: string;
category_title: string; category_title: string;
is_popular: boolean;
is_new_store_pick: boolean;
collection_slugs?: string[];
is_bookmarked: boolean; is_bookmarked: boolean;
} }
@ -83,16 +91,6 @@ export interface ApiProductMedia {
sort_order: number; sort_order: number;
} }
export interface ApiProductVariant {
id: number;
sku: string;
title: string;
attributes_json: Record<string, string>;
price_override: string | null;
stock_qty: number;
is_active: boolean;
}
export interface ApiReview { export interface ApiReview {
id: number; id: number;
product: number; product: number;
@ -110,11 +108,8 @@ export interface ApiProductDetail extends ApiProductCard {
condition_label: string; condition_label: string;
processing_time_label: string; processing_time_label: string;
product_type_label: string; product_type_label: string;
specs_json: Record<string, string>;
shipping_info_json: Record<string, string>;
store_detail: ApiStoreSummary; store_detail: ApiStoreSummary;
media: ApiProductMedia[]; media: ApiProductMedia[];
variants: ApiProductVariant[];
reviews: ApiReview[]; reviews: ApiReview[];
related_products: ApiProductCard[]; related_products: ApiProductCard[];
} }
@ -135,8 +130,6 @@ export interface ApiCartItem {
store_id: number; store_id: number;
store_slug: string; store_slug: string;
store_name: string; store_name: string;
variant: number | null;
variant_title: string;
quantity: number; quantity: number;
unit_price: string; unit_price: string;
formatted_unit_price: string; formatted_unit_price: string;
@ -365,9 +358,7 @@ export interface HomeFeedResponse {
banners: ApiBanner[]; banners: ApiBanner[];
quick_categories: ApiCategory[]; quick_categories: ApiCategory[];
categories: ApiCategory[]; categories: ApiCategory[];
popular_products: ApiProductCard[];
new_store_products: ApiProductCard[];
featured_stores: ApiStoreSummary[];
collections: ApiCollection[];
cart_items_count: number; cart_items_count: number;
} }
@ -375,21 +366,61 @@ export const shopApi = {
// Home & Catalog // Home & Catalog
fetchHomeFeed: () => shopRequest<HomeFeedResponse>('/home/'), fetchHomeFeed: () => shopRequest<HomeFeedResponse>('/home/'),
fetchCategories: (q?: string) =>
shopRequest<{ results: ApiCategory[] }>('/categories/', { query: { q } }),
fetchCategories: (q?: string, parent?: string) =>
shopRequest<{ results: ApiCategory[] }>('/categories/', {
query: { q, parent },
}),
fetchCategoryDetail: (slug: string, q?: string) => fetchCategoryDetail: (slug: string, q?: string) =>
shopRequest<{ category: ApiCategory; products: ApiProductCard[] }>(
`/categories/${encodeURIComponent(slug)}/`,
shopRequest<{
category: ApiCategory;
children?: ApiCategory[];
products: ApiProductCard[];
}>(`/categories/${encodeURIComponent(slug)}/`, { query: { q } }),
fetchCollections: (q?: string) =>
shopRequest<{ results: ApiCollection[] }>('/collections/', { query: { q } }),
fetchCollectionDetail: (slug: string, q?: string) =>
shopRequest<{ collection: ApiCollection; products: ApiProductCard[] }>(
`/collections/${encodeURIComponent(slug)}/`,
{ query: { q } } { query: { q } }
), ),
createCollection: (payload: {
slug: string;
title: string | { language_code: string; title: string }[];
display_order?: number;
is_active?: boolean;
product_ids?: (string | number)[];
}) =>
shopRequest<ApiCollection>('/collections/', { method: 'POST', body: payload }),
updateCollection: (
slug: string,
payload: Partial<{
slug: string;
title: string | { language_code: string; title: string }[];
display_order: number;
is_active: boolean;
product_ids: (string | number)[];
}>
) =>
shopRequest<ApiCollection>(`/collections/${encodeURIComponent(slug)}/`, {
method: 'PATCH',
body: payload,
}),
deleteCollection: (slug: string) =>
shopRequest<void>(`/collections/${encodeURIComponent(slug)}/`, {
method: 'DELETE',
}),
fetchProducts: (params?: { fetchProducts: (params?: {
q?: string; q?: string;
category?: string; category?: string;
collection?: string;
store?: string; store?: string;
popular?: boolean;
new_store?: boolean;
sort?: 'price_asc' | 'price_desc' | 'rating' | 'newest'; sort?: 'price_asc' | 'price_desc' | 'rating' | 'newest';
}) => }) =>
shopRequest<{ count: number; results: ApiProductCard[] }>('/products/', { shopRequest<{ count: number; results: ApiProductCard[] }>('/products/', {
@ -431,7 +462,6 @@ export const shopApi = {
addCartItem: (payload: { addCartItem: (payload: {
product_id: string | number; product_id: string | number;
variant_id?: number | null;
quantity?: number; quantity?: number;
}) => shopRequest<ApiCart>('/cart/items/', { method: 'POST', body: payload }), }) => shopRequest<ApiCart>('/cart/items/', { method: 'POST', body: payload }),
@ -567,7 +597,13 @@ export const shopApi = {
{ method: 'DELETE' } { method: 'DELETE' }
), ),
applyAsProvider: (payload: { store_name: string; description?: string }) =>
applyAsProvider: (payload: {
store_name: string;
description?: string;
country?: string;
city?: string;
currency?: string;
}) =>
shopRequest<{ shopRequest<{
id?: number; id?: number;
service: string; service: string;
@ -589,12 +625,25 @@ export const shopApi = {
subject?: string | number; subject?: string | number;
subject_label?: string; subject_label?: string;
description: string; description: string;
attachment?: File;
attachment_url?: string; attachment_url?: string;
}) =>
shopRequest<ApiSupportTicket>('/support/tickets/', {
}) => {
let body: BodyInit | Record<string, unknown> = payload;
if (payload.attachment) {
const form = new FormData();
form.append('description', payload.description);
form.append('attachment', payload.attachment);
if (payload.order_number !== undefined) form.append('order_number', String(payload.order_number));
if (payload.product_id !== undefined) form.append('product_id', String(payload.product_id));
if (payload.subject !== undefined) form.append('subject', String(payload.subject));
if (payload.subject_label !== undefined) form.append('subject_label', payload.subject_label);
body = form;
}
return shopRequest<ApiSupportTicket>('/support/tickets/', {
method: 'POST', method: 'POST',
body: payload,
}),
body,
});
},
fetchChatConversations: () => fetchChatConversations: () =>
shopRequest<{ count: number; results: ApiConversation[] }>('/chat/conversations/'), shopRequest<{ count: number; results: ApiConversation[] }>('/chat/conversations/'),
@ -613,14 +662,22 @@ export const shopApi = {
sendChatMessage: ( sendChatMessage: (
pkOrSlug: string | number, pkOrSlug: string | number,
payload: { text?: string; attachment_url?: string }
) =>
shopRequest<{
payload: { text?: string; attachment?: File; attachment_url?: string }
) => {
let body: BodyInit | Record<string, unknown> = payload;
if (payload.attachment) {
const form = new FormData();
if (payload.text) form.append('text', payload.text);
form.append('attachment', payload.attachment);
body = form;
}
return shopRequest<{
conversation: ApiConversation; conversation: ApiConversation;
message: ApiChatMessage; message: ApiChatMessage;
new_messages: ApiChatMessage[]; new_messages: ApiChatMessage[];
}>( }>(
`/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`, `/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`,
{ method: 'POST', body: payload }
),
{ method: 'POST', body }
);
},
}; };

60
src/lib/shopQueries.ts

@ -5,9 +5,11 @@ import {
useQueryClient, useQueryClient,
} from '@tanstack/react-query'; } from '@tanstack/react-query';
import { import {
type ApiCategory,
type ApiChatMessage, type ApiChatMessage,
type ApiConversation, type ApiConversation,
type ApiOrderDetail, type ApiOrderDetail,
type ApiProductCard,
type ApiProductDetail, type ApiProductDetail,
type ApiUserProfile, type ApiUserProfile,
shopApi, shopApi,
@ -36,6 +38,11 @@ export const shopKeys = {
categoryDetailsAll: () => ['shop', 'category'] as const, categoryDetailsAll: () => ['shop', 'category'] as const,
categoryDetail: (slug: string, q?: string) => categoryDetail: (slug: string, q?: string) =>
['shop', 'category', slug, q ?? ''] as const, ['shop', 'category', slug, q ?? ''] as const,
collectionsAll: () => ['shop', 'collections'] as const,
collections: (q?: string) => ['shop', 'collections', q ?? ''] as const,
collectionDetailsAll: () => ['shop', 'collection'] as const,
collectionDetail: (slug: string, q?: string) =>
['shop', 'collection', slug, q ?? ''] as const,
productsAll: () => ['shop', 'products'] as const, productsAll: () => ['shop', 'products'] as const,
products: (params?: ProductsQueryParams) => products: (params?: ProductsQueryParams) =>
['shop', 'products', params ?? {}] as const, ['shop', 'products', params ?? {}] as const,
@ -69,6 +76,37 @@ export const shopKeys = {
['shop', 'chat-messages', String(pkOrSlug)] as const, ['shop', 'chat-messages', String(pkOrSlug)] as const,
}; };
export function findCachedCategoryBySlug(
queryClient: QueryClient,
slug?: string
): ApiCategory | null {
if (!slug) return null;
const detailEntries = queryClient.getQueriesData<{
category?: ApiCategory;
children?: ApiCategory[];
products?: ApiProductCard[];
}>({ queryKey: shopKeys.categoryDetailsAll() });
for (const [, data] of detailEntries) {
if (data?.category?.slug === slug) return data.category;
const childMatch = data?.children?.find((c) => c.slug === slug);
if (childMatch) return childMatch;
}
const listEntries = queryClient.getQueriesData<{ results?: ApiCategory[] }>({
queryKey: shopKeys.categoriesAll(),
});
for (const [, data] of listEntries) {
const match = data?.results?.find((c) => c.slug === slug);
if (match) return match;
}
const homeData = queryClient.getQueryData<{ categories?: ApiCategory[] }>(
shopKeys.home()
);
return homeData?.categories?.find((c) => c.slug === slug) ?? null;
}
export function clearUserScopedCache(queryClient: QueryClient): void { export function clearUserScopedCache(queryClient: QueryClient): void {
queryClient.removeQueries({ queryKey: shopKeys.ordersAll() }); queryClient.removeQueries({ queryKey: shopKeys.ordersAll() });
queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() }); queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() });
@ -106,6 +144,26 @@ export function useCategoryDetailQuery(
}); });
} }
export function useCollectionsQuery(enabled = true, q?: string) {
return useQuery({
queryKey: shopKeys.collections(q),
queryFn: () => shopApi.fetchCollections(q),
enabled,
});
}
export function useCollectionDetailQuery(
slug: string,
enabled = true,
q?: string
) {
return useQuery({
queryKey: shopKeys.collectionDetail(slug, q),
queryFn: () => shopApi.fetchCollectionDetail(slug, q),
enabled: enabled && Boolean(slug),
});
}
export function useProductsQuery(params?: ProductsQueryParams, enabled = true) { export function useProductsQuery(params?: ProductsQueryParams, enabled = true) {
return useQuery({ return useQuery({
queryKey: shopKeys.products(params), queryKey: shopKeys.products(params),
@ -336,7 +394,7 @@ export function useApplyProviderMutation() {
export function useSendChatMessageMutation(resolvedConvRef: string | number) { export function useSendChatMessageMutation(resolvedConvRef: string | number) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (payload: { text?: string; attachment_url?: string }) =>
mutationFn: (payload: Parameters<typeof shopApi.sendChatMessage>[1]) =>
shopApi.sendChatMessage(resolvedConvRef, payload), shopApi.sendChatMessage(resolvedConvRef, payload),
onSuccess: (res) => { onSuccess: (res) => {
const incomingBatch = const incomingBatch =

337
src/lib/view-paddings.ts

@ -1,7 +1,47 @@
import type { FlutterResponsePayload } from '../types/window'; import type { FlutterResponsePayload } from '../types/window';
import { postActionToFlutter, isInFlutterWebView } from './webview-actions'; import { postActionToFlutter, isInFlutterWebView } from './webview-actions';
export interface KeyboardViewportInput {
innerHeight: number;
baselineInnerHeight: number;
flutterKbHeight: number;
vvHeight?: number;
vvOffsetTop?: number;
virtualKeyboardHeight?: number;
}
export interface KeyboardMetrics {
bottomInset: number;
topOffset: number;
kbOpen: boolean;
}
const NON_TEXT_INPUT_TYPES = new Set([
'button',
'checkbox',
'color',
'file',
'hidden',
'image',
'radio',
'range',
'reset',
'submit',
]);
const FOCUS_TOP_MARGIN_PX = 16;
const FOCUS_BOTTOM_MARGIN_PX = 22;
let lastFlutterKbHeight = 0; let lastFlutterKbHeight = 0;
let baselineInnerHeight = 0;
let baselineInnerWidth = 0;
let currentMetrics: KeyboardMetrics = {
bottomInset: 0,
topOffset: 0,
kbOpen: false,
};
let lastEmittedHeight = -1;
let lastEmittedVisible: boolean | null = null;
function toSafeAreaPx(rawPx: unknown, devicePixelRatio: number): number { function toSafeAreaPx(rawPx: unknown, devicePixelRatio: number): number {
const num = Number(rawPx); const num = Number(rawPx);
@ -18,17 +58,203 @@ function toKeyboardPx(rawPx: unknown): number {
return Math.round(num); return Math.round(num);
} }
function setKbHeightCssVar(kbPx: number): void {
if (typeof document === 'undefined') return;
const clamped = Math.max(0, Math.round(kbPx));
document.documentElement.style.setProperty('--kb-height', `${clamped}px`);
if (typeof window !== 'undefined') {
export function computeKeyboardMetrics(input: KeyboardViewportInput): KeyboardMetrics {
const innerH = Math.max(0, Math.round(input.innerHeight));
const baseH = Math.max(innerH, Math.round(input.baselineInnerHeight));
// Subtract any layout-viewport shrink so resizes-content + Flutter bridge never double-counts.
const layoutShrink = Math.max(0, baseH - innerH);
const flutterOverlayKb = Math.max(0, Math.round(input.flutterKbHeight) - layoutShrink);
const hasVv = typeof input.vvHeight === 'number' && Number.isFinite(input.vvHeight);
const rawVvDiff = hasVv ? Math.max(0, Math.round(innerH - (input.vvHeight as number))) : 0;
const hasVvKb = rawVvDiff > 80;
const vvTop = hasVvKb ? Math.max(0, Math.round(input.vvOffsetTop ?? 0)) : 0;
const vvBottomInset = hasVvKb
? Math.max(0, Math.round(innerH - (input.vvHeight as number) - (input.vvOffsetTop ?? 0)))
: 0;
const vkOverlay = Math.max(0, Math.round(input.virtualKeyboardHeight ?? 0));
const bottomInset = Math.max(flutterOverlayKb, vvBottomInset, vkOverlay);
const kbOpen =
input.flutterKbHeight > 0 || hasVvKb || vkOverlay > 0 || layoutShrink > 80;
return {
bottomInset,
topOffset: vvTop,
kbOpen,
};
}
export function computeFocusScrollDelta(
elTop: number,
elBottom: number,
bandTop: number,
bandBottom: number
): number {
if (bandBottom <= bandTop) return 0;
const elHeight = elBottom - elTop;
const availHeight = bandBottom - bandTop;
if (elHeight <= availHeight) {
if (elBottom > bandBottom) return elBottom - bandBottom;
if (elTop < bandTop) return elTop - bandTop;
return 0;
}
// Taller than visible band: bring into band without oscillating on repeated checks.
if (elTop < bandTop && elBottom < bandBottom) {
return Math.max(elTop - bandTop, elBottom - bandBottom);
}
if (elTop > bandTop) {
return Math.min(elTop - bandTop, elBottom - bandBottom);
}
return 0;
}
function isTextEntryElement(el: Element | null): el is HTMLElement {
if (!(el instanceof HTMLElement)) return false;
if (el instanceof HTMLTextAreaElement) {
return !el.disabled && !el.readOnly;
}
if (el instanceof HTMLInputElement) {
const type = (el.type || 'text').toLowerCase();
return !el.disabled && !el.readOnly && !NON_TEXT_INPUT_TYPES.has(type);
}
return el.isContentEditable;
}
type ScrollTarget =
| { kind: 'element'; el: HTMLElement }
| { kind: 'window' }
| { kind: 'none' };
function findScrollTarget(el: HTMLElement): ScrollTarget {
let cur: HTMLElement | null = el.parentElement;
while (cur && cur !== document.body && cur !== document.documentElement) {
const style = window.getComputedStyle(cur);
const overflowY = style.overflowY;
if (
(overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') &&
cur.scrollHeight > cur.clientHeight + 1
) {
return { kind: 'element', el: cur };
}
if (style.position === 'fixed') {
return { kind: 'none' };
}
cur = cur.parentElement;
}
return { kind: 'window' };
}
function getVirtualKeyboardHeight(): number {
if (typeof navigator === 'undefined') return 0;
const vk = (navigator as Navigator & {
virtualKeyboard?: { boundingRect?: DOMRectReadOnly };
}).virtualKeyboard;
return toKeyboardPx(vk?.boundingRect?.height);
}
function refreshBaselineViewport(): void {
if (typeof window === 'undefined') return;
const innerW = window.innerWidth;
const innerH = window.innerHeight;
const vv = window.visualViewport;
const rawVvDiff = vv ? innerH - vv.height : 0;
if (baselineInnerWidth === 0 || Math.abs(innerW - baselineInnerWidth) > 40) {
baselineInnerWidth = innerW;
baselineInnerHeight = innerH;
return;
}
if (innerH > baselineInnerHeight || (lastFlutterKbHeight === 0 && rawVvDiff <= 80)) {
baselineInnerHeight = Math.max(baselineInnerHeight, innerH);
}
}
function syncKeyboardMetrics(): boolean {
if (typeof window === 'undefined' || typeof document === 'undefined') return false;
refreshBaselineViewport();
const vv = window.visualViewport;
const next = computeKeyboardMetrics({
innerHeight: window.innerHeight,
baselineInnerHeight,
flutterKbHeight: lastFlutterKbHeight,
vvHeight: vv?.height,
vvOffsetTop: vv?.offsetTop,
virtualKeyboardHeight: getVirtualKeyboardHeight(),
});
currentMetrics = next;
const root = document.documentElement;
root.style.setProperty('--kb-height', `${next.bottomInset}px`);
root.style.setProperty('--kb-offset-top', `${next.topOffset}px`);
if (next.kbOpen) {
root.dataset.kbOpen = 'true';
} else {
delete root.dataset.kbOpen;
}
const changed =
next.bottomInset !== lastEmittedHeight || next.kbOpen !== lastEmittedVisible;
if (changed) {
lastEmittedHeight = next.bottomInset;
lastEmittedVisible = next.kbOpen;
window.dispatchEvent( window.dispatchEvent(
new CustomEvent('habib:keyboard-changed', { new CustomEvent('habib:keyboard-changed', {
detail: { height: clamped, visible: clamped > 0 },
detail: { height: next.bottomInset, visible: next.kbOpen },
}) })
); );
} }
return changed;
}
function ensureFocusedInputVisible(smooth: boolean): void {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
if (!currentMetrics.kbOpen) return;
const active = document.activeElement;
if (!isTextEntryElement(active)) return;
if (active.closest('[data-testid="chat-bottom-input-bar"]')) return;
const root = document.documentElement;
const safeTop = parseFloat(root.style.getPropertyValue('--safe-top')) || 0;
const visibleTop = currentMetrics.topOffset + safeTop;
const visibleBottom = Math.max(visibleTop, window.innerHeight - currentMetrics.bottomInset);
const elRect = active.getBoundingClientRect();
if (elRect.width === 0 && elRect.height === 0) return;
const target = findScrollTarget(active);
if (target.kind === 'none') return;
if (target.kind === 'element') {
const scrollerRect = target.el.getBoundingClientRect();
const bandTop = Math.max(visibleTop, scrollerRect.top) + FOCUS_TOP_MARGIN_PX;
const bandBottom = Math.min(visibleBottom, scrollerRect.bottom) - FOCUS_BOTTOM_MARGIN_PX;
const delta = computeFocusScrollDelta(elRect.top, elRect.bottom, bandTop, bandBottom);
if (Math.abs(delta) < 1) return;
if (smooth && typeof target.el.scrollBy === 'function') {
target.el.scrollBy({ top: delta, behavior: 'smooth' });
} else {
target.el.scrollTop += delta;
}
return;
}
const bandTop = visibleTop + FOCUS_TOP_MARGIN_PX;
const bandBottom = visibleBottom - FOCUS_BOTTOM_MARGIN_PX;
const delta = computeFocusScrollDelta(elRect.top, elRect.bottom, bandTop, bandBottom);
if (Math.abs(delta) < 1) return;
if (smooth) {
window.scrollBy({ top: delta, behavior: 'smooth' });
} else {
window.scrollBy(0, delta);
}
} }
function applySafeCssVars(action: string | undefined, data: Record<string, unknown>): void { function applySafeCssVars(action: string | undefined, data: Record<string, unknown>): void {
@ -38,9 +264,9 @@ function applySafeCssVars(action: string | undefined, data: Record<string, unkno
if (action === 'keyboard_changed') { if (action === 'keyboard_changed') {
const visible = data.visible !== false; const visible = data.visible !== false;
const rawKb = visible ? (data.height ?? data.keyboardHeight ?? 0) : 0;
const rawKb = visible ? (data.height ?? data.keyboardHeight ?? data.bottom ?? 0) : 0;
lastFlutterKbHeight = toKeyboardPx(rawKb); lastFlutterKbHeight = toKeyboardPx(rawKb);
setKbHeightCssVar(lastFlutterKbHeight);
syncKeyboardMetrics();
return; return;
} }
@ -70,7 +296,7 @@ function applySafeCssVars(action: string | undefined, data: Record<string, unkno
if (rawKb !== undefined) { if (rawKb !== undefined) {
lastFlutterKbHeight = toKeyboardPx(rawKb); lastFlutterKbHeight = toKeyboardPx(rawKb);
setKbHeightCssVar(lastFlutterKbHeight);
syncKeyboardMetrics();
} }
} }
@ -79,18 +305,57 @@ export function initFlutterViewPaddings(): () => void {
return () => {}; return () => {};
} }
refreshBaselineViewport();
let rafId: number | null = null;
let settleTimerId: number | null = null;
const clearPendingTimers = () => {
if (rafId !== null) {
window.cancelAnimationFrame(rafId);
rafId = null;
}
if (settleTimerId !== null) {
window.clearTimeout(settleTimerId);
settleTimerId = null;
}
};
const scheduleFocusReveal = (smooth: boolean, settleDelayMs: number) => {
if (rafId !== null) window.cancelAnimationFrame(rafId);
rafId = window.requestAnimationFrame(() => {
rafId = null;
ensureFocusedInputVisible(smooth);
});
if (settleTimerId !== null) window.clearTimeout(settleTimerId);
settleTimerId = window.setTimeout(() => {
settleTimerId = null;
ensureFocusedInputVisible(false);
}, settleDelayMs);
};
const handlePayload = (payload: FlutterResponsePayload) => { const handlePayload = (payload: FlutterResponsePayload) => {
if (!payload || typeof payload !== 'object') return; if (!payload || typeof payload !== 'object') return;
const action = payload.action;
const data = (payload.data || payload) as Record<string, unknown>;
const rawAction = payload.action ?? payload.type;
const action = typeof rawAction === 'string' ? rawAction.toLowerCase() : '';
const data = (payload.data || payload.payload || payload) as Record<string, unknown>;
if ( if (
action === 'initial_config' || action === 'initial_config' ||
action === 'initialconfig' ||
action === 'get_view_paddings' || action === 'get_view_paddings' ||
action === 'view_paddings_changed' || action === 'view_paddings_changed' ||
action === 'safe_area_changed' || action === 'safe_area_changed' ||
action === 'keyboard_changed' action === 'keyboard_changed'
) { ) {
applySafeCssVars(action, data); applySafeCssVars(action, data);
if (currentMetrics.kbOpen) {
scheduleFocusReveal(false, 90);
}
} else if (action === 'orientation_changed') {
baselineInnerWidth = 0;
syncKeyboardMetrics();
if (currentMetrics.kbOpen) {
scheduleFocusReveal(false, 120);
}
} }
}; };
@ -101,32 +366,62 @@ export function initFlutterViewPaddings(): () => void {
if (window.__HABIB_BOOTSTRAP__ && typeof window.__HABIB_BOOTSTRAP__ === 'object') { if (window.__HABIB_BOOTSTRAP__ && typeof window.__HABIB_BOOTSTRAP__ === 'object') {
applySafeCssVars('initial_config', window.__HABIB_BOOTSTRAP__); applySafeCssVars('initial_config', window.__HABIB_BOOTSTRAP__);
} else {
syncKeyboardMetrics();
} }
const vv = window.visualViewport; const vv = window.visualViewport;
const handleVisualViewport = () => {
if (!vv) return;
const vvDiff = Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop));
const visualKb = vvDiff > 80 ? vvDiff : 0;
const effectiveKb = Math.max(lastFlutterKbHeight, visualKb);
setKbHeightCssVar(effectiveKb);
const handleViewportChange = () => {
syncKeyboardMetrics();
if (currentMetrics.kbOpen) {
scheduleFocusReveal(false, 90);
}
};
const handleFocusIn = (event: FocusEvent) => {
if (!isTextEntryElement(event.target instanceof Element ? event.target : null)) return;
syncKeyboardMetrics();
scheduleFocusReveal(true, 300);
};
const handleFocusOut = () => {
window.setTimeout(() => {
if (!isTextEntryElement(document.activeElement)) {
clearPendingTimers();
}
}, 0);
};
const handleInput = (event: Event) => {
if (!currentMetrics.kbOpen) return;
if (!isTextEntryElement(event.target instanceof Element ? event.target : null)) return;
ensureFocusedInputVisible(false);
}; };
if (vv) { if (vv) {
vv.addEventListener('resize', handleVisualViewport);
vv.addEventListener('scroll', handleVisualViewport);
vv.addEventListener('resize', handleViewportChange);
vv.addEventListener('scroll', handleViewportChange);
} }
window.addEventListener('resize', handleViewportChange);
document.addEventListener('focusin', handleFocusIn, true);
document.addEventListener('focusout', handleFocusOut, true);
document.addEventListener('input', handleInput, true);
if (isInFlutterWebView()) { if (isInFlutterWebView()) {
postActionToFlutter('get_view_paddings'); postActionToFlutter('get_view_paddings');
} }
return () => { return () => {
clearPendingTimers();
unsubscribe(); unsubscribe();
if (vv) { if (vv) {
vv.removeEventListener('resize', handleVisualViewport);
vv.removeEventListener('scroll', handleVisualViewport);
vv.removeEventListener('resize', handleViewportChange);
vv.removeEventListener('scroll', handleViewportChange);
} }
window.removeEventListener('resize', handleViewportChange);
document.removeEventListener('focusin', handleFocusIn, true);
document.removeEventListener('focusout', handleFocusOut, true);
document.removeEventListener('input', handleInput, true);
}; };
} }

84
src/lib/webview-actions.ts

@ -248,9 +248,16 @@ function dataUrlToBlob(dataUrl: string): Blob | null {
} }
} }
export async function uploadFileViaFlutterBridge(
export interface PickedBridgeAttachment {
url: string;
file?: File;
name?: string;
isObjectUrl?: boolean;
}
export async function pickFileViaFlutterBridge(
mediaType: 'image' | 'video' | 'image+video' | 'audio' | 'file' = 'image' mediaType: 'image' | 'video' | 'image+video' | 'audio' | 'file' = 'image'
): Promise<string | null> {
): Promise<PickedBridgeAttachment | null> {
if (!isInFlutterWebView()) return null; if (!isInFlutterWebView()) return null;
const requestId = `upload-${Date.now()}`; const requestId = `upload-${Date.now()}`;
const uploadPayload = { const uploadPayload = {
@ -274,6 +281,10 @@ export async function uploadFileViaFlutterBridge(
? (data.files as Array<Record<string, unknown>>) ? (data.files as Array<Record<string, unknown>>)
: []; : [];
const firstFile = files[0] || {}; const firstFile = files[0] || {};
const fileName =
(typeof firstFile.name === 'string' && firstFile.name) ||
`attachment-${Date.now()}.jpg`;
const directUrl = const directUrl =
(typeof firstFile.url === 'string' && firstFile.url) || (typeof firstFile.url === 'string' && firstFile.url) ||
(typeof firstFile.path === 'string' && firstFile.path) || (typeof firstFile.path === 'string' && firstFile.path) ||
@ -282,7 +293,7 @@ export async function uploadFileViaFlutterBridge(
(typeof data.path === 'string' && data.path) || (typeof data.path === 'string' && data.path) ||
''; '';
if (directUrl) { if (directUrl) {
return directUrl;
return { url: directUrl, name: fileName };
} }
const base64DataUrl = const base64DataUrl =
@ -291,17 +302,33 @@ export async function uploadFileViaFlutterBridge(
''; '';
if (!base64DataUrl) return null; if (!base64DataUrl) return null;
const fileName =
(typeof firstFile.name === 'string' && firstFile.name) ||
`attachment-${Date.now()}.jpg`;
const blob = dataUrlToBlob(base64DataUrl); const blob = dataUrlToBlob(base64DataUrl);
if (blob) { if (blob) {
const file = new File([blob], fileName, { const file = new File([blob], fileName, {
type: blob.type || 'image/jpeg', type: blob.type || 'image/jpeg',
}); });
return uploadBrowserFileToTmpMedia(file, base64DataUrl);
return {
url: URL.createObjectURL(file),
file,
name: fileName,
isObjectUrl: true,
};
} }
return base64DataUrl;
return { url: base64DataUrl, name: fileName };
}
export async function uploadFileViaFlutterBridge(
mediaType: 'image' | 'video' | 'image+video' | 'audio' | 'file' = 'image'
): Promise<string | null> {
const picked = await pickFileViaFlutterBridge(mediaType);
if (!picked) return null;
if (picked.file) {
if (picked.isObjectUrl) {
URL.revokeObjectURL(picked.url);
}
return uploadBrowserFileToTmpMedia(picked.file);
}
return picked.url;
} }
export async function uploadBrowserFileToTmpMedia( export async function uploadBrowserFileToTmpMedia(
@ -316,31 +343,24 @@ export async function uploadBrowserFileToTmpMedia(
headers.Authorization = `Token ${token}`; headers.Authorization = `Token ${token}`;
} }
const endpoints = [
resolveMediaUrl('/api/shop/upload-tmp-media/'),
resolveMediaUrl('/upload-tmp-media/'),
];
for (const endpoint of endpoints) {
try {
const resp = await fetch(endpoint, {
method: 'POST',
headers,
body: formData,
});
if (resp.ok) {
const json = (await resp.json()) as Record<string, unknown>;
const resolved =
(typeof json.url === 'string' && json.url) ||
(typeof json.file_url === 'string' && json.file_url) ||
(typeof json.file === 'string' && json.file) ||
(typeof json.path === 'string' && json.path) ||
'';
if (resolved) return resolved;
}
} catch {
// try next endpoint or fallback to data URL
try {
const resp = await fetch(resolveMediaUrl('/upload-tmp-media/'), {
method: 'POST',
headers,
body: formData,
});
if (resp.ok) {
const json = (await resp.json()) as Record<string, unknown>;
const resolved =
(typeof json.url === 'string' && json.url) ||
(typeof json.file_url === 'string' && json.file_url) ||
(typeof json.file === 'string' && json.file) ||
(typeof json.path === 'string' && json.path) ||
'';
if (resolved) return resolved;
} }
} catch {
// fallback to data URL if tmp endpoint is unreachable
} }
if (fallbackDataUrl) return fallbackDataUrl; if (fallbackDataUrl) return fallbackDataUrl;

319
src/pages/account/LanguageSettingPage.tsx

@ -1,8 +1,12 @@
import React, { useMemo, useState } from 'react'; import React, { useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell'; import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import { AccountMenuRow } from '../../components/account/AccountMenuRow'; import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import {
EmptyStateBox,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import type { AccountMenuRowItem } from '../../data/accountData'; import type { AccountMenuRowItem } from '../../data/accountData';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { useAnimatedPresence } from '../../hooks/use-animated-presence'; import { useAnimatedPresence } from '../../hooks/use-animated-presence';
@ -117,8 +121,11 @@ export const LanguageSettingPage: React.FC = () => {
const smartBack = useSmartBack(ROUTES.account); const smartBack = useSmartBack(ROUTES.account);
const { const {
isUserAuthenticated,
profile, profile,
isProfilePending,
selectedAddress, selectedAddress,
isAddressesLoading,
orderCounters, orderCounters,
language, language,
changeLanguage, changeLanguage,
@ -196,14 +203,20 @@ export const LanguageSettingPage: React.FC = () => {
if (bare) return LANGUAGE_SETTING_MENU_ROWS; if (bare) return LANGUAGE_SETTING_MENU_ROWS;
const langLabel = const langLabel =
language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English'; language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English';
const activeOrders = orderCounters?.in_progress ?? 0;
const activeOrders = orderCounters?.current ?? orderCounters?.in_progress ?? 0;
return LANGUAGE_SETTING_MENU_ROWS.map((row) => { return LANGUAGE_SETTING_MENU_ROWS.map((row) => {
if (row.id === 'lang-location') { if (row.id === 'lang-location') {
return { return {
...row, ...row,
loadingSubtitle:
!bare &&
isUserAuthenticated &&
isAddressesLoading &&
!selectedAddress?.city,
subtitle: subtitle:
selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'), selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'),
rightIconType: 'arrow-right',
targetRoute: ROUTES.addresses, targetRoute: ROUTES.addresses,
}; };
} }
@ -211,7 +224,7 @@ export const LanguageSettingPage: React.FC = () => {
return { return {
...row, ...row,
subtitle: langLabel, subtitle: langLabel,
rightIconType: 'edit-path',
rightIconType: 'arrow-right',
targetRoute: '', targetRoute: '',
}; };
} }
@ -225,7 +238,7 @@ export const LanguageSettingPage: React.FC = () => {
if (row.id === 'lang-notes') { if (row.id === 'lang-notes') {
return { return {
...row, ...row,
targetRoute: ROUTES.bookmarks,
targetRoute: ROUTES.notes,
}; };
} }
return { return {
@ -233,7 +246,25 @@ export const LanguageSettingPage: React.FC = () => {
targetRoute: ROUTES.account, targetRoute: ROUTES.account,
}; };
}); });
}, [bare, language, orderCounters, selectedAddress, useMockFallback]);
}, [
bare,
isAddressesLoading,
isUserAuthenticated,
language,
orderCounters,
selectedAddress,
useMockFallback,
]);
const isNamePending =
!bare && isUserAuthenticated && isProfilePending && !profile?.full_name;
const isEmailPending =
!bare && isUserAuthenticated && isProfilePending && !profile?.email;
const isProviderReqsPending =
!bare &&
isUserAuthenticated &&
isProfilePending &&
!profile?.provider_requests?.length;
const handleBuyCoins = async () => { const handleBuyCoins = async () => {
if (bare) return; if (bare) return;
@ -352,38 +383,58 @@ export const LanguageSettingPage: React.FC = () => {
</div> </div>
{/* Name "Ahd Art" */} {/* Name "Ahd Art" */}
<div
style={{
marginTop: 8,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 22,
lineHeight: '26px',
color: '#151c31',
textAlign: 'center',
}}
>
{displayName}
</div>
{isNamePending ? (
<ShimmerBox
width={120}
height={22}
borderRadius={6}
style={{ marginTop: 10 }}
/>
) : (
<div
style={{
marginTop: 8,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 22,
lineHeight: '26px',
color: '#151c31',
textAlign: 'center',
}}
>
{displayName}
</div>
)}
{/* Email "Ahdart14@gmail.com" */} {/* Email "Ahdart14@gmail.com" */}
<div
style={{
marginTop: 3,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#2049eb',
textAlign: 'center',
}}
>
{displayEmail}
</div>
{isEmailPending ? (
<ShimmerBox
width={140}
height={14}
borderRadius={5}
style={{ marginTop: 5 }}
/>
) : (
<div
style={{
marginTop: 3,
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#2049eb',
textAlign: 'center',
}}
>
{displayEmail}
</div>
)}
</div> </div>
{/* Provider Requests Card (4214:11186) */} {/* Provider Requests Card (4214:11186) */}
{providerRows.length > 0 ? (
{isProviderReqsPending ? (
<ShimmerBox height={52} borderRadius={15} />
) : providerRows.length > 0 ? (
<div <div
style={{ style={{
width: '100%', width: '100%',
@ -976,3 +1027,207 @@ export const LanguageSettingPage: React.FC = () => {
</MobileShell> </MobileShell>
); );
}; };
interface ShopNoteItem {
id: string;
text: string;
createdAt: string;
}
const SHOP_NOTES_STORAGE_KEY = 'habib_shop_notes';
function readStoredNotes(): ShopNoteItem[] {
if (typeof window === 'undefined') return [];
try {
const raw = window.localStorage.getItem(SHOP_NOTES_STORAGE_KEY);
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.filter(
(item): item is ShopNoteItem =>
Boolean(item) &&
typeof item === 'object' &&
typeof (item as ShopNoteItem).id === 'string' &&
typeof (item as ShopNoteItem).text === 'string' &&
typeof (item as ShopNoteItem).createdAt === 'string'
);
} catch {
return [];
}
}
function writeStoredNotes(notes: ShopNoteItem[]): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(SHOP_NOTES_STORAGE_KEY, JSON.stringify(notes));
} catch {
// ignore storage quota / private mode errors
}
}
export const ShopNotesPage: React.FC = () => {
const { language, showToast } = useShopApp();
const [notes, setNotes] = useState<ShopNoteItem[]>(readStoredNotes);
const [draft, setDraft] = useState('');
const handleAddNote = (e: React.FormEvent) => {
e.preventDefault();
const trimmed = draft.trim();
if (!trimmed) return;
const next: ShopNoteItem[] = [
{
id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
text: trimmed,
createdAt: new Date().toLocaleDateString(),
},
...notes,
];
setNotes(next);
writeStoredNotes(next);
setDraft('');
showToast(tr('Note saved', language));
};
const handleDeleteNote = (id: string) => {
const next = notes.filter((n) => n.id !== id);
setNotes(next);
writeStoredNotes(next);
showToast(tr('Note removed', language));
};
return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef">
<StandardPageHeader title="Notes" backTo={ROUTES.settings} />
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '16px var(--page-px) calc(28px + var(--safe-bottom, 0px))',
gap: 16,
}}
>
<form
onSubmit={handleAddNote}
style={{
padding: 14,
borderRadius: 15,
backgroundColor: '#ffffff',
boxShadow: '0px 2px 13px rgba(180, 187, 200, 0.21)',
display: 'flex',
flexDirection: 'column',
gap: 10,
}}
>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={tr('Write a note...', language)}
rows={3}
style={{
width: '100%',
resize: 'vertical',
padding: '10px 12px',
borderRadius: 11,
border: '1px solid #e5e7eb',
fontFamily: 'var(--font-sans)',
fontSize: 13,
lineHeight: '19px',
color: '#111111',
backgroundColor: '#fbfbfc',
outline: 'none',
}}
/>
<button
type="submit"
disabled={!draft.trim()}
className="habib-cta-btn"
style={{
alignSelf: 'flex-end',
padding: '9px 18px',
borderRadius: 11,
border: 'none',
backgroundColor: draft.trim() ? '#d78e06' : '#cbd5e1',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
cursor: draft.trim() ? 'pointer' : 'default',
}}
>
{tr('Add Note', language)}
</button>
</form>
{notes.length === 0 ? (
<EmptyStateBox message="No notes yet" />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{notes.map((note) => (
<div
key={note.id}
style={{
padding: '14px 15px',
borderRadius: 15,
backgroundColor: '#ffffff',
boxShadow: '0px 2px 13px rgba(180, 187, 200, 0.18)',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontSize: 13,
lineHeight: '19px',
color: '#151c31',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{note.text}
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontSize: 11,
color: '#73889d',
}}
>
{note.createdAt}
</span>
<button
type="button"
onClick={() => handleDeleteNote(note.id)}
style={{
border: 'none',
background: 'transparent',
padding: 0,
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
color: '#d44747',
cursor: 'pointer',
}}
>
{tr('Remove', language)}
</button>
</div>
</div>
))}
</div>
)}
</div>
</MobileShell>
);
};

67
src/pages/account/ProviderRequestPage.tsx

@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell'; import { MobileShell } from '../../components/layout/MobileShell';
import { ShimmerBox } from '../../components/common/ShimmerSkeletons';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { useSmartBack } from '../../hooks/useSmartBack'; import { useSmartBack } from '../../hooks/useSmartBack';
import { isRtlLanguage, tr } from '../../lib/cookies'; import { isRtlLanguage, tr } from '../../lib/cookies';
@ -24,6 +25,7 @@ export const ProviderRequestPage: React.FC = () => {
isUserAuthenticated, isUserAuthenticated,
requireAuth, requireAuth,
profile, profile,
isProfilePending,
language, language,
showToast, showToast,
} = useShopApp(); } = useShopApp();
@ -32,12 +34,24 @@ export const ProviderRequestPage: React.FC = () => {
const updateProfileMutation = useUpdateProfileMutation(); const updateProfileMutation = useUpdateProfileMutation();
const savingProfile = updateProfileMutation.isPending; const savingProfile = updateProfileMutation.isPending;
const [fullName, setFullName] = useState(
useMockFallback ? 'Montazeran Mahdi' : ''
const [fullName, setFullName] = useState(() =>
!bare && profile?.full_name
? profile.full_name
: useMockFallback
? 'Montazeran Mahdi'
: ''
);
const [birthdate, setBirthdate] = useState(() =>
!bare && profile?.birthdate ? profile.birthdate : ''
);
const [waNumber, setWaNumber] = useState(() =>
!bare && (profile?.wa_number || profile?.phone_number)
? profile.wa_number || profile.phone_number || ''
: ''
);
const [email, setEmail] = useState(() =>
!bare && profile?.email ? profile.email : ''
); );
const [birthdate, setBirthdate] = useState('');
const [waNumber, setWaNumber] = useState('');
const [email, setEmail] = useState('');
const [focusedField, setFocusedField] = useState<string | null>(null); const [focusedField, setFocusedField] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
@ -236,21 +250,34 @@ export const ProviderRequestPage: React.FC = () => {
/> />
</div> </div>
<div
style={{
marginTop: 13,
padding: '3px 10px',
borderRadius: 8,
fontFamily: 'Inter, var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '20px',
color: '#d78e06',
textAlign: 'center',
}}
>
{headerEmailText}
</div>
{!bare &&
isUserAuthenticated &&
isProfilePending &&
!email.trim() &&
!profile?.email ? (
<ShimmerBox
width={136}
height={14}
borderRadius={5}
style={{ marginTop: 18 }}
/>
) : (
<div
style={{
marginTop: 13,
padding: '3px 10px',
borderRadius: 8,
fontFamily: 'Inter, var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '20px',
color: '#d78e06',
textAlign: 'center',
}}
>
{headerEmailText}
</div>
)}
</div> </div>
{/* Field 1: Full Name* (People will see this) (4220:13730) */} {/* Field 1: Full Name* (People will see this) (4220:13730) */}

118
src/pages/account/ShopAccountPage.tsx

@ -4,6 +4,7 @@ import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar'; import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { OrderCounterCard } from '../../components/account/OrderCounterCard'; import { OrderCounterCard } from '../../components/account/OrderCounterCard';
import { AccountMenuRow } from '../../components/account/AccountMenuRow'; import { AccountMenuRow } from '../../components/account/AccountMenuRow';
import { ShimmerBox } from '../../components/common/ShimmerSkeletons';
import { import {
ACCOUNT_ORDER_COUNTERS, ACCOUNT_ORDER_COUNTERS,
type AccountMenuRowItem, type AccountMenuRowItem,
@ -29,37 +30,58 @@ export const ShopAccountPage: React.FC = () => {
openLoginModal, openLoginModal,
requireAuth, requireAuth,
profile, profile,
isProfilePending,
orderCounters, orderCounters,
isOrderCountersLoading,
addresses, addresses,
isAddressesLoading,
selectedAddress, selectedAddress,
language, language,
cartItemsCount, cartItemsCount,
} = useShopApp(); } = useShopApp();
const counters = useMemo(() => { const counters = useMemo(() => {
if (bare || (!orderCounters && useMockFallback)) return ACCOUNT_ORDER_COUNTERS;
if (bare) return ACCOUNT_ORDER_COUNTERS;
if (!orderCounters && useMockFallback) {
return [
ACCOUNT_ORDER_COUNTERS[0],
ACCOUNT_ORDER_COUNTERS[1],
{ ...ACCOUNT_ORDER_COUNTERS[2], label: 'Canceled' },
];
}
if (!isUserAuthenticated) { if (!isUserAuthenticated) {
return [ return [
{ ...ACCOUNT_ORDER_COUNTERS[0], countText: '0 Orders' }, { ...ACCOUNT_ORDER_COUNTERS[0], countText: '0 Orders' },
{ ...ACCOUNT_ORDER_COUNTERS[1], countText: '0 Orders' }, { ...ACCOUNT_ORDER_COUNTERS[1], countText: '0 Orders' },
{ ...ACCOUNT_ORDER_COUNTERS[2], countText: '0 Orders' },
{ ...ACCOUNT_ORDER_COUNTERS[2], label: 'Canceled', countText: '0 Orders' },
];
}
if (isOrderCountersLoading && !orderCounters) {
return [
{ ...ACCOUNT_ORDER_COUNTERS[0], loadingCount: true },
{ ...ACCOUNT_ORDER_COUNTERS[1], loadingCount: true },
{ ...ACCOUNT_ORDER_COUNTERS[2], label: 'Canceled', loadingCount: true },
]; ];
} }
const currentCount = orderCounters?.current ?? orderCounters?.in_progress ?? 0;
const deliveredCount = orderCounters?.delivered ?? 0;
const canceledCount = orderCounters?.canceled ?? orderCounters?.returned ?? 0;
return [ return [
{ {
...ACCOUNT_ORDER_COUNTERS[0], ...ACCOUNT_ORDER_COUNTERS[0],
countText: `${orderCounters?.in_progress ?? 0} Orders`,
countText: `${currentCount} Orders`,
}, },
{ {
...ACCOUNT_ORDER_COUNTERS[1], ...ACCOUNT_ORDER_COUNTERS[1],
countText: `${orderCounters?.delivered ?? 0} Orders`,
countText: `${deliveredCount} Orders`,
}, },
{ {
...ACCOUNT_ORDER_COUNTERS[2], ...ACCOUNT_ORDER_COUNTERS[2],
countText: `${orderCounters?.returned ?? 0} Orders`,
label: 'Canceled',
countText: `${canceledCount} Orders`,
}, },
]; ];
}, [bare, isUserAuthenticated, orderCounters, useMockFallback]);
}, [bare, isOrderCountersLoading, isUserAuthenticated, orderCounters, useMockFallback]);
const menuRows = useMemo<AccountMenuRowItem[]>(() => { const menuRows = useMemo<AccountMenuRowItem[]>(() => {
if (bare) return SHOP_ACCOUNT_MENU_ROWS; if (bare) return SHOP_ACCOUNT_MENU_ROWS;
@ -77,6 +99,8 @@ export const ShopAccountPage: React.FC = () => {
const count = addresses.length; const count = addresses.length;
return { return {
...row, ...row,
loadingSubtitle:
!bare && isUserAuthenticated && isAddressesLoading && count === 0,
subtitle: isUserAuthenticated subtitle: isUserAuthenticated
? count > 0 ? count > 0
? `${count} ${count === 1 ? 'adress' : 'adresses'}` ? `${count} ${count === 1 ? 'adress' : 'adresses'}`
@ -98,7 +122,7 @@ export const ShopAccountPage: React.FC = () => {
} }
if (row.id === 'acc-notifications') { if (row.id === 'acc-notifications') {
const activeCount = isUserAuthenticated const activeCount = isUserAuthenticated
? orderCounters?.in_progress ?? 0
? orderCounters?.current ?? orderCounters?.in_progress ?? 0
: 0; : 0;
return { return {
...row, ...row,
@ -134,12 +158,22 @@ export const ShopAccountPage: React.FC = () => {
}, [ }, [
addresses.length, addresses.length,
bare, bare,
isAddressesLoading,
isUserAuthenticated, isUserAuthenticated,
language, language,
orderCounters, orderCounters,
useMockFallback, useMockFallback,
]); ]);
const isNamePending =
!bare && isUserAuthenticated && isProfilePending && !profile?.full_name;
const isSubPending =
!bare &&
isUserAuthenticated &&
isProfilePending &&
!profile?.phone_number &&
!profile?.email;
const displayName = bare const displayName = bare
? 'Habib shoper' ? 'Habib shoper'
: isUserAuthenticated : isUserAuthenticated
@ -230,34 +264,52 @@ export const ShopAccountPage: React.FC = () => {
</div> </div>
{/* User Name "Habib shoper" (4214:366) */} {/* User Name "Habib shoper" (4214:366) */}
<div
style={{
marginTop: 9,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '26px',
color: '#111111',
textAlign: 'center',
}}
>
{tr(displayName)}
</div>
{isNamePending ? (
<ShimmerBox
width={132}
height={22}
borderRadius={6}
style={{ marginTop: 11 }}
/>
) : (
<div
style={{
marginTop: 9,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '26px',
color: '#111111',
textAlign: 'center',
}}
>
{tr(displayName)}
</div>
)}
{/* Phone "09102036523" (4214:367) */} {/* Phone "09102036523" (4214:367) */}
<div
style={{
marginTop: 3,
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#8b8b8b',
textAlign: 'center',
}}
>
{tr(displaySub)}
</div>
{isSubPending ? (
<ShimmerBox
width={104}
height={13}
borderRadius={5}
style={{ marginTop: 5 }}
/>
) : (
<div
style={{
marginTop: 3,
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#8b8b8b',
textAlign: 'center',
}}
>
{tr(displaySub)}
</div>
)}
</div> </div>
{/* 3 Order Status Counter Cards (4215:11563) */} {/* 3 Order Status Counter Cards (4215:11563) */}

7
src/pages/account/ShopAddressPage.tsx

@ -6,6 +6,7 @@ import {
AddressCard, AddressCard,
AddNewAddressCard, AddNewAddressCard,
} from '../../components/checkout/AddressCard'; } from '../../components/checkout/AddressCard';
import { ShimmerBox } from '../../components/common/ShimmerSkeletons';
import { AddressFormSheet } from '../../components/modals/AddressFormSheet'; import { AddressFormSheet } from '../../components/modals/AddressFormSheet';
import { BUY01_ADDRESSES } from '../../data/checkoutData'; import { BUY01_ADDRESSES } from '../../data/checkoutData';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
@ -23,6 +24,7 @@ export const ShopAddressPage: React.FC = () => {
const { const {
addresses: apiAddresses, addresses: apiAddresses,
isAddressesLoading,
selectedAddressId, selectedAddressId,
selectAddress, selectAddress,
saveAddress, saveAddress,
@ -73,6 +75,11 @@ export const ShopAddressPage: React.FC = () => {
onSelect={() => setBareSelectedId(address.id)} onSelect={() => setBareSelectedId(address.id)}
/> />
)) ))
) : isAddressesLoading && apiAddresses.length === 0 ? (
<>
<ShimmerBox height={86} borderRadius={15} />
<ShimmerBox height={86} borderRadius={15} />
</>
) : apiAddresses.length > 0 ? ( ) : apiAddresses.length > 0 ? (
apiAddresses.map((addr, index) => ( apiAddresses.map((addr, index) => (
<AddressCard <AddressCard

402
src/pages/catalog/ShopBoothPage.tsx

@ -4,9 +4,9 @@ import { MobileShell } from '../../components/layout/MobileShell';
import { GridProductCard } from '../../components/common/GridProductCard'; import { GridProductCard } from '../../components/common/GridProductCard';
import { import {
EmptyStateBox, EmptyStateBox,
ProductGridShimmer,
RetryBanner, RetryBanner,
ShimmerBox, ShimmerBox,
StoreBoothBodyShimmer,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
import { TWO_COLUMN_GRID_PRODUCTS } from '../../data/catalogData'; import { TWO_COLUMN_GRID_PRODUCTS } from '../../data/catalogData';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
@ -39,6 +39,7 @@ export const ShopBoothPage: React.FC = () => {
const loadError = !isBare && storeQuery.isError; const loadError = !isBare && storeQuery.isError;
const liveStore = !isBare ? store : null; const liveStore = !isBare ? store : null;
const isStoreShimmer = !isBare && loading && !liveStore;
const handleShare = async () => { const handleShare = async () => {
const url = window.location.href; const url = window.location.href;
@ -71,7 +72,7 @@ export const ShopBoothPage: React.FC = () => {
return ( return (
<MobileShell width={375} height={1233} backgroundColor="#f3f1ef"> <MobileShell width={375} height={1233} backgroundColor="#f3f1ef">
{/* Top Banner Calligraphy Image & Floating Actions */}
{/* Top Store Logo Backdrop & Floating Actions */}
<div <div
style={{ style={{
position: 'relative', position: 'relative',
@ -81,13 +82,13 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
> >
{!isBare && loading ? (
{isStoreShimmer ? (
<ShimmerBox width="100%" height="100%" borderRadius={0} /> <ShimmerBox width="100%" height="100%" borderRadius={0} />
) : ( ) : (
<img <img
src={ src={
resolveMediaUrl(liveStore?.banner_url) ||
'/assets/images/bg-booth-calligraphy-header.png'
resolveMediaUrl(liveStore?.logo_url) ||
'/assets/images/avatar-tashakol-booth.png'
} }
alt="" alt=""
style={{ style={{
@ -191,9 +192,7 @@ export const ShopBoothPage: React.FC = () => {
</div> </div>
</div> </div>
{!isBare && loading ? (
<StoreBoothBodyShimmer />
) : !liveStore && !useMockFallback ? (
{!isStoreShimmer && !liveStore && !useMockFallback ? (
<div <div
style={{ style={{
flex: 1, flex: 1,
@ -226,70 +225,97 @@ export const ShopBoothPage: React.FC = () => {
}} }}
> >
{/* Circular Store Avatar */} {/* Circular Store Avatar */}
<img
src={
resolveMediaUrl(liveStore?.logo_url) ||
'/assets/images/avatar-tashakol-booth.png'
}
alt={liveStore?.name || 'TashakolFarzandan Rohhallah'}
style={{
width: 64,
height: 64,
borderRadius: 32,
border: '1px solid #ffffff',
objectFit: 'cover',
boxSizing: 'border-box',
}}
/>
{/* Store Title */}
<h1
style={{
marginTop: 12,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 16,
lineHeight: '20px',
color: '#151c31',
textAlign: 'center',
width: '100%',
}}
>
{liveStore?.name || 'TashakolFarzandan Rohhallah'}
</h1>
{/* Iran Flag + Origin */}
<div
style={{
marginTop: 6,
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
{isStoreShimmer ? (
<ShimmerBox
width={64}
height={64}
borderRadius={32}
style={{ border: '1px solid #ffffff', boxSizing: 'border-box' }}
/>
) : (
<img <img
src="/assets/images/icon-flag-iran-19.svg"
alt="Origin"
src={
resolveMediaUrl(liveStore?.logo_url) ||
'/assets/images/avatar-tashakol-booth.png'
}
alt={liveStore?.name || 'TashakolFarzandan Rohhallah'}
style={{ style={{
width: 19,
height: 19,
width: 64,
height: 64,
borderRadius: 32,
border: '1px solid #ffffff',
objectFit: 'cover',
boxSizing: 'border-box',
}} }}
/> />
<span
)}
{/* Store Title */}
{isStoreShimmer ? (
<ShimmerBox
width={186}
height={20}
borderRadius={6}
style={{ marginTop: 12 }}
/>
) : (
<h1
style={{ style={{
marginTop: 12,
fontFamily: 'var(--font-sans)', fontFamily: 'var(--font-sans)',
fontWeight: 700, fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#8b8b8b',
whiteSpace: 'nowrap',
fontSize: 16,
lineHeight: '20px',
color: '#151c31',
textAlign: 'center',
width: '100%',
}} }}
> >
{liveStore
? [liveStore.country, liveStore.city].filter(Boolean).join(' | ')
: 'Iran | Tehran'}
</span>
</div>
{liveStore?.name || 'TashakolFarzandan Rohhallah'}
</h1>
)}
{/* Iran Flag + Origin */}
{isStoreShimmer ? (
<ShimmerBox
width={104}
height={16}
borderRadius={5}
style={{ marginTop: 6 }}
/>
) : (
<div
style={{
marginTop: 6,
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
<img
src="/assets/images/icon-flag-iran-19.svg"
alt="Origin"
style={{
width: 19,
height: 19,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#8b8b8b',
whiteSpace: 'nowrap',
}}
>
{liveStore
? [liveStore.country, liveStore.city].filter(Boolean).join(' | ')
: 'Iran | Tehran'}
</span>
</div>
)}
{!isBare && loadError && !store && ( {!isBare && loadError && !store && (
<div style={{ width: '100%', marginTop: 14 }}> <div style={{ width: '100%', marginTop: 14 }}>
@ -323,26 +349,30 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${Number(
useMockFallback
? liveStore.rating_avg || 4.4
: liveStore.rating_avg ?? 0
).toFixed(1)} (${
liveStore.reviews_count ?? (useMockFallback ? 608 : 0)
})`
: '4.4 (608)'}
</span>
{isStoreShimmer ? (
<ShimmerBox width={46} height={12} borderRadius={4} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${Number(
useMockFallback
? liveStore.rating_avg || 4.4
: liveStore.rating_avg ?? 0
).toFixed(1)} (${
liveStore.reviews_count ?? (useMockFallback ? 608 : 0)
})`
: '4.4 (608)'}
</span>
)}
</div> </div>
<div <div
@ -354,19 +384,23 @@ export const ShopBoothPage: React.FC = () => {
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(liveStore?.membership_label || '+1 year membership')}
</span>
{isStoreShimmer ? (
<ShimmerBox width={84} height={12} borderRadius={4} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(liveStore?.membership_label || '+1 year membership')}
</span>
)}
<div <div
style={{ style={{
@ -377,19 +411,23 @@ export const ShopBoothPage: React.FC = () => {
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(liveStore?.sales_label || '+60 sales')}
</span>
{isStoreShimmer ? (
<ShimmerBox width={52} height={12} borderRadius={4} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 10,
lineHeight: '12.9px',
color: '#747474',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(liveStore?.sales_label || '+60 sales')}
</span>
)}
</div> </div>
{/* 3 Store Metric Cards */} {/* 3 Store Metric Cards */}
@ -423,20 +461,24 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore?.avg_response_time || '2h'}
</span>
{isStoreShimmer ? (
<ShimmerBox width={36} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore?.avg_response_time || '2h'}
</span>
)}
</div> </div>
<span <span
style={{ style={{
@ -478,22 +520,26 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.on_time_delivery_rate ?? 87).replace(/%+$/, '')}%`
: '87%'}
</span>
{isStoreShimmer ? (
<ShimmerBox width={36} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.on_time_delivery_rate ?? 87).replace(/%+$/, '')}%`
: '87%'}
</span>
)}
</div> </div>
<span <span
style={{ style={{
@ -535,22 +581,26 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.satisfaction_rate ?? 98).replace(/%+$/, '')}%`
: '98%'}
</span>
{isStoreShimmer ? (
<ShimmerBox width={36} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(14px, 4.3vw, 16px)',
lineHeight: '20px',
background: 'linear-gradient(195deg, #eaba73 0%, #d78e06 100%)',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
whiteSpace: 'nowrap',
}}
>
{liveStore
? `${String(liveStore.satisfaction_rate ?? 98).replace(/%+$/, '')}%`
: '98%'}
</span>
)}
</div> </div>
<span <span
style={{ style={{
@ -590,21 +640,29 @@ export const ShopBoothPage: React.FC = () => {
> >
{tr('About')} {tr('About')}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-wrap',
}}
>
{liveStore?.description ||
(useMockFallback
? 'In this room, we are going to talk about raising children from the perspective of Islam In this room, we are going to talk about raising children from the perspective of Islam of Islam In this room, we are going to talk about raising children from about the perspective talk about of Islam room.'
: tr('No description available.'))}
</div>
{isStoreShimmer ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<ShimmerBox width="96%" height={13} borderRadius={5} />
<ShimmerBox width="90%" height={13} borderRadius={5} />
<ShimmerBox width="68%" height={13} borderRadius={5} />
</div>
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-wrap',
}}
>
{liveStore?.description ||
(useMockFallback
? 'In this room, we are going to talk about raising children from the perspective of Islam In this room, we are going to talk about raising children from the perspective of Islam of Islam In this room, we are going to talk about raising children from about the perspective talk about of Islam room.'
: tr('No description available.'))}
</div>
)}
</section> </section>
{/* Products Section */} {/* Products Section */}
@ -629,7 +687,9 @@ export const ShopBoothPage: React.FC = () => {
{tr('Products')} {tr('Products')}
</div> </div>
{liveStore?.products?.length ? (
{isStoreShimmer ? (
<ProductGridShimmer count={4} />
) : liveStore?.products?.length ? (
<div className="habib-product-grid"> <div className="habib-product-grid">
{liveStore.products.map((product) => ( {liveStore.products.map((product) => (
<GridProductCard <GridProductCard

208
src/pages/catalog/ShopCatItemsPage.tsx

@ -1,26 +1,35 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useLocation, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useParams, useSearchParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell'; import { MobileShell } from '../../components/layout/MobileShell';
import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { StandardPageHeader } from '../../components/layout/TopHeader'; import { StandardPageHeader } from '../../components/layout/TopHeader';
import { SearchBar } from '../../components/common/SearchBar'; import { SearchBar } from '../../components/common/SearchBar';
import { CategoryCard } from '../../components/common/CategoryCard';
import { GridProductCard } from '../../components/common/GridProductCard'; import { GridProductCard } from '../../components/common/GridProductCard';
import { import {
CategoryGridShimmer,
EmptyStateBox, EmptyStateBox,
ProductGridShimmer, ProductGridShimmer,
RetryBanner, RetryBanner,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
import { TWO_COLUMN_GRID_PRODUCTS } from '../../data/catalogData';
import {
MOCK_SUBCATEGORY_TILES,
TWO_COLUMN_GRID_PRODUCTS,
} from '../../data/catalogData';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { tr } from '../../lib/cookies'; import { tr } from '../../lib/cookies';
import { mapProductToGridItem } from '../../lib/mappers';
import { mapCategoryToTile, mapProductToGridItem } from '../../lib/mappers';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes'; import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { import {
findCachedCategoryBySlug,
useCategoryDetailQuery, useCategoryDetailQuery,
useCollectionDetailQuery,
useProductsQuery, useProductsQuery,
} from '../../lib/shopQueries'; } from '../../lib/shopQueries';
interface ShopCatItemsPageProps { interface ShopCatItemsPageProps {
mode?: 'category' | 'search' | 'bookmarks';
mode?: 'category' | 'collection' | 'search' | 'bookmarks';
} }
function humanizeSlug(slug?: string): string { function humanizeSlug(slug?: string): string {
@ -31,62 +40,158 @@ function humanizeSlug(slug?: string): string {
} }
/** /**
* Node 4181:12817 — `shop-catitems` (Category Items, Search Results, Bookmarks, 375×814)
* Node 4181:12817 — `shop-catitems` (Subcategory Tree Node, Category Items, Search Results, Bookmarks, 375×814)
*/ */
export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({ export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
mode = 'category', mode = 'category',
}) => { }) => {
const location = useLocation(); const location = useLocation();
const queryClient = useQueryClient();
const isBare = isBareMode(location.search); const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA; const useMockFallback = isBare || USE_MOCK_DATA;
const { categorySlug } = useParams<{ categorySlug?: string }>();
const { categorySlug, collectionSlug } = useParams<{
categorySlug?: string;
collectionSlug?: string;
}>();
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const initialQ = searchParams.get('q') || ''; const initialQ = searchParams.get('q') || '';
const { hydrated, bookmarkedProducts, isBookmarked, toggleBookmark } =
useShopApp();
const {
isBookmarksLoading,
bookmarkedProducts,
isBookmarked,
toggleBookmark,
} = useShopApp();
const routeKey = `${location.pathname}?${initialQ}`;
const [prevRouteKey, setPrevRouteKey] = useState(routeKey);
const [query, setQuery] = useState(initialQ); const [query, setQuery] = useState(initialQ);
const isSearchOrAll = mode === 'search' || !categorySlug;
if (prevRouteKey !== routeKey) {
setPrevRouteKey(routeKey);
setQuery(initialQ);
}
const isCategoryMode = mode === 'category' && Boolean(categorySlug);
const isCollectionMode = mode === 'collection' && Boolean(collectionSlug);
const isSearchOrAll =
mode === 'search' || (!isCategoryMode && !isCollectionMode && mode !== 'bookmarks');
const shouldFetchLive = !isBare && mode !== 'bookmarks'; const shouldFetchLive = !isBare && mode !== 'bookmarks';
const cachedCategory = useMemo(
() =>
!isBare && isCategoryMode
? findCachedCategoryBySlug(queryClient, categorySlug)
: null,
[categorySlug, isBare, isCategoryMode, queryClient]
);
const productsQuery = useProductsQuery( const productsQuery = useProductsQuery(
{ q: initialQ || undefined }, { q: initialQ || undefined },
shouldFetchLive && isSearchOrAll shouldFetchLive && isSearchOrAll
); );
const categoryQuery = useCategoryDetailQuery( const categoryQuery = useCategoryDetailQuery(
categorySlug || '', categorySlug || '',
shouldFetchLive && !isSearchOrAll
shouldFetchLive && isCategoryMode
);
const collectionQuery = useCollectionDetailQuery(
collectionSlug || '',
shouldFetchLive && isCollectionMode
); );
const resolvedCategory = categoryQuery.data?.category ?? cachedCategory;
const liveChildren =
shouldFetchLive && isCategoryMode
? categoryQuery.data?.children ?? null
: null;
const mockChildren =
!isBare &&
USE_MOCK_DATA &&
isCategoryMode &&
!categoryQuery.data &&
categorySlug
? MOCK_SUBCATEGORY_TILES[categorySlug] ?? null
: null;
const products = !shouldFetchLive const products = !shouldFetchLive
? null ? null
: isSearchOrAll
? productsQuery.data?.results ?? null
: categoryQuery.data?.products ?? null;
: isCollectionMode
? collectionQuery.data?.products ?? null
: isCategoryMode
? categoryQuery.data?.products ?? null
: productsQuery.data?.results ?? null;
const activeQuery = isSearchOrAll ? productsQuery : categoryQuery;
const activeQuery = isCollectionMode
? collectionQuery
: isCategoryMode
? categoryQuery
: productsQuery;
const loading = const loading =
shouldFetchLive && shouldFetchLive &&
(activeQuery.isPending || (!products && activeQuery.isFetching));
(activeQuery.isPending ||
(!products && liveChildren === null && activeQuery.isFetching));
const loadError = shouldFetchLive && activeQuery.isError; const loadError = shouldFetchLive && activeQuery.isError;
const isSubcategoryView =
!isBare &&
isCategoryMode &&
(liveChildren !== null
? liveChildren.length > 0
: loading || loadError
? (cachedCategory?.children_count ?? 0) > 0 ||
Boolean(mockChildren && mockChildren.length > 0)
: Boolean(mockChildren && mockChildren.length > 0));
const headerTitle = useMemo(() => { const headerTitle = useMemo(() => {
if (mode === 'bookmarks') return 'Saved Items'; if (mode === 'bookmarks') return 'Saved Items';
if (isCollectionMode) {
const col = collectionQuery.data?.collection;
return (
col?.localized_title ||
col?.title ||
(collectionSlug ? humanizeSlug(collectionSlug) : 'Collection')
);
}
if (isSearchOrAll) { if (isSearchOrAll) {
return initialQ ? `Results for "${initialQ}"` : 'Explore Products'; return initialQ ? `Results for "${initialQ}"` : 'Explore Products';
} }
const cat = categoryQuery.data?.category;
return ( return (
cat?.localized_title ||
cat?.title ||
resolvedCategory?.localized_title ||
resolvedCategory?.title ||
(categorySlug ? humanizeSlug(categorySlug) : 'Home & Living') (categorySlug ? humanizeSlug(categorySlug) : 'Home & Living')
); );
}, [categoryQuery.data?.category, categorySlug, initialQ, isSearchOrAll, mode]);
}, [
categorySlug,
collectionQuery.data?.collection,
collectionSlug,
initialQ,
isCollectionMode,
isSearchOrAll,
mode,
resolvedCategory,
]);
useEffect(() => {
setQuery(initialQ);
}, [initialQ]);
const filteredChildren = useMemo(() => {
if (!liveChildren) return null;
const trimmed = query.trim().toLowerCase();
if (!trimmed) return liveChildren;
return liveChildren.filter(
(cat) =>
cat.title.toLowerCase().includes(trimmed) ||
(cat.localized_title || '').toLowerCase().includes(trimmed) ||
cat.slug.toLowerCase().includes(trimmed)
);
}, [liveChildren, query]);
const filteredMockChildren = useMemo(() => {
if (!mockChildren) return null;
const trimmed = query.trim().toLowerCase();
if (!trimmed) return mockChildren;
return mockChildren.filter(
(tile) =>
tile.label.toLowerCase().includes(trimmed) ||
(tile.slug || '').toLowerCase().includes(trimmed)
);
}, [mockChildren, query]);
const displayedProducts = useMemo(() => { const displayedProducts = useMemo(() => {
const source = mode === 'bookmarks' ? bookmarkedProducts : products; const source = mode === 'bookmarks' ? bookmarkedProducts : products;
@ -104,11 +209,17 @@ export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
const backFallback = const backFallback =
mode === 'bookmarks' mode === 'bookmarks'
? ROUTES.account ? ROUTES.account
: mode === 'search'
: mode === 'search' || isCollectionMode
? ROUTES.home ? ROUTES.home
: resolvedCategory?.parent_slug
? ROUTES.category(resolvedCategory.parent_slug)
: ROUTES.categories; : ROUTES.categories;
const isBookmarksLoading = !isBare && mode === 'bookmarks' && !hydrated;
const showBookmarksShimmer =
!isBare &&
mode === 'bookmarks' &&
isBookmarksLoading &&
bookmarkedProducts.length === 0;
return ( return (
<MobileShell width={375} height={814} backgroundColor="#f3f1ef"> <MobileShell width={375} height={814} backgroundColor="#f3f1ef">
@ -122,8 +233,10 @@ export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
flex: 1, flex: 1,
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
padding: '11px var(--page-px) 28px',
gap: 23,
padding: isSubcategoryView
? '11px var(--page-px) 24px'
: '11px var(--page-px) 28px',
gap: isSubcategoryView ? 20 : 23,
}} }}
> >
<SearchBar <SearchBar
@ -143,7 +256,44 @@ export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
} }
/> />
{!isBare && (loading || isBookmarksLoading) ? (
{isSubcategoryView ? (
loading && !liveChildren ? (
<CategoryGridShimmer count={6} />
) : filteredChildren ? (
filteredChildren.length > 0 ? (
<div className="habib-category-grid">
{filteredChildren.map((cat, idx) => (
<CategoryCard
key={cat.id}
tile={mapCategoryToTile(cat, idx)}
count={cat.products_count}
slug={cat.slug}
/>
))}
</div>
) : (
<EmptyStateBox message="No categories found." />
)
) : (
<>
{loadError && (
<RetryBanner
message="Could not load categories. Tap Retry to refresh."
onRetry={() => void activeQuery.refetch()}
/>
)}
{filteredMockChildren && filteredMockChildren.length > 0 ? (
<div className="habib-category-grid">
{filteredMockChildren.map((tile) => (
<CategoryCard key={tile.id} tile={tile} slug={tile.slug} />
))}
</div>
) : (
<EmptyStateBox message="No categories available." />
)}
</>
)
) : !isBare && ((loading && !products) || showBookmarksShimmer) ? (
<ProductGridShimmer count={6} /> <ProductGridShimmer count={6} />
) : !isBare && displayedProducts ? ( ) : !isBare && displayedProducts ? (
displayedProducts.length > 0 ? ( displayedProducts.length > 0 ? (
@ -198,6 +348,10 @@ export const ShopCatItemsPage: React.FC<ShopCatItemsPageProps> = ({
</> </>
)} )}
</div> </div>
{isSubcategoryView && (
<BottomNavBar activeTab="category" showCartBadge={true} />
)}
</MobileShell> </MobileShell>
); );
}; };

16
src/pages/catalog/ShopCategoryPage.tsx

@ -5,6 +5,7 @@ import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { SearchBar } from '../../components/common/SearchBar'; import { SearchBar } from '../../components/common/SearchBar';
import { CategoryCard } from '../../components/common/CategoryCard'; import { CategoryCard } from '../../components/common/CategoryCard';
import { import {
CategoryGridShimmer,
EmptyStateBox, EmptyStateBox,
RetryBanner, RetryBanner,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
@ -33,9 +34,10 @@ export const ShopCategoryPage: React.FC = () => {
const filteredCategories = useMemo(() => { const filteredCategories = useMemo(() => {
if (!categories) return null; if (!categories) return null;
const roots = categories.filter((cat) => cat.parent === null);
const q = searchQuery.trim().toLowerCase(); const q = searchQuery.trim().toLowerCase();
if (!q) return categories;
return categories.filter(
if (!q) return roots;
return roots.filter(
(cat) => (cat) =>
cat.title.toLowerCase().includes(q) || cat.title.toLowerCase().includes(q) ||
(cat.localized_title || '').toLowerCase().includes(q) || (cat.localized_title || '').toLowerCase().includes(q) ||
@ -60,7 +62,9 @@ export const ShopCategoryPage: React.FC = () => {
onChange={isBare ? undefined : setSearchQuery} onChange={isBare ? undefined : setSearchQuery}
/> />
{!isBare && loading && !categories ? null : (
{!isBare && loading && !categories ? (
<CategoryGridShimmer count={6} />
) : (
<> <>
{!isBare && loadError && !categories && ( {!isBare && loadError && !categories && (
<RetryBanner <RetryBanner
@ -86,7 +90,11 @@ export const ShopCategoryPage: React.FC = () => {
) : useMockFallback ? ( ) : useMockFallback ? (
<div className="habib-category-grid"> <div className="habib-category-grid">
{CATEGORY_GRID_TILES.map((tile) => ( {CATEGORY_GRID_TILES.map((tile) => (
<CategoryCard key={tile.id} tile={tile} />
<CategoryCard
key={tile.id}
tile={tile}
slug={isBare ? undefined : tile.slug}
/>
))} ))}
</div> </div>
) : ( ) : (

701
src/pages/catalog/ShopSinglePage.tsx

@ -3,9 +3,9 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell'; import { MobileShell } from '../../components/layout/MobileShell';
import { CompactProductCard } from '../../components/common/CompactProductCard'; import { CompactProductCard } from '../../components/common/CompactProductCard';
import { import {
CompactCarouselShimmer,
EmptyStateBox, EmptyStateBox,
InlineSpinner, InlineSpinner,
ProductDetailBodyShimmer,
RetryBanner, RetryBanner,
ShimmerBox, ShimmerBox,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
@ -179,12 +179,13 @@ export const ShopSinglePage: React.FC = () => {
const storeDetail = liveProduct?.store_detail; const storeDetail = liveProduct?.store_detail;
const storeSlug = storeDetail?.slug || liveProduct?.store_slug || 'al-hujjah-books'; const storeSlug = storeDetail?.slug || liveProduct?.store_slug || 'al-hujjah-books';
const inStock = liveProduct ? liveProduct.stock_qty > 0 : true; const inStock = liveProduct ? liveProduct.stock_qty > 0 : true;
const isProductShimmer = !isBare && loading && !liveProduct;
return ( return (
<MobileShell width={375} height={1233} backgroundColor="#f3f1ef"> <MobileShell width={375} height={1233} backgroundColor="#f3f1ef">
{/* Hero Product Image & Floating Top Controls */} {/* Hero Product Image & Floating Top Controls */}
<div className="habib-single-hero-wrap"> <div className="habib-single-hero-wrap">
{!isBare && loading ? (
{isProductShimmer ? (
<ShimmerBox width="100%" height="100%" borderRadius={0} /> <ShimmerBox width="100%" height="100%" borderRadius={0} />
) : !liveProduct && !useMockFallback ? ( ) : !liveProduct && !useMockFallback ? (
<div style={{ width: '100%', height: '100%', backgroundColor: '#e8e4df' }} /> <div style={{ width: '100%', height: '100%', backgroundColor: '#e8e4df' }} />
@ -288,23 +289,23 @@ export const ShopSinglePage: React.FC = () => {
</div> </div>
{/* Image Carousel Dots */} {/* Image Carousel Dots */}
<img
src="/assets/images/indicator-carousel-dots.svg"
alt=""
style={{
position: 'absolute',
left: '50%',
bottom: 56,
transform: 'translateX(-50%)',
width: 38,
height: 7,
}}
/>
{!isProductShimmer && (
<img
src="/assets/images/indicator-carousel-dots.svg"
alt=""
style={{
position: 'absolute',
left: '50%',
bottom: 56,
transform: 'translateX(-50%)',
width: 38,
height: 7,
}}
/>
)}
</div> </div>
{!isBare && loading ? (
<ProductDetailBodyShimmer />
) : !liveProduct && !useMockFallback ? (
{!isProductShimmer && !liveProduct && !useMockFallback ? (
<div <div
style={{ style={{
position: 'relative', position: 'relative',
@ -360,27 +361,31 @@ export const ShopSinglePage: React.FC = () => {
gap: 8, gap: 8,
}} }}
> >
<div
onClick={() => {
if (liveProduct?.category_slug) {
navigate(ROUTES.category(liveProduct.category_slug));
}
}}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#747474',
minWidth: 0,
cursor: liveProduct?.category_slug ? 'pointer' : undefined,
}}
>
{tr(
liveProduct?.breadcrumb ||
'Leather accessories and supplies / Leather bags'
)}
</div>
{isProductShimmer ? (
<ShimmerBox width="52%" height={12} borderRadius={5} />
) : (
<div
onClick={() => {
if (liveProduct?.category_slug) {
navigate(ROUTES.category(liveProduct.category_slug));
}
}}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#747474',
minWidth: 0,
cursor: liveProduct?.category_slug ? 'pointer' : undefined,
}}
>
{tr(
liveProduct?.breadcrumb ||
'Leather accessories and supplies / Leather bags'
)}
</div>
)}
<div <div
style={{ style={{
@ -472,18 +477,22 @@ export const ShopSinglePage: React.FC = () => {
{/* Product Title & Rating */} {/* Product Title & Rating */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<h1
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '26px',
color: '#111111',
margin: 0,
}}
>
{liveProduct?.title || 'Islam in the Bible Book'}
</h1>
{isProductShimmer ? (
<ShimmerBox width="78%" height={22} borderRadius={7} />
) : (
<h1
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '26px',
color: '#111111',
margin: 0,
}}
>
{liveProduct?.title || 'Islam in the Bible Book'}
</h1>
)}
<div <div
style={{ style={{
@ -501,41 +510,47 @@ export const ShopSinglePage: React.FC = () => {
height: 15, height: 15,
}} }}
/> />
{isProductShimmer ? (
<ShimmerBox width={88} height={14} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '17px',
color: '#3d3d3d',
}}
>
{liveProduct
? Number(
useMockFallback
? liveProduct.rating_avg || 4.4
: liveProduct.rating_avg ?? 0
).toFixed(1)
: '4.4'}
</span>
)}
</div>
{!isProductShimmer && (
<span <span
style={{ style={{
fontFamily: 'var(--font-sans)', fontFamily: 'var(--font-sans)',
fontWeight: 600, fontWeight: 600,
fontSize: 12, fontSize: 12,
lineHeight: '17px', lineHeight: '17px',
color: '#3d3d3d',
color: '#747474',
}} }}
> >
{liveProduct
? Number(
useMockFallback
? liveProduct.rating_avg || 4.4
: liveProduct.rating_avg ?? 0
).toFixed(1)
: '4.4'}
{tr(
isBare
? '0 Reviews'
: `${displayReviews.length} ${
displayReviews.length === 1 ? 'Review' : 'Reviews'
}`
)}
</span> </span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '17px',
color: '#747474',
}}
>
{tr(
isBare
? '0 Reviews'
: `${displayReviews.length} ${
displayReviews.length === 1 ? 'Review' : 'Reviews'
}`
)}
</span>
)}
</div> </div>
</div> </div>
@ -569,38 +584,42 @@ export const ShopSinglePage: React.FC = () => {
> >
{tr('Product Condition')} {tr('Product Condition')}
</div> </div>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
<span
style={{
width: 7,
height: 7,
borderRadius: '50%',
backgroundColor: inStock ? '#0eb13c' : '#d44747',
flexShrink: 0,
}}
/>
<span
{isProductShimmer ? (
<ShimmerBox width="68%" height={14} borderRadius={5} />
) : (
<div
style={{ style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: inStock ? '#0eb13c' : '#d44747',
whiteSpace: 'nowrap',
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}} }}
> >
{tr(
liveProduct?.condition_label ||
(inStock ? 'In Stock' : 'Out of Stock')
)}
</span>
</div>
<span
style={{
width: 7,
height: 7,
borderRadius: '50%',
backgroundColor: inStock ? '#0eb13c' : '#d44747',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: inStock ? '#0eb13c' : '#d44747',
whiteSpace: 'nowrap',
}}
>
{tr(
liveProduct?.condition_label ||
(inStock ? 'In Stock' : 'Out of Stock')
)}
</span>
</div>
)}
</div> </div>
{/* Pill 2: Processing Time -> 2–3 Days */} {/* Pill 2: Processing Time -> 2–3 Days */}
@ -631,18 +650,22 @@ export const ShopSinglePage: React.FC = () => {
> >
{tr('Processing Time')} {tr('Processing Time')}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr(liveProduct?.processing_time_label || '2–3 Days')}
</div>
{isProductShimmer ? (
<ShimmerBox width="68%" height={14} borderRadius={5} />
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr(liveProduct?.processing_time_label || '2–3 Days')}
</div>
)}
</div> </div>
{/* Pill 3: Product Type -> Bag */} {/* Pill 3: Product Type -> Bag */}
@ -673,65 +696,81 @@ export const ShopSinglePage: React.FC = () => {
> >
{tr('Product Type')} {tr('Product Type')}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr(liveProduct?.product_type_label || 'Bag')}
</div>
{isProductShimmer ? (
<ShimmerBox width="68%" height={14} borderRadius={5} />
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 'clamp(11px, 3.2vw, 12px)',
lineHeight: '17px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr(liveProduct?.product_type_label || 'Bag')}
</div>
)}
</div> </div>
</div> </div>
{/* Store Booth Row */} {/* Store Booth Row */}
<div <div
onClick={() => navigate(ROUTES.store(storeSlug))}
onClick={() => {
if (!isProductShimmer) {
navigate(ROUTES.store(storeSlug));
}
}}
style={{ style={{
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'space-between', justifyContent: 'space-between',
gap: 10, gap: 10,
minHeight: 49, minHeight: 49,
cursor: 'pointer',
cursor: isProductShimmer ? 'default' : 'pointer',
}} }}
> >
<div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<img
src={
resolveMediaUrl(storeDetail?.logo_url) ||
'/assets/images/avatar-al-hujjah-books.png'
}
alt={storeDetail?.name || 'Al-Hujjah Books'}
style={{
width: 39,
height: 39,
borderRadius: 108,
objectFit: 'cover',
flexShrink: 0,
}}
/>
{isProductShimmer ? (
<ShimmerBox width={39} height={39} borderRadius="50%" />
) : (
<img
src={
resolveMediaUrl(storeDetail?.logo_url) ||
'/assets/images/avatar-al-hujjah-books.png'
}
alt={storeDetail?.name || 'Al-Hujjah Books'}
style={{
width: 39,
height: 39,
borderRadius: 108,
objectFit: 'cover',
flexShrink: 0,
}}
/>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}> <div style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{storeDetail?.name ||
liveProduct?.store_name ||
(useMockFallback ? 'Al-Hujjah Books' : tr('Store'))}
</span>
{isProductShimmer ? (
<ShimmerBox width={116} height={15} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{storeDetail?.name ||
liveProduct?.store_name ||
(useMockFallback ? 'Al-Hujjah Books' : tr('Store'))}
</span>
)}
<img <img
src="/assets/images/icon-caret-right-gold.svg" src="/assets/images/icon-caret-right-gold.svg"
alt="" alt=""
@ -743,21 +782,25 @@ export const ShopSinglePage: React.FC = () => {
}} }}
/> />
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#8b8b8b',
}}
>
{storeDetail
? [storeDetail.city, storeDetail.country].filter(Boolean).join(', ')
: useMockFallback
? 'Qom, Iran'
: ''}
</div>
{isProductShimmer ? (
<ShimmerBox width={68} height={10} borderRadius={4} />
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#8b8b8b',
}}
>
{storeDetail
? [storeDetail.city, storeDetail.country].filter(Boolean).join(', ')
: useMockFallback
? 'Qom, Iran'
: ''}
</div>
)}
</div> </div>
</div> </div>
@ -780,39 +823,47 @@ export const ShopSinglePage: React.FC = () => {
height: 15, height: 15,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '16px',
color: '#36363c',
}}
>
{storeDetail
? Number(
useMockFallback
? storeDetail.rating_avg || 4.2
: storeDetail.rating_avg ?? 0
).toFixed(1)
: useMockFallback
? '4.2'
: '0.0'}
</span>
{isProductShimmer ? (
<ShimmerBox width={28} height={13} borderRadius={4} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '16px',
color: '#36363c',
}}
>
{storeDetail
? Number(
useMockFallback
? storeDetail.rating_avg || 4.2
: storeDetail.rating_avg ?? 0
).toFixed(1)
: useMockFallback
? '4.2'
: '0.0'}
</span>
)}
</div> </div>
{(storeDetail?.since_label || useMockFallback) && (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
({tr(storeDetail?.since_label || 'Since 2008')})
</div>
{isProductShimmer ? (
<ShimmerBox width={54} height={10} borderRadius={4} />
) : (
(storeDetail?.since_label || useMockFallback) && (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 8.5,
lineHeight: '12.52px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
({tr(storeDetail?.since_label || 'Since 2008')})
</div>
)
)} )}
</div> </div>
</div> </div>
@ -864,7 +915,7 @@ export const ShopSinglePage: React.FC = () => {
transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)', transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)',
}} }}
> >
{tr(`Review(${displayReviews.length})`)}
{isProductShimmer ? tr('Review') : tr(`Review(${displayReviews.length})`)}
</button> </button>
{/* Active Tab Indicator Bar */} {/* Active Tab Indicator Bar */}
@ -920,17 +971,21 @@ export const ShopSinglePage: React.FC = () => {
> >
{tr('Category')} {tr('Category')}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
}}
>
{tr(liveProduct?.category_title || 'Art & Handicrafts')}
</div>
{isProductShimmer ? (
<ShimmerBox width={118} height={14} borderRadius={5} />
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
}}
>
{tr(liveProduct?.category_title || 'Art & Handicrafts')}
</div>
)}
</div> </div>
{/* Introduction block */} {/* Introduction block */}
@ -946,21 +1001,29 @@ export const ShopSinglePage: React.FC = () => {
> >
{tr('Introduction')} {tr('Introduction')}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-line',
}}
>
{liveProduct?.description ||
(useMockFallback
? 'Mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt.\nVelit officia consequat duis enim velit mollit. Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.'
: tr('No description available.'))}
</div>
{isProductShimmer ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<ShimmerBox width="96%" height={13} borderRadius={5} />
<ShimmerBox width="90%" height={13} borderRadius={5} />
<ShimmerBox width="72%" height={13} borderRadius={5} />
</div>
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
whiteSpace: 'pre-line',
}}
>
{liveProduct?.description ||
(useMockFallback
? 'Mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt.\nVelit officia consequat duis enim velit mollit. Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.'
: tr('No description available.'))}
</div>
)}
</div> </div>
</div> </div>
) : ( ) : (
@ -988,7 +1051,9 @@ export const ShopSinglePage: React.FC = () => {
color: '#3d3d3d', color: '#3d3d3d',
}} }}
> >
{tr(`Customer Reviews (${displayReviews.length})`)}
{isProductShimmer
? tr('Customer Reviews')
: tr(`Customer Reviews (${displayReviews.length})`)}
</span> </span>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}> <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img <img
@ -996,23 +1061,27 @@ export const ShopSinglePage: React.FC = () => {
alt="" alt=""
style={{ width: 14, height: 13 }} style={{ width: 14, height: 13 }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#3d3d3d',
}}
>
{liveProduct
? Number(
useMockFallback
? liveProduct.rating_avg || 4.4
: liveProduct.rating_avg ?? 0
).toFixed(1)
: '4.4'}
</span>
{isProductShimmer ? (
<ShimmerBox width={26} height={14} borderRadius={4} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#3d3d3d',
}}
>
{liveProduct
? Number(
useMockFallback
? liveProduct.rating_avg || 4.4
: liveProduct.rating_avg ?? 0
).toFixed(1)
: '4.4'}
</span>
)}
<span <span
style={{ style={{
fontFamily: 'var(--font-sans)', fontFamily: 'var(--font-sans)',
@ -1117,7 +1186,12 @@ export const ShopSinglePage: React.FC = () => {
</form> </form>
)} )}
{displayReviews.length === 0 && !useMockFallback ? (
{isProductShimmer ? (
<>
<ShimmerBox height={78} borderRadius={15} />
<ShimmerBox height={78} borderRadius={15} />
</>
) : displayReviews.length === 0 && !useMockFallback ? (
<EmptyStateBox message="No reviews yet." compact /> <EmptyStateBox message="No reviews yet." compact />
) : ( ) : (
displayReviews.map((review) => ( displayReviews.map((review) => (
@ -1251,7 +1325,7 @@ export const ShopSinglePage: React.FC = () => {
{tr('Populars')} {tr('Populars')}
</div> </div>
<div <div
onClick={() => navigate(ROUTES.search())}
onClick={() => navigate(isBare ? ROUTES.search() : ROUTES.collection('popular'))}
style={{ style={{
display: 'inline-flex', display: 'inline-flex',
alignItems: 'center', alignItems: 'center',
@ -1283,7 +1357,9 @@ export const ShopSinglePage: React.FC = () => {
</div> </div>
</div> </div>
{liveProduct?.related_products?.length ? (
{isProductShimmer ? (
<CompactCarouselShimmer count={3} />
) : liveProduct?.related_products?.length ? (
<div className="habib-carousel-scroller habib-scroll-container"> <div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track"> <div className="habib-carousel-track">
{liveProduct.related_products.map((rel) => ( {liveProduct.related_products.map((rel) => (
@ -1317,6 +1393,7 @@ export const ShopSinglePage: React.FC = () => {
{/* Bottom Sticky Add to Cart Bar */} {/* Bottom Sticky Add to Cart Bar */}
<div <div
className="habib-sticky-bottom-bar"
style={{ style={{
position: 'sticky', position: 'sticky',
bottom: 0, bottom: 0,
@ -1334,63 +1411,67 @@ export const ShopSinglePage: React.FC = () => {
}} }}
> >
{/* Left Price & Discount Badge */} {/* Left Price & Discount Badge */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{(isBare || liveProduct?.formatted_old_price || liveProduct?.discount_badge) && (
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
{(isBare || liveProduct?.formatted_old_price) && (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
textDecoration: 'line-through',
}}
>
{isBare ? '$28.50' : liveProduct?.formatted_old_price}
</span>
)}
{(isBare || liveProduct?.discount_badge) && (
<span
style={{
minWidth: 29,
height: 16,
padding: '0 5px',
borderRadius: 10,
backgroundColor: '#d44747',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#f5f5f5',
}}
>
{isBare ? '20%' : liveProduct?.discount_badge}
</span>
)}
{isProductShimmer ? (
<ShimmerBox width={84} height={24} borderRadius={7} />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{(isBare || liveProduct?.formatted_old_price || liveProduct?.discount_badge) && (
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
{(isBare || liveProduct?.formatted_old_price) && (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#747474',
textDecoration: 'line-through',
}}
>
{isBare ? '$28.50' : liveProduct?.formatted_old_price}
</span>
)}
{(isBare || liveProduct?.discount_badge) && (
<span
style={{
minWidth: 29,
height: 16,
padding: '0 5px',
borderRadius: 10,
backgroundColor: '#d44747',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#f5f5f5',
}}
>
{isBare ? '20%' : liveProduct?.discount_badge}
</span>
)}
</div>
)}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 22,
lineHeight: '26px',
color: '#3d3d3d',
}}
>
{isBare ? '$24.00' : liveProduct?.formatted_price || '$24.00'}
</div> </div>
)}
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 22,
lineHeight: '26px',
color: '#3d3d3d',
}}
>
{isBare ? '$24.00' : liveProduct?.formatted_price || '$24.00'}
</div> </div>
</div>
)}
{/* Add to Cart Button */} {/* Add to Cart Button */}
<button <button
type="button" type="button"
disabled={isCartBusy || !inStock}
disabled={isProductShimmer || isCartBusy || !inStock}
className="habib-cta-btn" className="habib-cta-btn"
onClick={() => { onClick={() => {
void handleAddToCart(); void handleAddToCart();
@ -1402,8 +1483,8 @@ export const ShopSinglePage: React.FC = () => {
padding: '0 14px', padding: '0 14px',
borderRadius: 11, borderRadius: 11,
border: 'none', border: 'none',
cursor: isCartBusy || !inStock ? 'not-allowed' : 'pointer',
opacity: isCartBusy || !inStock ? 0.65 : 1,
cursor: isProductShimmer || isCartBusy || !inStock ? 'not-allowed' : 'pointer',
opacity: isProductShimmer || isCartBusy || !inStock ? 0.65 : 1,
display: 'inline-flex', display: 'inline-flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center', justifyContent: 'center',
@ -1434,7 +1515,11 @@ export const ShopSinglePage: React.FC = () => {
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
}} }}
> >
{isCartBusy ? tr('Adding...') : inStock ? tr('Add to Cart') : tr('Sold Out')}
{isCartBusy
? tr('Adding...')
: isProductShimmer || inStock
? tr('Add to Cart')
: tr('Sold Out')}
</span> </span>
</button> </button>
</div> </div>

256
src/pages/chat/ShopChatPage.tsx

@ -5,6 +5,7 @@ import {
ChatThreadShimmer, ChatThreadShimmer,
EmptyStateBox, EmptyStateBox,
InlineSpinner, InlineSpinner,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler';
@ -15,23 +16,30 @@ import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import { import {
type ApiChatMessage, type ApiChatMessage,
type ApiConversation, type ApiConversation,
type ApiStoreSummary,
shopApi, shopApi,
} from '../../lib/shopApi'; } from '../../lib/shopApi';
import { import {
isInFlutterWebView, isInFlutterWebView,
uploadBrowserFileToTmpMedia,
uploadFileViaFlutterBridge,
pickFileViaFlutterBridge,
} from '../../lib/webview-actions'; } from '../../lib/webview-actions';
const MAX_CHAT_ATTACHMENT_BYTES = 10 * 1024 * 1024;
interface FailedOutgoingDraft { interface FailedOutgoingDraft {
tempId: string; tempId: string;
text: string; text: string;
attachmentFile?: File;
attachmentUrl?: string; attachmentUrl?: string;
attachmentKind?: 'image' | 'audio';
isObjectUrl?: boolean;
timeLabel: string; timeLabel: string;
} }
interface StagedAttachment { interface StagedAttachment {
url: string; url: string;
file?: File;
isObjectUrl?: boolean;
kind: 'image' | 'audio'; kind: 'image' | 'audio';
label: string; label: string;
durationSec?: number; durationSec?: number;
@ -236,7 +244,7 @@ export const ShopChatPage: React.FC = () => {
const { conversationId } = useParams<{ conversationId?: string }>(); const { conversationId } = useParams<{ conversationId?: string }>();
const resolvedConvRef = conversationId || 'al-hujjah-books'; const resolvedConvRef = conversationId || 'al-hujjah-books';
const smartBack = useSmartBack(ROUTES.store(resolvedConvRef)); const smartBack = useSmartBack(ROUTES.store(resolvedConvRef));
const { showToast, language } = useShopApp();
const { isUserAuthenticated, requireAuth, showToast, language } = useShopApp();
const isRtl = isRtlLanguage(language); const isRtl = isRtlLanguage(language);
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
@ -247,8 +255,11 @@ export const ShopChatPage: React.FC = () => {
const [isRecording, setIsRecording] = useState(false); const [isRecording, setIsRecording] = useState(false);
const [recordingSeconds, setRecordingSeconds] = useState(0); const [recordingSeconds, setRecordingSeconds] = useState(0);
const [conversation, setConversation] = useState<ApiConversation | null>(null); const [conversation, setConversation] = useState<ApiConversation | null>(null);
const [publicStore, setPublicStore] = useState<ApiStoreSummary | null>(null);
const [messages, setMessages] = useState<ApiChatMessage[]>([]); const [messages, setMessages] = useState<ApiChatMessage[]>([]);
const [loadingInitial, setLoadingInitial] = useState<boolean>(() => !isBare);
const [loadingInitial, setLoadingInitial] = useState<boolean>(
() => !isBare && isUserAuthenticated
);
const [failedDrafts, setFailedDrafts] = useState<FailedOutgoingDraft[]>([]); const [failedDrafts, setFailedDrafts] = useState<FailedOutgoingDraft[]>([]);
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
@ -313,6 +324,18 @@ export const ShopChatPage: React.FC = () => {
return true; return true;
}, menuOpen); }, menuOpen);
const replaceStagedAttachment = useCallback(
(next: StagedAttachment | null) => {
setStagedAttachment((prev) => {
if (prev?.isObjectUrl && prev.url && prev.url !== next?.url) {
URL.revokeObjectURL(prev.url);
}
return next;
});
},
[]
);
useEffect(() => { useEffect(() => {
if (isBare) { if (isBare) {
setLoadingInitial(false); setLoadingInitial(false);
@ -320,6 +343,24 @@ export const ShopChatPage: React.FC = () => {
} }
let cancelled = false; let cancelled = false;
lastIdRef.current = undefined; lastIdRef.current = undefined;
if (!isUserAuthenticated) {
setConversation(null);
setMessages([]);
setLoadingInitial(false);
void shopApi
.fetchStoreDetail(resolvedConvRef)
.then((store) => {
if (!cancelled) setPublicStore(store);
})
.catch(() => {
// ignore if conv ref is not a store slug
});
return () => {
cancelled = true;
};
}
setLoadingInitial(true); setLoadingInitial(true);
const loadInitial = async () => { const loadInitial = async () => {
@ -370,7 +411,7 @@ export const ShopChatPage: React.FC = () => {
cancelled = true; cancelled = true;
window.clearInterval(interval); window.clearInterval(interval);
}; };
}, [isBare, resolvedConvRef]);
}, [isBare, isUserAuthenticated, resolvedConvRef]);
useEffect(() => { useEffect(() => {
if (!isBare) { if (!isBare) {
@ -379,18 +420,34 @@ export const ShopChatPage: React.FC = () => {
}, [isBare, messages.length, failedDrafts.length]); }, [isBare, messages.length, failedDrafts.length]);
const dispatchMessage = useCallback( const dispatchMessage = useCallback(
async (text: string, attachmentUrl?: string, retryId?: string) => {
if ((!text.trim() && !attachmentUrl) || sending) return;
async (
text: string,
attachment?: {
file?: File;
url?: string;
kind?: 'image' | 'audio';
isObjectUrl?: boolean;
},
retryId?: string
) => {
const hasAttachment = Boolean(attachment?.file || attachment?.url);
if ((!text.trim() && !hasAttachment) || sending) return;
if (isBare) { if (isBare) {
setMessageText(''); setMessageText('');
return; return;
} }
if (!isUserAuthenticated) {
const authed = await requireAuth({ featureName: 'store chat' });
if (!authed) return;
}
setSending(true); setSending(true);
try { try {
const res = await shopApi.sendChatMessage(resolvedConvRef, { const res = await shopApi.sendChatMessage(resolvedConvRef, {
text: text.trim(), text: text.trim(),
attachment_url: attachmentUrl,
attachment: attachment?.file,
attachment_url: attachment?.file ? undefined : attachment?.url,
}); });
if (res.conversation) setConversation(res.conversation); if (res.conversation) setConversation(res.conversation);
const incomingBatch = const incomingBatch =
@ -406,10 +463,13 @@ export const ShopChatPage: React.FC = () => {
} }
return merged; return merged;
}); });
if (attachment?.isObjectUrl && attachment.url) {
URL.revokeObjectURL(attachment.url);
}
if (retryId) { if (retryId) {
setFailedDrafts((prev) => prev.filter((d) => d.tempId !== retryId)); setFailedDrafts((prev) => prev.filter((d) => d.tempId !== retryId));
} }
} catch {
} catch (err) {
const now = new Date(); const now = new Date();
const hh = String(now.getHours()).padStart(2, '0'); const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0'); const mm = String(now.getMinutes()).padStart(2, '0');
@ -419,42 +479,77 @@ export const ShopChatPage: React.FC = () => {
{ {
tempId: `failed-${Date.now()}`, tempId: `failed-${Date.now()}`,
text: text.trim(), text: text.trim(),
attachmentUrl,
attachmentFile: attachment?.file,
attachmentUrl: attachment?.url,
attachmentKind: attachment?.kind,
isObjectUrl: attachment?.isObjectUrl,
timeLabel: `${hh}:${mm}`, timeLabel: `${hh}:${mm}`,
}, },
]); ]);
} }
showToast('Message could not be sent — tap Try Again');
showToast(
err instanceof Error && err.message
? err.message
: 'Message could not be sent — tap Try Again'
);
} finally { } finally {
setSending(false); setSending(false);
} }
}, },
[isBare, resolvedConvRef, sending, showToast]
[isBare, isUserAuthenticated, requireAuth, resolvedConvRef, sending, showToast]
); );
const handleSendText = async () => { const handleSendText = async () => {
const trimmed = messageText.trim(); const trimmed = messageText.trim();
const attachmentToSend = stagedAttachment; const attachmentToSend = stagedAttachment;
if (!trimmed && !attachmentToSend) return; if (!trimmed && !attachmentToSend) return;
if (!isBare && !isUserAuthenticated) {
const authed = await requireAuth({ featureName: 'store chat' });
if (!authed) return;
}
setMessageText(''); setMessageText('');
setStagedAttachment(null); setStagedAttachment(null);
const outgoingText = const outgoingText =
trimmed || trimmed ||
(attachmentToSend?.kind === 'audio' ? 'Voice message' : ''); (attachmentToSend?.kind === 'audio' ? 'Voice message' : '');
void dispatchMessage(outgoingText, attachmentToSend?.url);
void dispatchMessage(
outgoingText,
attachmentToSend
? {
file: attachmentToSend.file,
url: attachmentToSend.url,
kind: attachmentToSend.kind,
isObjectUrl: attachmentToSend.isObjectUrl,
}
: undefined
);
}; };
const handleAttachmentClick = async () => { const handleAttachmentClick = async () => {
if (isBare || attachingMedia) return; if (isBare || attachingMedia) return;
if (!isUserAuthenticated) {
const authed = await requireAuth({ featureName: 'store chat' });
if (!authed) return;
}
if (isInFlutterWebView()) { if (isInFlutterWebView()) {
setAttachingMedia(true); setAttachingMedia(true);
try { try {
const uploadedUrl = await uploadFileViaFlutterBridge('image');
if (uploadedUrl) {
setStagedAttachment({
url: uploadedUrl,
kind: isAudioAttachmentUrl(uploadedUrl) ? 'audio' : 'image',
label: 'Attached image',
const picked = await pickFileViaFlutterBridge('image');
if (picked) {
if (picked.file && picked.file.size > MAX_CHAT_ATTACHMENT_BYTES) {
if (picked.isObjectUrl) URL.revokeObjectURL(picked.url);
showToast('Attachment exceeds the 10 MB size limit');
return;
}
const isAudio =
picked.file?.type.startsWith('audio/') ||
isAudioAttachmentUrl(picked.url);
replaceStagedAttachment({
url: picked.url,
file: picked.file,
isObjectUrl: picked.isObjectUrl,
kind: isAudio ? 'audio' : 'image',
label: picked.name || 'Attached image',
}); });
} }
} finally { } finally {
@ -465,29 +560,33 @@ export const ShopChatPage: React.FC = () => {
fileInputRef.current?.click(); fileInputRef.current?.click();
}; };
const handleFileInputChange = async (
const handleFileInputChange = (
e: React.ChangeEvent<HTMLInputElement> e: React.ChangeEvent<HTMLInputElement>
) => { ) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
e.target.value = ''; e.target.value = '';
setAttachingMedia(true);
try {
const url = await uploadBrowserFileToTmpMedia(file);
const isAudio =
file.type.startsWith('audio/') || isAudioAttachmentUrl(url);
setStagedAttachment({
url,
kind: isAudio ? 'audio' : 'image',
label: file.name || (isAudio ? 'Voice message' : 'Attached image'),
});
} finally {
setAttachingMedia(false);
if (file.size > MAX_CHAT_ATTACHMENT_BYTES) {
showToast('Attachment exceeds the 10 MB size limit');
return;
} }
const previewUrl = URL.createObjectURL(file);
const isAudio = file.type.startsWith('audio/');
replaceStagedAttachment({
url: previewUrl,
file,
isObjectUrl: true,
kind: isAudio ? 'audio' : 'image',
label: file.name || (isAudio ? 'Voice message' : 'Attached image'),
});
}; };
const handleStartRecording = async () => { const handleStartRecording = async () => {
if (isBare || isRecording || sending) return; if (isBare || isRecording || sending) return;
if (!isUserAuthenticated) {
const authed = await requireAuth({ featureName: 'store chat' });
if (!authed) return;
}
recordedChunksRef.current = []; recordedChunksRef.current = [];
recordingStartMsRef.current = Date.now(); recordingStartMsRef.current = Date.now();
@ -570,41 +669,45 @@ export const ShopChatPage: React.FC = () => {
setAttachingMedia(true); setAttachingMedia(true);
try { try {
let audioUrl = '';
let audioFile: File | null = null;
if (recordedChunksRef.current.length > 0) { if (recordedChunksRef.current.length > 0) {
const mimeType = recorder?.mimeType || 'audio/webm';
const ext = mimeType.includes('mp4')
const rawMime = recorder?.mimeType || 'audio/webm';
const cleanMime = rawMime.split(';', 1)[0].trim() || 'audio/webm';
const ext = cleanMime.includes('mp4')
? 'm4a' ? 'm4a'
: mimeType.includes('ogg')
: cleanMime.includes('ogg')
? 'ogg' ? 'ogg'
: mimeType.includes('wav')
: cleanMime.includes('wav')
? 'wav' ? 'wav'
: 'webm'; : 'webm';
const blob = new Blob(recordedChunksRef.current, { type: mimeType });
const blob = new Blob(recordedChunksRef.current, { type: cleanMime });
if (blob.size > 100) { if (blob.size > 100) {
const file = new File([blob], `voice-${Date.now()}.${ext}`, {
type: mimeType,
audioFile = new File([blob], `voice-${Date.now()}.${ext}`, {
type: cleanMime,
}); });
audioUrl = await uploadBrowserFileToTmpMedia(file);
} }
} }
if (!audioUrl) {
const synth = createSynthesizedVoiceWav(elapsedSec);
audioUrl = await uploadBrowserFileToTmpMedia(
synth.file,
synth.dataUrl
);
if (!audioFile) {
audioFile = createSynthesizedVoiceWav(elapsedSec).file;
} }
recordedChunksRef.current = []; recordedChunksRef.current = [];
const durationLabel = formatDurationMmSs(elapsedSec); const durationLabel = formatDurationMmSs(elapsedSec);
const previewUrl = URL.createObjectURL(audioFile);
if (sendImmediately) { if (sendImmediately) {
await dispatchMessage(`Voice message (${durationLabel})`, audioUrl);
await dispatchMessage(`Voice message (${durationLabel})`, {
file: audioFile,
url: previewUrl,
kind: 'audio',
isObjectUrl: true,
});
} else { } else {
setStagedAttachment({
url: audioUrl,
replaceStagedAttachment({
url: previewUrl,
file: audioFile,
isObjectUrl: true,
kind: 'audio', kind: 'audio',
label: `Voice message (${durationLabel})`, label: `Voice message (${durationLabel})`,
durationSec: elapsedSec, durationSec: elapsedSec,
@ -615,7 +718,7 @@ export const ShopChatPage: React.FC = () => {
} }
}; };
const storeDetail = conversation?.store_detail;
const storeDetail = conversation?.store_detail ?? publicStore;
const fallbackStoreName = resolvedConvRef const fallbackStoreName = resolvedConvRef
.replace(/-/g, ' ') .replace(/-/g, ' ')
.replace(/\b\w/g, (ch) => ch.toUpperCase()); .replace(/\b\w/g, (ch) => ch.toUpperCase());
@ -718,19 +821,28 @@ export const ShopChatPage: React.FC = () => {
> >
{storeTitle} {storeTitle}
</div> </div>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#8b8b8b',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(storeLocation)}
</div>
{!isBare && loadingInitial && !storeDetail ? (
<ShimmerBox
width={72}
height={11}
borderRadius={4}
style={{ marginTop: 2 }}
/>
) : (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#8b8b8b',
textAlign: 'center',
whiteSpace: 'nowrap',
}}
>
{tr(storeLocation)}
</div>
)}
</div> </div>
{/* Right 3-Dots Menu Button */} {/* Right 3-Dots Menu Button */}
@ -927,7 +1039,7 @@ export const ShopChatPage: React.FC = () => {
padding: '24px var(--page-px) 16px', padding: '24px var(--page-px) 16px',
}} }}
> >
{!isBare && loadingInitial ? (
{!isBare && loadingInitial && messages.length === 0 ? (
<ChatThreadShimmer /> <ChatThreadShimmer />
) : !isBare && ) : !isBare &&
(messages.length > 0 || (!useMockFallback && failedDrafts.length > 0)) ? ( (messages.length > 0 || (!useMockFallback && failedDrafts.length > 0)) ? (
@ -1108,7 +1220,14 @@ export const ShopChatPage: React.FC = () => {
onClick={() => { onClick={() => {
void dispatchMessage( void dispatchMessage(
draft.text, draft.text,
draft.attachmentUrl,
draft.attachmentFile || draft.attachmentUrl
? {
file: draft.attachmentFile,
url: draft.attachmentUrl,
kind: draft.attachmentKind,
isObjectUrl: draft.isObjectUrl,
}
: undefined,
draft.tempId draft.tempId
); );
}} }}
@ -1154,7 +1273,8 @@ export const ShopChatPage: React.FC = () => {
}} }}
> >
{draft.attachmentUrl && {draft.attachmentUrl &&
(isAudioAttachmentUrl(draft.attachmentUrl) ? (
(draft.attachmentKind === 'audio' ||
isAudioAttachmentUrl(draft.attachmentUrl) ? (
<VoiceMessagePlayer <VoiceMessagePlayer
src={resolveMediaUrl(draft.attachmentUrl)} src={resolveMediaUrl(draft.attachmentUrl)}
isCustomer isCustomer
@ -1675,7 +1795,7 @@ export const ShopChatPage: React.FC = () => {
<button <button
type="button" type="button"
aria-label="Remove attachment" aria-label="Remove attachment"
onClick={() => setStagedAttachment(null)}
onClick={() => replaceStagedAttachment(null)}
style={{ style={{
width: 24, width: 24,
height: 24, height: 24,

17
src/pages/checkout/ShopBuy01Page.tsx

@ -4,7 +4,10 @@ import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader'; import { StandardPageHeader } from '../../components/layout/TopHeader';
import { StickyFooterBar } from '../../components/layout/StickyFooterBar'; import { StickyFooterBar } from '../../components/layout/StickyFooterBar';
import { AddressCard, AddNewAddressCard } from '../../components/checkout/AddressCard'; import { AddressCard, AddNewAddressCard } from '../../components/checkout/AddressCard';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import {
EmptyStateBox,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import { AddressFormSheet } from '../../components/modals/AddressFormSheet'; import { AddressFormSheet } from '../../components/modals/AddressFormSheet';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { BUY01_ADDRESSES } from '../../data/checkoutData'; import { BUY01_ADDRESSES } from '../../data/checkoutData';
@ -27,14 +30,17 @@ export const ShopBuy01Page: React.FC = () => {
isUserAuthenticated, isUserAuthenticated,
requireAuth, requireAuth,
addresses, addresses,
isAddressesLoading,
selectedAddress, selectedAddress,
selectedAddressId, selectedAddressId,
selectAddress, selectAddress,
saveAddress, saveAddress,
shippingMethods, shippingMethods,
isShippingMethodsLoading,
selectedShippingMethod, selectedShippingMethod,
selectShippingMethod, selectShippingMethod,
cart, cart,
isCartLoading,
showToast, showToast,
} = useShopApp(); } = useShopApp();
@ -147,6 +153,8 @@ export const ShopBuy01Page: React.FC = () => {
onSelect={() => setBareSelectedId(address.id)} onSelect={() => setBareSelectedId(address.id)}
/> />
)) ))
) : isAddressesLoading && liveAddressOptions.length === 0 ? (
<ShimmerBox height={86} borderRadius={15} />
) : liveAddressOptions.length > 0 ? ( ) : liveAddressOptions.length > 0 ? (
liveAddressOptions.map((option, idx) => ( liveAddressOptions.map((option, idx) => (
<AddressCard <AddressCard
@ -202,7 +210,11 @@ export const ShopBuy01Page: React.FC = () => {
</span> </span>
</div> </div>
{!isBare && shippingMethods.length > 0 ? (
{!isBare &&
isShippingMethodsLoading &&
shippingMethods.length === 0 ? (
<ShimmerBox height={58} borderRadius={15} />
) : !isBare && shippingMethods.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{shippingMethods.map((method) => { {shippingMethods.map((method) => {
const isSelected = selectedShippingMethod?.code === method.code; const isSelected = selectedShippingMethod?.code === method.code;
@ -446,6 +458,7 @@ export const ShopBuy01Page: React.FC = () => {
<StickyFooterBar <StickyFooterBar
height={90} height={90}
price={computedTotalText} price={computedTotalText}
loadingPrice={!isBare && isCartLoading && !cart?.pricing}
topLabel="Total Cost" topLabel="Total Cost"
buttonText="Continue" buttonText="Continue"
buttonFontWeight={700} buttonFontWeight={700}

25
src/pages/checkout/ShopCartPage.tsx

@ -5,7 +5,11 @@ import { BottomNavBar } from '../../components/layout/BottomNavBar';
import { StickyFooterBar } from '../../components/layout/StickyFooterBar'; import { StickyFooterBar } from '../../components/layout/StickyFooterBar';
import { MainCartItemCard } from '../../components/checkout/CartItemCard'; import { MainCartItemCard } from '../../components/checkout/CartItemCard';
import type { SummaryLineRow } from '../../components/checkout/OrderSummaryRows'; import type { SummaryLineRow } from '../../components/checkout/OrderSummaryRows';
import { InlineSpinner } from '../../components/common/ShimmerSkeletons';
import {
CartItemsShimmer,
InlineSpinner,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import { OrderSummarySheet } from '../../components/modals/OrderSummarySheet'; import { OrderSummarySheet } from '../../components/modals/OrderSummarySheet';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { CART_ITEMS_MAIN, type CartItemData } from '../../data/checkoutData'; import { CART_ITEMS_MAIN, type CartItemData } from '../../data/checkoutData';
@ -40,7 +44,7 @@ export const ShopCartPage: React.FC = () => {
const useMockFallback = isBare || USE_MOCK_DATA; const useMockFallback = isBare || USE_MOCK_DATA;
const { const {
hydrated,
isCartLoading,
requireAuth, requireAuth,
cart, cart,
isCartBusy, isCartBusy,
@ -77,6 +81,7 @@ export const ShopCartPage: React.FC = () => {
); );
const useFigmaSnapshot = isBare && !hasInteractedBare; const useFigmaSnapshot = isBare && !hasInteractedBare;
const isCartShimmer = !isBare && isCartLoading && !cart;
const hasAnyItems = isBare ? bareItems.length > 0 : liveItems.length > 0; const hasAnyItems = isBare ? bareItems.length > 0 : liveItems.length > 0;
@ -191,11 +196,15 @@ export const ShopCartPage: React.FC = () => {
color: '#292a2e', color: '#292a2e',
}} }}
> >
<span>{tr(topInfoText)}</span>
{isCartShimmer ? (
<ShimmerBox width={108} height={14} borderRadius={5} />
) : (
<span>{tr(topInfoText)}</span>
)}
{!isBare && isCartBusy && <InlineSpinner size={12} gold />} {!isBare && isCartBusy && <InlineSpinner size={12} gold />}
</div> </div>
{(hasAnyItems || useMockFallback) && (
{!isCartShimmer && (hasAnyItems || useMockFallback) && (
<div <div
onClick={() => { onClick={() => {
if (!isCartBusy) { if (!isCartBusy) {
@ -222,7 +231,9 @@ export const ShopCartPage: React.FC = () => {
</div> </div>
{/* Cart Item Cards */} {/* Cart Item Cards */}
{!isBare && !hydrated ? null : hasAnyItems ? (
{isCartShimmer ? (
<CartItemsShimmer count={2} />
) : hasAnyItems ? (
<div <div
style={{ style={{
display: 'flex', display: 'flex',
@ -398,6 +409,8 @@ export const ShopCartPage: React.FC = () => {
price={footerPrice} price={footerPrice}
oldPrice={footerOldPrice} oldPrice={footerOldPrice}
totalItemsLabel={footerTotalItemsLabel} totalItemsLabel={footerTotalItemsLabel}
loadingTopMeta={isCartShimmer}
loadingPrice={isCartShimmer}
onTotalItemsClick={() => setIsSummaryOpen(true)} onTotalItemsClick={() => setIsSummaryOpen(true)}
buttonText="checkout" buttonText="checkout"
buttonFontWeight={700} buttonFontWeight={700}
@ -413,7 +426,7 @@ export const ShopCartPage: React.FC = () => {
onAuthenticated: () => navigate(ROUTES.checkoutShipping), onAuthenticated: () => navigate(ROUTES.checkoutShipping),
}); });
}} }}
disabled={!hasAnyItems || isCartBusy}
disabled={isCartShimmer || !hasAnyItems || isCartBusy}
/> />
<BottomNavBar <BottomNavBar

50
src/pages/checkout/ShopPayResultPage.tsx

@ -228,32 +228,36 @@ export const ShopPayResultPage: React.FC = () => {
</span> </span>
</div> </div>
<div
style={{
padding: '0 6px',
height: 19,
borderRadius: 3,
border: '1px solid #000000',
boxSizing: 'border-box',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<span
{!isBare && loading && !receipt && !orderId ? (
<ShimmerBox width={76} height={19} borderRadius={3} />
) : (
<div
style={{ style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
whiteSpace: 'nowrap',
padding: '0 6px',
height: 19,
borderRadius: 3,
border: '1px solid #000000',
boxSizing: 'border-box',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}} }}
> >
{isBare ? 'ORD-28465' : activeOrderCode}
</span>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
whiteSpace: 'nowrap',
}}
>
{isBare ? 'ORD-28465' : activeOrderCode}
</span>
</div>
)}
</div> </div>
{/* Row 2: Payment method */} {/* Row 2: Payment method */}

34
src/pages/checkout/ShopPaymentPage.tsx

@ -8,7 +8,10 @@ import {
OrderSummaryRows, OrderSummaryRows,
type SummaryLineRow, type SummaryLineRow,
} from '../../components/checkout/OrderSummaryRows'; } from '../../components/checkout/OrderSummaryRows';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import {
EmptyStateBox,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import { PaymentMethodsSheet } from '../../components/modals/PaymentMethodsSheet'; import { PaymentMethodsSheet } from '../../components/modals/PaymentMethodsSheet';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { import {
@ -39,8 +42,11 @@ export const ShopPaymentPage: React.FC = () => {
isUserAuthenticated, isUserAuthenticated,
requireAuth, requireAuth,
cart, cart,
isCartLoading,
selectedAddress, selectedAddress,
isAddressesLoading,
selectedShippingMethod, selectedShippingMethod,
isShippingMethodsLoading,
selectedPaymentMethod, selectedPaymentMethod,
setSelectedPaymentMethod, setSelectedPaymentMethod,
showToast, showToast,
@ -208,7 +214,12 @@ export const ShopPaymentPage: React.FC = () => {
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{!isBare && cart?.items?.length ? (
{!isBare && isCartLoading && !cart?.items?.length ? (
<>
<ShimmerBox height={76} borderRadius={15} />
<ShimmerBox height={76} borderRadius={15} />
</>
) : !isBare && cart?.items?.length ? (
cart.items.map((item, idx) => ( cart.items.map((item, idx) => (
<ReviewItemCard <ReviewItemCard
key={item.id} key={item.id}
@ -275,7 +286,9 @@ export const ShopPaymentPage: React.FC = () => {
</div> </div>
{/* Read-only Address Card */} {/* Read-only Address Card */}
{!isBare && !selectedAddress && !useMockFallback ? (
{!isBare && isAddressesLoading && !selectedAddress ? (
<ShimmerBox height={74} borderRadius={15} />
) : !isBare && !selectedAddress && !useMockFallback ? (
<EmptyStateBox message="No delivery address selected." compact /> <EmptyStateBox message="No delivery address selected." compact />
) : ( ) : (
<div <div
@ -383,6 +396,11 @@ export const ShopPaymentPage: React.FC = () => {
<OrderSummaryRows <OrderSummaryRows
rows={rows} rows={rows}
totalText={isBare ? '$70.50' : totalText} totalText={isBare ? '$70.50' : totalText}
loading={
!isBare &&
(isCartLoading || isShippingMethodsLoading) &&
!livePricing
}
/> />
</div> </div>
</section> </section>
@ -392,12 +410,15 @@ export const ShopPaymentPage: React.FC = () => {
<StickyFooterBar <StickyFooterBar
height={90} height={90}
price={isBare ? '$24.00' : totalText} price={isBare ? '$24.00' : totalText}
loadingPrice={!isBare && isCartLoading && !livePricing}
topLabel="Total Cost" topLabel="Total Cost"
buttonText="Payment" buttonText="Payment"
buttonFontWeight={700} buttonFontWeight={700}
iconSrc="/assets/images/icon-credit-card-white.svg" iconSrc="/assets/images/icon-credit-card-white.svg"
targetRoute={ROUTES.checkoutReview} targetRoute={ROUTES.checkoutReview}
disabled={!isBare && (!cart?.items || cart.items.length === 0)}
disabled={
!isBare && (isCartLoading || !cart?.items || cart.items.length === 0)
}
onButtonClick={() => { onButtonClick={() => {
if (isBare) { if (isBare) {
setPaymentSheetOpen(true); setPaymentSheetOpen(true);
@ -421,6 +442,11 @@ export const ShopPaymentPage: React.FC = () => {
void handleConfirmPurchase(); void handleConfirmPurchase();
}} }}
isSubmitting={submitting} isSubmitting={submitting}
isLoading={
!isBare &&
paymentMethodsQuery.isPending &&
!paymentMethodsData?.results?.length
}
/> />
</MobileShell> </MobileShell>
); );

371
src/pages/home/ShopHomePage.tsx

@ -6,6 +6,7 @@ import { SearchBar } from '../../components/common/SearchBar';
import { CompactProductCard } from '../../components/common/CompactProductCard'; import { CompactProductCard } from '../../components/common/CompactProductCard';
import { import {
EmptyStateBox, EmptyStateBox,
HomeFeedShimmer,
RetryBanner, RetryBanner,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
import { import {
@ -121,7 +122,7 @@ export const ShopHomePage: React.FC = () => {
cat.id === 'cat-more' cat.id === 'cat-more'
? ROUTES.categories ? ROUTES.categories
: cat.id === 'cat-bag' : cat.id === 'cat-bag'
? ROUTES.category('bag')
? ROUTES.category('bags')
: cat.id === 'cat-beauty' : cat.id === 'cat-beauty'
? ROUTES.category('beauty') ? ROUTES.category('beauty')
: cat.id === 'cat-art' : cat.id === 'cat-art'
@ -262,15 +263,7 @@ export const ShopHomePage: React.FC = () => {
); );
}; };
const livePopulars = !isBare && feed?.popular_products?.length ? feed.popular_products : null;
const liveNewStores =
!isBare && feed?.new_store_products?.length ? feed.new_store_products : null;
const featuredStoreRoute =
!isBare && feed?.featured_stores?.[0]?.slug
? ROUTES.store(feed.featured_stores[0].slug)
: useMockFallback
? ROUTES.store('tashakol-farzandan-rohhallah')
: ROUTES.search();
const liveCollections = !isBare && feed?.collections ? feed.collections : null;
return ( return (
<MobileShell width={375} height={1074} backgroundColor="#f3f1ef"> <MobileShell width={375} height={1074} backgroundColor="#f3f1ef">
@ -450,7 +443,9 @@ export const ShopHomePage: React.FC = () => {
onSubmit={(q) => navigate(ROUTES.search(q))} onSubmit={(q) => navigate(ROUTES.search(q))}
/> />
{!isBare && loading && !feed ? null : (
{!isBare && loading && !feed ? (
<HomeFeedShimmer />
) : (
<> <>
{!isBare && loadError && !feed && ( {!isBare && loadError && !feed && (
<RetryBanner <RetryBanner
@ -726,176 +721,220 @@ export const ShopHomePage: React.FC = () => {
</div> </div>
)} )}
{/* Populars Section */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#36363c',
}}
>
{tr('Populars')}
</div>
<div
onClick={() => navigate(ROUTES.search())}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
cursor: 'pointer',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
{/* Dynamic Collections Sections (Populars, New Products, & any added collections) */}
{liveCollections ? (
liveCollections.map((collection) => {
const colProducts = collection.products ?? [];
const colTitle = collection.localized_title || collection.title;
return (
<section
key={collection.id || collection.slug}
style={{ display: 'flex', flexDirection: 'column', gap: 10 }}
> >
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#36363c',
}}
>
{colTitle}
</div>
<div
onClick={() => navigate(ROUTES.collection(collection.slug))}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
cursor: 'pointer',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
}}
/>
</div>
</div>
{colProducts.length > 0 ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{colProducts.map((prod) => (
<CompactProductCard
key={prod.id}
item={mapProductToCompactItem(
prod,
isBookmarked(prod.id, prod.slug)
)}
slugOrId={prod.slug}
onToggleBookmark={() => {
void toggleBookmark(prod.slug, prod.id, prod.slug);
}}
/>
))}
</div>
</div>
) : (
<EmptyStateBox message="No products in this collection yet." compact />
)}
</section>
);
})
) : useMockFallback ? (
<>
{/* Populars Section (Mock / ?bare=1 Fallback) */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{ style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}} }}
/>
</div>
</div>
{livePopulars ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{livePopulars.map((prod) => (
<CompactProductCard
key={prod.id}
item={mapProductToCompactItem(
prod,
isBookmarked(prod.id, prod.slug)
)}
slugOrId={prod.slug}
onToggleBookmark={() => {
void toggleBookmark(prod.slug, prod.id, prod.slug);
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#36363c',
}}
>
{tr('Populars')}
</div>
<div
onClick={() => navigate(ROUTES.search())}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
cursor: 'pointer',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
}} }}
/> />
))}
</div>
</div> </div>
</div>
) : useMockFallback ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_POPULAR_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_POPULAR_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
</div>
</div> </div>
</div>
) : (
<EmptyStateBox message="No popular products yet." compact />
)}
</section>
</section>
{/* New Stores Section */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}}
>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#36363c',
whiteSpace: 'nowrap',
}}
>
{tr('New Stores')}
</div>
<div
onClick={() => navigate(featuredStoreRoute)}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
cursor: 'pointer',
}}
>
<span
{/* New Stores Section (Mock / ?bare=1 Fallback) */}
<section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
style={{ style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 2px',
}} }}
> >
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
}}
/>
</div>
</div>
{liveNewStores ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{liveNewStores.map((prod) => (
<CompactProductCard
key={prod.id}
item={mapProductToCompactItem(
prod,
isBookmarked(prod.id, prod.slug)
)}
slugOrId={prod.slug}
onToggleBookmark={() => {
void toggleBookmark(prod.slug, prod.id, prod.slug);
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '19px',
color: '#36363c',
whiteSpace: 'nowrap',
}}
>
{tr('New Stores')}
</div>
<div
onClick={() => navigate(ROUTES.store('tashakol-farzandan-rohhallah'))}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
cursor: 'pointer',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{tr('See more')}
</span>
<img
src="/assets/images/icon-arrow-right-circle-grey.svg"
alt=""
style={{
width: 13,
height: 13,
transform: isRtl ? 'scaleX(-1)' : undefined,
}} }}
/> />
))}
</div>
</div> </div>
</div>
) : useMockFallback ? (
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_NEW_STORES_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
<div className="habib-carousel-scroller habib-scroll-container">
<div className="habib-carousel-track">
{HOME_NEW_STORES_PRODUCTS.map((product) => (
<CompactProductCard key={product.id} item={product} />
))}
</div>
</div> </div>
</div>
) : (
<EmptyStateBox message="No new store products yet." compact />
)}
</section>
</section>
</>
) : null}
</> </>
)} )}
</div> </div>

240
src/pages/orders/ShopOrderDetailPage.tsx

@ -7,6 +7,7 @@ import {
InlineSpinner, InlineSpinner,
OrderDetailShimmer, OrderDetailShimmer,
RetryBanner, RetryBanner,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons'; } from '../../components/common/ShimmerSkeletons';
import { ShipmentStatusCard } from '../../components/orders/ShipmentStatusCard'; import { ShipmentStatusCard } from '../../components/orders/ShipmentStatusCard';
import { ShipmentTrackingSheet } from '../../components/modals/ShipmentTrackingSheet'; import { ShipmentTrackingSheet } from '../../components/modals/ShipmentTrackingSheet';
@ -43,6 +44,7 @@ export const ShopOrderDetailPage: React.FC = () => {
const canceling = cancelOrderMutation.isPending; const canceling = cancelOrderMutation.isPending;
const liveOrder = !isBare ? order : null; const liveOrder = !isBare ? order : null;
const isOrderShimmer = !isBare && loading && !liveOrder;
const canCancel = const canCancel =
liveOrder && liveOrder &&
(liveOrder.status === 'processing' || liveOrder.status === 'pending_payment'); (liveOrder.status === 'processing' || liveOrder.status === 'pending_payment');
@ -75,9 +77,7 @@ export const ShopOrderDetailPage: React.FC = () => {
gap: 20, gap: 20,
}} }}
> >
{!isBare && loading ? (
<OrderDetailShimmer />
) : !liveOrder && !useMockFallback ? (
{!isOrderShimmer && !liveOrder && !useMockFallback ? (
<> <>
{loadError && ( {loadError && (
<RetryBanner <RetryBanner
@ -127,18 +127,22 @@ export const ShopOrderDetailPage: React.FC = () => {
flexWrap: 'wrap', flexWrap: 'wrap',
}} }}
> >
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.order_number || resolvedOrderNumber}
</span>
{isOrderShimmer && !orderId ? (
<ShimmerBox width={92} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.order_number || resolvedOrderNumber}
</span>
)}
<span <span
style={{ style={{
@ -150,18 +154,22 @@ export const ShopOrderDetailPage: React.FC = () => {
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_total || '$24.00'}
</span>
{isOrderShimmer ? (
<ShimmerBox width={58} height={18} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '24px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_total || '$24.00'}
</span>
)}
</div> </div>
{/* Date on right */} {/* Date on right */}
@ -181,18 +189,22 @@ export const ShopOrderDetailPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_date || 'Mar 15,2025'}
</span>
{isOrderShimmer ? (
<ShimmerBox width={84} height={14} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#747474',
whiteSpace: 'nowrap',
}}
>
{liveOrder?.formatted_date || 'Mar 15,2025'}
</span>
)}
</div> </div>
</div> </div>
@ -228,18 +240,22 @@ export const ShopOrderDetailPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(liveOrder ? `${liveOrder.items_count} item` : '3 item')}
</span>
{isOrderShimmer ? (
<ShimmerBox width={46} height={14} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(liveOrder ? `${liveOrder.items_count} item` : '3 item')}
</span>
)}
</div> </div>
{/* Vertical divider */} {/* Vertical divider */}
@ -262,78 +278,88 @@ export const ShopOrderDetailPage: React.FC = () => {
flexShrink: 0, flexShrink: 0,
}} }}
/> />
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(liveOrder ? `${liveOrder.shops_count} shop` : '1 shop')}
</span>
{isOrderShimmer ? (
<ShimmerBox width={46} height={14} borderRadius={5} />
) : (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 14,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(liveOrder ? `${liveOrder.shops_count} shop` : '1 shop')}
</span>
)}
</div> </div>
</div> </div>
{/* Right delivery count */} {/* Right delivery count */}
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
}}
>
{isOrderShimmer ? (
<ShimmerBox width={82} height={16} borderRadius={6} />
) : (
<div <div
style={{ style={{
width: 16,
height: 16,
borderRadius: 10,
backgroundColor:
liveOrder?.status === 'canceled' ? '#d44747' : '#0eb13c',
display: 'flex',
display: 'inline-flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
gap: 4,
}} }}
> >
<img
src="/assets/images/icon-check-white-tiny.svg"
alt=""
<div
style={{ style={{
width: 8,
height: 6,
width: 16,
height: 16,
borderRadius: 10,
backgroundColor:
liveOrder?.status === 'canceled' ? '#d44747' : '#0eb13c',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}} }}
/>
>
<img
src="/assets/images/icon-check-white-tiny.svg"
alt=""
style={{
width: 8,
height: 6,
}}
/>
</div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(
liveOrder
? liveOrder.status === 'canceled'
? 'Canceled'
: `${liveOrder.delivered_shipments_count} / ${Math.max(
1,
liveOrder.total_shipments_count
)} Delivery`
: '1 / 3 Delivery'
)}
</span>
</div> </div>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '14px',
color: '#111111',
whiteSpace: 'nowrap',
}}
>
{tr(
liveOrder
? liveOrder.status === 'canceled'
? 'Canceled'
: `${liveOrder.delivered_shipments_count} / ${Math.max(
1,
liveOrder.total_shipments_count
)} Delivery`
: '1 / 3 Delivery'
)}
</span>
</div>
)}
</div> </div>
</div> </div>
{/* Shipment Cards */} {/* Shipment Cards */}
{liveOrder?.shipments?.length ? (
{isOrderShimmer ? (
<OrderDetailShimmer count={2} />
) : liveOrder?.shipments?.length ? (
<div className="habib-orders-grid"> <div className="habib-orders-grid">
{liveOrder.shipments.map((shipment, idx) => ( {liveOrder.shipments.map((shipment, idx) => (
<div <div

11
src/pages/orders/ShopOrdersPage.tsx

@ -29,7 +29,7 @@ export const ShopOrdersPage: React.FC = () => {
const isBare = isBareMode(location.search); const isBare = isBareMode(location.search);
const useMockFallback = isBare || USE_MOCK_DATA; const useMockFallback = isBare || USE_MOCK_DATA;
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const { orderCounters } = useShopApp();
const { orderCounters, isOrderCountersLoading } = useShopApp();
const paramTab = searchParams.get('tab'); const paramTab = searchParams.get('tab');
const initialTab: OrderFilterTabItem['id'] = const initialTab: OrderFilterTabItem['id'] =
@ -65,10 +65,10 @@ export const ShopOrdersPage: React.FC = () => {
...tab, ...tab,
count: count:
tab.id === 'current' tab.id === 'current'
? String(orderCounters.current)
? String(orderCounters.current ?? orderCounters.in_progress ?? 0)
: tab.id === 'delivered' : tab.id === 'delivered'
? String(orderCounters.delivered)
: String(orderCounters.canceled),
? String(orderCounters.delivered ?? 0)
: String(orderCounters.canceled ?? orderCounters.returned ?? 0),
})); }));
}, [isBare, orderCounters, useMockFallback]); }, [isBare, orderCounters, useMockFallback]);
@ -102,10 +102,11 @@ export const ShopOrdersPage: React.FC = () => {
tabs={tabs} tabs={tabs}
activeTabId={activeTabId} activeTabId={activeTabId}
onSelectTab={handleSelectTab} onSelectTab={handleSelectTab}
loadingCounts={!isBare && isOrderCountersLoading && !orderCounters}
/> />
{/* Order Cards */} {/* Order Cards */}
{!isBare && loading ? (
{!isBare && loading && !orders ? (
<OrdersListShimmer count={2} /> <OrdersListShimmer count={2} />
) : !isBare && orders ? ( ) : !isBare && orders ? (
orders.length > 0 ? ( orders.length > 0 ? (

180
src/pages/orders/ShopSupportPage.tsx

@ -2,7 +2,10 @@ import React, { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell'; import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader'; import { StandardPageHeader } from '../../components/layout/TopHeader';
import { EmptyStateBox } from '../../components/common/ShimmerSkeletons';
import {
EmptyStateBox,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import { useShopApp } from '../../context/ShopAppContext'; import { useShopApp } from '../../context/ShopAppContext';
import { SUPPORT_SUBJECT_OPTIONS } from '../../data/ordersData'; import { SUPPORT_SUBJECT_OPTIONS } from '../../data/ordersData';
import { resolveMediaUrl } from '../../lib/http'; import { resolveMediaUrl } from '../../lib/http';
@ -15,10 +18,11 @@ import {
} from '../../lib/shopQueries'; } from '../../lib/shopQueries';
import { import {
isInFlutterWebView, isInFlutterWebView,
uploadBrowserFileToTmpMedia,
uploadFileViaFlutterBridge,
pickFileViaFlutterBridge,
} from '../../lib/webview-actions'; } from '../../lib/webview-actions';
const MAX_SUPPORT_ATTACHMENT_BYTES = 25 * 1024 * 1024;
/** /**
* Node 4177:11244 — `shop-support` (Order Support Request Form, 375×1061) * Node 4177:11244 — `shop-support` (Order Support Request Form, 375×1061)
*/ */
@ -33,6 +37,8 @@ export const ShopSupportPage: React.FC = () => {
const [selectedSubjectId, setSelectedSubjectId] = useState('subj-counterfeit'); const [selectedSubjectId, setSelectedSubjectId] = useState('subj-counterfeit');
const [description, setDescription] = useState(''); const [description, setDescription] = useState('');
const [attachmentUrl, setAttachmentUrl] = useState(''); const [attachmentUrl, setAttachmentUrl] = useState('');
const [attachmentFile, setAttachmentFile] = useState<File | undefined>(undefined);
const [attachmentIsObjectUrl, setAttachmentIsObjectUrl] = useState(false);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null); const fileInputRef = useRef<HTMLInputElement | null>(null);
@ -57,14 +63,32 @@ export const ShopSupportPage: React.FC = () => {
}); });
}, [isBare, subjects]); }, [isBare, subjects]);
const setStagedEvidence = (
nextUrl: string,
nextFile?: File,
isObjectUrl = false
) => {
if (attachmentIsObjectUrl && attachmentUrl && attachmentUrl !== nextUrl) {
URL.revokeObjectURL(attachmentUrl);
}
setAttachmentUrl(nextUrl);
setAttachmentFile(nextFile);
setAttachmentIsObjectUrl(isObjectUrl);
};
const handleUploadClick = async () => { const handleUploadClick = async () => {
if (isBare || uploading) return; if (isBare || uploading) return;
if (isInFlutterWebView()) { if (isInFlutterWebView()) {
setUploading(true); setUploading(true);
try { try {
const url = await uploadFileViaFlutterBridge();
if (url) {
setAttachmentUrl(url);
const picked = await pickFileViaFlutterBridge('image+video');
if (picked) {
if (picked.file && picked.file.size > MAX_SUPPORT_ATTACHMENT_BYTES) {
if (picked.isObjectUrl) URL.revokeObjectURL(picked.url);
showToast('Attachment exceeds the 25 MB size limit');
return;
}
setStagedEvidence(picked.url, picked.file, Boolean(picked.isObjectUrl));
showToast('Evidence attached'); showToast('Evidence attached');
} }
} finally { } finally {
@ -75,18 +99,16 @@ export const ShopSupportPage: React.FC = () => {
fileInputRef.current?.click(); fileInputRef.current?.click();
}; };
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
e.target.value = ''; e.target.value = '';
setUploading(true);
try {
const url = await uploadBrowserFileToTmpMedia(file);
setAttachmentUrl(url);
showToast('Evidence attached');
} finally {
setUploading(false);
if (file.size > MAX_SUPPORT_ATTACHMENT_BYTES) {
showToast('Attachment exceeds the 25 MB size limit');
return;
} }
setStagedEvidence(URL.createObjectURL(file), file, true);
showToast('Evidence attached');
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
@ -117,8 +139,12 @@ export const ShopSupportPage: React.FC = () => {
subject_label: subject_label:
chosenApiSubj?.label || chosenStaticSubj?.label || 'Order Support', chosenApiSubj?.label || chosenStaticSubj?.label || 'Order Support',
description: description.trim(), description: description.trim(),
attachment_url: attachmentUrl || undefined,
attachment: attachmentFile,
attachment_url: attachmentFile ? undefined : attachmentUrl || undefined,
}); });
if (attachmentIsObjectUrl && attachmentUrl) {
URL.revokeObjectURL(attachmentUrl);
}
showToast(`Support ticket ${ticket.ticket_number} submitted`); showToast(`Support ticket ${ticket.ticket_number} submitted`);
navigate(orderId ? ROUTES.orderDetail(orderId) : ROUTES.orders()); navigate(orderId ? ROUTES.orderDetail(orderId) : ROUTES.orders());
} catch (err) { } catch (err) {
@ -127,6 +153,12 @@ export const ShopSupportPage: React.FC = () => {
}; };
const firstItem = !isBare ? orderDetail?.items?.[0] : null; const firstItem = !isBare ? orderDetail?.items?.[0] : null;
const isOrderLoading =
!isBare && Boolean(orderId) && orderDetailQuery.isPending && !orderDetail;
const isSubjectsLoading =
!isBare &&
(subjectsQuery.isPending || (!subjects && subjectsQuery.isFetching)) &&
!subjects;
const backTarget = orderId ? ROUTES.orderDetail(orderId) : ROUTES.account; const backTarget = orderId ? ROUTES.orderDetail(orderId) : ROUTES.account;
const displaySubjects = const displaySubjects =
@ -187,7 +219,7 @@ export const ShopSupportPage: React.FC = () => {
}} }}
> >
{/* Product Box */} {/* Product Box */}
{(useMockFallback || Boolean(firstItem || orderDetail)) && (
{(useMockFallback || Boolean(firstItem || orderDetail) || isOrderLoading) && (
<div <div
style={{ style={{
width: '100%', width: '100%',
@ -200,20 +232,24 @@ export const ShopSupportPage: React.FC = () => {
gap: 8, gap: 8,
}} }}
> >
<img
src={
resolveMediaUrl(firstItem?.image_snapshot) ||
'/assets/images/product-grey-tshirt-model.png'
}
alt={firstItem?.title_snapshot || 'Islam in the Bible Book'}
style={{
width: 59.3,
height: 57,
borderRadius: 8,
objectFit: 'cover',
flexShrink: 0,
}}
/>
{isOrderLoading ? (
<ShimmerBox width={59.3} height={57} borderRadius={8} />
) : (
<img
src={
resolveMediaUrl(firstItem?.image_snapshot) ||
'/assets/images/product-grey-tshirt-model.png'
}
alt={firstItem?.title_snapshot || 'Islam in the Bible Book'}
style={{
width: 59.3,
height: 57,
borderRadius: 8,
objectFit: 'cover',
flexShrink: 0,
}}
/>
)}
<div <div
style={{ style={{
@ -253,47 +289,55 @@ export const ShopSupportPage: React.FC = () => {
gap: 8, gap: 8,
}} }}
> >
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 18,
lineHeight: '26px',
color: '#3d3d3d',
whiteSpace: 'nowrap',
}}
>
{firstItem?.formatted_unit_price ||
orderDetail?.formatted_total ||
(useMockFallback ? '$24.00' : '$0.00')}
</span>
{/* Quantity Badge */}
<div
style={{
width: 35,
height: 34,
borderRadius: 6.58,
backgroundColor: 'rgba(255, 255, 255, 0.1)',
boxShadow: '0px 1.64px 10.69px rgba(30, 30, 30, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
{isOrderLoading ? (
<ShimmerBox width={62} height={20} borderRadius={5} />
) : (
<span <span
style={{ style={{
fontFamily: 'var(--font-sans)', fontFamily: 'var(--font-sans)',
fontWeight: 700, fontWeight: 700,
fontSize: 11.51,
lineHeight: '15.62px',
color: '#151c31',
fontSize: 18,
lineHeight: '26px',
color: '#3d3d3d',
whiteSpace: 'nowrap',
}} }}
> >
{firstItem?.quantity ?? 1}
{firstItem?.formatted_unit_price ||
orderDetail?.formatted_total ||
(useMockFallback ? '$24.00' : '$0.00')}
</span> </span>
</div>
)}
{/* Quantity Badge */}
{isOrderLoading ? (
<ShimmerBox width={35} height={34} borderRadius={6.58} />
) : (
<div
style={{
width: 35,
height: 34,
borderRadius: 6.58,
backgroundColor: 'rgba(255, 255, 255, 0.1)',
boxShadow: '0px 1.64px 10.69px rgba(30, 30, 30, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 11.51,
lineHeight: '15.62px',
color: '#151c31',
}}
>
{firstItem?.quantity ?? 1}
</span>
</div>
)}
</div> </div>
</div> </div>
</div> </div>
@ -381,7 +425,13 @@ export const ShopSupportPage: React.FC = () => {
</div> </div>
{/* 6 Subject Tiles Grid */} {/* 6 Subject Tiles Grid */}
{displaySubjects.length > 0 ? (
{isSubjectsLoading ? (
<div className="habib-support-subjects-grid">
{[0, 1, 2, 3, 4, 5].map((i) => (
<ShimmerBox key={i} height={63} borderRadius={15} />
))}
</div>
) : displaySubjects.length > 0 ? (
<div className="habib-support-subjects-grid"> <div className="habib-support-subjects-grid">
{displaySubjects.map((option) => { {displaySubjects.map((option) => {
const isSelected = option.id === selectedSubjectId; const isSelected = option.id === selectedSubjectId;

Loading…
Cancel
Save