freshyo/apps/user-ui/hooks/useHomeCatalog.ts
2026-11-16 01:28:18 +05:30

122 lines
4.6 KiB
TypeScript

import { useCallback, useEffect, useMemo, useState } from 'react'
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
/** Rows per page, same as the "Show More" step on the home catalogue. */
export const HOME_CATALOG_PAGE_SIZE = 21
/**
* Home catalogue derivation: the products payload, the per-tag rows and the
* sorted "All Products" feed.
*
* This used to live inside `Dashboard`, which made that component the largest
* file in the folder and left the sort effect reading `getQuickestSlot` and
* `isSlotsLoaded` without listing them. Keeping it here leaves the screen with
* just its layout concerns, and the effect lists every value it reads.
*
* The catalogue itself comes from the central product store — the only place
* that reads the products document — so every product field (price flags,
* coupon price, ...) has one source across the app.
*/
export function useHomeCatalog() {
const products = useCentralProductStore((state) => state.products)
const dashboardTags = useCentralProductStore((state) => state.tags)
const isLoading = useCentralProductStore((state) => state.isLoading)
const error = useCentralProductStore((state) => state.error)
const { getQuickestSlot } = useProductSlotIdentifier()
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded)
// Single source of truth for the catalogue rows: the per-tag rows are derived
// from the same products list the "All Products" feed pages through, so the
// screen never holds two views of the same payload that can drift apart.
const productsByTagId = useMemo(() => {
const productById = new Map<number, any>()
for (const product of products) {
productById.set(product.id, product)
}
const map: Record<number, any[]> = {}
for (const tag of dashboardTags) {
// Respect the admin-curated order — tag.productIds is already ordered by
// the tag's sortOrder (backend reorders it when building the cache).
// Unknown ids are skipped and a repeated id only renders once.
const ordered: any[] = []
const seen = new Set<number>()
for (const id of tag.productIds || []) {
if (seen.has(id)) continue
seen.add(id)
const product = productById.get(id)
if (product) ordered.push(product)
}
// Out-of-stock items are pushed to the end, preserving their relative order.
const inStock: any[] = []
const outOfStock: any[] = []
for (const product of ordered) {
const isOut =
Boolean(productSlotsMap[product.id]?.isOutOfStock) ||
(isSlotsLoaded && !getQuickestSlot(product.id))
if (isOut) outOfStock.push(product)
else inStock.push(product)
}
map[tag.id] = [...inStock, ...outOfStock]
}
return map
}, [products, dashboardTags, productSlotsMap, isSlotsLoaded, getQuickestSlot])
// Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and
// TagScene), so a tap does not re-render Dashboard or rebuild the list below.
const [displayedProducts, setDisplayedProducts] = useState<any[]>([])
const [visibleCount, setVisibleCount] = useState(HOME_CATALOG_PAGE_SIZE)
useEffect(() => {
if (products.length === 0) {
setDisplayedProducts([])
return
}
const allSorted = products
.filter((product) => typeof product.id === 'number')
.sort((a, b) => {
const slotA = getQuickestSlot(a.id)
const slotB = getQuickestSlot(b.id)
const aOutOfStock =
Boolean(productSlotsMap[a.id]?.isOutOfStock) || (isSlotsLoaded && !slotA)
const bOutOfStock =
Boolean(productSlotsMap[b.id]?.isOutOfStock) || (isSlotsLoaded && !slotB)
if (aOutOfStock && !bOutOfStock) return 1
if (!aOutOfStock && bOutOfStock) return -1
return 0
})
setDisplayedProducts(allSorted)
setVisibleCount(HOME_CATALOG_PAGE_SIZE)
}, [products, productSlotsMap, getQuickestSlot, isSlotsLoaded])
// Derived, not state: the old version set this from inside the setVisibleCount
// updater, which React may replay.
const hasMore = visibleCount < displayedProducts.length
// Pure updater; the footer reads `hasMore` above.
const showMore = useCallback(() => {
setVisibleCount((prev) => prev + HOME_CATALOG_PAGE_SIZE)
}, [])
return {
isLoading,
error,
products,
dashboardTags,
productsByTagId,
displayedProducts,
visibleCount,
hasMore,
showMore,
}
}