From 0ca0a95aa854143ecb9e2fef404550df3c993b70 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:06:37 +0530 Subject: [PATCH] enh --- apps/user-ui/JEST-TEST-CASES.md | 3 + .../flash-delivery/(products)/index.tsx | 4 +- apps/user-ui/components/ProductCard.tsx | 5 +- apps/user-ui/components/SlotSpecificView.tsx | 504 +++++++++------ apps/user-ui/src/lib/region-switch.ts | 3 + apps/user-ui/src/store/flashTabStore.ts | 45 ++ apps/user-ui/tests/helpers/reset.ts | 2 + apps/user-ui/tests/lib/stores.test.ts | 34 + apps/web-ui/src/lib/region-switch.ts | 3 + apps/web-ui/src/lib/stores/flash-tab-store.ts | 41 ++ apps/web-ui/src/routes/flash.tsx | 589 ++++++++++-------- change-log.txt | 52 ++ 12 files changed, 855 insertions(+), 430 deletions(-) create mode 100644 apps/user-ui/src/store/flashTabStore.ts create mode 100644 apps/web-ui/src/lib/stores/flash-tab-store.ts diff --git a/apps/user-ui/JEST-TEST-CASES.md b/apps/user-ui/JEST-TEST-CASES.md index 9d63f43..bd780e6 100644 --- a/apps/user-ui/JEST-TEST-CASES.md +++ b/apps/user-ui/JEST-TEST-CASES.md @@ -1600,6 +1600,9 @@ Covered by HOME-81..98, plus: | STORE-20 | edge | same value written twice | map identity preserved (no subscriber wake) | | STORE-21 | edge | tag selected twice | store identity preserved (no subscriber wake) | | STORE-22 | edge | resetHomeTags | selection null and expansion empty | +| STORE-23 | edge | flash tag/store selected twice | store identity preserved (no subscriber wake) | +| STORE-24 | edge | resetFlashTabs | tag/store null and search empty | +| STORE-25 | edge | unchanged flash search query | store identity preserved (no subscriber wake) | ### App helpers diff --git a/apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx index 595de2e..7515b1f 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx @@ -67,9 +67,9 @@ export default function FlashDeliveryView() { }, [shouldNavigateToCart, router]) ); - const handleProductPress = (productId: number) => { + const handleProductPress = React.useCallback((productId: number) => { router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${productId}`); - }; + }, [router]); return ( <> diff --git a/apps/user-ui/components/ProductCard.tsx b/apps/user-ui/components/ProductCard.tsx index 546fed8..5b7c276 100644 --- a/apps/user-ui/components/ProductCard.tsx +++ b/apps/user-ui/components/ProductCard.tsx @@ -297,4 +297,7 @@ const ProductCard: React.FC = ({ ); }; -export default ProductCard; +// Memoised: list pages re-render their section on selection changes, and an +// unmemoised card re-runs its cart/slot hooks and rebuilds its image for every +// sibling. Parents pass a stable `item` and a stable `onPress`. +export default React.memo(ProductCard); diff --git a/apps/user-ui/components/SlotSpecificView.tsx b/apps/user-ui/components/SlotSpecificView.tsx index 065ccb1..2ea7a08 100644 --- a/apps/user-ui/components/SlotSpecificView.tsx +++ b/apps/user-ui/components/SlotSpecificView.tsx @@ -16,6 +16,7 @@ import { useHideTabNav } from '@/src/hooks/useHideTabNav'; import CartIcon from '@/components/icons/CartIcon'; import ProductCard from '@/components/ProductCard'; import { useSlotStore } from '@/components/stores/slotStore'; +import { useFlashTabStore } from '@/src/store/flashTabStore'; import { LinearGradient } from 'expo-linear-gradient'; import FloatingCartBar from '@/components/floating-cart-bar'; @@ -552,13 +553,253 @@ const flashItemWidth = (screenWidth - 48) / 3; // Three rows per page, like the home catalog. const FLASH_PAGE_SIZE = 9; -export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDeliveryProductsProps) { +interface FlashTabItem { + id: number; + label: string; +} + +/** Active tab, resolved the way the page always did: the picked id while it + * still exists in this region's catalogue, otherwise the first tab. */ +function resolveActiveId(items: FlashTabItem[], picked: number | null): number | null { + if (picked != null && items.some((item) => item.id === picked)) return picked; + return items[0]?.id ?? null; +} + +/** + * Tag strip. Reads the selection straight from the store, so a tap does not + * re-render the page, and receives a memoised `items` array so its memo holds. + */ +const FlashTagStrip = React.memo(({ items }: { items: FlashTabItem[] }) => { + const selectedTagId = useFlashTabStore((state) => state.selectedTagId); + const selectTag = useFlashTabStore((state) => state.selectTag); + + return ( + + ); +}); +FlashTagStrip.displayName = 'FlashTagStrip'; + +const FlashStoreStrip = React.memo(({ items }: { items: FlashTabItem[] }) => { + const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId); + const selectStore = useFlashTabStore((state) => state.selectStore); + + return ( + + ); +}); +FlashStoreStrip.displayName = 'FlashStoreStrip'; + +/** Search box. Owns the store subscription so typing never re-renders the page. */ +const FlashSearchBar = React.memo(() => { + const searchQuery = useFlashTabStore((state) => state.searchQuery); + const setSearchQuery = useFlashTabStore((state) => state.setSearchQuery); + + return ( + + ); +}); +FlashSearchBar.displayName = 'FlashSearchBar'; + +interface FlashProductItemProps { + item: any; + onPress: (productId: number) => void; +} + +/** One card. `onPress` is derived from the id so the parent's handler identity + * is the only prop that matters. */ +const FlashProductItem = React.memo(({ item, onPress }: FlashProductItemProps) => { + const handlePress = React.useCallback(() => onPress(item.id), [item.id, onPress]); + + return ( + + + + ); +}); +FlashProductItem.displayName = 'FlashProductItem'; + +interface FlashProductGridProps { + products: any[]; + onProductPress: (productId: number) => void; + gridTestID: string; + showMoreTestID: string; +} + +/** + * One paged grid. Owns its visible count, and is keyed by the active tab so a + * tab switch resets the page size on the first render instead of in an effect. + * The search value lives in the store, so only the grids wake on typing. + */ +const FlashProductGrid = React.memo(({ + products, + onProductPress, + gridTestID, + showMoreTestID, +}: FlashProductGridProps) => { + const searchQuery = useFlashTabStore((state) => state.searchQuery); + const trimmedQuery = searchQuery.trim().toLowerCase(); + + const filtered = React.useMemo(() => { + if (!trimmedQuery) return products; + return products.filter((product: any) => + product.name?.toLowerCase().includes(trimmedQuery) + ); + }, [products, trimmedQuery]); + + const [visibleCount, setVisibleCount] = React.useState(FLASH_PAGE_SIZE); + // Adjust during render, not in an effect: an effect would paint the new + // results with the previous count and then reset, costing a second render. + const [lastQuery, setLastQuery] = React.useState(trimmedQuery); + if (lastQuery !== trimmedQuery) { + setLastQuery(trimmedQuery); + setVisibleCount(FLASH_PAGE_SIZE); + } + + const visible = filtered.length > visibleCount ? filtered.slice(0, visibleCount) : filtered; + + if (filtered.length === 0) { + return ( + + No 1 Hr Delivery products available. + + ); + } + + return ( + <> + + {visible.map((product: any) => ( + + ))} + + {filtered.length > visibleCount && ( + + setVisibleCount((count) => count + FLASH_PAGE_SIZE)} + > + Show More + + + )} + + ); +}); +FlashProductGrid.displayName = 'FlashProductGrid'; + +interface FlashTagSectionProps { + tagItems: FlashTabItem[]; + tagIds: number[]; + productsByTagId: Record; + /** With no tags configured the section lists every flash product. */ + fallbackProducts: any[]; + onProductPress: (productId: number) => void; +} + +/** Tag strip + its grid. Only this section re-renders when a tag is picked. */ +const FlashTagSection = React.memo(({ + tagItems, + tagIds, + productsByTagId, + fallbackProducts, + onProductPress, +}: FlashTagSectionProps) => { + const selectedTagId = useFlashTabStore((state) => state.selectedTagId); + const tagId = + selectedTagId != null && tagIds.includes(selectedTagId) + ? selectedTagId + : tagIds[0] ?? null; + const products = tagId == null ? fallbackProducts : productsByTagId[tagId] ?? []; + + return ( + <> + + + + + + ); +}); +FlashTagSection.displayName = 'FlashTagSection'; + +interface FlashStoreSectionProps { + storeItems: FlashTabItem[]; + storeIds: number[]; + productsByStoreId: Record; + onProductPress: (productId: number) => void; +} + +/** "Shop by Store" heading, its strip and grid. Picking a store wakes only this. */ +const FlashStoreSection = React.memo(({ + storeItems, + storeIds, + productsByStoreId, + onProductPress, +}: FlashStoreSectionProps) => { + const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId); + const storeId = + selectedStoreId != null && storeIds.includes(selectedStoreId) + ? selectedStoreId + : storeIds[0] ?? null; + + return ( + + + + Shop by Store + + + + + + + + ); +}); +FlashStoreSection.displayName = 'FlashStoreSection'; + +export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsProps) { useHideTabNav('quick_delivery'); - const [searchQuery, setSearchQuery] = useState(''); - const [selectedTagId, setSelectedTagId] = useState(null); - const [selectedStoreId, setSelectedStoreId] = useState(null); - const [tagVisibleCount, setTagVisibleCount] = useState(FLASH_PAGE_SIZE); - const [storeVisibleCount, setStoreVisibleCount] = useState(FLASH_PAGE_SIZE); // Owned by the user's pull, not by React Query: `isFetching` is true for every // background fetch (remount-after-stale, invalidation, version bump), which // made the pull-to-refresh spinner pop up on its own. @@ -569,92 +810,75 @@ export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDelivery const { data: storesData, refetch: refetchStores } = useStores(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); - const tags = productsQuery?.data?.tags || []; - const stores = storesData?.stores || []; - - const trimmedQuery = searchQuery.trim().toLowerCase(); - - const flashProducts = React.useMemo(() => { + // Single memo for the flash catalogue. Tabs, per-tab rows and per-store rows + // are derived together so the screen never holds two views of the same + // payload that can drift apart. Picking a tab no longer touches any of it. + const { + tagItems, + tagIds, + productsByTagId, + storeItems, + storeIds, + productsByStoreId, + flashProducts, + } = React.useMemo(() => { const products = productsQuery?.data?.products || []; - return products.filter((p: any) => { - const info = productSlotsMap[p.id]; + const tags = productsQuery?.data?.tags || []; + const stores = storesData?.stores || []; + + const flashProducts = products.filter((product: any) => { + const info = productSlotsMap[product.id]; return info?.isFlashAvailable && !info?.isOutOfStock; }); - }, [productsQuery?.data?.products, productSlotsMap]); - const flashProductIds = React.useMemo( - () => new Set(flashProducts.map((p: any) => p.id)), - [flashProducts] + const flashProductIds = new Set(flashProducts.map((product: any) => product.id)); + const flashStoreIds = new Set(flashProducts.map((product: any) => product.storeId)); + + // A tab only exists if it has at least one in-stock flash product; empty + // tags and stores are not shown at all. + const tagTabs = tags.filter((tag: any) => + ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) + ); + const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id)); + + const productsByTagId: Record = {}; + for (const tag of tagTabs) { + const ids = new Set((tag.productIds || []) as number[]); + productsByTagId[tag.id] = flashProducts.filter((product: any) => ids.has(product.id)); + } + + const productsByStoreId: Record = {}; + for (const store of storeTabs) { + productsByStoreId[store.id] = flashProducts.filter( + (product: any) => product.storeId === store.id + ); + } + + return { + tagItems: tagTabs.map((tag: any) => ({ id: tag.id, label: tag.tagName })), + tagIds: tagTabs.map((tag: any) => tag.id), + productsByTagId, + storeItems: storeTabs.map((store: any) => ({ + id: store.id, + label: store.name.replace(/^The\s+/i, ''), + })), + storeIds: storeTabs.map((store: any) => store.id), + productsByStoreId, + flashProducts, + }; + }, [productsQuery?.data, storesData, productSlotsMap]); + + // Stable so FlashProductItem/FlashProductGrid memos survive a re-render. + const handleProductPress = React.useCallback( + (productId: number) => { + if (onProductPress) { + onProductPress(productId); + } else { + router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${productId}`); + } + }, + [onProductPress, router] ); - const flashStoreIds = React.useMemo( - () => new Set(flashProducts.map((p: any) => p.storeId)), - [flashProducts] - ); - - // A tab only exists if it has at least one in-stock flash product; empty - // tags and stores are not shown at all. - const tagTabs = React.useMemo( - () => - tags.filter((tag: any) => - ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) - ), - [tags, flashProductIds] - ); - const storeTabs = React.useMemo( - () => stores.filter((store: any) => flashStoreIds.has(store.id)), - [stores, flashStoreIds] - ); - - // First visible tab is the default, matching the home page. - const activeTagId = tagTabs.some((tag: any) => tag.id === selectedTagId) - ? selectedTagId - : tagTabs[0]?.id ?? null; - const activeStoreId = storeTabs.some((store: any) => store.id === selectedStoreId) - ? selectedStoreId - : storeTabs[0]?.id ?? null; - - const tagProductIds = React.useMemo(() => { - const tag = tagTabs.find((t: any) => t.id === activeTagId); - return new Set((tag?.productIds || []) as number[]); - }, [tagTabs, activeTagId]); - - const matchesSearch = React.useCallback( - (product: any) => - !trimmedQuery || product.name?.toLowerCase().includes(trimmedQuery), - [trimmedQuery] - ); - - const tagProducts = React.useMemo( - () => - flashProducts.filter( - (product: any) => - (activeTagId == null || tagProductIds.has(product.id)) && - matchesSearch(product) - ), - [flashProducts, activeTagId, tagProductIds, matchesSearch] - ); - - const storeProducts = React.useMemo( - () => - flashProducts.filter( - (product: any) => - (activeStoreId == null || product.storeId === activeStoreId) && - matchesSearch(product) - ), - [flashProducts, activeStoreId, matchesSearch] - ); - - // Each section pages independently; a tab or search change starts over. - React.useEffect(() => { - setTagVisibleCount(FLASH_PAGE_SIZE); - }, [activeTagId, trimmedQuery]); - - React.useEffect(() => { - setStoreVisibleCount(FLASH_PAGE_SIZE); - }, [activeStoreId, trimmedQuery]); - - const visibleTagProducts = tagProducts.slice(0, tagVisibleCount); - const visibleStoreProducts = storeProducts.slice(0, storeVisibleCount); const refetchProducts = productsQuery?.refetch; const handleRefresh = React.useCallback(async () => { @@ -679,52 +903,6 @@ export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDelivery [isRefreshing, handleRefresh] ); - const renderProduct = (item: any) => ( - - { - if (onProductPress) { - onProductPress(item.id); - } else { - router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${item.id}`); - } - }} - /> - - ); - - const renderGrid = (products: any[], testID: string) => ( - - {products.map(renderProduct)} - - ); - - const renderShowMore = (testID: string, onPress: () => void) => ( - - - Show More - - - ); - - const renderEmpty = () => ( - - No 1 Hr Delivery products available. - - ); - if (productsQuery?.isLoading) { return ( @@ -754,60 +932,26 @@ export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDelivery refreshControl={refreshControl} > - + {/* Tag section — tabs scroll with the page, not sticky. */} - ({ id: tag.id, label: tag.tagName }))} - activeId={activeTagId} - onSelect={setSelectedTagId} + - - {tagProducts.length > 0 - ? renderGrid(visibleTagProducts, 'flash-tag-grid') - : renderEmpty()} - {tagProducts.length > tagVisibleCount && - renderShowMore('flash-products-show-more', () => - setTagVisibleCount((count) => count + FLASH_PAGE_SIZE) - )} - {/* Shop by Store — one tab per store. */} - {storeTabs.length > 0 && ( - - - - Shop by Store - - - ({ - id: store.id, - label: store.name.replace(/^The\s+/i, ''), - }))} - activeId={activeStoreId} - onSelect={setSelectedStoreId} + {storeIds.length > 0 && ( + - - {storeProducts.length > 0 - ? renderGrid(visibleStoreProducts, 'flash-store-grid') - : renderEmpty()} - {storeProducts.length > storeVisibleCount && - renderShowMore('flash-store-show-more', () => - setStoreVisibleCount((count) => count + FLASH_PAGE_SIZE) - )} - - )} ); diff --git a/apps/user-ui/src/lib/region-switch.ts b/apps/user-ui/src/lib/region-switch.ts index b1d7c85..dec6984 100644 --- a/apps/user-ui/src/lib/region-switch.ts +++ b/apps/user-ui/src/lib/region-switch.ts @@ -11,6 +11,7 @@ import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useHomeTagStore } from '@/src/store/homeTagStore' +import { useFlashTabStore } from '@/src/store/flashTabStore' /** * The one and only way to change the browsing region. @@ -57,6 +58,8 @@ export async function confirmRegionSwitch( // Tag ids belong to the outgoing region; a stale selection would point at a // tag the new catalog does not have. useHomeTagStore.getState().resetHomeTags() + // Same for the 1 Hr Delivery tag/store tabs and its search box. + useFlashTabStore.getState().resetFlashTabs() // 3. Drop cached regional catalog/slot snapshots so they cannot leak across. const productStore = useCentralProductStore.getState() diff --git a/apps/user-ui/src/store/flashTabStore.ts b/apps/user-ui/src/store/flashTabStore.ts new file mode 100644 index 0000000..cd3aff1 --- /dev/null +++ b/apps/user-ui/src/store/flashTabStore.ts @@ -0,0 +1,45 @@ +import { create } from 'zustand' + +interface FlashTabState { + /** User-picked flash tag; null means "first tag with flash products". */ + selectedTagId: number | null + /** User-picked store in "Shop by Store"; null means the first store tab. */ + selectedStoreId: number | null + /** Search box value; kept here so typing wakes only the two grids. */ + searchQuery: string + selectTag: (tagId: number) => void + selectStore: (storeId: number) => void + setSearchQuery: (query: string) => void + resetFlashTabs: () => void +} + +/** + * Flash page selection lives outside FlashDeliveryProducts on purpose: while it + * was local state, every tap re-rendered the page, both tab strips, both grids + * and every ProductCard. Only FlashTagStrip/FlashStoreStrip, FlashSearchBar and + * the two scene components subscribe here. + */ +export const useFlashTabStore = create((set) => ({ + selectedTagId: null, + selectedStoreId: null, + searchQuery: '', + + // No-op when unchanged: re-selecting the active tab must not wake + // subscribers (same guard as homeTagStore.selectTag). + selectTag: (tagId) => + set((state) => + state.selectedTagId === tagId ? state : { selectedTagId: tagId } + ), + + selectStore: (storeId) => + set((state) => + state.selectedStoreId === storeId ? state : { selectedStoreId: storeId } + ), + + setSearchQuery: (query) => + set((state) => (state.searchQuery === query ? state : { searchQuery: query })), + + // Tag and store ids are region-scoped, so a region switch has to drop them. + resetFlashTabs: () => + set({ selectedTagId: null, selectedStoreId: null, searchQuery: '' }), +})) diff --git a/apps/user-ui/tests/helpers/reset.ts b/apps/user-ui/tests/helpers/reset.ts index 6ddb26f..b2e1fff 100644 --- a/apps/user-ui/tests/helpers/reset.ts +++ b/apps/user-ui/tests/helpers/reset.ts @@ -26,6 +26,7 @@ import { useLocationStore } from '@/src/store/locationStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useHomeTagStore } from '@/src/store/homeTagStore' +import { useFlashTabStore } from '@/src/store/flashTabStore' export function resetStores() { useAppStore.setState({ hideTabsNav: {} }) @@ -56,6 +57,7 @@ export function resetStores() { useSlotStore.setState({ slotId: undefined, storeId: undefined }) useFlashNavigationStore.setState({ shouldNavigateToCart: false }) useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} }) + useFlashTabStore.setState({ selectedTagId: null, selectedStoreId: null, searchQuery: '' }) useLocationStore.getState().stop() useLocationStore.setState({ coords: null, status: 'idle', error: null }) } diff --git a/apps/user-ui/tests/lib/stores.test.ts b/apps/user-ui/tests/lib/stores.test.ts index d65be8b..8b63c0b 100644 --- a/apps/user-ui/tests/lib/stores.test.ts +++ b/apps/user-ui/tests/lib/stores.test.ts @@ -22,6 +22,7 @@ import { useRegionStore } from '@/src/store/regionStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useHomeTagStore } from '@/src/store/homeTagStore' +import { useFlashTabStore } from '@/src/store/flashTabStore' import { AVAILABILITY, MERGED_PRODUCTS, @@ -82,6 +83,39 @@ describe('stores', () => { expect(useHomeTagStore.getState().expandedByTagId).toEqual({}) }) + it('STORE-23: re-selecting the active flash tab keeps the store identity', () => { + useFlashTabStore.getState().selectTag(5) + useFlashTabStore.getState().selectStore(3) + const before = useFlashTabStore.getState() + + useFlashTabStore.getState().selectTag(5) + useFlashTabStore.getState().selectStore(3) + + // Same state object, so the strips and sections are not woken. + expect(useFlashTabStore.getState()).toBe(before) + }) + + it('STORE-24: resetFlashTabs drops both selections and the search box', () => { + useFlashTabStore.getState().selectTag(5) + useFlashTabStore.getState().selectStore(3) + useFlashTabStore.getState().setSearchQuery('chick') + + useFlashTabStore.getState().resetFlashTabs() + + expect(useFlashTabStore.getState().selectedTagId).toBeNull() + expect(useFlashTabStore.getState().selectedStoreId).toBeNull() + expect(useFlashTabStore.getState().searchQuery).toBe('') + }) + + it('STORE-25: an unchanged flash search query keeps the store identity', () => { + useFlashTabStore.getState().setSearchQuery('chick') + const before = useFlashTabStore.getState() + + useFlashTabStore.getState().setSearchQuery('chick') + + expect(useFlashTabStore.getState()).toBe(before) + }) + it('STORE-02: addressStore selects and clears an address id', () => { useAddressStore.getState().setSelectedAddressId(11) expect(useAddressStore.getState().selectedAddressId).toBe(11) diff --git a/apps/web-ui/src/lib/region-switch.ts b/apps/web-ui/src/lib/region-switch.ts index 14ee7f6..3edbefc 100644 --- a/apps/web-ui/src/lib/region-switch.ts +++ b/apps/web-ui/src/lib/region-switch.ts @@ -11,6 +11,7 @@ import { useCentralSlotStore } from './stores/central-slot-store' import { useSlotStore } from './stores/slot-store' import { useFlashNavigationStore } from './stores/flash-navigation-store' import { useHomeTagStore } from './stores/home-tag-store' +import { useFlashTabStore } from './stores/flash-tab-store' /** * The one and only way to change the browsing region. @@ -54,6 +55,8 @@ export async function confirmRegionSwitch( // Tag ids belong to the outgoing region; a stale selection would point at a // tag the new catalog does not have. useHomeTagStore.getState().resetHomeTags() + // Same for the 1 Hr Delivery tag/store tabs and its search box. + useFlashTabStore.getState().resetFlashTabs() // 3. Drop cached regional catalog/slot snapshots so they cannot leak across. const productStore = useCentralProductStore.getState() diff --git a/apps/web-ui/src/lib/stores/flash-tab-store.ts b/apps/web-ui/src/lib/stores/flash-tab-store.ts new file mode 100644 index 0000000..28b03c3 --- /dev/null +++ b/apps/web-ui/src/lib/stores/flash-tab-store.ts @@ -0,0 +1,41 @@ +import { create } from 'zustand' + +interface FlashTabState { + /** User-picked flash tag; null means "first tag with flash products". */ + selectedTagId: number | null + /** User-picked store in "Shop by Store"; null means the first store tab. */ + selectedStoreId: number | null + /** Search box value; kept here so typing wakes only the two grids. */ + searchQuery: string + selectTag: (tagId: number) => void + selectStore: (storeId: number) => void + setSearchQuery: (query: string) => void + resetFlashTabs: () => void +} + +/** + * Mirrors apps/user-ui/src/store/flashTabStore.ts. The web flash page is + * split into the same memoized sections, so the state shape and reset + * behaviour stay identical to the native app. + */ +export const useFlashTabStore = create((set) => ({ + selectedTagId: null, + selectedStoreId: null, + searchQuery: '', + + selectTag: (tagId) => + set((state) => + state.selectedTagId === tagId ? state : { selectedTagId: tagId } + ), + + selectStore: (storeId) => + set((state) => + state.selectedStoreId === storeId ? state : { selectedStoreId: storeId } + ), + + setSearchQuery: (query) => + set((state) => (state.searchQuery === query ? state : { searchQuery: query })), + + resetFlashTabs: () => + set({ selectedTagId: null, selectedStoreId: null, searchQuery: '' }), +})) diff --git a/apps/web-ui/src/routes/flash.tsx b/apps/web-ui/src/routes/flash.tsx index 10fc41b..2ac8bd4 100644 --- a/apps/web-ui/src/routes/flash.tsx +++ b/apps/web-ui/src/routes/flash.tsx @@ -1,9 +1,10 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router' -import { useState, useMemo, useRef, useEffect } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { MiniQuantifier } from 'web-components' import { useAllProducts, useStores } from '../hooks/prominent-api-hooks' import { useCentralProductStore } from '../lib/stores/central-product-store' import { useCentralSlotStore } from '../lib/stores/central-slot-store' +import { useFlashTabStore } from '../lib/stores/flash-tab-store' import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks' import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores' import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore' @@ -18,9 +19,262 @@ export const Route = createFileRoute('/flash')({ // Three rows of three at a time, like the home catalog. const PAGE_SIZE = 9 -function FlashDeliveryPage() { - const navigate = useNavigate() +const GRID_CLASS = + 'grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5' +const STRIP_CLASS = + 'scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0' +interface TabItem { + id: number + label: string +} + +/** Active tab, resolved the way the page always did: the picked id while it + * still exists in this region's catalogue, otherwise the first tab. */ +function resolveActiveId(items: TabItem[], picked: number | null): number | null { + if (picked != null && items.some((item) => item.id === picked)) return picked + return items[0]?.id ?? null +} + +/** + * Tag tabs. Reads the selection from the store, so a tap re-renders only this + * strip and the tag grid — mirroring the native FlashTagStrip/TagScene split. + */ +const FlashTagStrip = memo(({ items }: { items: TabItem[] }) => { + const selectedTagId = useFlashTabStore((state) => state.selectedTagId) + const selectTag = useFlashTabStore((state) => state.selectTag) + + const scrollRef = useRef(null) + const positions = useRef([]) + const activeId = resolveActiveId(items, selectedTagId) + const index = Math.max( + 0, + items.findIndex((item) => item.id === activeId) + ) + + useEffect(() => { + const x = positions.current[index] + if (x != null) { + scrollRef.current?.scrollTo({ left: Math.max(0, x - 16), behavior: 'smooth' }) + } + }, [index]) + + if (items.length === 0) return null + + return ( +
+ {items.map((item, i) => { + const active = item.id === activeId + return ( + + ) + })} +
+ ) +}) +FlashTagStrip.displayName = 'FlashTagStrip' + +const FlashStoreStrip = memo(({ items }: { items: TabItem[] }) => { + const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId) + const selectStore = useFlashTabStore((state) => state.selectStore) + + const activeId = resolveActiveId(items, selectedStoreId) + + if (items.length === 0) return null + + return ( +
+ {items.map((item) => { + const active = item.id === activeId + return ( + + ) + })} +
+ ) +}) +FlashStoreStrip.displayName = 'FlashStoreStrip' + +/** One card. Navigation is derived from the id so the parent handler identity + * is the only prop that can invalidate the memo. */ +const FlashProductItem = memo( + ({ item, onAddToCart }: { item: any; onAddToCart: (productId: number) => void }) => { + const navigate = useNavigate() + const handlePress = useCallback(() => { + navigate({ to: '/flash/product/$id', params: { id: String(item.id) } }) + }, [navigate, item.id]) + + return ( + + ) + } +) +FlashProductItem.displayName = 'FlashProductItem' + +interface FlashProductGridProps { + products: any[] + onAddToCart: (productId: number) => void +} + +/** + * One paged grid. Owns its visible count and is keyed by the active tab, so a + * tab switch resets the page size on the first render instead of in an effect. + */ +const FlashProductGrid = memo(({ products, onAddToCart }: FlashProductGridProps) => { + const [visibleCount, setVisibleCount] = useState(PAGE_SIZE) + const visible = products.length > visibleCount ? products.slice(0, visibleCount) : products + + if (products.length === 0) { + return ( +
+

No flash delivery products available.

+
+ ) + } + + return ( + <> +
+ {visible.map((product: any) => ( + + ))} +
+ + {products.length > visibleCount && ( +
+ +
+ )} + + ) +}) +FlashProductGrid.displayName = 'FlashProductGrid' + +interface FlashTagSectionProps { + tagItems: TabItem[] + tagIds: number[] + productsByTagId: Record + /** With no tags configured the section lists every flash product. */ + fallbackProducts: any[] + onAddToCart: (productId: number) => void +} + +const FlashTagSection = memo( + ({ + tagItems, + tagIds, + productsByTagId, + fallbackProducts, + onAddToCart, + }: FlashTagSectionProps) => { + const selectedTagId = useFlashTabStore((state) => state.selectedTagId) + const tagId = + selectedTagId != null && tagIds.includes(selectedTagId) + ? selectedTagId + : tagIds[0] ?? null + const products = tagId == null ? fallbackProducts : productsByTagId[tagId] ?? [] + const label = tagItems.find((item) => item.id === tagId)?.label ?? 'All Products' + + return ( + <> + + +
+

{label}

+

{products.length} items

+
+ + + + ) + } +) +FlashTagSection.displayName = 'FlashTagSection' + +interface FlashStoreSectionProps { + storeItems: TabItem[] + storeIds: number[] + productsByStoreId: Record + onAddToCart: (productId: number) => void +} + +const FlashStoreSection = memo( + ({ storeItems, storeIds, productsByStoreId, onAddToCart }: FlashStoreSectionProps) => { + const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId) + const storeId = + selectedStoreId != null && storeIds.includes(selectedStoreId) + ? selectedStoreId + : storeIds[0] ?? null + const products = productsByStoreId[storeId ?? -1] ?? [] + + return ( +
+
+

Shop by Store

+

{products.length} items

+
+ + + + +
+ ) + } +) +FlashStoreSection.displayName = 'FlashStoreSection' + +function FlashDeliveryPage() { // Populate central stores so flash-eligible products resolve on direct load usePopulateCentralStores() usePopulateCentralProductStore() @@ -30,111 +284,84 @@ function FlashDeliveryPage() { const { productsById } = useCentralProductStore() const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) - const tags = productsData?.tags || [] - const stores = storesData?.stores || [] - const addToCart = useAddToCart('flash') const { data: cartData } = useGetCart('flash') - // Get flash products from central store - const allFlashProducts = useMemo(() => { - return Object.values(productsById).filter( + // Single memo for the flash catalogue: tabs and per-tab rows are derived + // together so the page never holds two views of the same payload. Picking a + // tab no longer touches any of it. + const { + tagItems, + tagIds, + productsByTagId, + storeItems, + storeIds, + productsByStoreId, + allFlashProducts, + } = useMemo(() => { + const tags = productsData?.tags || [] + const stores = storesData?.stores || [] + + const allFlashProducts = Object.values(productsById).filter( (product: any) => product && productSlotsMap[product.id]?.isFlashAvailable && !productSlotsMap[product.id]?.isOutOfStock ) - }, [productsById, productSlotsMap]) - const flashProductIds = useMemo( - () => new Set(allFlashProducts.map((p: any) => p.id)), - [allFlashProducts] - ) - const flashStoreIds = useMemo( - () => new Set(allFlashProducts.map((p: any) => p.storeId)), - [allFlashProducts] - ) + const flashProductIds = new Set(allFlashProducts.map((p: any) => p.id)) + const flashStoreIds = new Set(allFlashProducts.map((p: any) => p.storeId)) - // A tab only exists when it has at least one in-stock flash product. - const tagTabs = useMemo( - () => - tags.filter((tag: any) => - ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) - ), - [tags, flashProductIds] - ) - const storeTabs = useMemo( - () => stores.filter((store: any) => flashStoreIds.has(store.id)), - [stores, flashStoreIds] - ) - - // Tag tabs — same order and default as the home page. - const [selectedTagId, setSelectedTagId] = useState(null) - const activeTagId = tagTabs.some((tag: any) => tag.id === selectedTagId) - ? selectedTagId - : tagTabs[0]?.id ?? null - const activeTag = tagTabs.find((tag: any) => tag.id === activeTagId) || null - const tagProductIds = useMemo( - () => new Set((activeTag?.productIds || []) as number[]), - [activeTag] - ) - - // Auto-scroll the active tag into view - const tabsScrollRef = useRef(null) - const tabPositions = useRef([]) - const activeTabIndex = Math.max( - 0, - tagTabs.findIndex((tag: any) => tag.id === activeTagId) - ) - - useEffect(() => { - const x = tabPositions.current[activeTabIndex] - if (x != null) { - tabsScrollRef.current?.scrollTo({ left: Math.max(0, x - 16), behavior: 'smooth' }) - } - }, [activeTabIndex]) - - // Products to show: the active tag's flash items, or everything when no - // tags are configured. - const filteredProducts = useMemo(() => { - if (activeTagId == null) return allFlashProducts - return allFlashProducts.filter((p: any) => tagProductIds.has(p.id)) - }, [activeTagId, allFlashProducts, tagProductIds]) - - // Home's pattern: a page at a time, with a Show More button. - const [visibleCount, setVisibleCount] = useState(PAGE_SIZE) - useEffect(() => { - setVisibleCount(PAGE_SIZE) - }, [activeTagId]) - const visibleProducts = filteredProducts.slice(0, visibleCount) - - // Shop by Store — one tab per store that has flash products. - const [selectedStoreId, setSelectedStoreId] = useState(null) - const activeStoreId = storeTabs.some((store: any) => store.id === selectedStoreId) - ? selectedStoreId - : storeTabs[0]?.id ?? null - const storeProducts = useMemo(() => { - if (activeStoreId == null) return allFlashProducts - return allFlashProducts.filter((p: any) => p.storeId === activeStoreId) - }, [activeStoreId, allFlashProducts]) - - const [storeVisibleCount, setStoreVisibleCount] = useState(PAGE_SIZE) - useEffect(() => { - setStoreVisibleCount(PAGE_SIZE) - }, [activeStoreId]) - const visibleStoreProducts = storeProducts.slice(0, storeVisibleCount) - - const handleAddToCart = (productId: number) => { - const item = allFlashProducts.find((p: any) => p.id === productId) - addToCart.mutate( - { skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 }, - { - onSuccess: () => { - alert(`Added ${item?.name || 'item'} for 1 Hr Delivery`) - }, - } + // A tab only exists when it has at least one in-stock flash product. + const tagTabs = tags.filter((tag: any) => + ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) ) - } + const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id)) + + const productsByTagId: Record = {} + for (const tag of tagTabs) { + const ids = new Set((tag.productIds || []) as number[]) + productsByTagId[tag.id] = allFlashProducts.filter((product: any) => + ids.has(product.id) + ) + } + + const productsByStoreId: Record = {} + for (const store of storeTabs) { + productsByStoreId[store.id] = allFlashProducts.filter( + (product: any) => product.storeId === store.id + ) + } + + return { + tagItems: tagTabs.map((tag: any) => ({ id: tag.id, label: tag.tagName })), + tagIds: tagTabs.map((tag: any) => tag.id), + productsByTagId, + storeItems: storeTabs.map((store: any) => ({ + id: store.id, + label: store.name.replace(/^The\s+/i, ''), + })), + storeIds: storeTabs.map((store: any) => store.id), + productsByStoreId, + allFlashProducts, + } + }, [productsData, storesData, productsById, productSlotsMap]) + + // Stable so FlashProductItem memos survive a section re-render. + const handleAddToCart = useCallback( + (productId: number) => { + const item = allFlashProducts.find((p: any) => p.id === productId) + addToCart.mutate( + { skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 }, + { + onSuccess: () => { + alert(`Added ${item?.name || 'item'} for 1 Hr Delivery`) + }, + } + ) + }, + [addToCart, allFlashProducts] + ) return ( @@ -161,155 +388,21 @@ function FlashDeliveryPage() { {/* Tag tabs — same model as the home page tabs */} - {tagTabs.length > 0 && ( -
- {tagTabs.map((tag: any, i: number) => { - const active = activeTagId === tag.id - return ( - - ) - })} -
- )} + -
-

