diff --git a/BACKEND_SPEC.md b/BACKEND_SPEC.md index 2f3fb31..622c949 100644 --- a/BACKEND_SPEC.md +++ b/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/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/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. | diff --git a/index.html b/index.html index 84893ec..bbc2e21 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ Habib Shop -
- -
+
diff --git a/public/assets/images/icon-cat-apparel-large.svg b/public/assets/images/icon-cat-apparel-large.svg new file mode 100644 index 0000000..b55dbad --- /dev/null +++ b/public/assets/images/icon-cat-apparel-large.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-apparel-small.svg b/public/assets/images/icon-cat-apparel-small.svg new file mode 100644 index 0000000..25bd410 --- /dev/null +++ b/public/assets/images/icon-cat-apparel-small.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-attar-large.svg b/public/assets/images/icon-cat-attar-large.svg new file mode 100644 index 0000000..f790dcd --- /dev/null +++ b/public/assets/images/icon-cat-attar-large.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-attar-small.svg b/public/assets/images/icon-cat-attar-small.svg new file mode 100644 index 0000000..eeee569 --- /dev/null +++ b/public/assets/images/icon-cat-attar-small.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-backpack-large.svg b/public/assets/images/icon-cat-backpack-large.svg new file mode 100644 index 0000000..8361e1e --- /dev/null +++ b/public/assets/images/icon-cat-backpack-large.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/assets/images/icon-cat-backpack-small.svg b/public/assets/images/icon-cat-backpack-small.svg new file mode 100644 index 0000000..e532b42 --- /dev/null +++ b/public/assets/images/icon-cat-backpack-small.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/assets/images/icon-cat-book-large.svg b/public/assets/images/icon-cat-book-large.svg new file mode 100644 index 0000000..07ce3b2 --- /dev/null +++ b/public/assets/images/icon-cat-book-large.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-book-small.svg b/public/assets/images/icon-cat-book-small.svg new file mode 100644 index 0000000..f01d73c --- /dev/null +++ b/public/assets/images/icon-cat-book-small.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-calligraphy-large.svg b/public/assets/images/icon-cat-calligraphy-large.svg new file mode 100644 index 0000000..65398b5 --- /dev/null +++ b/public/assets/images/icon-cat-calligraphy-large.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-calligraphy-small.svg b/public/assets/images/icon-cat-calligraphy-small.svg new file mode 100644 index 0000000..9d11430 --- /dev/null +++ b/public/assets/images/icon-cat-calligraphy-small.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-duffel-large.svg b/public/assets/images/icon-cat-duffel-large.svg new file mode 100644 index 0000000..77519e8 --- /dev/null +++ b/public/assets/images/icon-cat-duffel-large.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-duffel-small.svg b/public/assets/images/icon-cat-duffel-small.svg new file mode 100644 index 0000000..7a7cd71 --- /dev/null +++ b/public/assets/images/icon-cat-duffel-small.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-heritage-large.svg b/public/assets/images/icon-cat-heritage-large.svg new file mode 100644 index 0000000..650ba3e --- /dev/null +++ b/public/assets/images/icon-cat-heritage-large.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-heritage-small.svg b/public/assets/images/icon-cat-heritage-small.svg new file mode 100644 index 0000000..fc8a8e6 --- /dev/null +++ b/public/assets/images/icon-cat-heritage-small.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-khatam-large.svg b/public/assets/images/icon-cat-khatam-large.svg new file mode 100644 index 0000000..a6bc612 --- /dev/null +++ b/public/assets/images/icon-cat-khatam-large.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-khatam-small.svg b/public/assets/images/icon-cat-khatam-small.svg new file mode 100644 index 0000000..44ba0a1 --- /dev/null +++ b/public/assets/images/icon-cat-khatam-small.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-modest-large.svg b/public/assets/images/icon-cat-modest-large.svg new file mode 100644 index 0000000..f85adc1 --- /dev/null +++ b/public/assets/images/icon-cat-modest-large.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/assets/images/icon-cat-modest-small.svg b/public/assets/images/icon-cat-modest-small.svg new file mode 100644 index 0000000..4788106 --- /dev/null +++ b/public/assets/images/icon-cat-modest-small.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/assets/images/icon-cat-prayer-large.svg b/public/assets/images/icon-cat-prayer-large.svg new file mode 100644 index 0000000..cd65c07 --- /dev/null +++ b/public/assets/images/icon-cat-prayer-large.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/assets/images/icon-cat-prayer-small.svg b/public/assets/images/icon-cat-prayer-small.svg new file mode 100644 index 0000000..eea2dd5 --- /dev/null +++ b/public/assets/images/icon-cat-prayer-small.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/public/assets/images/icon-cat-rosewater-large.svg b/public/assets/images/icon-cat-rosewater-large.svg new file mode 100644 index 0000000..ee4bded --- /dev/null +++ b/public/assets/images/icon-cat-rosewater-large.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-rosewater-small.svg b/public/assets/images/icon-cat-rosewater-small.svg new file mode 100644 index 0000000..2be0a1b --- /dev/null +++ b/public/assets/images/icon-cat-rosewater-small.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/images/icon-cat-scripture-large.svg b/public/assets/images/icon-cat-scripture-large.svg new file mode 100644 index 0000000..9d3bd60 --- /dev/null +++ b/public/assets/images/icon-cat-scripture-large.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/assets/images/icon-cat-scripture-small.svg b/public/assets/images/icon-cat-scripture-small.svg new file mode 100644 index 0000000..882f28c --- /dev/null +++ b/public/assets/images/icon-cat-scripture-small.svg @@ -0,0 +1,4 @@ + + + + diff --git a/public/assets/images/icon-cat-textiles-large.svg b/public/assets/images/icon-cat-textiles-large.svg new file mode 100644 index 0000000..947112f --- /dev/null +++ b/public/assets/images/icon-cat-textiles-large.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-textiles-small.svg b/public/assets/images/icon-cat-textiles-small.svg new file mode 100644 index 0000000..36035d4 --- /dev/null +++ b/public/assets/images/icon-cat-textiles-small.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/assets/images/icon-cat-tshirt-large.svg b/public/assets/images/icon-cat-tshirt-large.svg new file mode 100644 index 0000000..6c27802 --- /dev/null +++ b/public/assets/images/icon-cat-tshirt-large.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/assets/images/icon-cat-tshirt-small.svg b/public/assets/images/icon-cat-tshirt-small.svg new file mode 100644 index 0000000..7351d08 --- /dev/null +++ b/public/assets/images/icon-cat-tshirt-small.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/App.tsx b/src/App.tsx index 8f5205b..91f6d00 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -38,7 +38,10 @@ import { ShopSupportPage } from './pages/orders/ShopSupportPage'; import { ShopAccountPage } from './pages/account/ShopAccountPage'; import { ShopAddressPage } from './pages/account/ShopAddressPage'; 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) import { StandaloneNodesPage } from './pages/standalone/StandaloneNodesPage'; @@ -76,16 +79,15 @@ const AppRoutes: React.FC = () => { const activeMajorTab = isBare ? null : resolveMajorTab(location.pathname); const visibleSlots = homeBootSettled ? MAJOR_PAGE_SLOTS - : MAJOR_PAGE_SLOTS.filter(({ tab }) => tab === 'home'); + : MAJOR_PAGE_SLOTS.filter( + ({ tab }) => tab === 'home' || tab === activeMajorTab + ); return ( <> {!isNonShellRoute && visibleSlots.map(({ tab, element }) => { - const isActive = - !homeBootSettled && activeMajorTab !== null - ? tab === 'home' - : activeMajorTab === tab; + const isActive = activeMajorTab === tab; return (
{ path="/categories/:categorySlug" element={} /> + } + /> } @@ -144,6 +150,7 @@ const AppRoutes: React.FC = () => { path="/account/bookmarks" element={} /> + } /> } /> } /> } /> diff --git a/src/components/account/AccountMenuRow.tsx b/src/components/account/AccountMenuRow.tsx index 08e07e8..a5a50ba 100644 --- a/src/components/account/AccountMenuRow.tsx +++ b/src/components/account/AccountMenuRow.tsx @@ -1,7 +1,9 @@ import React from 'react'; import { useNavigate } from 'react-router-dom'; +import { useShopApp } from '../../context/ShopAppContext'; import type { AccountMenuRowItem } from '../../data/accountData'; -import { tr } from '../../lib/cookies'; +import { ShimmerBox } from '../common/ShimmerSkeletons'; +import { isRtlLanguage, tr } from '../../lib/cookies'; interface AccountMenuRowProps { row: AccountMenuRowItem; @@ -14,6 +16,8 @@ interface AccountMenuRowProps { */ export const AccountMenuRow: React.FC = ({ row, onClick }) => { const navigate = useNavigate(); + const { language } = useShopApp(); + const isRtl = isRtlLanguage(language); return (
= ({ row, onClick }) textOverflow: 'ellipsis', }} > - {tr(row.title)} + {tr(row.title, language)}
- {row.subtitle && ( -
- {tr(row.subtitle)} -
+ {row.loadingSubtitle ? ( + + ) : ( + row.subtitle && ( +
+ {tr(row.subtitle, language)} +
+ ) )}
@@ -152,6 +165,7 @@ export const AccountMenuRow: React.FC = ({ row, onClick }) width: 5, height: 10, flexShrink: 0, + transform: isRtl ? 'scaleX(-1)' : undefined, }} /> )} diff --git a/src/components/account/OrderCounterCard.tsx b/src/components/account/OrderCounterCard.tsx index a003293..3d53747 100644 --- a/src/components/account/OrderCounterCard.tsx +++ b/src/components/account/OrderCounterCard.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { useNavigate } from 'react-router-dom'; import type { OrderStatusCounterItem } from '../../data/accountData'; +import { ShimmerBox } from '../common/ShimmerSkeletons'; import { tr } from '../../lib/cookies'; import { ROUTES } from '../../lib/routes'; @@ -91,20 +92,29 @@ export const OrderCounterCard: React.FC = ({ > {tr(counter.label)} -
- {tr(counter.countText)} -
+ {counter.loadingCount ? ( + + ) : ( +
+ {tr(counter.countText)} +
+ )} ); diff --git a/src/components/checkout/OrderSummaryRows.tsx b/src/components/checkout/OrderSummaryRows.tsx index 9c08946..fde239d 100644 --- a/src/components/checkout/OrderSummaryRows.tsx +++ b/src/components/checkout/OrderSummaryRows.tsx @@ -1,5 +1,6 @@ import React from 'react'; import { ORDER_SUMMARY_ROWS } from '../../data/checkoutData'; +import { ShimmerBox } from '../common/ShimmerSkeletons'; import { tr } from '../../lib/cookies'; export interface SummaryLineRow { @@ -16,12 +17,21 @@ interface OrderSummaryRowsProps { totalValueLeft?: number; rows?: SummaryLineRow[]; totalText?: string; + loading?: boolean; } export const OrderSummaryRows: React.FC = ({ rows = ORDER_SUMMARY_ROWS, totalText = '$70.50', + loading = false, }) => { + const displayRows: SummaryLineRow[] = loading + ? [ + { id: 'row-items', label: 'Items', value: '' }, + { id: 'row-shipping', label: 'Shipping', value: '' }, + ] + : rows; + return (
= ({ gap: '10px', }} > - {rows.map((row) => ( + {displayRows.map((row) => (
= ({ > {tr(row.label)} - - {row.value} - + {loading ? ( + + ) : ( + + {row.value} + + )}
))}
@@ -107,18 +121,22 @@ export const OrderSummaryRows: React.FC = ({ > {tr('Total')} - - {totalText} - + {loading ? ( + + ) : ( + + {totalText} + + )} ); diff --git a/src/components/common/PhoneNumberInput.tsx b/src/components/common/PhoneNumberInput.tsx index 43df37b..4ada631 100644 --- a/src/components/common/PhoneNumberInput.tsx +++ b/src/components/common/PhoneNumberInput.tsx @@ -258,7 +258,12 @@ export const PhoneNumberInput: React.FC = ({ ) : ( - )} + + {tr(totalItemsLabel)} + + + + ))} {topLabel && ( = ({ )} - - {price} - + {loadingPrice ? ( + + ) : ( + + {price} + + )} {/* Primary Gold CTA Button */} diff --git a/src/components/modals/AddressFormSheet.tsx b/src/components/modals/AddressFormSheet.tsx index 24b1c39..f6b9174 100644 --- a/src/components/modals/AddressFormSheet.tsx +++ b/src/components/modals/AddressFormSheet.tsx @@ -270,6 +270,9 @@ export const AddressFormSheet: React.FC = ({ }; const handlePickMap = () => { + if (typeof document !== 'undefined' && document.activeElement instanceof HTMLElement) { + document.activeElement.blur(); + } const startLat = lat !== null && Number.isFinite(lat) ? lat : 36.1901; const startLon = @@ -570,6 +573,7 @@ export const AddressFormSheet: React.FC = ({ gap: '14px', maxHeight: '88dvh', overflowY: 'auto', + overscrollBehavior: 'contain', }} >
= ({ )}
- {/* Anchored User GPS Location Marker (Blue Dot + Accuracy Circle + Badge on Map) */} + {/* Anchored User GPS Location Marker (Core Blue Dot on Map) */} {gpsPointOffsetPx && (
= ({ zIndex: 3, }} > - {/* Accuracy halo */} -
- {/* Radar pulse wave */}
- {/* Core Blue GPS Dot */} -
- {/* "Your GPS" label pill anchored to the GPS dot */} -
- {tr('Your GPS')} -
)} diff --git a/src/components/modals/PaymentMethodsSheet.tsx b/src/components/modals/PaymentMethodsSheet.tsx index 4e0683f..1628a23 100644 --- a/src/components/modals/PaymentMethodsSheet.tsx +++ b/src/components/modals/PaymentMethodsSheet.tsx @@ -2,7 +2,11 @@ import React from 'react'; import { useAnimatedPresence } from '../../hooks/use-animated-presence'; import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; import { tr } from '../../lib/cookies'; -import { EmptyStateBox, InlineSpinner } from '../common/ShimmerSkeletons'; +import { + EmptyStateBox, + InlineSpinner, + ShimmerBox, +} from '../common/ShimmerSkeletons'; import { PaymentMethodCard } from '../checkout/PaymentMethodCard'; import type { PaymentMethodItem } from '../../data/checkoutData'; @@ -15,6 +19,7 @@ interface PaymentMethodsSheetProps { totalPriceText: string; onConfirmPurchase: () => void; isSubmitting?: boolean; + isLoading?: boolean; } export const PaymentMethodsSheet: React.FC = ({ @@ -26,6 +31,7 @@ export const PaymentMethodsSheet: React.FC = ({ totalPriceText, onConfirmPurchase, isSubmitting = false, + isLoading = false, }) => { const { shouldRender, isClosing } = useAnimatedPresence(isOpen, 200); @@ -123,7 +129,13 @@ export const PaymentMethodsSheet: React.FC = ({ gap: '12px', }} > - {methods.length > 0 ? ( + {isLoading && methods.length === 0 ? ( + <> + + + + + ) : methods.length > 0 ? ( methods.map((method) => ( void; } @@ -16,6 +18,7 @@ interface OrderFilterTabsProps { export const OrderFilterTabs: React.FC = ({ tabs, activeTabId, + loadingCounts = false, onSelectTab, }) => { const isRtl = isRtlLanguage(); @@ -105,32 +108,41 @@ export const OrderFilterTabs: React.FC = ({ {/* Count badge pill 19×19 */} - + {loadingCounts ? ( + + ) : ( - {tab.count} + + {tab.count} + - + )} ); })} diff --git a/src/context/ShopAppContext.tsx b/src/context/ShopAppContext.tsx index e6d9e4e..ea12931 100644 --- a/src/context/ShopAppContext.tsx +++ b/src/context/ShopAppContext.tsx @@ -11,6 +11,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useLocation } from 'react-router-dom'; import { clearSettledPathnames, + isInitialBootSettled, useHomeBootSettled, } from '../components/layout/MobileShell'; import { InlineSpinner } from '../components/common/ShimmerSkeletons'; @@ -70,15 +71,19 @@ interface ShopAppContextValue { cart: ApiCart | null; cartItemsCount: number; cartTotalQuantity: number; + isCartLoading: boolean; isCartBusy: boolean; addresses: ApiAddress[]; + isAddressesLoading: boolean; selectedAddressId: number | null; selectedAddress: ApiAddress | null; shippingMethods: ApiShippingMethod[]; + isShippingMethodsLoading: boolean; selectedShippingMethod: ApiShippingMethod | null; selectedPaymentMethod: string; setSelectedPaymentMethod: (code: string) => void; bookmarkedProducts: ApiProductCard[]; + isBookmarksLoading: boolean; isBookmarked: (productId?: number | null, slug?: string | null) => boolean; toggleBookmark: ( productRef: string | number, @@ -87,13 +92,14 @@ interface ShopAppContextValue { ) => Promise; profile: ApiUserProfile | null; isProfileLoading: boolean; + isProfilePending: boolean; orderCounters: ApiOrderCounters | null; + isOrderCountersLoading: boolean; language: string; changeLanguage: (lang: string) => void; addToCart: ( productRef: string | number, - quantity?: number, - variantId?: number | null + quantity?: number ) => Promise; updateCartItemQuantity: (itemId: number, quantity: number) => Promise; removeCartItem: (itemId: number) => Promise; @@ -148,6 +154,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const hasAuthToken = Boolean(authToken); const homeBootSettled = useHomeBootSettled(); + const isHomeRoute = + location.pathname === '/' || location.pathname === '/shop-home'; + const enableSecondaryQueries = !isBare && (homeBootSettled || !isHomeRoute); const homeQuery = useQuery({ queryKey: shopKeys.home(), @@ -158,7 +167,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const categoriesQuery = useQuery({ queryKey: shopKeys.categories(), queryFn: () => shopApi.fetchCategories(), - enabled: !isBare && homeBootSettled, + enabled: enableSecondaryQueries, }); useEffect(() => { @@ -175,38 +184,38 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const cartQuery = useQuery({ queryKey: shopKeys.cart(), queryFn: () => shopApi.fetchCart(false), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, }); const profileQuery = useQuery({ queryKey: shopKeys.profile(), queryFn: () => shopApi.fetchProfile(), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, }); const addressesQuery = useQuery({ queryKey: shopKeys.addresses(), queryFn: () => shopApi.fetchAddresses(), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, }); const shippingMethodsQuery = useQuery({ queryKey: shopKeys.shippingMethods(), queryFn: () => shopApi.fetchShippingMethods(), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, staleTime: 5 * 60_000, }); const bookmarksQuery = useQuery({ queryKey: shopKeys.bookmarks(), queryFn: () => shopApi.fetchBookmarks(), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, }); const orderCountersQuery = useQuery({ queryKey: shopKeys.orderCounters(), queryFn: () => shopApi.fetchOrderCounters(), - enabled: !isBare && hasAuthToken && homeBootSettled, + enabled: enableSecondaryQueries && hasAuthToken, }); const publicMajorHydrated = @@ -223,9 +232,65 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const hydrated = isBare || (publicMajorHydrated && authMajorHydrated); const cart = cartQuery.data ?? null; - const profile = profileQuery.data ?? null; + + const bootstrapHint = useMemo( + () => (!isBare && hasAuthToken ? readBootstrapUserHint() : null), + [hasAuthToken, isBare] + ); + + const profile = useMemo(() => { + 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 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(() => { if (isBare) return true; if (profile !== null) { @@ -234,20 +299,8 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ return Boolean(authToken || getToken()); }, [authToken, isBare, profile]); - const hasProfileIdentity = Boolean( - profile?.full_name?.trim() || - profile?.avatar_url?.trim() || - profile?.email?.trim() || - profile?.phone_number?.trim() - ); - const isProfileLoading = - !isBare && - isUserAuthenticated && - (isAuthProfileSyncing || - (!hasProfileIdentity && - homeBootSettled && - (profileQuery.isPending || profileQuery.isFetching))); + !isBare && isUserAuthenticated && isAuthProfileSyncing; const addresses = useMemo( () => addressesQuery.data?.results ?? [], @@ -358,12 +411,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ }); }, [queryClient]); - useEffect(() => { - if (!isBare && hasAuthToken) { - seedProfileFromBridgeHint(); - } - }, [hasAuthToken, isBare, seedProfileFromBridgeHint]); - const refreshCart = useCallback(async () => { if (!getToken()) { await queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); @@ -408,7 +455,10 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const refreshAccountData = useCallback(async () => { if (!getToken()) return; seedProfileFromBridgeHint(); - setIsAuthProfileSyncing(true); + const shouldShowOverlaySpinner = isInitialBootSettled(); + if (shouldShowOverlaySpinner) { + setIsAuthProfileSyncing(true); + } try { await Promise.allSettled([ queryClient @@ -526,6 +576,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const token = await ensureToken(60000, { forceLogin: true }); if (token) { setAuthToken(token); + setIsAuthProfileSyncing(true); seedProfileFromBridgeHint(); const pendingCallback = loginModalState.onAuthenticated; setIsLoggingIn(false); @@ -562,8 +613,7 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const addToCart = useCallback( async ( productRef: string | number, - quantity = 1, - variantId?: number | null + quantity = 1 ): Promise => { if (!isBare && !isUserAuthenticated) { const authed = await requireAuth({ @@ -576,7 +626,6 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ const updated = await shopApi.addCartItem({ product_id: productRef, quantity, - variant_id: variantId, }); queryClient.setQueryData(shopKeys.cart(), updated); void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); @@ -804,20 +853,26 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ cart, cartItemsCount, cartTotalQuantity, + isCartLoading, isCartBusy, addresses, + isAddressesLoading, selectedAddressId: resolvedSelectedAddressId, selectedAddress, shippingMethods, + isShippingMethodsLoading, selectedShippingMethod, selectedPaymentMethod, setSelectedPaymentMethod, bookmarkedProducts, + isBookmarksLoading, isBookmarked, toggleBookmark, profile, isProfileLoading, + isProfilePending, orderCounters, + isOrderCountersLoading, language, changeLanguage, addToCart, @@ -842,19 +897,25 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ cart, cartItemsCount, cartTotalQuantity, + isCartLoading, isCartBusy, addresses, + isAddressesLoading, resolvedSelectedAddressId, selectedAddress, shippingMethods, + isShippingMethodsLoading, selectedShippingMethod, selectedPaymentMethod, bookmarkedProducts, + isBookmarksLoading, isBookmarked, toggleBookmark, profile, isProfileLoading, + isProfilePending, orderCounters, + isOrderCountersLoading, language, changeLanguage, addToCart, diff --git a/src/data/accountData.ts b/src/data/accountData.ts index 080417c..e68202c 100644 --- a/src/data/accountData.ts +++ b/src/data/accountData.ts @@ -4,6 +4,7 @@ export interface OrderStatusCounterItem { label: string; labelWidth: number; countText: string; + loadingCount?: boolean; bgColor: string; iconSrc: string; } @@ -15,6 +16,7 @@ export interface AccountMenuRowItem { titleWidth: number; titleColor: string; subtitle?: string; + loadingSubtitle?: boolean; subtitleWidth?: number; iconBoxBg: string; iconSrc: string; diff --git a/src/data/catalogData.ts b/src/data/catalogData.ts index 045f223..59b0480 100644 --- a/src/data/catalogData.ts +++ b/src/data/catalogData.ts @@ -50,6 +50,7 @@ export interface GridProductItem { export interface CategoryTileItem { id: string; + slug?: string; x: number; y: number; width: number; @@ -334,21 +335,48 @@ export const TWO_COLUMN_GRID_PRODUCTS: GridProductItem[] = [ export const CATEGORY_GRID_TILES: CategoryTileItem[] = [ // 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) - { 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) - { 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) - { 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) - { 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) - { 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 = { + 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 }, + ], +}; diff --git a/src/index.css b/src/index.css index d26cc47..840259b 100644 --- a/src/index.css +++ b/src/index.css @@ -7,6 +7,7 @@ --safe-left: 0px; --safe-right: 0px; --kb-height: 0px; + --kb-offset-top: 0px; } @media (max-width: 359.98px) { @@ -427,6 +428,43 @@ a { 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 { animation: habib-fade-up 200ms cubic-bezier(0.22, 1, 0.36, 1); } @@ -880,33 +918,6 @@ a { 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) */ @media (max-width: 359.98px) { .habib-mobile-viewport:not(.is-embed) .habib-product-grid, diff --git a/src/lib/cookies.ts b/src/lib/cookies.ts index 0a27219..0ddf730 100644 --- a/src/lib/cookies.ts +++ b/src/lib/cookies.ts @@ -213,6 +213,7 @@ const FA_DICTIONARY: Record = { 'تخفیف‌های ویژه روی محصولات اصیل و دست‌ساز', 'Explore Now': 'مشاهده کنید', Populars: 'محبوب‌ترین‌ها', + 'New Products': 'محصولات جدید', 'See All': 'مشاهده همه', 'View All': 'مشاهده همه', 'See more': 'مشاهده بیشتر', @@ -230,6 +231,7 @@ const FA_DICTIONARY: Record = { 'No categories available yet.': 'هنوز دسته‌بندی‌ای موجود نیست.', 'No popular products yet.': 'هنوز محصول محبوبی ثبت نشده است.', 'No new store products yet.': 'هنوز محصولی در فروشگاه‌های جدید ثبت نشده است.', + 'No products in this collection yet.': 'هنوز محصولی در این مجموعه ثبت نشده است.', 'No products found in this category.': 'محصولی در این دسته‌بندی یافت نشد.', 'No products available in this booth yet.': 'هنوز محصولی در این غرفه موجود نیست.', 'Islam in the Biblebran Transfer Book': 'کتاب انتقال اسلام در کتاب مقدس', @@ -439,6 +441,11 @@ const FA_DICTIONARY: Record = { 'About us': 'درباره ما', Notifications: 'اعلان‌ها', Notes: 'یادداشت‌ها', + 'No notes yet': 'هنوز یادداشتی ثبت نشده است', + 'Write a note...': 'یادداشت خود را بنویسید...', + 'Add Note': 'افزودن یادداشت', + 'Note saved': 'یادداشت ذخیره شد', + 'Note removed': 'یادداشت حذف شد', 'Program Access and Permissions': 'دسترسی‌ها و مجوزهای برنامه', 'Azan Setting': 'تنظیمات اذان', Location: 'موقعیت مکانی', @@ -772,6 +779,7 @@ const AR_DICTIONARY: Record = { 'خصومات حصرية على المنتجات اليدوية الأصيلة', 'Explore Now': 'استكشف الآن', Populars: 'الأكثر شعبية', + 'New Products': 'منتجات جديدة', 'See All': 'عرض الكل', 'View All': 'عرض الكل', 'See more': 'عرض المزيد', @@ -789,6 +797,7 @@ const AR_DICTIONARY: Record = { 'No categories available yet.': 'لا توجد فئات متاحة بعد.', 'No popular products yet.': 'لا توجد منتجات شائعة بعد.', 'No new store products yet.': 'لا توجد منتجات متاجر جديدة بعد.', + 'No products in this collection yet.': 'لا توجد منتجات في هذه المجموعة بعد.', 'No products found in this category.': 'لم يتم العثور على منتجات في هذه الفئة.', 'No products available in this booth yet.': 'لا توجد منتجات متاحة في هذا المتجر بعد.', 'Islam in the Biblebran Transfer Book': 'كتاب الإسلام في الكتاب المقدس', @@ -995,6 +1004,11 @@ const AR_DICTIONARY: Record = { 'About us': 'من نحن', Notifications: 'الإشعارات', Notes: 'الملاحظات', + 'No notes yet': 'لا توجد ملاحظات بعد', + 'Write a note...': 'اكتب ملاحظة...', + 'Add Note': 'إضافة ملاحظة', + 'Note saved': 'تم حفظ الملاحظة', + 'Note removed': 'تم حذف الملاحظة', 'Program Access and Permissions': 'صلاحيات وأذونات البرنامج', 'Azan Setting': 'إعدادات الأذان', Location: 'الموقع', diff --git a/src/lib/mappers.ts b/src/lib/mappers.ts index 817a6df..d4a22f3 100644 --- a/src/lib/mappers.ts +++ b/src/lib/mappers.ts @@ -111,9 +111,7 @@ export function mapCartItemToCard(item: ApiCartItem, index: number): CartItemDat imageSrc: resolveMediaUrl(item.image_url) || '/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, titleLineHeight: item.title.length > 24 ? 14 : 17, originRelY: item.title.length > 24 ? 34 : 19, diff --git a/src/lib/routes.ts b/src/lib/routes.ts index 9535f0d..db9d093 100644 --- a/src/lib/routes.ts +++ b/src/lib/routes.ts @@ -2,6 +2,7 @@ export const ROUTES = { home: '/', categories: '/categories', category: (slug: string = 'home-living') => `/categories/${encodeURIComponent(slug)}`, + collection: (slug: string = 'popular') => `/collections/${encodeURIComponent(slug)}`, search: (query?: string) => query && query.trim() ? `/search?q=${encodeURIComponent(query.trim())}` @@ -28,6 +29,7 @@ export const ROUTES = { support: '/support', account: '/account', bookmarks: '/account/bookmarks', + notes: '/account/notes', addresses: '/account/addresses', profile: '/account/profile', settings: '/account/settings', diff --git a/src/lib/shopApi.ts b/src/lib/shopApi.ts index b72c118..0c5d5b1 100644 --- a/src/lib/shopApi.ts +++ b/src/lib/shopApi.ts @@ -14,28 +14,38 @@ export interface ApiBanner { export interface ApiCategory { id: number; parent: number | null; + parent_slug?: string | null; slug: string; title: string; localized_title: string; icon_url: string; small_icon_url: string; - accent_color: string; display_order: number; is_quick: boolean; 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 { id: number; slug: string; name: string; - tagline: string; country: string; city: string; + currency: string; origin_label: string; logo_url: string; - banner_url: string; - badge: string; membership_label: string; sales_label: string; since_label: string; @@ -57,7 +67,6 @@ export interface ApiProductCard { hero_image_url: string; price: string; formatted_price: string; - compare_at_price: string | null; formatted_old_price: string | null; discount_badge: string; currency: string; @@ -71,8 +80,7 @@ export interface ApiProductCard { category: number; category_slug: string; category_title: string; - is_popular: boolean; - is_new_store_pick: boolean; + collection_slugs?: string[]; is_bookmarked: boolean; } @@ -83,16 +91,6 @@ export interface ApiProductMedia { sort_order: number; } -export interface ApiProductVariant { - id: number; - sku: string; - title: string; - attributes_json: Record; - price_override: string | null; - stock_qty: number; - is_active: boolean; -} - export interface ApiReview { id: number; product: number; @@ -110,11 +108,8 @@ export interface ApiProductDetail extends ApiProductCard { condition_label: string; processing_time_label: string; product_type_label: string; - specs_json: Record; - shipping_info_json: Record; store_detail: ApiStoreSummary; media: ApiProductMedia[]; - variants: ApiProductVariant[]; reviews: ApiReview[]; related_products: ApiProductCard[]; } @@ -135,8 +130,6 @@ export interface ApiCartItem { store_id: number; store_slug: string; store_name: string; - variant: number | null; - variant_title: string; quantity: number; unit_price: string; formatted_unit_price: string; @@ -365,9 +358,7 @@ export interface HomeFeedResponse { banners: ApiBanner[]; quick_categories: ApiCategory[]; categories: ApiCategory[]; - popular_products: ApiProductCard[]; - new_store_products: ApiProductCard[]; - featured_stores: ApiStoreSummary[]; + collections: ApiCollection[]; cart_items_count: number; } @@ -375,21 +366,61 @@ export const shopApi = { // Home & Catalog fetchHomeFeed: () => shopRequest('/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) => - 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 } } ), + createCollection: (payload: { + slug: string; + title: string | { language_code: string; title: string }[]; + display_order?: number; + is_active?: boolean; + product_ids?: (string | number)[]; + }) => + shopRequest('/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(`/collections/${encodeURIComponent(slug)}/`, { + method: 'PATCH', + body: payload, + }), + + deleteCollection: (slug: string) => + shopRequest(`/collections/${encodeURIComponent(slug)}/`, { + method: 'DELETE', + }), + fetchProducts: (params?: { q?: string; category?: string; + collection?: string; store?: string; - popular?: boolean; - new_store?: boolean; sort?: 'price_asc' | 'price_desc' | 'rating' | 'newest'; }) => shopRequest<{ count: number; results: ApiProductCard[] }>('/products/', { @@ -431,7 +462,6 @@ export const shopApi = { addCartItem: (payload: { product_id: string | number; - variant_id?: number | null; quantity?: number; }) => shopRequest('/cart/items/', { method: 'POST', body: payload }), @@ -567,7 +597,13 @@ export const shopApi = { { method: 'DELETE' } ), - applyAsProvider: (payload: { store_name: string; description?: string }) => + applyAsProvider: (payload: { + store_name: string; + description?: string; + country?: string; + city?: string; + currency?: string; + }) => shopRequest<{ id?: number; service: string; @@ -589,12 +625,25 @@ export const shopApi = { subject?: string | number; subject_label?: string; description: string; + attachment?: File; attachment_url?: string; - }) => - shopRequest('/support/tickets/', { + }) => { + let body: BodyInit | Record = 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('/support/tickets/', { method: 'POST', - body: payload, - }), + body, + }); + }, fetchChatConversations: () => shopRequest<{ count: number; results: ApiConversation[] }>('/chat/conversations/'), @@ -613,14 +662,22 @@ export const shopApi = { sendChatMessage: ( pkOrSlug: string | number, - payload: { text?: string; attachment_url?: string } - ) => - shopRequest<{ + payload: { text?: string; attachment?: File; attachment_url?: string } + ) => { + let body: BodyInit | Record = 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; message: ApiChatMessage; new_messages: ApiChatMessage[]; }>( `/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`, - { method: 'POST', body: payload } - ), + { method: 'POST', body } + ); + }, }; diff --git a/src/lib/shopQueries.ts b/src/lib/shopQueries.ts index e11a06c..aac70ac 100644 --- a/src/lib/shopQueries.ts +++ b/src/lib/shopQueries.ts @@ -5,9 +5,11 @@ import { useQueryClient, } from '@tanstack/react-query'; import { + type ApiCategory, type ApiChatMessage, type ApiConversation, type ApiOrderDetail, + type ApiProductCard, type ApiProductDetail, type ApiUserProfile, shopApi, @@ -36,6 +38,11 @@ export const shopKeys = { categoryDetailsAll: () => ['shop', 'category'] as const, categoryDetail: (slug: string, q?: string) => ['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, products: (params?: ProductsQueryParams) => ['shop', 'products', params ?? {}] as const, @@ -69,6 +76,37 @@ export const shopKeys = { ['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 { queryClient.removeQueries({ queryKey: shopKeys.ordersAll() }); 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) { return useQuery({ queryKey: shopKeys.products(params), @@ -336,7 +394,7 @@ export function useApplyProviderMutation() { export function useSendChatMessageMutation(resolvedConvRef: string | number) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: (payload: { text?: string; attachment_url?: string }) => + mutationFn: (payload: Parameters[1]) => shopApi.sendChatMessage(resolvedConvRef, payload), onSuccess: (res) => { const incomingBatch = diff --git a/src/lib/view-paddings.ts b/src/lib/view-paddings.ts index 9eea384..6f4ad89 100644 --- a/src/lib/view-paddings.ts +++ b/src/lib/view-paddings.ts @@ -1,7 +1,47 @@ import type { FlutterResponsePayload } from '../types/window'; 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 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 { const num = Number(rawPx); @@ -18,17 +58,203 @@ function toKeyboardPx(rawPx: unknown): number { 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( 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): void { @@ -38,9 +264,9 @@ function applySafeCssVars(action: string | undefined, data: Record void { 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) => { if (!payload || typeof payload !== 'object') return; - const action = payload.action; - const data = (payload.data || payload) as Record; + const rawAction = payload.action ?? payload.type; + const action = typeof rawAction === 'string' ? rawAction.toLowerCase() : ''; + const data = (payload.data || payload.payload || payload) as Record; if ( action === 'initial_config' || + action === 'initialconfig' || action === 'get_view_paddings' || action === 'view_paddings_changed' || action === 'safe_area_changed' || action === 'keyboard_changed' ) { 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') { applySafeCssVars('initial_config', window.__HABIB_BOOTSTRAP__); + } else { + syncKeyboardMetrics(); } 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) { - 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()) { postActionToFlutter('get_view_paddings'); } return () => { + clearPendingTimers(); unsubscribe(); 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); }; } diff --git a/src/lib/webview-actions.ts b/src/lib/webview-actions.ts index dc69d06..a3a73ba 100644 --- a/src/lib/webview-actions.ts +++ b/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' -): Promise { +): Promise { if (!isInFlutterWebView()) return null; const requestId = `upload-${Date.now()}`; const uploadPayload = { @@ -274,6 +281,10 @@ export async function uploadFileViaFlutterBridge( ? (data.files as Array>) : []; const firstFile = files[0] || {}; + const fileName = + (typeof firstFile.name === 'string' && firstFile.name) || + `attachment-${Date.now()}.jpg`; + const directUrl = (typeof firstFile.url === 'string' && firstFile.url) || (typeof firstFile.path === 'string' && firstFile.path) || @@ -282,7 +293,7 @@ export async function uploadFileViaFlutterBridge( (typeof data.path === 'string' && data.path) || ''; if (directUrl) { - return directUrl; + return { url: directUrl, name: fileName }; } const base64DataUrl = @@ -291,17 +302,33 @@ export async function uploadFileViaFlutterBridge( ''; if (!base64DataUrl) return null; - const fileName = - (typeof firstFile.name === 'string' && firstFile.name) || - `attachment-${Date.now()}.jpg`; const blob = dataUrlToBlob(base64DataUrl); if (blob) { const file = new File([blob], fileName, { 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 { + 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( @@ -316,31 +343,24 @@ export async function uploadBrowserFileToTmpMedia( 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; - 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; + 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; diff --git a/src/pages/account/LanguageSettingPage.tsx b/src/pages/account/LanguageSettingPage.tsx index 0d888a8..8541df4 100644 --- a/src/pages/account/LanguageSettingPage.tsx +++ b/src/pages/account/LanguageSettingPage.tsx @@ -1,8 +1,12 @@ import React, { useMemo, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { MobileShell } from '../../components/layout/MobileShell'; +import { StandardPageHeader } from '../../components/layout/TopHeader'; 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 { useShopApp } from '../../context/ShopAppContext'; import { useAnimatedPresence } from '../../hooks/use-animated-presence'; @@ -117,8 +121,11 @@ export const LanguageSettingPage: React.FC = () => { const smartBack = useSmartBack(ROUTES.account); const { + isUserAuthenticated, profile, + isProfilePending, selectedAddress, + isAddressesLoading, orderCounters, language, changeLanguage, @@ -196,14 +203,20 @@ export const LanguageSettingPage: React.FC = () => { if (bare) return LANGUAGE_SETTING_MENU_ROWS; const langLabel = 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) => { if (row.id === 'lang-location') { return { ...row, + loadingSubtitle: + !bare && + isUserAuthenticated && + isAddressesLoading && + !selectedAddress?.city, subtitle: selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'), + rightIconType: 'arrow-right', targetRoute: ROUTES.addresses, }; } @@ -211,7 +224,7 @@ export const LanguageSettingPage: React.FC = () => { return { ...row, subtitle: langLabel, - rightIconType: 'edit-path', + rightIconType: 'arrow-right', targetRoute: '', }; } @@ -225,7 +238,7 @@ export const LanguageSettingPage: React.FC = () => { if (row.id === 'lang-notes') { return { ...row, - targetRoute: ROUTES.bookmarks, + targetRoute: ROUTES.notes, }; } return { @@ -233,7 +246,25 @@ export const LanguageSettingPage: React.FC = () => { 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 () => { if (bare) return; @@ -352,38 +383,58 @@ export const LanguageSettingPage: React.FC = () => {
{/* Name "Ahd Art" */} -
- {displayName} -
+ {isNamePending ? ( + + ) : ( +
+ {displayName} +
+ )} {/* Email "Ahdart14@gmail.com" */} -
- {displayEmail} -
+ {isEmailPending ? ( + + ) : ( +
+ {displayEmail} +
+ )}
{/* Provider Requests Card (4214:11186) */} - {providerRows.length > 0 ? ( + {isProviderReqsPending ? ( + + ) : providerRows.length > 0 ? (
{ ); }; + +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(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 ( + + + +
+
+