This commit is contained in:
shafi54 2026-11-01 19:29:01 +05:30
parent cfdac49def
commit 172368d1a5
4 changed files with 284 additions and 164 deletions

View file

@ -31,6 +31,7 @@ import TabLayoutWrapper from "@/components/TabLayoutWrapper";
import LocationBar from "@/src/components/LocationBar"; import LocationBar from "@/src/components/LocationBar";
import { useNavigationStore } from "@/src/store/navigationStore"; import { useNavigationStore } from "@/src/store/navigationStore";
import { useHomeTagStore } from "@/src/store/homeTagStore"; import { useHomeTagStore } from "@/src/store/homeTagStore";
import { HOME_INITIAL_RENDER_COUNT, HOME_MAX_RENDER_BATCH, HOME_WINDOW_SIZE } from "@/src/lib/home-list-tuning";
import NextOrderGlimpse from "@/components/NextOrderGlimpse"; import NextOrderGlimpse from "@/components/NextOrderGlimpse";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@ -365,116 +366,128 @@ const ProductItem = memo(({ item, onPress }: ProductItemProps) => {
); );
}); });
interface ListHeaderProps { type CatalogItem =
dashboardTags: any[]; | { key: string; kind: 'glimpse' }
productsByTagId: Record<number, any[]>; | { key: string; kind: 'tagStrip' }
onProductPress: (id: number) => void; | { key: string; kind: 'tagScene' }
storesData: any; | { key: string; kind: 'stores' }
sortedSlots: any[]; | { key: string; kind: 'slots' }
} | { key: string; kind: 'allProductsTitle' }
| { key: string; kind: 'empty' }
| { key: string; kind: 'row'; products: any[] };
const ListHeader = memo(({ const HomeGlimpse = memo(() => (
<View style={tw`pt-2`}>
<NextOrderGlimpse />
</View>
));
// The tag grid is its own list item so it can unmount with the rest of the top
// block instead of being pinned inside one giant header cell.
const TagSceneBlock = memo(({
dashboardTags, dashboardTags,
productsByTagId, productsByTagId,
onProductPress, onProductPress,
storesData, }: TagSceneProps) => (
sortedSlots, <View
}: ListHeaderProps) => { style={[
tw`mx-4 mt-1 rounded-[28px] px-3 pt-3 pb-4`,
{ backgroundColor: theme.colors.brand25 },
]}
>
<TagScene
dashboardTags={dashboardTags}
productsByTagId={productsByTagId}
onProductPress={onProductPress}
/>
</View>
));
const StoresSection = memo(({ storesData }: { storesData: any }) => {
if (!storesData?.stores || storesData.stores.length === 0) return null;
return (
<View style={tw`bg-white px-4`}>
<View style={tw`mt-4 mb-5 rounded-[28px] bg-white shadow-sm border border-gray-100 px-3 pt-4 pb-2`}>
<View style={tw`flex-row items-center justify-between mb-4 px-1`}>
<View>
<MyText style={tw`text-xl font-extrabold text-gray-900 tracking-tight`}>
Our Stores
</MyText>
<MyText style={tw`text-xs font-medium mt-0.5 text-gray-500`}>Fresh from our locations</MyText>
</View>
</View>
<View style={tw`pb-2`}>
<View style={tw`flex-row flex-wrap`}>
{storesData.stores.map((store: any) => (
<View key={store.id} style={tw`w-1/4 p-1`}>
<RenderStore item={store} />
</View>
))}
</View>
</View>
</View>
</View>
);
});
const SlotsSection = memo(({ sortedSlots }: { sortedSlots: any[] }) => {
const renderSlotItem = useCallback(({ item }: { item: any }) => ( const renderSlotItem = useCallback(({ item }: { item: any }) => (
<SlotItem item={item} /> <SlotItem item={item} />
), []); ), []);
if (sortedSlots.length === 0) return null;
return ( return (
<> <View style={tw`bg-white px-4`}>
<View style={tw`pt-2`}> <View style={tw`mt-2 mb-4`}>
<NextOrderGlimpse /> <View style={tw`flex-row items-center justify-between px-1 mb-6`}>
</View> <View>
{dashboardTags.length > 0 && ( <View style={tw`flex-row items-center mb-1.5`}>
<TagTabStrip dashboardTags={dashboardTags} /> <View style={tw`w-1 h-5 rounded-full bg-brand500 mr-2.5`} />
)} <MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>Upcoming Delivery Slots</MyText>
{dashboardTags.length > 0 && (
<View
style={[
tw`mx-4 mt-1 rounded-[28px] px-3 pt-3 pb-4`,
{ backgroundColor: theme.colors.brand25 },
]}
>
<TagScene
dashboardTags={dashboardTags}
productsByTagId={productsByTagId}
onProductPress={onProductPress}
/>
</View>
)}
<View
style={[
tw`rounded-t-3xl px-4`,
{ backgroundColor: '#FFFFFF' },
]}
>
{storesData?.stores && storesData.stores.length > 0 && (
<View style={tw`mt-4 mb-5 rounded-[28px] bg-white shadow-sm border border-gray-100 px-3 pt-4 pb-2`}>
<View style={tw`flex-row items-center justify-between mb-4 px-1`}>
<View>
<MyText style={tw`text-xl font-extrabold text-gray-900 tracking-tight`}>
Our Stores
</MyText>
<MyText style={tw`text-xs font-medium mt-0.5 text-gray-500`}>Fresh from our locations</MyText>
</View>
</View>
<View style={tw`pb-2`}>
<View style={tw`flex-row flex-wrap`}>
{storesData.stores.map((store: any) => (
<View key={store.id} style={tw`w-1/4 p-1`}>
<RenderStore item={store} />
</View>
))}
</View>
</View>
</View>
)}
{sortedSlots.length > 0 && (
<View style={tw`mt-2 mb-4`}>
<View style={tw`flex-row items-center justify-between px-1 mb-6`}>
<View>
<View style={tw`flex-row items-center mb-1.5`}>
<View style={tw`w-1 h-5 rounded-full bg-brand500 mr-2.5`} />
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>Upcoming Delivery Slots</MyText>
</View>
<MyText style={tw`text-sm text-gray-500 font-medium ml-4`}>Plan your fresh deliveries ahead</MyText>
</View>
</View>
<MyFlatList
data={sortedSlots.slice(0, 5)}
keyExtractor={(item) => item.id.toString()}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={staticStyles.slotsListContent}
decelerationRate="fast"
snapToInterval={280 + 16}
renderItem={renderSlotItem}
removeClippedSubviews={true}
/>
</View>
)}
<View style={tw`mt-2 mb-[11px]`}>
<View style={tw`flex-row items-center justify-between px-1 mb-2`}>
<View>
<View style={tw`flex-row items-center mb-1.5`}>
<View style={tw`w-1 h-5 rounded-full bg-brand500 mr-2.5`} />
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>All Available Products</MyText>
</View>
<MyText style={tw`text-sm text-gray-500 font-medium ml-4`}>Browse our complete selection</MyText>
</View> </View>
<MyText style={tw`text-sm text-gray-500 font-medium ml-4`}>Plan your fresh deliveries ahead</MyText>
</View> </View>
</View> </View>
<MyFlatList
data={sortedSlots.slice(0, 5)}
keyExtractor={(item) => item.id.toString()}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={staticStyles.slotsListContent}
decelerationRate="fast"
snapToInterval={280 + 16}
renderItem={renderSlotItem}
removeClippedSubviews={true}
/>
</View> </View>
</> </View>
); );
}); });
const AllProductsTitle = memo(() => (
<View style={tw`bg-white px-4`}>
<View style={tw`mt-2 mb-[11px]`}>
<View style={tw`flex-row items-center justify-between px-1 mb-2`}>
<View>
<View style={tw`flex-row items-center mb-1.5`}>
<View style={tw`w-1 h-5 rounded-full bg-brand500 mr-2.5`} />
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>All Available Products</MyText>
</View>
<MyText style={tw`text-sm text-gray-500 font-medium ml-4`}>Browse our complete selection</MyText>
</View>
</View>
</View>
</View>
));
const EmptyCatalog = memo(() => (
<View style={tw`items-center py-8`}>
<MyText style={tw`text-gray-500`}>No products available</MyText>
</View>
));
export default function Dashboard() { export default function Dashboard() {
const router = useRouter(); const router = useRouter();
const userDetails = useUserDetails(); const userDetails = useUserDetails();
@ -645,15 +658,115 @@ export default function Dashboard() {
{ backgroundColor: '#FFFFFF' } { backgroundColor: '#FFFFFF' }
], []); ], []);
const listHeader = useMemo(() => ( // One virtualized item per top section instead of a single giant header cell:
<ListHeader // VirtualizedList pins the first `initialNumToRender` items, so keeping the
dashboardTags={dashboardTags} // whole top block in one item kept it (and its images) mounted forever.
productsByTagId={productsByTagId} const listItems = useMemo<CatalogItem[]>(() => {
onProductPress={handleProductPress} const items: CatalogItem[] = [{ key: 'glimpse', kind: 'glimpse' }];
storesData={storesData}
sortedSlots={sortedSlots} if (dashboardTags.length > 0) {
/> items.push({ key: 'tag-strip', kind: 'tagStrip' });
), [dashboardTags, productsByTagId, handleProductPress, storesData, sortedSlots]); items.push({ key: 'tag-scene', kind: 'tagScene' });
}
if (storesData?.stores && storesData.stores.length > 0) {
items.push({ key: 'stores', kind: 'stores' });
}
if (sortedSlots.length > 0) {
items.push({ key: 'slots', kind: 'slots' });
}
items.push({ key: 'all-products-title', kind: 'allProductsTitle' });
if (displayedProducts.length === 0) {
items.push({ key: 'empty', kind: 'empty' });
return items;
}
const visible = Math.min(displayedProducts.length, visibleCount);
for (let index = 0; index < visible; index += 3) {
const products = displayedProducts.slice(index, index + 3);
items.push({
key: products.map((product) => product.id).join('-'),
kind: 'row',
products,
});
}
return items;
}, [dashboardTags, displayedProducts, visibleCount, storesData, sortedSlots]);
const sections = useMemo(() => [{ data: listItems }], [listItems]);
const renderCatalogItem = useCallback(({ item }: { item: CatalogItem }) => {
switch (item.kind) {
case 'glimpse':
return <HomeGlimpse />;
case 'tagStrip':
return <TagTabStrip dashboardTags={dashboardTags} />;
case 'tagScene':
return (
<TagSceneBlock
dashboardTags={dashboardTags}
productsByTagId={productsByTagId}
onProductPress={handleProductPress}
/>
);
case 'stores':
return <StoresSection storesData={storesData} />;
case 'slots':
return <SlotsSection sortedSlots={sortedSlots} />;
case 'allProductsTitle':
return <AllProductsTitle />;
case 'empty':
return <EmptyCatalog />;
case 'row':
return (
<View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
{item.products.map((product) => (
<React.Fragment key={product.id}>
{renderProductItem({ item: product })}
</React.Fragment>
))}
</View>
);
}
}, [dashboardTags, handleProductPress, productsByTagId, renderProductItem, sortedSlots, storesData]);
const keyExtractor = useCallback((item: CatalogItem) => item.key, []);
const renderSectionHeader = useCallback(() => (
<View style={searchBarContainerStyle}>
<SearchBar
testID="home-search"
value={""}
onChangeText={() => { }}
onPress={handleSearchPress}
editable={false}
containerStyle={tw`bg-white`}
onSubmitEditing={() => {
if (inputQuery.trim()) {
router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
}
}}
returnKeyType="search"
/>
</View>
), [handleSearchPress, inputQuery, router, searchBarContainerStyle]);
const listFooter = useMemo(() => (
hasMore ? (
<View style={tw`items-center py-4`}>
<MyTouchableOpacity
testID="products-show-more"
style={tw`px-6 py-3 rounded-full bg-brand500 shadow-sm`}
activeOpacity={0.85}
onPress={handleShowMore}
>
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
</MyTouchableOpacity>
</View>
) : null
), [handleShowMore, hasMore]);
const listContentContainerStyle = useMemo(() => [ const listContentContainerStyle = useMemo(() => [
tw`pb-24`, tw`pb-24`,
@ -687,65 +800,15 @@ export default function Dashboard() {
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}> <TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
<View style={pageTintStyle}> <View style={pageTintStyle}>
<SectionList <SectionList
sections={[{ data: [[], ...Array.from( sections={sections}
{ length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) }, keyExtractor={keyExtractor}
(_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
)] }]}
keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
stickySectionHeadersEnabled stickySectionHeadersEnabled
style={{ backgroundColor: '#FFFFFF' }} style={{ backgroundColor: '#FFFFFF' }}
contentContainerStyle={listContentContainerStyle} contentContainerStyle={listContentContainerStyle}
ListHeaderComponent={<LocationBar />} ListHeaderComponent={<LocationBar />}
renderSectionHeader={() => ( renderSectionHeader={renderSectionHeader}
<View style={searchBarContainerStyle}> renderItem={renderCatalogItem}
<SearchBar ListFooterComponent={listFooter}
testID="home-search"
value={""}
onChangeText={() => { }}
onPress={handleSearchPress}
editable={false}
containerStyle={tw`bg-white`}
onSubmitEditing={() => {
if (inputQuery.trim()) {
router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
}
}}
returnKeyType="search"
/>
</View>
)}
renderItem={({ item: row, index }) => index === 0 ? (
<>
{listHeader}
{displayedProducts.length === 0 && (
<View style={tw`items-center py-8`}>
<MyText style={tw`text-gray-500`}>No products available</MyText>
</View>
)}
</>
) : (
<View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
{row.map((item) => (
<React.Fragment key={item.id}>
{renderProductItem({ item })}
</React.Fragment>
))}
</View>
)}
ListFooterComponent={
hasMore ? (
<View style={tw`items-center py-4`}>
<MyTouchableOpacity
testID="products-show-more"
style={tw`px-6 py-3 rounded-full bg-brand500 shadow-sm`}
activeOpacity={0.85}
onPress={handleShowMore}
>
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
</MyTouchableOpacity>
</View>
) : null
}
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={isRefreshing} refreshing={isRefreshing}
@ -755,11 +818,11 @@ export default function Dashboard() {
/> />
} }
// NOTE: do not add removeClippedSubviews here - it breaks touch // NOTE: do not add removeClippedSubviews here - it breaks touch
// delivery to the nested horizontal scrollables in ListHeaderComponent // delivery to the nested horizontal scrollables (tag tabs / slots) on
// (tag tabs / slots) on Android. // Android.
maxToRenderPerBatch={10} maxToRenderPerBatch={HOME_MAX_RENDER_BATCH}
windowSize={5} windowSize={HOME_WINDOW_SIZE}
initialNumToRender={10} initialNumToRender={HOME_INITIAL_RENDER_COUNT}
updateCellsBatchingPeriod={50} updateCellsBatchingPeriod={50}
/> />

View file

@ -0,0 +1,14 @@
/**
* Virtualization tuning for the home catalog.
*
* VirtualizedList keeps the first `initialNumToRender` cells mounted forever as
* a "scroll-to-top" optimisation, so it must stay small: the top sections
* (glimpse, tag strip, tag grid, stores, slots, title) are separate list items
* and should be allowed to unmount once scrolled away.
*
* Tests mock this module with a larger initial count so interaction assertions
* have product rows mounted (jsdom never scrolls a virtualized list).
*/
export const HOME_INITIAL_RENDER_COUNT = 2
export const HOME_WINDOW_SIZE = 3
export const HOME_MAX_RENDER_BATCH = 6

View file

@ -37,6 +37,14 @@ import { StorageServiceCasual, tw } from 'common-ui'
import { flush, renderWithProviders, seedBoot, seedSelectedAddress } from '../helpers/test-utils' import { flush, renderWithProviders, seedBoot, seedSelectedAddress } from '../helpers/test-utils'
import { buildEssentialUrls } from '@packages/shared' import { buildEssentialUrls } from '@packages/shared'
// The production list keeps only two pinned cells so the top sections can
// unmount; tests need the product rows mounted to fire events on them.
jest.mock('@/src/lib/home-list-tuning', () => ({
HOME_INITIAL_RENDER_COUNT: 20,
HOME_WINDOW_SIZE: 3,
HOME_MAX_RENDER_BATCH: 6,
}))
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
procedureQueryCalls, procedureQueryCalls,
@ -124,7 +132,9 @@ function idsFrom(nodes: any[], prefix: string): number[] {
*/ */
function mainListIds(utils: any): number[] { function mainListIds(utils: any): number[] {
const sections = utils.UNSAFE_getByType(SectionList).props.sections as any[] const sections = utils.UNSAFE_getByType(SectionList).props.sections as any[]
return (sections[0].data as any[]).flat().map((product: any) => product.id) return (sections[0].data as any[])
.filter((item: any) => item.kind === 'row')
.flatMap((item: any) => item.products.map((product: any) => product.id))
} }
async function renderHome(options: { queryClient?: any } = {}) { async function renderHome(options: { queryClient?: any } = {}) {

View file

@ -353,3 +353,36 @@ foreground. Results in a maximum age of 3 days for any cached image.
+ IMGCACHE-08..10: missing/corrupt file and the write path. + IMGCACHE-08..10: missing/corrupt file and the write path.
--- apps/user-ui/JEST-TEST-CASES.md --- apps/user-ui/JEST-TEST-CASES.md
+ rows for IMGCACHE-01..10. + rows for IMGCACHE-01..10.
[2026-11-01 19:19:30 IST] home: split the monolithic list header into separate virtualized items and tighten the render window.
The whole top block (glimpse + tag strip + tag grid + stores + slots + "All
Available Products" title) was a single SectionList item, and the first
`initialNumToRender` items are pinned by VirtualizedList. With
initialNumToRender=10 and windowSize=5, the header plus ~27 cards stayed mounted
forever, growing worse as Show More appended rows.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Removed the ListHeader component/wrapper. The list data is now a list of
typed items: glimpse, tagStrip, tagScene, stores, slots, allProductsTitle,
empty and row (3 products). Each renders independently, so the top sections
unmount as they scroll out of the window.
~ Per-item white/px-4 wrappers replace the old rounded-t-3xl wrapper (page
background is white, so the rounded edge was not visible).
~ Extracted HomeGlimpse, TagSceneBlock, StoresSection, SlotsSection and
AllProductsTitle (all memoized); SlotsSection keeps its own renderSlotItem.
~ sections, keyExtractor, renderItem, renderSectionHeader and the footer are
memoized/callback-stable so unrelated Dashboard renders no longer rebuild
the list props.
--- apps/user-ui/src/lib/home-list-tuning.ts (new)
+ HOME_INITIAL_RENDER_COUNT=2, HOME_WINDOW_SIZE=3, HOME_MAX_RENDER_BATCH=6.
VirtualizedList pins the first initialNumToRender cells forever, so it must
stay small for the split top sections to unmount.
~ Virtualization props now read those constants (was windowSize 5,
initialNumToRender 10, maxToRenderPerBatch 10). removeClippedSubviews stays
off (nested horizontal scrollers).
- ProductCard's 5s interval left untouched, as requested.
--- apps/user-ui/tests/pages/home.test.tsx
~ mainListIds reads the row items from sections[0].data (kind === 'row').
~ Mocks home-list-tuning with initialNumToRender 20 so interaction assertions
have product rows mounted (jsdom never scrolls a virtualized list).