- {activeTag?.tagName ?? 'All Products'} -

-

- {filteredProducts.length} items -

-
- -
- {visibleProducts.map((product: any) => ( - - navigate({ - to: '/flash/product/$id', - params: { id: String(product.id) }, - }) - } - /> - ))} -
- - {filteredProducts.length > visibleCount && ( -
- -
- )} - - {filteredProducts.length === 0 && ( -
-

- No flash delivery products available. -

-
- )} - - {storeTabs.length > 0 && ( -
-
-

Shop by Store

-

{storeProducts.length} items

-
- - {/* Store tabs — one per store, scrolled by the page itself */} -
- {storeTabs.map((store: any) => { - const active = activeStoreId === store.id - return ( - - ) - })} -
- -
- {visibleStoreProducts.map((product: any) => ( - - navigate({ - to: '/flash/product/$id', - params: { id: String(product.id) }, - }) - } - /> - ))} -
- - {storeProducts.length > storeVisibleCount && ( -
- -
- )} - - {storeProducts.length === 0 && ( -
-

- No flash delivery products available. -

-
- )} -
+ {storeIds.length > 0 && ( + )} @@ -317,7 +410,9 @@ function FlashDeliveryPage() { ) } -function CompactProductCard({ +// Memoised: identical to the native ProductCard change — an unmemoised card +// re-runs its cart hooks for every sibling whenever its section re-renders. +const CompactProductCard = memo(function CompactProductCard({ item, handleAddToCart, onPress, @@ -401,4 +496,4 @@ function CompactProductCard({ ); -} +}) diff --git a/change-log.txt b/change-log.txt index 1e54791..b34effa 100644 --- a/change-log.txt +++ b/change-log.txt @@ -436,3 +436,55 @@ list keeps roughly a seventh of the off-screen rows it used to. ~ src/components/CouponForm.tsx ~ src/components/TagForm.tsx - admin-web uses the non-virtualized web MyFlatList; unchanged. + +[2026-11-02 08:01:30 IST] flash-delivery: move tab/search selection out of the page component so a tab tap stops re-rendering the whole screen. + +The page held selectedTagId, selectedStoreId, searchQuery and both visible +counts in FlashDeliveryProducts. A tap re-rendered the page, both strips, both +grids and every ProductCard (ProductCard is not memoized and renderProduct +built a new onPress per render). Tabs also rendered twice per tap: the +visible-count reset lived in a useEffect that ran after paint. + +--- apps/user-ui/src/store/flashTabStore.ts (new) ++ selectedTagId / selectedStoreId / searchQuery plus selectTag, selectStore, + setSearchQuery, resetFlashTabs. select* are same-value no-ops (same guard as + homeTagStore) so re-tapping the active tab does not wake subscribers. +--- apps/web-ui/src/lib/stores/flash-tab-store.ts (new) ++ mirror of the native store (same shape, same reset). +--- apps/user-ui/components/SlotSpecificView.tsx +~ FlashDeliveryProducts now only derives the catalog: one memo builds + tagTabs, storeTabs, per-tag rows (productsByTagId) and per-store rows + (productsByStoreId), plus the stable tab item arrays. +~ New FlashSearchBar subscribes to the store, so typing no longer re-renders + the page, the strips or the other grid. +~ New FlashTagStrip / FlashStoreStrip wrappers subscribe to the store and + derive activeId themselves; FlashTabStrip keeps its memo and now receives + stable items/onSelect, so it no longer rebuilds on every keystroke. +~ New FlashTagSection / FlashStoreSection (memo) subscribe to the store, so a + tag tap re-renders only the tag grid and a store tap only the store section. +~ New FlashProductGrid owns visibleCount; the grid is keyed by active id so a + tab switch resets the page size in one render (no effect, no double paint). + A search change resets it during render with the same pattern. +~ New FlashProductItem (memo) derives its onPress from item.id; the page's + onProductPress handler is a useCallback. +--- apps/user-ui/components/ProductCard.tsx +~ default export wrapped in React.memo; parents pass stable item/onPress. +--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx +~ handleProductPress wrapped in useCallback (it was recreated every render, + which defeated memoisation on every card). +--- apps/user-ui/src/lib/region-switch.ts, apps/web-ui/src/lib/region-switch.ts +~ resetFlashTabs() on region switch: tag/store ids are region-scoped. +--- apps/user-ui/tests/helpers/reset.ts +~ reset the flash tab store between cases. +--- apps/web-ui/src/routes/flash.tsx +~ same restructure: store-backed selection/search, memoized + FlashTagStrip / FlashStoreStrip / FlashProductGrid / FlashProductItem, + CompactProductCard wrapped in memo with a stable handleAddToCart. +- Flash grids are still plain maps inside the page ScrollView (no FlatList); + virtualization left for a follow-up since the page stacks two sections. +--- apps/user-ui/tests/lib/stores.test.ts ++ STORE-23: re-selecting the active flash tag/store keeps the store identity. ++ STORE-24: resetFlashTabs drops both selections and the search box. ++ STORE-25: an unchanged flash search query keeps the store identity. +--- apps/user-ui/JEST-TEST-CASES.md +~ catalogue rows STORE-23..25 added.