max-with for category name

This commit is contained in:
hamid zarghami
2026-06-06 11:39:53 +03:30
parent 22be2ab19e
commit 347017f1be
+155 -72
View File
@@ -1,44 +1,63 @@
'use client'; "use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import SearchBox from "@/components/input/SearchBox";
import TextAlignIcon from "@/components/icons/TextAlignIcon";
import VerticalScrollView from "@/components/listview/VerticalScrollView";
import MenuItemRenderer from "@/components/listview/MenuItemRenderer";
import MenuItem from "@/components/listview/MenuItem";
import { Candle2 } from "iconsax-react";
import { useQueryState } from "next-usequerystate";
import clsx from "clsx";
import { motion } from "framer-motion";
import { useTranslation } from "react-i18next";
import useToggle from "@/hooks/helpers/useToggle";
import CategoryScroll from "@/app/[name]/(Main)/components/CategoryScroll"; import CategoryScroll from "@/app/[name]/(Main)/components/CategoryScroll";
import MenuFilterDrawer from "@/app/[name]/(Main)/components/MenuFilterDrawer"; import MenuFilterDrawer from "@/app/[name]/(Main)/components/MenuFilterDrawer";
import MenuSortingDrawer from "@/app/[name]/(Main)/components/MenuSortingDrawer";
import MenuSkeleton from "@/app/[name]/(Main)/components/MenuSkeleton"; import MenuSkeleton from "@/app/[name]/(Main)/components/MenuSkeleton";
import MenuSortingDrawer from "@/app/[name]/(Main)/components/MenuSortingDrawer";
import TextAlignIcon from "@/components/icons/TextAlignIcon";
import SearchBox from "@/components/input/SearchBox";
import MenuItem from "@/components/listview/MenuItem";
import MenuItemRenderer from "@/components/listview/MenuItemRenderer";
import VerticalScrollView from "@/components/listview/VerticalScrollView";
import useToggle from "@/hooks/helpers/useToggle";
import clsx from "clsx";
import { motion } from "framer-motion";
import { Candle2 } from "iconsax-react";
import { useQueryState } from "next-usequerystate";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useGetCategories, useGetFoods } from "../hooks/useMenuData"; import { useGetCategories, useGetFoods } from "../hooks/useMenuData";
import type { Food, Category } from "../types/Types"; import type { Category, Food } from "../types/Types";
const sortings = ["PopularityDescending", "RateDescending", "PriceAscending", "PriceDescending"] as const; const sortings = [
"PopularityDescending",
"RateDescending",
"PriceAscending",
"PriceDescending",
] as const;
const MenuIndex = () => { const MenuIndex = () => {
const { data: foodsData, isLoading: foodsLoading } = useGetFoods(); const { data: foodsData, isLoading: foodsLoading } = useGetFoods();
const { data: categoriesData, isLoading: categoriesLoading } = useGetCategories(); const { data: categoriesData, isLoading: categoriesLoading } =
useGetCategories();
const foods = useMemo<Food[]>(() => foodsData?.data || [], [foodsData?.data]); const foods = useMemo<Food[]>(() => foodsData?.data || [], [foodsData?.data]);
const categories = useMemo<Category[]>(() => categoriesData?.data || [], [categoriesData?.data]); const categories = useMemo<Category[]>(
() => categoriesData?.data || [],
[categoriesData?.data],
);
const isLoading = foodsLoading || categoriesLoading; const isLoading = foodsLoading || categoriesLoading;
const { t: tCommon } = useTranslation('common'); const { t: tCommon } = useTranslation("common");
const { t: tMenu } = useTranslation('menu', { keyPrefix: "Menu" }); const { t: tMenu } = useTranslation("menu", { keyPrefix: "Menu" });
const { state: filterModal, toggle: toggleFilterModal } = useToggle(); const { state: filterModal, toggle: toggleFilterModal } = useToggle();
const { state: sortingModal, toggle: toggleSortingModal } = useToggle(); const { state: sortingModal, toggle: toggleSortingModal } = useToggle();
const [sorting, setSorting] = useQueryState('sortBy', { defaultValue: '0' }); const [sorting, setSorting] = useQueryState("sortBy", { defaultValue: "0" });
const [search, setSearch] = useQueryState("q", { defaultValue: '' }); const [search, setSearch] = useQueryState("q", { defaultValue: "" });
const [selectedCategory, setSelectedCategory] = useQueryState('category', { defaultValue: '0' }); const [selectedCategory, setSelectedCategory] = useQueryState("category", {
const [selectedIngredients, setSelectedIngredients] = useQueryState('ingredients', { defaultValue: '' }); defaultValue: "0",
const [selectedDeliveryId, setSelectedDeliveryId] = useQueryState('delivery', { defaultValue: '0' }); });
const smallCategoriesRef: React.RefObject<HTMLDivElement | null> = useRef(null); const [selectedIngredients, setSelectedIngredients] = useQueryState(
"ingredients",
{ defaultValue: "" },
);
const [selectedDeliveryId, setSelectedDeliveryId] = useQueryState(
"delivery",
{ defaultValue: "0" },
);
const smallCategoriesRef: React.RefObject<HTMLDivElement | null> =
useRef(null);
const wrapperRef: React.RefObject<HTMLDivElement | null> = useRef(null); const wrapperRef: React.RefObject<HTMLDivElement | null> = useRef(null);
const [smallCategoriesVisible, setSmallCategoriesVisibility] = useState(false); const [smallCategoriesVisible, setSmallCategoriesVisibility] =
useState(false);
const [isInitialMount, setIsInitialMount] = useState(true); const [isInitialMount, setIsInitialMount] = useState(true);
useEffect(() => { useEffect(() => {
@@ -49,16 +68,21 @@ const MenuIndex = () => {
setSorting(null); setSorting(null);
setIsInitialMount(false); setIsInitialMount(false);
} }
}, [isInitialMount, setSearch, setSelectedIngredients, setSelectedDeliveryId, setSorting]); }, [
isInitialMount,
setSearch,
setSelectedIngredients,
setSelectedDeliveryId,
setSorting,
]);
useEffect(() => { useEffect(() => {
if (categoriesData?.data && selectedCategory === '0') { if (categoriesData?.data && selectedCategory === "0") {
setSelectedCategory(categoriesData?.data?.[0]?.id) setSelectedCategory(categoriesData?.data?.[0]?.id);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedCategory, categoriesData]) }, [selectedCategory, categoriesData]);
useEffect(() => { useEffect(() => {
if (isLoading || !wrapperRef.current) return; if (isLoading || !wrapperRef.current) return;
@@ -73,46 +97,61 @@ const MenuIndex = () => {
); );
}; };
scrollContainer.addEventListener('scroll', handleScroll, { passive: true }); scrollContainer.addEventListener("scroll", handleScroll, { passive: true });
handleScroll(); handleScroll();
return () => { return () => {
scrollContainer.removeEventListener('scroll', handleScroll); scrollContainer.removeEventListener("scroll", handleScroll);
}; };
}, [isLoading]); }, [isLoading]);
const updateSearch = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value);
},
[setSearch],
);
const updateSearch = useCallback((e: React.ChangeEvent<HTMLInputElement>) => { const updateCategory = useCallback(
setSearch(e.target.value); (categoryId: string) => {
}, [setSearch]); setSelectedCategory(categoryId);
},
const updateCategory = useCallback((categoryId: string) => { [setSelectedCategory],
setSelectedCategory(categoryId); );
}, [setSelectedCategory]);
const sortingIndex = Number(sorting); const sortingIndex = Number(sorting);
const activeSortingIndex = Number.isNaN(sortingIndex) ? 0 : sortingIndex; const activeSortingIndex = Number.isNaN(sortingIndex) ? 0 : sortingIndex;
const activeSortingKey = sortings[activeSortingIndex] ?? sortings[0]; const activeSortingKey = sortings[activeSortingIndex] ?? sortings[0];
const activeSortingLabel = tMenu(`MenuSortingDrawer.Options.${activeSortingKey}`); const activeSortingLabel = tMenu(
`MenuSortingDrawer.Options.${activeSortingKey}`,
);
const changeSorting = (index: number) => { const changeSorting = (index: number) => {
setSorting(() => String(index)); setSorting(() => String(index));
toggleSortingModal(); toggleSortingModal();
}; };
const changeSelectedIngredients = useCallback((value: string) => { const changeSelectedIngredients = useCallback(
setSelectedIngredients(value); (value: string) => {
}, [setSelectedIngredients]); setSelectedIngredients(value);
},
[setSelectedIngredients],
);
const changeSelectedDelivery = useCallback((value: string) => { const changeSelectedDelivery = useCallback(
setSelectedDeliveryId(() => value); (value: string) => {
}, [setSelectedDeliveryId]); setSelectedDeliveryId(() => value);
},
[setSelectedDeliveryId],
);
const filteredReceiptItems = useMemo(() => { const filteredReceiptItems = useMemo(() => {
if (!foods.length) return []; if (!foods.length) return [];
const lowerSearch = search.toLowerCase(); const lowerSearch = search.toLowerCase();
const lowerIngredients = selectedIngredients ? selectedIngredients.toLowerCase() : ""; const lowerIngredients = selectedIngredients
const selectedCatId = selectedCategory === '0' ? null : selectedCategory; ? selectedIngredients.toLowerCase()
: "";
const selectedCatId = selectedCategory === "0" ? null : selectedCategory;
const filtered = foods.filter((item) => { const filtered = foods.filter((item) => {
const matchesCategory = !selectedCatId || item.category === selectedCatId; const matchesCategory = !selectedCatId || item.category === selectedCatId;
@@ -120,21 +159,32 @@ const MenuIndex = () => {
const matchesSearch = const matchesSearch =
!search || itemName.toLowerCase().includes(lowerSearch); !search || itemName.toLowerCase().includes(lowerSearch);
const matchesIngredients = !selectedIngredients || const matchesIngredients =
!selectedIngredients ||
(() => { (() => {
if (item.content && Array.isArray(item.content) && item.content.length > 0) { if (
item.content &&
Array.isArray(item.content) &&
item.content.length > 0
) {
return item.content.some((content: string) => return item.content.some((content: string) =>
content.toLowerCase().includes(lowerIngredients) content.toLowerCase().includes(lowerIngredients),
); );
} }
return item.desc.toLowerCase().includes(lowerIngredients); return item.desc.toLowerCase().includes(lowerIngredients);
})(); })();
const matchesDelivery = selectedDeliveryId === "0" || const matchesDelivery =
selectedDeliveryId === "0" ||
(selectedDeliveryId === "pickup" && item.pickupServe) || (selectedDeliveryId === "pickup" && item.pickupServe) ||
(selectedDeliveryId === "inPlace" && item.inPlaceServe); (selectedDeliveryId === "inPlace" && item.inPlaceServe);
return matchesCategory && matchesSearch && matchesIngredients && matchesDelivery; return (
matchesCategory &&
matchesSearch &&
matchesIngredients &&
matchesDelivery
);
}); });
const sortingKey = sortings[Number(sorting)] || sortings[0]; const sortingKey = sortings[Number(sorting)] || sortings[0];
@@ -152,16 +202,30 @@ const MenuIndex = () => {
return 0; return 0;
} }
}); });
}, [selectedCategory, search, selectedIngredients, selectedDeliveryId, foods, sorting]); }, [
selectedCategory,
search,
selectedIngredients,
selectedDeliveryId,
foods,
sorting,
]);
if (isLoading) { if (isLoading) {
return <MenuSkeleton />; return <MenuSkeleton />;
} }
return ( return (
<div className="flex flex-col gap-4 items-center pt-8 mb-8" ref={wrapperRef}> <div
className="flex flex-col gap-4 items-center pt-8 mb-8"
ref={wrapperRef}
>
<div className="w-full"> <div className="w-full">
<SearchBox value={search} placeholder={tCommon('SearchPlaceholder')} onChange={updateSearch} /> <SearchBox
value={search}
placeholder={tCommon("SearchPlaceholder")}
onChange={updateSearch}
/>
<CategoryScroll <CategoryScroll
categories={categories} categories={categories}
selectedCategory={selectedCategory} selectedCategory={selectedCategory}
@@ -170,33 +234,52 @@ const MenuIndex = () => {
</div> </div>
<section className="w-full"> <section className="w-full">
<div className="flex gap-2 justify-between items-center relative" ref={smallCategoriesRef} > <div
<span className="sm:text-base text-sm font-medium"> className="flex gap-2 justify-between items-center relative"
{selectedCategory === '0' ? '' : categories.find(c => c.id === selectedCategory)?.title || ''} ref={smallCategoriesRef}
>
<span className="sm:text-base text-sm font-medium max-w-[113px] sm:max-w-auto">
{selectedCategory === "0"
? ""
: categories.find((c) => c.id === selectedCategory)?.title || ""}
</span> </span>
<div className="inline-flex min-w-[247px] gap-2 justify-around items-center"> <div className="inline-flex min-w-[247px] gap-2 justify-around items-center">
<button onClick={toggleFilterModal} className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center justify-between gap-[7px]"> <button
onClick={toggleFilterModal}
className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center justify-between gap-[7px]"
>
<Candle2 className="stroke-foreground" size={16} /> <Candle2 className="stroke-foreground" size={16} />
<span className="text-xs leading-5 font-medium">{tMenu('MenuFilterDrawer.Label')}</span> <span className="text-xs leading-5 font-medium">
{tMenu("MenuFilterDrawer.Label")}
</span>
</button> </button>
<button <button
onClick={toggleSortingModal} onClick={toggleSortingModal}
className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center gap-2" className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center gap-2"
> >
<TextAlignIcon className="text-foreground" /> <TextAlignIcon className="text-foreground" />
<span className="text-xs leading-5 font-medium">{activeSortingLabel}</span> <span className="text-xs leading-5 font-medium">
{activeSortingLabel}
</span>
</button> </button>
</div> </div>
</div> </div>
<motion.div <motion.div
initial={{ y: smallCategoriesVisible ? 0 : -50, opacity: smallCategoriesVisible ? 1 : 0 }} initial={{
animate={{ y: smallCategoriesVisible ? 0 : -50, opacity: smallCategoriesVisible ? 1 : 0 }} y: smallCategoriesVisible ? 0 : -50,
transition={{ duration: .1 }} opacity: smallCategoriesVisible ? 1 : 0,
}}
animate={{
y: smallCategoriesVisible ? 0 : -50,
opacity: smallCategoriesVisible ? 1 : 0,
}}
transition={{ duration: 0.1 }}
className={clsx( className={clsx(
'fixed left-0 z-10 top-0 px-4 pt-16 bg-[#F4F5F9CC] dark:bg-background/70 backdrop-blur-[44px] right-0 xl:pr-72 xl:pt-20', "fixed left-0 z-10 top-0 px-4 pt-16 bg-[#F4F5F9CC] dark:bg-background/70 backdrop-blur-[44px] right-0 xl:pr-72 xl:pt-20",
!smallCategoriesVisible && 'pointer-events-none', !smallCategoriesVisible && "pointer-events-none",
)}> )}
>
<CategoryScroll <CategoryScroll
categories={categories} categories={categories}
selectedCategory={selectedCategory} selectedCategory={selectedCategory}
@@ -208,7 +291,7 @@ const MenuIndex = () => {
<VerticalScrollView className="mt-5! overflow-y-auto h-full"> <VerticalScrollView className="mt-5! overflow-y-auto h-full">
{filteredReceiptItems.length === 0 ? ( {filteredReceiptItems.length === 0 ? (
<div className="text-center text-foreground/60 py-8"> <div className="text-center text-foreground/60 py-8">
{foodsData ? 'غذایی یافت نشد' : 'در حال بارگذاری...'} {foodsData ? "غذایی یافت نشد" : "در حال بارگذاری..."}
</div> </div>
) : ( ) : (
filteredReceiptItems.map((food) => ( filteredReceiptItems.map((food) => (
@@ -227,7 +310,7 @@ const MenuIndex = () => {
selectedDeliveryId={selectedDeliveryId} selectedDeliveryId={selectedDeliveryId}
onIngredientsChange={changeSelectedIngredients} onIngredientsChange={changeSelectedIngredients}
onDeliveryChange={changeSelectedDelivery} onDeliveryChange={changeSelectedDelivery}
onApply={() => { }} onApply={() => {}}
tMenu={tMenu} tMenu={tMenu}
/> />