fix(wiki): compact mobile cards and add pagination
Deploy Canina / deploy (push) Successful in 2m9s

This commit is contained in:
devops committed 2026-10-17 11:18:52 +00:00
1 parent 092933860a
commit 80d9dc2f45
2 files changed
+141 -31

No files matched your search

@@ -51,12 +51,12 @@ function formatIngredientDisplayName(item: { nameFa?: string; scientificName?: s
const rawName = item.nameFa || item.name || '';
const cleanFa = rawName.replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim();
const sub = (item.scientificName || item.nameEn || '').replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim();
if (!cleanFa) return sub || rawName || item.slug || '';
if (!sub || cleanFa.toLowerCase() === sub.toLowerCase() || /[\u0600-\u06FF]/.test(sub)) {
return cleanFa;
}
return `${cleanFa} (${sub})`;
}
@@ -67,6 +67,7 @@ export default function IngredientWiki() {
const [ingredientsWiki, setIngredientsWiki] = useState<IngredientInfo[]>([]);
const [products, setProducts] = useState<Product[]>([]);
const [searchQuery, setSearchQuery] = useState("");
const [visibleCount, setVisibleCount] = useState(8);
useEffect(() => {
productService.getProducts({ limit: 999 })
@@ -110,7 +111,15 @@ export default function IngredientWiki() {
}, 200);
}
}
}, [termParam, ingredientsWiki]);
}, [termParam, ingredientsWiki, visibleCount]);
useEffect(() => {
if (!termParam || ingredientsWiki.length === 0) return;
const targetIndex = ingredientsWiki.findIndex(ing => ing.id === termParam);
if (targetIndex >= visibleCount) {
setVisibleCount(Math.ceil((targetIndex + 1) / 8) * 8);
}
}, [termParam, ingredientsWiki, visibleCount]);
// Product matcher for each ingredient
const getProductsForIngredient = useMemo(() => {
@@ -146,11 +155,11 @@ export default function IngredientWiki() {
}, [products]);
return (
<div className="bg-white py-12 px-4 overflow-hidden font-vazir" dir="rtl">
<div className="bg-white pt-3 pb-8 sm:py-12 px-4 overflow-hidden font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">
{/* Standard Breadcrumb Navigation & Integrated Back Button */}
<div className="flex items-center justify-between mb-8 pb-4 border-b border-medical-gray-200/60 font-vazir" dir="rtl">
<div className="flex items-center justify-between mb-4 sm:mb-8 pb-3 sm:pb-4 border-b border-medical-gray-200/60 font-vazir" dir="rtl">
<div className="flex items-center gap-2 text-xs font-bold text-medical-gray-400 whitespace-nowrap">
<span className="cursor-pointer hover:text-canina-blue transition-colors" onClick={() => router.push('/')}>خانه</span>
<ChevronLeft className="w-3 h-3 text-medical-gray-300" />
@@ -183,7 +192,10 @@ export default function IngredientWiki() {
type="text"
placeholder="جستجوی ماده مؤثره (مثلاً: صدف لب‌سبز، آغوز، بیوتین)..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onChange={(e) => {
setSearchQuery(e.target.value);
setVisibleCount(8);
}}
className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs"
/>
</div>
@@ -218,15 +230,20 @@ export default function IngredientWiki() {
);
}
const visibleIngredients = filtered.slice(0, visibleCount);
const remainingCount = Math.max(filtered.length - visibleCount, 0);
const nextCount = Math.min(8, remainingCount);
return (
<div className="space-y-5 sm:space-y-12">
{filtered.map((ing, idx) => {
<>
<div className="space-y-5 sm:space-y-12">
{visibleIngredients.map((ing, idx) => {
const hasIngredient = getProductsForIngredient(ing.id, ing.name);
const isTargeted = termParam === ing.id;
return (
<div
key={ing.id}
<div
key={ing.id}
id={`wiki-${ing.id}`}
className={`flex flex-col lg:flex-row items-stretch gap-5 sm:gap-10 p-4 sm:p-8 lg:p-10 rounded-2xl sm:rounded-[2.5rem] transition-all duration-300 border border-medical-gray-200/80 shadow-xs hover:shadow-lg ${isTargeted ? 'bg-canina-blue/5 border-2 border-canina-blue ring-4 ring-canina-blue/10 shadow-xl' : 'bg-white'} ${idx % 2 === 1 ? 'lg:flex-row-reverse' : ''}`}
>
@@ -247,7 +264,7 @@ export default function IngredientWiki() {
<span className="text-[12px] text-canina-blue font-bold tracking-wider font-vazir inline-block mt-1 bg-canina-blue/5 px-2.5 py-0.5 rounded-lg border border-canina-blue/10">کد ماده مؤثره: <span className="font-mono">{ing.id}</span></span>
</div>
</div>
<p className="text-xs sm:text-sm text-medical-gray-600 leading-relaxed mb-3 sm:mb-4 font-vazir">
{ing.description}
</p>
@@ -265,7 +282,7 @@ export default function IngredientWiki() {
{/* Products Linking */}
<div className="lg:w-1/2 relative flex">
<motion.div
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true }}
@@ -284,26 +301,29 @@ export default function IngredientWiki() {
{hasIngredient.length} محصول
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 relative z-10">
<div data-testid="wiki-related-products-grid"
className="grid grid-cols-2 gap-2 sm:gap-4 relative z-10">
{hasIngredient.length > 0 ? hasIngredient.slice(0, 4).map(p => (
<Link
<Link
key={p.id}
href={`/shop/${p.slug || p.id}`}
className="bg-white rounded-[2rem] p-4 shadow-sm border border-medical-gray-200 hover:border-canina-blue hover:shadow-lg hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between"
data-testid="wiki-related-product-card"
className="bg-white rounded-xl sm:rounded-[2rem] p-2 sm:p-4 shadow-sm border border-medical-gray-200 hover:border-canina-blue hover:shadow-lg hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between min-w-0"
>
<div className="aspect-square bg-medical-gray-50 rounded-2xl p-3 mb-3 flex items-center justify-center relative overflow-hidden">
<Image
src={p.image || '/assets/images/canina-product-placeholder.png'}
alt={p.name}
width={96}
height={96}
className="max-h-20 w-auto object-contain group-hover:scale-110 transition-transform duration-300"
unoptimized
<div data-testid="wiki-related-product-image"
className="h-20 sm:h-auto sm:aspect-square bg-medical-gray-50 rounded-lg sm:rounded-2xl p-1.5 sm:p-3 mb-1.5 sm:mb-3 flex items-center justify-center relative overflow-hidden">
<Image
src={p.image || '/assets/images/canina-product-placeholder.png'}
alt={p.name}
width={96}
height={96}
className="max-h-16 sm:max-h-20 w-auto object-contain group-hover:scale-110 transition-transform duration-300"
unoptimized
onError={(e: any) => { e.currentTarget.src = '/assets/images/canina-product-placeholder.png'; }}
/>
</div>
<h4 className="text-xs font-black text-center text-medical-gray-900 group-hover:text-canina-blue transition-colors px-1 leading-snug font-vazir line-clamp-2">{p.name}</h4>
<h4 className="text-[10px] sm:text-xs font-black text-center text-medical-gray-900 group-hover:text-canina-blue transition-colors px-0.5 sm:px-1 leading-snug font-vazir line-clamp-2">{p.name}</h4>
</Link>
)) : (
<div className="col-span-full py-8 text-center">
@@ -321,7 +341,7 @@ export default function IngredientWiki() {
{hasIngredient.length > 4 && (
<div className="mt-4 pt-3 border-t border-medical-gray-200/50 text-center">
<Link
<Link
href={`/shop?search=${encodeURIComponent(ing.name.replace(/\s*\([^)]*\)\s*/g, '').trim())}`}
className="text-xs font-black text-canina-blue hover:text-medical-gray-900 transition-colors font-vazir inline-flex items-center gap-1.5"
>
@@ -330,7 +350,7 @@ export default function IngredientWiki() {
</Link>
</div>
)}
{/* Decorative backdrop */}
<div className="absolute -bottom-20 -left-20 w-80 h-80 bg-canina-blue rounded-full blur-[100px] opacity-10 pointer-events-none" />
</motion.div>
@@ -338,7 +358,24 @@ export default function IngredientWiki() {
</div>
);
})}
</div>
</div>
{remainingCount > 0 && (
<div className="mt-7 sm:mt-10 flex flex-col items-center gap-2">
<button
type="button"
onClick={() => setVisibleCount(count => count + 8)}
className="inline-flex items-center justify-center px-6 py-3 rounded-2xl bg-white border border-medical-gray-200 text-canina-blue text-xs sm:text-sm font-black shadow-xs hover:border-canina-blue hover:shadow-md active:scale-95 transition-all cursor-pointer"
aria-label={`مشاهده ${nextCount.toLocaleString('fa-IR')} ماده بیشتر`}
>
مشاهده {nextCount.toLocaleString('fa-IR')} ماده بیشتر
</button>
<span className="text-[11px] font-bold text-medical-gray-400">
نمایش {Math.min(visibleCount, filtered.length).toLocaleString('fa-IR')} از {filtered.length.toLocaleString('fa-IR')} ماده
</span>
</div>
)}
</>
);
})()}
</div>
@@ -32,8 +32,8 @@ vi.mock('next/image', () => ({
// Mock next/link
vi.mock('next/link', () => ({
default: ({ children, href, className }: any) => (
<a href={href} className={className}>
default: ({ children, href, className, ...props }: any) => (
<a href={href} className={className} {...props}>
{children}
</a>
),
@@ -217,4 +217,77 @@ describe('IngredientWiki Component', () => {
expect(screen.getByText(/آغوز گاو/)).toBeInTheDocument();
});
});
it('shows only the first 8 ingredients and loads the next page on demand', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 18 }, (_, index) => ({
id: `ingredient-${index + 1}`,
slug: `ingredient-${index + 1}`,
nameFa: `ماده شماره ${index + 1}`,
description: `توضیح ماده ${index + 1}`,
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('ماده شماره 1')).toBeInTheDocument());
expect(screen.getByText('ماده شماره 8')).toBeInTheDocument();
expect(screen.queryByText('ماده شماره 9')).not.toBeInTheDocument();
expect(screen.getByText(/نمایش ۸ از ۱۸ ماده/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۸ ماده بیشتر/ }));
expect(screen.getByText('ماده شماره 16')).toBeInTheDocument();
expect(screen.queryByText('ماده شماره 17')).not.toBeInTheDocument();
expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument();
});
it('resets ingredient pagination when the search query changes', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 12 }, (_, index) => ({
id: `item-${index + 1}`,
slug: `item-${index + 1}`,
nameFa: index < 10 ? `مشترک ${index + 1}` : `دیگر ${index + 1}`,
description: 'توضیح مشترک',
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('مشترک 1')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۴ ماده بیشتر/ }));
expect(screen.getByText('دیگر 12')).toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText(/جستجوی ماده مؤثره/), { target: { value: 'مشترک' } });
expect(screen.getByText('مشترک 8')).toBeInTheDocument();
expect(screen.queryByText('مشترک 9')).not.toBeInTheDocument();
});
it('uses compact two-column related-product cards on mobile', async () => {
(api.get as any).mockResolvedValueOnce({ data: [{
id: 'biotin', slug: 'biotin', nameFa: 'بیوتین', description: 'توضیح', benefits: [],
}] });
(productService.getProducts as any).mockResolvedValueOnce({ data: [{
id: 'p-1', slug: 'biotin-tabs', name: 'محصول بیوتین', main_ingredients: ['بیوتین'], image: '/biotin.png',
}] });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('محصول بیوتین')).toBeInTheDocument());
expect(screen.getByTestId('wiki-related-products-grid')).toHaveClass('grid-cols-2');
expect(screen.getByTestId('wiki-related-product-card')).toHaveClass('p-2');
expect(screen.getByTestId('wiki-related-product-image')).toHaveClass('h-20');
});
it('keeps the mobile breadcrumb close to the top edge', () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
(api.get as any).mockResolvedValueOnce({ data: [] });
const { container } = render(<IngredientWiki />);
expect(container.firstElementChild).toHaveClass('pt-3', 'pb-8', 'sm:py-12');
expect(container.firstElementChild).not.toHaveClass('py-12');
});
});