780 lines
26 KiB
TypeScript
Executable file
780 lines
26 KiB
TypeScript
Executable file
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
|
import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
|
|
import { ScrollView } from "react-native-gesture-handler";
|
|
import { useRouter } from "expo-router";
|
|
import {
|
|
theme,
|
|
tw,
|
|
useManualRefresh,
|
|
useMarkDataFetchers,
|
|
LoadingDialog,
|
|
MyTouchableOpacity,
|
|
MyText, SearchBar
|
|
} from "common-ui";
|
|
|
|
import dayjs from "dayjs";
|
|
import relativeTime from "dayjs/plugin/relativeTime";
|
|
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
|
|
import ProductCard from "@/components/ProductCard";
|
|
import AddToCartDialog from "@/src/components/AddToCartDialog";
|
|
import MyFlatList from "common-ui/src/components/flat-list";
|
|
|
|
import { trpc } from "@/src/trpc-client";
|
|
import type { ListItemProps } from '@packages/shared';
|
|
import { useStores, useSlots, useGetEssentialConsts } from "@/src/hooks/prominent-api-hooks";
|
|
import { useCentralSlotStore } from "@/src/store/centralSlotStore";
|
|
import { useCentralProductStore } from "@/src/store/centralProductStore";
|
|
import FloatingCartBar from "@/components/floating-cart-bar";
|
|
import { useUserDetails } from "@/src/contexts/AuthContext";
|
|
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
|
import LocationBar from "@/src/components/LocationBar";
|
|
import { useNavigationStore } from "@/src/store/navigationStore";
|
|
import { useHomeTagStore } from "@/src/store/homeTagStore";
|
|
import { useHomeCatalog } from "@/hooks/useHomeCatalog";
|
|
import { HOME_INITIAL_RENDER_COUNT, HOME_MAX_RENDER_BATCH, HOME_WINDOW_SIZE } from "@/src/lib/home-list-tuning";
|
|
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
|
dayjs.extend(relativeTime);
|
|
|
|
const { width: screenWidth } = Dimensions.get("window");
|
|
const itemWidth = screenWidth * 0.45;
|
|
const heroItemWidth = (screenWidth - 72) / 3;
|
|
// Catalog rows sit on the page's 16px margin: 32px of gutter + two 8px gaps
|
|
// leaves each of the three cards this wide.
|
|
const catalogItemWidth = (screenWidth - 48) / 3;
|
|
const gridItemWidth = (screenWidth - 48) / 2;
|
|
|
|
const formatTimeRange = (deliveryTime: string) => {
|
|
const time = dayjs(deliveryTime);
|
|
const endTime = time.add(1, 'hour');
|
|
const startPeriod = time.format('A');
|
|
const endPeriod = endTime.format('A');
|
|
|
|
if (startPeriod === endPeriod) {
|
|
return `${time.format('h')}-${endTime.format('h')} ${startPeriod}`;
|
|
} else {
|
|
return `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`;
|
|
}
|
|
};
|
|
|
|
const staticStyles = {
|
|
flatListContent: { gap: 16 },
|
|
// 16px page margin, matching the rest of the screen. With catalogItemWidth
|
|
// that leaves an 8px gap between the three cards, like the tag grid.
|
|
columnWrapper: { justifyContent: 'space-between', paddingHorizontal: 16 },
|
|
slotsListContent: { paddingBottom: 24 },
|
|
} as const;
|
|
|
|
const RenderStore = memo(({ item }: ListItemProps) => {
|
|
const router = useRouter();
|
|
const { setNavigatedFromHome, setSelectedStoreId } = useNavigationStore();
|
|
|
|
const handlePress = useCallback(() => {
|
|
setNavigatedFromHome(true);
|
|
setSelectedStoreId(item.id);
|
|
router.push('/(drawer)/(tabs)/stores');
|
|
}, [item.id, router, setNavigatedFromHome, setSelectedStoreId]);
|
|
|
|
return (
|
|
<MyTouchableOpacity
|
|
testID={`store-item-${item.id}`}
|
|
style={tw`items-center mb-4`}
|
|
onPress={handlePress}
|
|
activeOpacity={0.7}
|
|
>
|
|
<View
|
|
style={tw`w-16 h-16 rounded-2xl bg-brand50 border border-brand100 items-center justify-center mb-2 shadow-sm overflow-hidden`}
|
|
>
|
|
{item.signedImageUrl ? (
|
|
<Image source={{ uri: item.signedImageUrl }} style={tw`w-16 h-16 rounded-2xl`} resizeMode="cover" />
|
|
) : (
|
|
<MaterialIcons name="storefront" size={28} color={theme.colors.brand600} />
|
|
)}
|
|
</View>
|
|
<MyText style={tw`font-bold text-xs text-center tracking-wide text-neutral-800`} numberOfLines={1}>
|
|
{item.name.replace(/^The\s+/i, "")}
|
|
</MyText>
|
|
</MyTouchableOpacity>
|
|
);
|
|
});
|
|
RenderStore.displayName = 'RenderStore';
|
|
|
|
interface SlotCardProps {
|
|
slot: any;
|
|
}
|
|
|
|
const SlotCard = memo(({ slot }: SlotCardProps) => {
|
|
const router = useRouter();
|
|
const now = dayjs();
|
|
const freezeTime = dayjs(slot.freezeTime);
|
|
const isClosingSoon = freezeTime.diff(now, "hour") < 4 && freezeTime.isAfter(now);
|
|
|
|
const handlePress = useCallback(() => {
|
|
router.push(`/(drawer)/(tabs)/home/slot-view?slotId=${slot.id}`);
|
|
}, [router, slot.id]);
|
|
|
|
return (
|
|
<MyTouchableOpacity
|
|
testID={`slot-card-${slot.id}`}
|
|
style={[
|
|
tw`bg-white rounded-[24px] p-5 mr-4 shadow-sm border border-gray-100 min-w-[280px]`,
|
|
isClosingSoon ? tw`border-l-4 border-l-amber-400` : tw`border-l-4 border-l-brand500`,
|
|
]}
|
|
onPress={handlePress}
|
|
activeOpacity={0.9}
|
|
>
|
|
<View style={tw`flex-row justify-end items-start mb-4`}>
|
|
{isClosingSoon && (
|
|
<View style={tw`bg-amber-50 px-2 py-0.5 rounded-md border border-amber-100 flex-row items-center`}>
|
|
<View style={tw`w-1 h-1 rounded-full bg-amber-500 mr-1`} />
|
|
<MyText style={tw`text-[10px] font-bold text-amber-700`}>CLOSING SOON</MyText>
|
|
</View>
|
|
)}
|
|
</View>
|
|
|
|
<View style={tw`flex-row justify-between mb-5`}>
|
|
<View style={tw`flex-1 mr-4`}>
|
|
<View style={tw`flex-row items-center mb-1.5`}>
|
|
<View style={tw`bg-brand50 p-1 rounded-md mr-1.5`}>
|
|
<MaterialIcons name="local-shipping" size={12} color={theme.colors.brand600} />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-brand700 uppercase`}>Delivery At</MyText>
|
|
</View>
|
|
<MyText style={tw`text-sm font-extrabold text-slate-900`}>{formatTimeRange(slot.deliveryTime)}</MyText>
|
|
<MyText style={tw`text-[11px] font-bold text-slate-500`}>{dayjs(slot.deliveryTime).format("ddd, MMM DD")}</MyText>
|
|
</View>
|
|
|
|
<View style={tw`flex-1`}>
|
|
<View style={tw`flex-row items-center mb-1.5`}>
|
|
<View style={tw`bg-amber-50 p-1 rounded-md mr-1.5`}>
|
|
<MaterialIcons name="timer" size={12} color="#D97706" />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-amber-700 uppercase`}>Order By</MyText>
|
|
</View>
|
|
<MyText style={tw`text-sm font-extrabold text-slate-900`}>{dayjs(slot.freezeTime).format("h:mm A")}</MyText>
|
|
<MyText style={tw`text-[11px] font-bold text-slate-500`}>{dayjs(slot.freezeTime).format("ddd, MMM DD")}</MyText>
|
|
</View>
|
|
</View>
|
|
|
|
<View style={tw`flex-row items-center`}>
|
|
<View style={tw`flex-row mr-3`}>
|
|
{slot.products.slice(0, 3).map((p: any, i: number) => (
|
|
<View
|
|
key={p.id}
|
|
style={[tw`w-8 h-8 rounded-full border-2 border-white bg-slate-100 overflow-hidden`, i > 0 && tw`-ml-3`]}
|
|
>
|
|
{p.images?.[0] ? (
|
|
<Image source={{ uri: p.images?.[0] }} style={tw`w-full h-full`} />
|
|
) : (
|
|
<MaterialIcons name="image" size={14} color="#94A3B8" />
|
|
)}
|
|
</View>
|
|
))}
|
|
</View>
|
|
<View style={tw`flex-row items-center bg-brand50 rounded-full px-3 py-1.5`}>
|
|
<MyText style={tw`text-[11px] font-bold text-brand700`}>View all {slot.products.length} items</MyText>
|
|
<MaterialIcons name="chevron-right" size={16} color={theme.colors.brand600} style={tw`ml-0.5`} />
|
|
</View>
|
|
</View>
|
|
</MyTouchableOpacity>
|
|
);
|
|
});
|
|
|
|
interface TagTabStripProps {
|
|
dashboardTags: any[];
|
|
}
|
|
|
|
// Fixed, horizontally scrollable tab strip (plain ScrollView — no nesting,
|
|
// so it scrolls reliably on Android). Sits OUTSIDE the vertical FlatList.
|
|
const TagTabStrip = memo(({
|
|
dashboardTags,
|
|
}: TagTabStripProps) => {
|
|
// Selection is read here, not in Dashboard: a tap must not re-render the
|
|
// page (see homeTagStore).
|
|
const selectedTagId = useHomeTagStore((state) => state.selectedTagId);
|
|
const selectTag = useHomeTagStore((state) => state.selectTag);
|
|
const activeTagId = selectedTagId ?? dashboardTags[0]?.id ?? null;
|
|
const scrollRef = useRef<any>(null);
|
|
const positions = useRef<number[]>([]);
|
|
|
|
const routes = useMemo(
|
|
() => dashboardTags.map((tag) => ({ key: String(tag.id), title: tag.tagName })),
|
|
[dashboardTags]
|
|
);
|
|
|
|
const index = useMemo(() => {
|
|
const idx = dashboardTags.findIndex((tag) => tag.id === activeTagId);
|
|
return idx < 0 ? 0 : idx;
|
|
}, [dashboardTags, activeTagId]);
|
|
|
|
useEffect(() => {
|
|
const x = positions.current[index];
|
|
if (x != null) {
|
|
scrollRef.current?.scrollTo({ x: Math.max(0, x - 16), animated: true });
|
|
}
|
|
}, [index]);
|
|
|
|
return (
|
|
<ScrollView
|
|
ref={scrollRef}
|
|
horizontal
|
|
testID="home-tag-strip"
|
|
showsHorizontalScrollIndicator={false}
|
|
// horizontal ScrollViews default to flexGrow: 1 — pin it to content height
|
|
// so it doesn't eat the page space below the tabs
|
|
style={[tw`bg-transparent`, { flexGrow: 0, height: 48 }]}
|
|
contentContainerStyle={tw`px-2 items-center`}
|
|
>
|
|
{routes.map((route, i) => {
|
|
const isActive = i === index;
|
|
return (
|
|
<MyTouchableOpacity
|
|
key={route.key}
|
|
testID={`tag-tab-${route.key}`}
|
|
onLayout={(e: any) => {
|
|
positions.current[i] = e.nativeEvent.layout.x;
|
|
}}
|
|
onPress={() => selectTag(Number(route.key))}
|
|
style={tw`h-12 px-3 justify-center`}
|
|
activeOpacity={0.7}
|
|
>
|
|
<View style={tw`items-center justify-center`}>
|
|
<MyText
|
|
style={[
|
|
tw`text-sm font-bold`,
|
|
isActive
|
|
? { color: theme.colors.brand600 }
|
|
: { color: '#64748B' },
|
|
]}
|
|
>
|
|
{route.title}
|
|
</MyText>
|
|
<View
|
|
style={[
|
|
tw`h-1 rounded-full mt-1 self-stretch`,
|
|
{
|
|
backgroundColor: isActive
|
|
? theme.colors.brand500
|
|
: 'transparent',
|
|
},
|
|
]}
|
|
/>
|
|
</View>
|
|
</MyTouchableOpacity>
|
|
);
|
|
})}
|
|
</ScrollView>
|
|
);
|
|
});
|
|
|
|
interface TagSceneProps {
|
|
dashboardTags: any[];
|
|
productsByTagId: Record<number, any[]>;
|
|
onProductPress: (id: number) => void;
|
|
}
|
|
|
|
// Active tag's products grid — rendered inside the vertical FlatList so it
|
|
// scrolls with the page.
|
|
const TagScene = memo(({
|
|
dashboardTags,
|
|
productsByTagId,
|
|
onProductPress,
|
|
}: TagSceneProps) => {
|
|
const selectedTagId = useHomeTagStore((state) => state.selectedTagId);
|
|
const tagId = selectedTagId ?? dashboardTags[0]?.id ?? null;
|
|
// One boolean selector per tag, so expanding another tag does not re-render
|
|
// this scene (or anything above it).
|
|
const expanded = useHomeTagStore((state) =>
|
|
tagId == null ? false : !!state.expandedByTagId[tagId]
|
|
);
|
|
const expandTag = useHomeTagStore((state) => state.expandTag);
|
|
|
|
if (tagId == null) return null;
|
|
|
|
const products = productsByTagId[tagId] || [];
|
|
const visible = expanded ? products : products.slice(0, 6);
|
|
const hasMore = products.length > 6 && !expanded;
|
|
|
|
return (
|
|
<View style={tw`mt-3`} testID={`tag-grid-${tagId}`}>
|
|
{products.length > 0 ? (
|
|
<View style={tw`flex-row flex-wrap justify-between`}>
|
|
{visible.map((product: any) => (
|
|
<ExploreProductItem key={product.id} item={product} onPress={onProductPress} />
|
|
))}
|
|
</View>
|
|
) : (
|
|
<View style={tw`py-6 items-center`}>
|
|
<MyText style={tw`text-sm text-gray-500 font-medium`}>
|
|
No products in this category yet
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
{hasMore && (
|
|
<MyTouchableOpacity
|
|
testID={`tag-show-more-${tagId}`}
|
|
style={tw`self-center mt-1 mb-2 px-5 py-2.5 rounded-full bg-brand500 shadow-sm`}
|
|
activeOpacity={0.85}
|
|
onPress={() => expandTag(tagId)}
|
|
>
|
|
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
|
</MyTouchableOpacity>
|
|
)}
|
|
</View>
|
|
);
|
|
});
|
|
|
|
const ExploreProductItem = memo(({ item, onPress }: ProductItemProps) => {
|
|
const handlePress = useCallback(() => onPress(item.id), [item.id, onPress]);
|
|
|
|
return (
|
|
<View style={tw`mb-3`} testID={`tag-product-${item.id}`}>
|
|
<ProductCard
|
|
item={item}
|
|
itemWidth={heroItemWidth}
|
|
onPress={handlePress}
|
|
showDeliveryInfo={false}
|
|
useAddToCartDialog={true}
|
|
miniView={true}
|
|
variant="hero"
|
|
/>
|
|
</View>
|
|
);
|
|
});
|
|
|
|
const SlotItem = memo(({ item }: ListItemProps) => <SlotCard slot={item} />);
|
|
|
|
interface ProductItemProps {
|
|
item: any;
|
|
onPress: (id: number) => void;
|
|
}
|
|
|
|
const ProductItem = memo(({ item, onPress }: ProductItemProps) => {
|
|
const handlePress = useCallback(() => onPress(item.id), [item.id, onPress]);
|
|
|
|
return (
|
|
<View style={tw`mb-3`} testID={`product-item-${item.id}`}>
|
|
<ProductCard
|
|
item={item}
|
|
itemWidth={catalogItemWidth}
|
|
onPress={handlePress}
|
|
showDeliveryInfo={false}
|
|
miniView={true}
|
|
useAddToCartDialog={true}
|
|
variant="hero"
|
|
/>
|
|
</View>
|
|
);
|
|
});
|
|
|
|
type CatalogItem =
|
|
| { key: string; kind: 'glimpse' }
|
|
| { key: string; kind: 'tagStrip' }
|
|
| { key: string; kind: 'tagScene' }
|
|
| { key: string; kind: 'stores' }
|
|
| { key: string; kind: 'slots' }
|
|
| { key: string; kind: 'allProductsTitle' }
|
|
| { key: string; kind: 'empty' }
|
|
| { key: string; kind: 'row'; products: any[] };
|
|
|
|
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,
|
|
productsByTagId,
|
|
onProductPress,
|
|
}: TagSceneProps) => (
|
|
<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>
|
|
));
|
|
|
|
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 SectionHeading = memo(({
|
|
title,
|
|
subtitle,
|
|
style,
|
|
}: {
|
|
title: string;
|
|
subtitle: string;
|
|
/** Outer spacing; the two callers sit in different section wrappers. */
|
|
style?: any;
|
|
}) => (
|
|
<View style={[tw`flex-row items-center justify-between px-1`, style]}>
|
|
<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`}>{title}</MyText>
|
|
</View>
|
|
<MyText style={tw`text-sm text-gray-500 font-medium ml-4`}>{subtitle}</MyText>
|
|
</View>
|
|
</View>
|
|
));
|
|
SectionHeading.displayName = 'SectionHeading';
|
|
|
|
const SlotsSection = memo(({ sortedSlots }: { sortedSlots: any[] }) => {
|
|
const renderSlotItem = useCallback(({ item }: { item: any }) => (
|
|
<SlotItem item={item} />
|
|
), []);
|
|
|
|
if (sortedSlots.length === 0) return null;
|
|
|
|
return (
|
|
<View style={tw`bg-white px-4`}>
|
|
<View style={tw`mt-2 mb-4`}>
|
|
<SectionHeading
|
|
title="Upcoming Delivery Slots"
|
|
subtitle="Plan your fresh deliveries ahead"
|
|
style={tw`mb-6`}
|
|
/>
|
|
<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>
|
|
);
|
|
});
|
|
|
|
const AllProductsTitle = memo(() => (
|
|
<View style={tw`bg-white px-4`}>
|
|
<View style={tw`mt-2 mb-[11px]`}>
|
|
<SectionHeading
|
|
title="All Available Products"
|
|
subtitle="Browse our complete selection"
|
|
style={tw`mb-2`}
|
|
/>
|
|
</View>
|
|
</View>
|
|
));
|
|
|
|
const EmptyCatalog = memo(() => (
|
|
<View style={tw`items-center py-8`}>
|
|
<MyText style={tw`text-gray-500`}>No products available</MyText>
|
|
</View>
|
|
));
|
|
|
|
/**
|
|
* Rendered as an element, not memoised in Dashboard: the screen takes an early
|
|
* return for loading/error, and building this before that check is wasted work.
|
|
*/
|
|
const ShowMoreFooter = memo(({ visible, onPress }: { visible: boolean; onPress: () => void }) => {
|
|
if (!visible) return null;
|
|
|
|
return (
|
|
<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={onPress}
|
|
>
|
|
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
);
|
|
});
|
|
ShowMoreFooter.displayName = 'ShowMoreFooter';
|
|
|
|
export default function Dashboard() {
|
|
const router = useRouter();
|
|
const userDetails = useUserDetails();
|
|
const [inputQuery, setInputQuery] = useState("");
|
|
const [isLoadingDialogOpen, setIsLoadingDialogOpen] = useState(false);
|
|
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
|
|
const refetchSlotsFromStore = useCentralSlotStore((state) => state.refetchSlots);
|
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
|
|
|
// Catalogue state lives in the hook: the products payload, the per-tag rows,
|
|
// the sorted "All Products" feed and the Show More paging.
|
|
const {
|
|
isLoading,
|
|
error,
|
|
products,
|
|
dashboardTags,
|
|
productsByTagId,
|
|
displayedProducts,
|
|
visibleCount,
|
|
hasMore,
|
|
showMore,
|
|
} = useHomeCatalog();
|
|
|
|
const { data: essentialConsts, error: constsError, refetch: refetchConsts } = useGetEssentialConsts();
|
|
|
|
const { data: storesData, refetch: refetchStores } = useStores();
|
|
const { data: slotsData } = useSlots();
|
|
|
|
const sortedSlots = useMemo(() => {
|
|
if (!slotsData?.slots) return [];
|
|
const now = dayjs();
|
|
return [...slotsData.slots]
|
|
.filter(slot => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now))
|
|
.sort((a, b) => {
|
|
const deliveryDiff = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime));
|
|
if (deliveryDiff !== 0) return deliveryDiff;
|
|
return dayjs(a.freezeTime).diff(dayjs(b.freezeTime));
|
|
});
|
|
}, [slotsData]);
|
|
|
|
const handleRefresh = useCallback(async () => {
|
|
setIsRefreshing(true);
|
|
try {
|
|
const promises = [];
|
|
|
|
if (refetchProducts) {
|
|
promises.push(refetchProducts());
|
|
}
|
|
if (refetchSlotsFromStore) {
|
|
promises.push(refetchSlotsFromStore());
|
|
}
|
|
promises.push(refetchStores());
|
|
promises.push(refetchConsts());
|
|
|
|
await Promise.all(promises);
|
|
} finally {
|
|
setIsRefreshing(false);
|
|
}
|
|
}, [refetchProducts, refetchSlotsFromStore, refetchStores, refetchConsts]);
|
|
|
|
useManualRefresh(() => {
|
|
handleRefresh();
|
|
});
|
|
|
|
useMarkDataFetchers(() => {
|
|
handleRefresh();
|
|
});
|
|
|
|
const handleProductPress = useCallback((id: number) => {
|
|
router.push(`/(drawer)/(tabs)/home/product-detail/${id}`);
|
|
}, [router]);
|
|
|
|
const handleSearchPress = useCallback(() => {
|
|
router.push("/(drawer)/(tabs)/home/search-results");
|
|
}, [router]);
|
|
|
|
const renderProductItem = useCallback(({ item }: { item: any }) => (
|
|
<ProductItem item={item} onPress={handleProductPress} />
|
|
// <Image style={{ width: 150, height: 235 }} source={{ uri: item.images[0]}} />
|
|
), [handleProductPress]);
|
|
|
|
// The page background stays white (the per-tag tint was never enabled).
|
|
const pageTintStyle = useMemo(() => [
|
|
tw`flex-1`,
|
|
{ backgroundColor: '#FFFFFF' }
|
|
], []);
|
|
|
|
const searchBarContainerStyle = useMemo(() => [
|
|
tw`w-full px-4 pt-4 pb-0`,
|
|
{ backgroundColor: '#FFFFFF' }
|
|
], []);
|
|
|
|
// One virtualized item per top section instead of a single giant header cell:
|
|
// VirtualizedList pins the first `initialNumToRender` items, so keeping the
|
|
// whole top block in one item kept it (and its images) mounted forever.
|
|
const listItems = useMemo<CatalogItem[]>(() => {
|
|
const items: CatalogItem[] = [{ key: 'glimpse', kind: 'glimpse' }];
|
|
|
|
if (dashboardTags.length > 0) {
|
|
items.push({ key: 'tag-strip', kind: 'tagStrip' });
|
|
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 listContentContainerStyle = useMemo(() => [
|
|
tw`pb-24`,
|
|
staticStyles.flatListContent
|
|
], []);
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MyText style={tw`text-gray-500 font-medium`}>
|
|
Loading products...
|
|
</MyText>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
// Only take over the screen when there is nothing else to show. A failed
|
|
// background refresh keeps the last loaded catalog on screen.
|
|
if ((error || constsError) && products.length === 0) {
|
|
return (
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
|
|
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
|
|
<MyText style={tw`text-gray-500 mt-2`}>
|
|
{error ? 'Failed to load products' : 'Failed to load app settings'}
|
|
</MyText>
|
|
</View>
|
|
);
|
|
}
|
|
return (
|
|
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
|
<View style={pageTintStyle}>
|
|
<SectionList
|
|
sections={sections}
|
|
keyExtractor={keyExtractor}
|
|
stickySectionHeadersEnabled
|
|
style={{ backgroundColor: '#FFFFFF' }}
|
|
contentContainerStyle={listContentContainerStyle}
|
|
ListHeaderComponent={<LocationBar />}
|
|
renderSectionHeader={renderSectionHeader}
|
|
renderItem={renderCatalogItem}
|
|
ListFooterComponent={<ShowMoreFooter visible={hasMore} onPress={showMore} />}
|
|
refreshControl={
|
|
<RefreshControl
|
|
refreshing={isRefreshing}
|
|
onRefresh={handleRefresh}
|
|
tintColor={theme.colors.brand500}
|
|
colors={[theme.colors.brand500]}
|
|
/>
|
|
}
|
|
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
|
// delivery to the nested horizontal scrollables (tag tabs / slots) on
|
|
// Android.
|
|
maxToRenderPerBatch={HOME_MAX_RENDER_BATCH}
|
|
windowSize={HOME_WINDOW_SIZE}
|
|
initialNumToRender={HOME_INITIAL_RENDER_COUNT}
|
|
updateCellsBatchingPeriod={50}
|
|
/>
|
|
|
|
<LoadingDialog open={isLoadingDialogOpen} message="Adding to cart..." />
|
|
<AddToCartDialog />
|
|
<View style={tw`absolute bottom-2 left-4 right-4`}>
|
|
<FloatingCartBar />
|
|
</View>
|
|
</View>
|
|
</TabLayoutWrapper>
|
|
);
|
|
}
|