feat(ux-26): implement real shop pagination with deep-link page support and regression test

This commit is contained in:
devops committed 2026-10-17 18:15:42 +00:00
1 parent 92065cc7f2
commit 21f7768cce
3 files changed
+115 -22

No files matched your search

+71 -21
View File
@@ -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<string>("createdAt");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
const [visibleCount, setVisibleCount] = useState<number>(12);
const [currentPage, setCurrentPage] = useState<number>(() => Math.max(1, initialPage));
const pageSize = Math.max(1, initialLimit);
const [isMounted, setIsMounted] = useState<boolean>(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({
</section>
))}
{hasMore && (
<div className="mt-8 mb-4 text-center">
<button
type="button"
onClick={() => setVisibleCount(prev => prev + 12)}
className="inline-flex items-center gap-2 px-6 py-3 bg-white border border-medical-gray-200 hover:border-canina-blue text-canina-blue font-black text-xs sm:text-sm rounded-2xl shadow-xs hover:shadow-md active:scale-95 transition-all cursor-pointer font-vazir"
>
<span>مشاهده ۱۲ محصول بیشتر</span>
<span className="text-xs text-medical-gray-400 font-bold">
(نمایش {toPersian(slicedProducts.length)} از {toPersian(filteredProducts.length)})
</span>
</button>
</div>
{/* Pagination Controls */}
{totalPages > 1 && (
<nav aria-label="صفحه‌بندی محصولات" data-testid="shop-pagination" className="mt-10 mb-4 flex flex-col sm:flex-row items-center justify-between gap-4 bg-white border border-medical-gray-200/80 rounded-2xl p-4 shadow-xs font-vazir">
<div className="text-xs text-medical-gray-500 font-bold order-2 sm:order-1">
صفحه {toPersian(safeCurrentPage)} از {toPersian(totalPages)} (کل محصولات: {toPersian(filteredProducts.length)})
</div>
<div className="flex items-center gap-2 order-1 sm:order-2">
<button
type="button"
disabled={safeCurrentPage <= 1}
onClick={() => {
setCurrentPage(prev => Math.max(1, prev - 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه قبل"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
قبلی
</button>
<div className="flex items-center gap-1.5">
{Array.from({ length: totalPages }).map((_, i) => {
const pageNum = i + 1;
const isActive = pageNum === safeCurrentPage;
return (
<button
key={pageNum}
type="button"
onClick={() => {
setCurrentPage(pageNum);
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-current={isActive ? "page" : undefined}
className={isActive ? "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer bg-canina-blue text-white shadow-sm" : "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer text-medical-gray-700 hover:bg-medical-gray-100 border border-medical-gray-200/60"}
>
{toPersian(pageNum)}
</button>
);
})}
</div>
<button
type="button"
disabled={safeCurrentPage >= totalPages}
onClick={() => {
setCurrentPage(prev => Math.min(totalPages, prev + 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه بعد"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
بعدی
</button>
</div>
</nav>
)}
</>
);
@@ -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(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} />);
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(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} initialPage={2} />);
await waitFor(() => {
expect(screen.getByText("محصول تست 13")).toBeInTheDocument();
expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument();
});
});
});