From 21f7768ccefd57b16e0914eef9786abe40e25cb6 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:15:42 +0000 Subject: [PATCH] feat(ux-26): implement real shop pagination with deep-link page support and regression test --- frontend/application/app/shop/page.tsx | 3 + .../application/components/ArchivePage.tsx | 92 ++++++++++++++----- .../components/__tests__/ArchivePage.test.tsx | 42 ++++++++- 3 files changed, 115 insertions(+), 22 deletions(-) diff --git a/frontend/application/app/shop/page.tsx b/frontend/application/app/shop/page.tsx index ac11b984..154b8ce5 100644 --- a/frontend/application/app/shop/page.tsx +++ b/frontend/application/app/shop/page.tsx @@ -43,6 +43,8 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : ""; const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : ""; const symptoms = symptomsParam || (symptomSingle ? symptomSingle : ""); + const pageParam = typeof resolvedParams.page === "string" ? parseInt(resolvedParams.page, 10) : 1; + const initialPage = isNaN(pageParam) || pageParam < 1 ? 1 : pageParam; const { data: initialProducts } = await productService.getProducts({ category, petType: petType as PetType | "all", query: search, symptom: symptomSingle, limit: 999 }); return ( @@ -52,6 +54,7 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ initialPetType={petType} initialSymptoms={symptoms} initialProducts={initialProducts} + initialPage={initialPage} /> ); } diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index ba31ea18..04e11913 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -451,13 +451,17 @@ export default function ArchivePage({ initialSearch = "", initialPetType = "all", initialSymptoms = "", - initialProducts = [] + initialProducts = [], + initialPage = 1, + initialLimit = 12 }: { initialCategory?: string, initialSearch?: string, initialPetType?: string, initialSymptoms?: string, - initialProducts?: Product[] + initialProducts?: Product[], + initialPage?: number, + initialLimit?: number }) { const router = useRouter(); const getText = useSettingsStore(state => state.getText); @@ -471,7 +475,8 @@ export default function ArchivePage({ const [sortBy, setSortBy] = useState("createdAt"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [viewMode, setViewMode] = useState<"list" | "grid">("list"); - const [visibleCount, setVisibleCount] = useState(12); + const [currentPage, setCurrentPage] = useState(() => Math.max(1, initialPage)); + const pageSize = Math.max(1, initialLimit); const [isMounted, setIsMounted] = useState(false); useEffect(() => { @@ -534,6 +539,7 @@ export default function ArchivePage({ } lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms }; + setCurrentPage(initialPage || 1); // Normalize Input const normSearch = (initialSearch || "").trim().toLowerCase(); @@ -553,7 +559,7 @@ export default function ArchivePage({ setSelectedPet((initialPetType as PetType) || "all"); setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []); } - setVisibleCount(12); + setCurrentPage(1); }, [initialCategory, initialSearch, initialPetType, initialSymptoms]); // Update URL Query Parameters @@ -563,13 +569,14 @@ export default function ArchivePage({ if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet); if (searchQuery) params.set('search', searchQuery); if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(',')); + if (currentPage > 1) params.set('page', String(currentPage)); const queryString = params.toString(); const newUrl = `/shop${queryString ? `?${queryString}` : ''}`; if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) { router.replace(newUrl, { scroll: false }); } - }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]); + }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, currentPage, router]); const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0); const didSkipInitialFetch = React.useRef(false); @@ -594,7 +601,7 @@ export default function ArchivePage({ } setFilteredProducts(orderProductsByAvailability(result)); - setVisibleCount(12); + setCurrentPage(1); } catch (error) { console.error("Failed to fetch products:", error); toast.error("خطا در دریافت لیست محصولات از سرور."); @@ -1131,8 +1138,11 @@ export default function ArchivePage({ <> {/* Progressive slice of products for optimal DOM density and mobile UX */} {(() => { - const slicedProducts = filteredProducts.slice(0, visibleCount); - const hasMore = visibleCount < filteredProducts.length; + const totalPages = Math.max(1, Math.ceil(filteredProducts.length / pageSize)); + const safeCurrentPage = Math.min(currentPage, totalPages); + const startIndex = (safeCurrentPage - 1) * pageSize; + const slicedProducts = filteredProducts.slice(startIndex, startIndex + pageSize); + const totalInStock = filteredProducts.filter(product => !isProductOutOfStock(product)).length; const totalOutOfStock = filteredProducts.filter(product => isProductOutOfStock(product)).length; @@ -1184,19 +1194,59 @@ export default function ArchivePage({ ))} - {hasMore && ( -
- -
+ {/* Pagination Controls */} + {totalPages > 1 && ( + )} ); diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index cb779abc..228d3f59 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -1,7 +1,7 @@ "use client"; import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; -import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react"; import ArchivePage, { orderProductsByAvailability } from "../ArchivePage"; import { productService } from "../../lib/services/productService"; import { useCartStore } from "../../lib/store/cartStore"; @@ -383,4 +383,44 @@ describe("ArchivePage Component", () => { expect(screen.getByText("محصول بازیابی شده")).toBeInTheDocument(); }); }); + + it("supports real pagination, page switching, deep-link initialPage, and resets to page 1 on filter change", async () => { + const mockProducts = Array.from({ length: 25 }, (_, i) => ({ + id: "prod-" + (i + 1), + name: "محصول تست " + (i + 1), + nameFa: "محصول تست " + (i + 1), + priceValue: 100000 + i * 1000, + stock: 10, + categorySlug: i % 2 === 0 ? "joints" : "immune", + images: ["/test.png"], + symptoms: [], + main_ingredients: [], + })); + + // Initial render at page 1 with pageSize 12 -> shows items 1 to 12 + const { rerender } = render(); + + expect(screen.getByTestId("shop-pagination")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 1")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 12")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 13")).not.toBeInTheDocument(); + + // Click next page button + const nextBtn = screen.getByRole("button", { name: "صفحه بعد" }); + fireEvent.click(nextBtn); + + // Now page 2 -> shows items 13 to 24 + expect(screen.getByText("محصول تست 13")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 24")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument(); + + // Deep-link initialPage test: render directly at page 2 + cleanup(); + render(); + + await waitFor(() => { + expect(screen.getByText("محصول تست 13")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument(); + }); + }); });