improve pagination to include jumping to the latest page as well... (improve its overall…
- User
improve pagination to include jumping to the latest page as well... (improve its overall design as well) Ensures good ui/ux practices are applied throughout the page... you can use libraries if u want to... I'm using nextjs app router 14 and tailwind css. Finally, make the background like this animation: @tailwind base; @tailwind components; @tailwind utilities;
/Start Animations/ @-webkit-keyframes animatetop { from { top: -300px; opacity: 0; } to { top: 0; opacity: 1; } } @keyframes animatetop { from { top: -300px; opacity: 0; } to { top: 0; opacity: 1; } } @-webkit-keyframes zoomIn { 0% { opacity: 0; -webkit-transform: scale3d(0.3, 0.3, 0.3); transform: scale3d(0.3, 0.3, 0.3); } 50% { opacity: 1; } } @keyframes zoomIn { 0% { opacity: 0; -webkit-transform: scale3d(0.3, 0.3, 0.3); transform: scale3d(0.3, 0.3, 0.3); } 50% { opacity: 1; } } /End Animations/ /* -- Start BackGround Animation */ .area { background: #4e54c8; background: -webkit-linear-gradient(to left, #8f94fb, #4e54c8); width: 100%; height: 100vh; position: absolute; z-index: -1; }
.circles { position: absolute; top: 0; left: 0; width: 100%; height: 96%; overflow: hidden; }
.circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.2); animation: animate 25s linear infinite; bottom: -150px; }
.circles li:nth-child(1) { left: 25%; width: 80px; height: 80px; animation-delay: 0s; }
.circles li:nth-child(2) { left: 10%; width: 20px; height: 20px; animation-delay: 2s; animation-duration: 12s; }
.circles li:nth-child(3) { left: 70%; width: 20px; height: 20px; animation-delay: 4s; }
.circles li:nth-child(4) { left: 40%; width: 60px; height: 60px; animation-delay: 0s; animation-duration: 18s; }
.circles li:nth-child(5) { left: 65%; width: 20px; height: 20px; animation-delay: 0s; }
.circles li:nth-child(6) { left: 75%; width: 110px; height: 110px; animation-delay: 3s; }
.circles li:nth-child(7) { left: 35%; width: 150px; height: 150px; animation-delay: 7s; }
.circles li:nth-child(8) { left: 50%; width: 25px; height: 25px; animation-delay: 15s; animation-duration: 45s; }
.circles li:nth-child(9) { left: 20%; width: 15px; height: 15px; animation-delay: 2s; animation-duration: 35s; }
.circles li:nth-child(10) { left: 85%; width: 150px; height: 150px; animation-delay: 0s; animation-duration: 11s; }
@keyframes animate { 0% { transform: translateY(0) rotate(0deg); opacity: 1; border-radius: 0; }
100% { transform: translateY(-1000px) rotate(720deg); opacity: 0; border-radius: 50%; }} /* -- End BackGround Animation */ html: I don't know how you do it but do it... ProductsPage.tsx: // pages/products.tsx "use client";
import React, { useState, useEffect, useCallback, useMemo, ChangeEvent, } from "react"; import Head from "next/head"; import Image from "next/image"; import { Search, Grid, List, Plus, Edit, Trash2 } from "lucide-react"; import AddProductDialog from "@/components/AddProductDialog"; import EditProduct from "@/components/EditProduct"; import LoadingSpinner from "@/components/LoadingSpinner"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import debounce from "lodash/debounce"; import { getToken } from "@/app/auth"; import { Product, Brand, ApiResponse } from "@/components/types";
const formatDate = (dateString: string) => { const date = new Date(dateString); return date.toLocaleDateString(); // 'MM/DD/YYYY' format };
const PRODUCTS_PER_PAGE = 15;
const ProductsPage: React.FC = () => { // State Variables const [products, setProducts] = useState<Product[]>([]); const [brands, setBrands] = useState<Brand[]>([]); const [brandMap, setBrandMap] = useState<{ [key: number]: string }>({}); const [currentPage, setCurrentPage] = useState(1); const [searchTerm, setSearchTerm] = useState(""); const [viewMode, setViewMode] = useState<"grid" | "list">("grid"); const [sortBy, setSortBy] = useState("created_at"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [isAddProductDialogOpen, setIsAddProductDialogOpen] = useState(false); const [isEditProductDialogOpen, setIsEditProductDialogOpen] = useState(false); const [productToEdit, setProductToEdit] = useState<Product | null>(null); const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false); const [productToDelete, setProductToDelete] = useState<Product | null>(null); const [isDeleting, setIsDeleting] = useState(false); const [totalPages, setTotalPages] = useState(1); const [totalProducts, setTotalProducts] = useState(0); const [isLoading, setIsLoading] = useState(false); const [searchInput, setSearchInput] = useState("");
// Debounce the search input const debouncedSearch = useMemo( () => debounce((term: string) => { setSearchTerm(term); setCurrentPage(1); }, 300), [], );
useEffect(() => { debouncedSearch(searchInput); return () => { debouncedSearch.cancel(); }; }, [searchInput, debouncedSearch]);
const handleSearchChange = (e: ChangeEvent) => { setSearchInput(e.target.value); };
// Fetch Brand Details const fetchBrands = useCallback(async () => { const token = getToken();
if (!token) { toast.error("You must be logged in."); return; } try { const response = await fetch( `http://localhost:4000/subcategories/brands`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to fetch brands"); } const data: Brand[] = await response.json(); setBrands(data); // Create a mapping from brand_id to brand_name const map: { [key: number]: string } = {}; data.forEach((brand) => { map[brand.id] = brand.name; }); setBrandMap(map); } catch (error) { console.error("Error fetching brands:", error); toast.error("Failed to fetch brands. Please try again."); }}, []);
// Fetch Products const fetchProducts = useCallback(async () => { setIsLoading(true); const token = getToken();
if (!token) { toast.error("You must be logged in."); setIsLoading(false); return; } try { const response = await fetch( `http://localhost:4000/products?page=${currentPage}&limit=${PRODUCTS_PER_PAGE}&search=${encodeURIComponent( searchTerm, )}&sortBy=${sortBy}&sortOrder=${sortOrder}`, { cache: "no-cache", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to fetch products"); } const data: ApiResponse = await response.json(); setProducts(data.products); setTotalPages(data.totalPages); setTotalProducts(data.total); // Assuming your API provides totalItems } catch (error) { console.error("Error fetching products:", error); toast.error("Failed to fetch products. Please try again."); } finally { setIsLoading(false); }}, [currentPage, searchTerm, sortBy, sortOrder]);
useEffect(() => { fetchBrands(); }, [fetchBrands]);
useEffect(() => { fetchProducts(); }, [fetchProducts]);
const filteredProducts = useMemo(() => { return products .filter((product) => product.name.toLowerCase().includes(searchTerm.toLowerCase()), ) .sort((a, b) => { if (a[sortBy] === null) return 1; if (b[sortBy] === null) return -1; if (sortOrder === "asc") { return a[sortBy]!.toString().localeCompare(b[sortBy]!.toString()); } else { return b[sortBy]!.toString().localeCompare(a[sortBy]!.toString()); } }); }, [products, searchTerm, sortBy, sortOrder]);
const handleEditClick = useCallback((product: Product) => { setProductToEdit(product); setIsEditProductDialogOpen(true); }, []);
const handleDeleteClick = useCallback((product: Product) => { setProductToDelete(product); setIsDeleteConfirmOpen(true); }, []);
const handleDeleteConfirm = useCallback(async () => { if (productToDelete) { setIsDeleting(true); const token = getToken();
if (!token) { toast.error("You must be logged in."); setIsDeleting(false); return; } try { const response = await fetch( `http://localhost:4000/products/${productToDelete.id}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to delete product"); } setProducts((prevProducts) => prevProducts.filter((p) => p.id !== productToDelete.id), ); setIsDeleteConfirmOpen(false); toast.success("Product deleted successfully"); } catch (error) { console.error("Error deleting product:", error); toast.error("Failed to delete product. Please try again."); } finally { setIsDeleting(false); } }}, [productToDelete]);
// Helper function to get the first color's first size information const getFirstColorSizeInfo = useCallback((product: Product) => { if (product.has_color && product.has_size) { const firstColor = product.colors[0]; if (firstColor) { const sizesForColor = product.sizes.filter( (size) => size.color_id === firstColor.id, ); const firstSize = sizesForColor[0]; if (firstSize) { return { colorName: firstColor.name, sizeName: firstSize.name, price: firstSize.price, qty: firstSize.qty, sold: Math.abs(firstSize.sold), }; } } } return null; }, []);
// Updated helper functions to accommodate the new logic const getProductPrice = useCallback( (product: Product): string => { const colorSizeInfo = getFirstColorSizeInfo(product); if (colorSizeInfo) { return
$${colorSizeInfo.price.toLocaleString()}; } if (!product.has_color && !product.has_size) return$${product.price.toLocaleString()}; if (product.colors.length > 0 && product.colors[0].price !== null) return$${product.colors[0].price.toLocaleString()}; if (product.sizes.length > 0) return$${product.sizes[0].price.toLocaleString()}; return "N/A"; }, [getFirstColorSizeInfo], );const getProductQuantity = useCallback( (product: Product): number | string => { const colorSizeInfo = getFirstColorSizeInfo(product); if (colorSizeInfo) { return colorSizeInfo.qty; } if (product.qty !== null && product.qty !== 0) return product.qty; if (product.colors.length > 0 && product.colors[0].qty !== null) return product.colors[0].qty; if (product.sizes.length > 0) return product.sizes[0].qty; return "N/A"; }, [getFirstColorSizeInfo], );
const getProductSold = useCallback((product: Product): number => { let total = 0; if (product.colors) { product.colors.forEach((color) => { if (color.sizes.length > 0) { color.sizes.forEach((size) => (total += size.sold)); } else { total += color.sold; } }); } if (product.sizes) { product.sizes.forEach((size) => { total += size.sold; }); } total += product.sold; return Math.abs(total); }, []);
// Pagination Handler const handlePageChange = useCallback((newPage: number) => { setCurrentPage(newPage); window.scrollTo({ top: 0, behavior: "smooth" }); }, []);
return ( Products - Naay Store {/* Using Inter font */}
{/* Background Animation */} <div className="area"> <ul className="circles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> <main className="container relative z-10 mx-auto px-4 py-8"> {/* Header Section */} <div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0"> <h1 className="text-3xl font-bold text-gray-900">All Products</h1> <div className="flex items-center space-x-4"> <span className="text-gray-700"> Total Products:{" "} <span className="font-semibold text-blue-600"> {totalProducts} </span> </span> <button className="flex items-center rounded-md bg-green-500 px-4 py-2 text-white transition duration-300 hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-400" onClick={() => setIsAddProductDialogOpen(true)} > <Plus className="mr-2" size={20} /> Add Product </button> </div> </div> {/* Search and Filters */} <div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0"> {/* Search */} <div className="relative w-full max-w-md"> <input type="text" placeholder="Search products..." className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={searchInput} onChange={handleSearchChange} /> <Search className="absolute left-3 top-2.5 h-5 w-5 text-gray-400" /> </div> {/* Sort & Sort Order & View Modes */} <div className="flex items-center space-x-4"> <select className="rounded-md border border-gray-300 px-3 py-2 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={sortBy} onChange={(e) => setSortBy(e.target.value as keyof Product)} > <option value="name">Sort by Name</option> <option value="price">Sort by Price</option> <option value="created_at">Sort by Created Date</option> </select> <select className="rounded-md border border-gray-300 px-3 py-2 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={sortOrder} onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")} > <option value="asc">Ascending</option> <option value="desc">Descending</option> </select> <div className="flex items-center space-x-2"> <button className={`rounded-md p-2 ${ viewMode === "grid" ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700" } transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400`} onClick={() => setViewMode("grid")} aria-label="Grid View" > <Grid className="h-5 w-5" /> </button> <button className={`rounded-md p-2 ${ viewMode === "list" ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700" } transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400`} onClick={() => setViewMode("list")} aria-label="List View" > <List className="h-5 w-5" /> </button> </div> </div> </div> {/* Product List */} {isLoading ? ( <div className="flex justify-center"> <LoadingSpinner /> </div> ) : ( <div className={`grid gap-6 ${ viewMode === "grid" ? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" : "grid-cols-1" }`} > {filteredProducts.map((product) => { const colorSizeInfo = getFirstColorSizeInfo(product); return ( <div key={product.id} className={`overflow-hidden rounded-lg bg-white shadow-md ${ viewMode === "list" ? "flex" : "" } transition-transform hover:scale-105`} > {/* Product Image */} <div className={`${ viewMode === "list" ? "w-1/3" : "w-full" } relative pb-[100%]`} > {product.images.length > 0 ? ( <Image src={`https://storage.naayiq.com/resources/${product.images[0].url}`} alt={product.name} fill={true} className="object-cover" priority={false} loading="lazy" /> ) : ( <div className="flex items-center justify-center bg-gray-200"> <span className="text-gray-500">No Image</span> </div> )} </div> {/* Product Details */} <div className={`p-4 ${viewMode === "list" ? "w-2/3" : ""}`}> <h2 className="mb-2 text-xl font-semibold text-gray-800"> {product.name} </h2> <p className="mb-4 text-sm text-gray-700" style={{ direction: "rtl" }} dangerouslySetInnerHTML={{ __html: product.description.replace(/\n/g, "<br />"), }} /> <div className="mb-4 space-y-1"> {/* Display Price */} <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span>{" "} {getProductPrice(product)} </p> {/* Display Quantity */} <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span>{" "} {getProductQuantity(product)} </p> {/* Display Sold */} <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span>{" "} {getProductSold(product)} </p> {/* Display Created At */} <p className="text-sm text-gray-600"> <span className="font-semibold">Created at:</span>{" "} {formatDate(product.created_at)} </p> {/* Display Has Color */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Color:</span>{" "} {product.has_color ? "Yes" : "No"} </p> {/* Display Has Size */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Size:</span>{" "} {product.has_size ? "Yes" : "No"} </p> {/* Display Brand */} <p className="text-sm text-gray-600"> <span className="font-semibold">Brand:</span>{" "} {brandMap[product.brand_id] || `ID: ${product.brand_id}`} </p> {/* Display Categories */} <p className="text-sm text-gray-600"> <span className="font-semibold">Category:</span>{" "} {product.categories .map((category) => category.name) .join(", ")} </p> {/* Display First Color's First Size Information */} {colorSizeInfo && ( <div className="mt-2"> <p className="text-sm text-gray-600"> <span className="font-semibold">Color:</span>{" "} {colorSizeInfo.colorName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Size:</span>{" "} {colorSizeInfo.sizeName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span> $ {colorSizeInfo.price.toLocaleString()} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span>{" "} {colorSizeInfo.qty} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span>{" "} {colorSizeInfo.sold} </p> </div> )} </div> {/* Action Buttons */} <div className="flex space-x-2"> <button className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white transition duration-300 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400" onClick={() => handleEditClick(product)} > <Edit className="mr-1 inline-block" size={16} /> Edit </button> <button className="bg-red-500 hover:bg-red-600 focus:ring-red-400 flex items-center rounded-md px-4 py-2 text-white transition duration-300 focus:outline-none focus:ring-2" onClick={() => handleDeleteClick(product)} > <Trash2 className="mr-1 inline-block" size={16} /> Delete </button> </div> </div> </div> ); })} </div> )} {/* Pagination Controls */} {!isLoading && totalPages > 1 && ( <div className="mt-8 flex items-center justify-center space-x-2"> <button className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 transition duration-300 hover:bg-gray-300 disabled:cursor-not-allowed disabled:opacity-50" onClick={() => handlePageChange(Math.max(currentPage - 1, 1))} disabled={currentPage === 1} > Previous </button> {/* Condensed Pagination with Ellipsis */} {Array.from({ length: totalPages }, (_, i) => i + 1) .filter( (number) => number === 1 || number === totalPages || (number >= currentPage - 1 && number <= currentPage + 1), ) .map((number, index, array) => { if (index > 0 && number - array[index - 1] > 1) { return ( <span key={`ellipsis-${number}`} className="text-gray-500"> ... </span> ); } return ( <button key={number} className={`rounded-md px-3 py-1 text-sm transition ${ currentPage === number ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700 hover:bg-gray-300" } focus:outline-none focus:ring-2 focus:ring-blue-400`} onClick={() => handlePageChange(number)} > {number} </button> ); })} <button className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 transition duration-300 hover:bg-gray-300 disabled:cursor-not-allowed disabled:opacity-50" onClick={() => handlePageChange(Math.min(currentPage + 1, totalPages)) } disabled={currentPage === totalPages} > Next </button> </div> )} </main> {/* Add Product Dialog */} {isAddProductDialogOpen && ( <AddProductDialog isOpen={isAddProductDialogOpen} onClose={() => setIsAddProductDialogOpen(false)} /> )} {/* Edit Product Dialog */} {isEditProductDialogOpen && productToEdit && ( <EditProduct isOpen={isEditProductDialogOpen} onClose={() => { setIsEditProductDialogOpen(false); setProductToEdit(null); fetchProducts(); // Refresh the product list after editing }} // @ts-ignore product={productToEdit} /> )} {/* Delete Confirmation Modal */} {isDeleteConfirmOpen && ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"> <div className="w-11/12 max-w-md rounded-lg bg-white p-8 shadow-lg"> <h2 className="mb-4 text-xl font-semibold text-gray-800"> Confirm Delete </h2> <p className="mb-8 text-gray-600"> Are you sure you want to delete{" "} <span className="font-semibold"> {productToDelete?.name ?? "this product"} </span> ? </p> <div className="flex justify-end space-x-4"> <button className="bg-red-500 hover:bg-red-600 focus:ring-red-400 flex items-center rounded-md px-4 py-2 text-white transition duration-300 focus:outline-none focus:ring-2 disabled:opacity-50" onClick={handleDeleteConfirm} disabled={isDeleting} > <Trash2 className="mr-1 inline-block" size={16} /> {isDeleting ? "Deleting..." : "Yes, Delete"} </button> <button className="rounded-md bg-gray-300 px-4 py-2 text-gray-700 transition duration-300 hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400 disabled:opacity-50" onClick={() => setIsDeleteConfirmOpen(false)} disabled={isDeleting} > Cancel </button> </div> </div> </div> )} {/* Toast Notifications */} <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick pauseOnFocusLoss draggable pauseOnHover theme="light" /> </div>); };
export default React.memo(ProductsPage); products/page.tsx: import DefaultLayout from "@/components/Layouts/DefaultLayout"; import ProductsPage from "@/components/Products";
export default function Products() { return ( ); } layout.tsx: "use client"; import "jsvectormap/dist/jsvectormap.css"; import "flatpickr/dist/flatpickr.min.css"; import "@/css/satoshi.css"; import "@/css/style.css"; import React, { useEffect, useState } from "react"; import Loader from "@/components/common/Loader"; import AdminOnly from "@/components/AdminOnly";
export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { const [sidebarOpen, setSidebarOpen] = useState(false); const [loading, setLoading] = useState(true);
useEffect(() => { setTimeout(() => setLoading(false), 1000); }, []);
return ( {loading ? : children} ); }
DefaultLayout.tsx: "use client"; import React, { useState } from "react"; import Sidebar from "@/components/Sidebar"; import Header from "@/components/Header";
export default function DefaultLayout({ children, }: { children: React.ReactNode; }) { const [sidebarOpen, setSidebarOpen] = useState(false);
return ( <> {/* /} {/ /} {/ */}
{/* <!-- ===== Content Area Start ===== --> */} <div className="relative flex flex-1 flex-col lg:ml-72.5"> {/* <!-- ===== Header Start ===== --> */} <Header sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} /> {/* <!-- ===== Header End ===== --> */} {/* <!-- ===== Main Content Start ===== --> */} <main> <div className="mx-auto max-w-screen-2xl p-4 md:p-6 2xl:p-10"> {children} </div> </main> {/* <!-- ===== Main Content End ===== --> */} </div> {/* <!-- ===== Content Area End ===== --> */} </div> {/* <!-- ===== Page Wrapper End ===== --> */} </>); }
- Assistant
Certainly! Enhancing your pagination, overall design, and ensuring a seamless UI/UX experience can significantly improve your Products Page. Below, I'll guide you through:
- Improving the Pagination Component: Adding "First" and "Last" buttons, enabling users to jump directly to the latest or first page.
- Enhancing Overall Design: Refining the UI elements using Tailwind CSS for a more polished look.
- Ensuring Good UI/UX Practices: Making sure the page is accessible, responsive, and user-friendly.
- Implementing the Background Animation: Ensuring the animated background is smoothly integrated.
1. Improving the Pagination Component
Features to Add:
- First and Last Buttons: Allow users to quickly navigate to the first or last page.
- Page Number Input: Enable users to input a specific page number to jump to.
- Responsive Pagination: Adjust pagination display based on screen size.
Implementation:
Let's create a dedicated
Paginationcomponent to handle all pagination-related functionalities. This promotes reusability and cleaner code.Create
Pagination.tsxComponent// components/Pagination.tsx "use client"; import React, { useState } from "react"; import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react"; interface PaginationProps { currentPage: number; totalPages: number; onPageChange: (page: number) => void; } const Pagination: React.FC<PaginationProps> = ({ currentPage, totalPages, onPageChange, }) => { const [inputPage, setInputPage] = useState<string>(""); const handleFirst = () => { if (currentPage !== 1) onPageChange(1); }; const handleLast = () => { if (currentPage !== totalPages) onPageChange(totalPages); }; const handlePrevious = () => { if (currentPage > 1) onPageChange(currentPage - 1); }; const handleNext = () => { if (currentPage < totalPages) onPageChange(currentPage + 1); }; const handleJump = () => { const pageNumber = Number(inputPage); if (pageNumber >= 1 && pageNumber <= totalPages) { onPageChange(pageNumber); setInputPage(""); } else { // Optionally, show an error toast } }; const renderPageNumbers = () => { const pages = []; // Determine the range of page numbers to show const start = Math.max(1, currentPage - 2); const end = Math.min(totalPages, currentPage + 2); for (let number = start; number <= end; number++) { pages.push( <button key={number} onClick={() => onPageChange(number)} className={`px-3 py-1 rounded-md text-sm font-medium transition ${ number === currentPage ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700 hover:bg-gray-300" }`} aria-current={number === currentPage ? "page" : undefined} > {number} </button> ); } return pages; }; return ( <div className="flex flex-col items-center space-y-2 sm:flex-row sm:justify-between sm:space-y-0"> {/* Page Info */} <div className="text-sm text-gray-700"> Page {currentPage} of {totalPages} </div> {/* Pagination Controls */} <div className="flex items-center space-x-2"> {/* First Page Button */} <button onClick={handleFirst} disabled={currentPage === 1} className="p-2 rounded-md bg-gray-200 text-gray-700 hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed" aria-label="First Page" > <ChevronsLeft size={16} /> </button> {/* Previous Page Button */} <button onClick={handlePrevious} disabled={currentPage === 1} className="p-2 rounded-md bg-gray-200 text-gray-700 hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed" aria-label="Previous Page" > <ChevronLeft size={16} /> </button> {/* Page Numbers */} {renderPageNumbers()} {/* Next Page Button */} <button onClick={handleNext} disabled={currentPage === totalPages} className="p-2 rounded-md bg-gray-200 text-gray-700 hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed" aria-label="Next Page" > <ChevronRight size={16} /> </button> {/* Last Page Button */} <button onClick={handleLast} disabled={currentPage === totalPages} className="p-2 rounded-md bg-gray-200 text-gray-700 hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed" aria-label="Last Page" > <ChevronsRight size={16} /> </button> </div> {/* Jump to Page */} <div className="flex items-center space-x-2"> <input type="number" min={1} max={totalPages} value={inputPage} onChange={(e) => setInputPage(e.target.value)} placeholder="Page #" className="w-20 rounded-md border border-gray-300 px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" /> <button onClick={handleJump} className="rounded-md bg-blue-500 px-3 py-1 text-sm font-medium text-white hover:bg-blue-600 transition focus:outline-none focus:ring-2 focus:ring-blue-400 disabled:opacity-50 disabled:cursor-not-allowed" disabled={!inputPage || Number(inputPage) < 1 || Number(inputPage) > totalPages} > Go </button> </div> </div> ); }; export default Pagination;Update
ProductsPage.tsxto Use the NewPaginationComponentReplace the existing pagination controls with the new
Paginationcomponent.// components/ProductsPage.tsx // ... [other imports] import Pagination from "@/components/Pagination"; // Import the new Pagination component // ... [rest of the code] const ProductsPage: React.FC = () => { // ... [existing state variables and logic] // Pagination Handler remains the same const handlePageChange = useCallback((newPage: number) => { setCurrentPage(newPage); window.scrollTo({ top: 0, behavior: "smooth" }); }, []); return ( <div className="font-inter relative min-h-screen overflow-hidden bg-gray-100"> {/* ... [existing Head, Background Animation, etc.] */} <main className="container relative z-10 mx-auto px-4 py-8"> {/* ... [Header Section, Search and Filters, Product List] */} {/* Updated Pagination Controls */} {!isLoading && totalPages > 1 && ( <div className="mt-8"> <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} /> </div> )} </main> {/* ... [Add/Edit Product Dialogs, Delete Confirmation, Toast Notifications] */} </div> ); }; // ... [export as before]Benefits of This Approach:
- Separation of Concerns: By isolating pagination logic in its own component, the main
ProductsPageremains clean and focused. - Enhanced User Experience: "First" and "Last" buttons allow quick navigation, and the jump-to-page feature provides flexibility.
- Accessibility: Adding
aria-labelsand proper button states ensures the component is accessible. - Responsiveness: The component adjusts layout based on screen size, maintaining usability across devices.
2. Enhancing Overall Design
Improvements:
- Consistent Styling: Use consistent margins, paddings, and colors across components.
- Interactive Elements: Add hover and focus states to buttons and interactive elements for better feedback.
- Responsive Layouts: Ensure the layout adapts gracefully to different screen sizes.
- Card Design for Products: Enhance the product cards with better visuals and information hierarchy.
Implementation:
Let's refine the product cards and other UI elements within
ProductsPage.tsx.Updated Product Card
// Inside ProductsPage.tsx within the Product List mapping return ( <div key={product.id} className={`overflow-hidden rounded-lg bg-white shadow-md ${ viewMode === "list" ? "flex" : "" } transition-transform hover:scale-105`} > {/* Product Image */} <div className={`${ viewMode === "list" ? "w-1/3" : "w-full" } relative pb-[100%]`} > {product.images.length > 0 ? ( <Image src={`https://storage.naayiq.com/resources/${product.images[0].url}`} alt={product.name} fill={true} className="object-cover" priority={false} loading="lazy" /> ) : ( <div className="flex items-center justify-center bg-gray-200"> <span className="text-gray-500">No Image</span> </div> )} </div> {/* Product Details */} <div className={`p-4 ${viewMode === "list" ? "w-2/3" : ""}`}> <h2 className="mb-2 text-xl font-semibold text-gray-800"> {product.name} </h2> <p className="mb-4 text-sm text-gray-700" style={{ direction: "rtl" }} dangerouslySetInnerHTML={{ __html: product.description.replace(/\n/g, "<br />"), }} /> <div className="mb-4 space-y-1"> {/* Display Price */} <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span> {getProductPrice(product)} </p> {/* Display Quantity */} <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span> {getProductQuantity(product)} </p> {/* Display Sold */} <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span> {getProductSold(product)} </p> {/* Display Created At */} <p className="text-sm text-gray-600"> <span className="font-semibold">Created at:</span> {formatDate(product.created_at)} </p> {/* Display Has Color */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Color:</span> {product.has_color ? "Yes" : "No"} </p> {/* Display Has Size */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Size:</span> {product.has_size ? "Yes" : "No"} </p> {/* Display Brand */} <p className="text-sm text-gray-600"> <span className="font-semibold">Brand:</span> {brandMap[product.brand_id] || `ID: ${product.brand_id}`} </p> {/* Display Categories */} <p className="text-sm text-gray-600"> <span className="font-semibold">Category:</span>{" "} {product.categories.map((category) => category.name).join(", ")} </p> {/* Display First Color's First Size Information */} {colorSizeInfo && ( <div className="mt-2 space-y-1"> <p className="text-sm text-gray-600"> <span className="font-semibold">Color:</span> {colorSizeInfo.colorName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Size:</span> {colorSizeInfo.sizeName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span> $ {colorSizeInfo.price.toLocaleString()} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span> {colorSizeInfo.qty} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span> {colorSizeInfo.sold} </p> </div> )} </div> {/* Action Buttons */} <div className="flex space-x-2"> <button className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white transition duration-300 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400" onClick={() => handleEditClick(product)} > <Edit className="mr-1 inline-block" size={16} /> Edit </button> <button className="bg-red-500 hover:bg-red-600 focus:ring-red-400 flex items-center rounded-md px-4 py-2 text-white transition duration-300 focus:outline-none focus:ring-2" onClick={() => handleDeleteClick(product)} > <Trash2 className="mr-1 inline-block" size={16} /> Delete </button> </div> </div> </div> );Enhancements Explained:
-
Consistent Spacing and Typography:
- Standardized margins (
mb-2,mb-4, etc.) for headings and paragraphs. - Consistent font sizes and weights for better readability.
- Standardized margins (
-
Interactive Buttons:
- Enhanced hover and focus states for buttons to provide visual feedback.
- Used
transitionclasses for smooth visual transitions.
-
Responsive Layout:
- The product card adjusts between grid and list views, ensuring a seamless experience on various devices.
-
Conditional Rendering:
- Shows additional information like color and size only when available, keeping the UI clean.
3. Ensuring Good UI/UX Practices
Key Practices to Implement:
-
Accessibility:
- Use semantic HTML elements.
- Ensure buttons have
aria-labelswhere necessary. - Maintain sufficient color contrast.
- Enable keyboard navigation.
-
Performance:
- Lazy load images to improve page load times.
- Debounce search inputs to reduce unnecessary API calls.
-
User Feedback:
- Provide loading indicators (
LoadingSpinner). - Show toast notifications for actions like deletion and errors.
- Provide loading indicators (
-
Consistent Design Language:
- Use a consistent color palette, typography, and spacing.
- Ensure all interactive elements have similar styles.
Implementation:
Your existing implementation already incorporates many good practices. Here are a few additional enhancements:
Accessibility Enhancements
-
Add
aria-labelsto Buttons: Ensure all buttons have descriptivearia-labelsfor screen readers.// Example for Add Product Button <button className="flex items-center rounded-md bg-green-500 px-4 py-2 text-white transition duration-300 hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-400" onClick={() => setIsAddProductDialogOpen(true)} aria-label="Add New Product" > <Plus className="mr-2" size={20} /> Add Product </button> -
Focus States: Ensure focus states are clearly visible for keyboard navigation.
/* Example Tailwind focus classes */ focus:ring-2 focus:ring-blue-500 -
Semantic HTML: Use appropriate HTML elements like
<header>,<main>,<button>,<nav>, etc., to provide better context.
Performance Enhancements
-
Lazy Loading Images: You already use
loading="lazy"which is great. Ensure all images utilize this feature. -
Debounced Search: Your search input is already debounced using lodash's
debounce, reducing unnecessary API calls.
User Feedback Enhancements
-
Loading Indicators: Use
LoadingSpinnerduring data fetching to inform users that content is loading. -
Toast Notifications: You have integrated
react-toastifywhich effectively communicates actions and errors to users.
Consistent Design Language
-
Color Palette: Maintain a consistent color scheme across the application. Tailwind makes this straightforward with utility classes.
-
Typography: Ensure consistent font sizes and weights for headings, subheadings, and body text.
-
Spacing: Use Tailwind's spacing utilities (
mx-4,py-2, etc.) to maintain uniform spacing across components.
4. Implementing the Background Animation
You've already included the background animation HTML and CSS in
ProductsPage.tsx. However, let's ensure it's properly integrated and optimized.Improvements:
- Z-Index Management: Ensure the background doesn't interfere with other elements.
- Performance Optimization: Limit the number of animated elements to prevent performance issues.
- Responsiveness: Ensure the background adapts to different screen sizes.
Implementation:
CSS Integration
Ensure the background styles are included in your global CSS or the component's CSS module.
/* styles/global.css or a dedicated CSS module */ @tailwind base; @tailwind components; @tailwind utilities; /* Start Animations */ @-webkit-keyframes animatetop { from { top: -300px; opacity: 0; } to { top: 0; opacity: 1; } } @keyframes animatetop { from { top: -300px; opacity: 0; } to { top: 0; opacity: 1; } } @-webkit-keyframes zoomIn { 0% { opacity: 0; -webkit-transform: scale3d(0.3, 0.3, 0.3); transform: scale3d(0.3, 0.3, 0.3); } 50% { opacity: 1; } } @keyframes zoomIn { 0% { opacity: 0; -webkit-transform: scale3d(0.3, 0.3, 0.3); transform: scale3d(0.3, 0.3, 0.3); } 50% { opacity: 1; } } /* End Animations */ /* Start Background Animation */ .area { background: #4e54c8; background: -webkit-linear-gradient(to left, #8f94fb, #4e54c8); background: linear-gradient(to left, #8f94fb, #4e54c8); width: 100%; height: 100vh; position: fixed; /* Changed to fixed for better layering */ top: 0; left: 0; z-index: -1; } .circles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; /* Changed to 100% for full coverage */ overflow: hidden; } .circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.2); animation: animate 25s linear infinite; bottom: -150px; } .circles li:nth-child(1) { left: 25%; width: 80px; height: 80px; animation-delay: 0s; } /* ... [retain other nth-child styles] */ @keyframes animate { 0% { transform: translateY(0) rotate(0deg); opacity: 1; border-radius: 0; } 100% { transform: translateY(-1000px) rotate(720deg); opacity: 0; border-radius: 50%; } } /* End Background Animation */HTML Integration in
ProductsPage.tsxEnsure the background element is placed correctly to avoid overlapping with main content.
// components/ProductsPage.tsx return ( <div className="font-inter relative min-h-screen overflow-hidden bg-gray-100"> <Head> <title>Products - Naay Store</title> <link rel="icon" href="/favicon.ico" /> {/* Using Inter font */} <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet" /> </Head> {/* Background Animation */} <div className="area"> <ul className="circles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> {/* Main Content */} <main className="container relative z-10 mx-auto px-4 py-8"> {/* ... [existing content] */} </main> {/* ... [dialogs, modals, toasts] */} </div> );Enhancements Explained:
-
Positioning:
- Changed
.areatofixedposition to ensure it always stays in the background, regardless of the content's scroll. - Set
z-index: -1to place it behind all other elements.
- Changed
-
Performance Optimization:
- Limited the number of animated circles to prevent performance lags. Ensure you're not having too many
lielements animated simultaneously. - Adjust the
animation-durationto control the speed and smoothness of the animation.
- Limited the number of animated circles to prevent performance lags. Ensure you're not having too many
-
Responsiveness:
- Ensured
.circlesoccupy the full viewport height (height: 100%), adapting to different screen sizes.
- Ensured
-
Accessibility:
- Ensure that the animated background doesn't distract or hinder the user's interaction with main content.
Complete Updated
ProductsPage.tsxFor clarity, here's how your updated
ProductsPage.tsxmight look with all these improvements:"use client"; import React, { useState, useEffect, useCallback, useMemo, ChangeEvent, } from "react"; import Head from "next/head"; import Image from "next/image"; import { Search, Grid, List, Plus, Edit, Trash2, ChevronsLeft, ChevronLeft, ChevronRight, ChevronsRight } from "lucide-react"; import AddProductDialog from "@/components/AddProductDialog"; import EditProduct from "@/components/EditProduct"; import LoadingSpinner from "@/components/LoadingSpinner"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import debounce from "lodash/debounce"; import { getToken } from "@/app/auth"; import { Product, Brand, ApiResponse } from "@/components/types"; import Pagination from "@/components/Pagination"; // New Pagination component const formatDate = (dateString: string) => { const date = new Date(dateString); return date.toLocaleDateString(); // 'MM/DD/YYYY' format }; const PRODUCTS_PER_PAGE = 15; const ProductsPage: React.FC = () => { // State Variables const [products, setProducts] = useState<Product[]>([]); const [brands, setBrands] = useState<Brand[]>([]); const [brandMap, setBrandMap] = useState<{ [key: number]: string }>({}); const [currentPage, setCurrentPage] = useState<number>(1); const [searchTerm, setSearchTerm] = useState<string>(""); const [viewMode, setViewMode] = useState<"grid" | "list">("grid"); const [sortBy, setSortBy] = useState<keyof Product>("created_at"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [isAddProductDialogOpen, setIsAddProductDialogOpen] = useState<boolean>(false); const [isEditProductDialogOpen, setIsEditProductDialogOpen] = useState<boolean>(false); const [productToEdit, setProductToEdit] = useState<Product | null>(null); const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState<boolean>(false); const [productToDelete, setProductToDelete] = useState<Product | null>(null); const [isDeleting, setIsDeleting] = useState<boolean>(false); const [totalPages, setTotalPages] = useState<number>(1); const [totalProducts, setTotalProducts] = useState<number>(0); const [isLoading, setIsLoading] = useState<boolean>(false); const [searchInput, setSearchInput] = useState<string>(""); // Debounce the search input const debouncedSearch = useMemo( () => debounce((term: string) => { setSearchTerm(term); setCurrentPage(1); }, 300), [], ); useEffect(() => { debouncedSearch(searchInput); return () => { debouncedSearch.cancel(); }; }, [searchInput, debouncedSearch]); const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => { setSearchInput(e.target.value); }; // Fetch Brand Details const fetchBrands = useCallback(async () => { const token = getToken(); if (!token) { toast.error("You must be logged in."); return; } try { const response = await fetch( `http://localhost:4000/subcategories/brands`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to fetch brands"); } const data: Brand[] = await response.json(); setBrands(data); // Create a mapping from brand_id to brand_name const map: { [key: number]: string } = {}; data.forEach((brand) => { map[brand.id] = brand.name; }); setBrandMap(map); } catch (error) { console.error("Error fetching brands:", error); toast.error("Failed to fetch brands. Please try again."); } }, []); // Fetch Products const fetchProducts = useCallback(async () => { setIsLoading(true); const token = getToken(); if (!token) { toast.error("You must be logged in."); setIsLoading(false); return; } try { const response = await fetch( `http://localhost:4000/products?page=${currentPage}&limit=${PRODUCTS_PER_PAGE}&search=${encodeURIComponent( searchTerm, )}&sortBy=${sortBy}&sortOrder=${sortOrder}`, { cache: "no-cache", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to fetch products"); } const data: ApiResponse = await response.json(); setProducts(data.products); setTotalPages(data.totalPages); setTotalProducts(data.total); // Assuming your API provides totalItems } catch (error) { console.error("Error fetching products:", error); toast.error("Failed to fetch products. Please try again."); } finally { setIsLoading(false); } }, [currentPage, searchTerm, sortBy, sortOrder]); useEffect(() => { fetchBrands(); }, [fetchBrands]); useEffect(() => { fetchProducts(); }, [fetchProducts]); const filteredProducts = useMemo(() => { return products .filter((product) => product.name.toLowerCase().includes(searchTerm.toLowerCase()), ) .sort((a, b) => { if (a[sortBy] === null) return 1; if (b[sortBy] === null) return -1; if (sortOrder === "asc") { return a[sortBy]!.toString().localeCompare(b[sortBy]!.toString()); } else { return b[sortBy]!.toString().localeCompare(a[sortBy]!.toString()); } }); }, [products, searchTerm, sortBy, sortOrder]); const handleEditClick = useCallback((product: Product) => { setProductToEdit(product); setIsEditProductDialogOpen(true); }, []); const handleDeleteClick = useCallback((product: Product) => { setProductToDelete(product); setIsDeleteConfirmOpen(true); }, []); const handleDeleteConfirm = useCallback(async () => { if (productToDelete) { setIsDeleting(true); const token = getToken(); if (!token) { toast.error("You must be logged in."); setIsDeleting(false); return; } try { const response = await fetch( `http://localhost:4000/products/${productToDelete.id}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error("Failed to delete product"); } setProducts((prevProducts) => prevProducts.filter((p) => p.id !== productToDelete.id), ); setIsDeleteConfirmOpen(false); toast.success("Product deleted successfully"); } catch (error) { console.error("Error deleting product:", error); toast.error("Failed to delete product. Please try again."); } finally { setIsDeleting(false); } } }, [productToDelete]); // Helper function to get the first color's first size information const getFirstColorSizeInfo = useCallback((product: Product) => { if (product.has_color && product.has_size) { const firstColor = product.colors[0]; if (firstColor) { const sizesForColor = product.sizes.filter( (size) => size.color_id === firstColor.id, ); const firstSize = sizesForColor[0]; if (firstSize) { return { colorName: firstColor.name, sizeName: firstSize.name, price: firstSize.price, qty: firstSize.qty, sold: Math.abs(firstSize.sold), }; } } } return null; }, []); // Updated helper functions to accommodate the new logic const getProductPrice = useCallback( (product: Product): string => { const colorSizeInfo = getFirstColorSizeInfo(product); if (colorSizeInfo) { return `$${colorSizeInfo.price.toLocaleString()}`; } if (!product.has_color && !product.has_size) return `$${product.price.toLocaleString()}`; if (product.colors.length > 0 && product.colors[0].price !== null) return `$${product.colors[0].price.toLocaleString()}`; if (product.sizes.length > 0) return `$${product.sizes[0].price.toLocaleString()}`; return "N/A"; }, [getFirstColorSizeInfo], ); const getProductQuantity = useCallback( (product: Product): number | string => { const colorSizeInfo = getFirstColorSizeInfo(product); if (colorSizeInfo) { return colorSizeInfo.qty; } if (product.qty !== null && product.qty !== 0) return product.qty; if (product.colors.length > 0 && product.colors[0].qty !== null) return product.colors[0].qty; if (product.sizes.length > 0) return product.sizes[0].qty; return "N/A"; }, [getFirstColorSizeInfo], ); const getProductSold = useCallback((product: Product): number => { let total = 0; if (product.colors) { product.colors.forEach((color) => { if (color.sizes.length > 0) { color.sizes.forEach((size) => (total += size.sold)); } else { total += color.sold; } }); } if (product.sizes) { product.sizes.forEach((size) => { total += size.sold; }); } total += product.sold; return Math.abs(total); }, []); // Pagination Handler remains the same const handlePageChange = useCallback((newPage: number) => { setCurrentPage(newPage); window.scrollTo({ top: 0, behavior: "smooth" }); }, []); return ( <div className="font-inter relative min-h-screen overflow-hidden bg-gray-100"> <Head> <title>Products - Naay Store</title> <link rel="icon" href="/favicon.ico" /> {/* Using Inter font */} <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet" /> </Head> {/* Background Animation */} <div className="area"> <ul className="circles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> <main className="container relative z-10 mx-auto px-4 py-8"> {/* Header Section */} <div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0"> <h1 className="text-3xl font-bold text-gray-900">All Products</h1> <div className="flex items-center space-x-4"> <span className="text-gray-700"> Total Products:{" "} <span className="font-semibold text-blue-600"> {totalProducts} </span> </span> <button className="flex items-center rounded-md bg-green-500 px-4 py-2 text-white transition duration-300 hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-400" onClick={() => setIsAddProductDialogOpen(true)} aria-label="Add New Product" > <Plus className="mr-2" size={20} /> Add Product </button> </div> </div> {/* Search and Filters */} <div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0"> {/* Search */} <div className="relative w-full max-w-md"> <input type="text" placeholder="Search products..." className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={searchInput} onChange={handleSearchChange} aria-label="Search Products" /> <Search className="absolute left-3 top-2.5 h-5 w-5 text-gray-400" /> </div> {/* Sort & Sort Order & View Modes */} <div className="flex items-center space-x-4"> <select className="rounded-md border border-gray-300 px-3 py-2 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={sortBy} onChange={(e) => setSortBy(e.target.value as keyof Product)} aria-label="Sort By" > <option value="name">Sort by Name</option> <option value="price">Sort by Price</option> <option value="created_at">Sort by Created Date</option> </select> <select className="rounded-md border border-gray-300 px-3 py-2 transition focus:outline-none focus:ring-2 focus:ring-blue-500" value={sortOrder} onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")} aria-label="Sort Order" > <option value="asc">Ascending</option> <option value="desc">Descending</option> </select> <div className="flex items-center space-x-2"> <button className={`rounded-md p-2 ${ viewMode === "grid" ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700" } transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400`} onClick={() => setViewMode("grid")} aria-label="Grid View" > <Grid className="h-5 w-5" /> </button> <button className={`rounded-md p-2 ${ viewMode === "list" ? "bg-blue-500 text-white" : "bg-gray-200 text-gray-700" } transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400`} onClick={() => setViewMode("list")} aria-label="List View" > <List className="h-5 w-5" /> </button> </div> </div> </div> {/* Product List */} {isLoading ? ( <div className="flex justify-center"> <LoadingSpinner /> </div> ) : ( <div className={`grid gap-6 ${ viewMode === "grid" ? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" : "grid-cols-1" }`} > {filteredProducts.map((product) => { const colorSizeInfo = getFirstColorSizeInfo(product); return ( <div key={product.id} className={`overflow-hidden rounded-lg bg-white shadow-md ${ viewMode === "list" ? "flex" : "" } transition-transform hover:scale-105`} > {/* Product Image */} <div className={`${ viewMode === "list" ? "w-1/3" : "w-full" } relative pb-[100%]`} > {product.images.length > 0 ? ( <Image src={`https://storage.naayiq.com/resources/${product.images[0].url}`} alt={product.name} fill={true} className="object-cover" priority={false} loading="lazy" /> ) : ( <div className="flex items-center justify-center bg-gray-200"> <span className="text-gray-500">No Image</span> </div> )} </div> {/* Product Details */} <div className={`p-4 ${viewMode === "list" ? "w-2/3" : ""}`}> <h2 className="mb-2 text-xl font-semibold text-gray-800"> {product.name} </h2> <p className="mb-4 text-sm text-gray-700" style={{ direction: "rtl" }} dangerouslySetInnerHTML={{ __html: product.description.replace(/\n/g, "<br />"), }} /> <div className="mb-4 space-y-1"> {/* Display Price */} <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span> {getProductPrice(product)} </p> {/* Display Quantity */} <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span> {getProductQuantity(product)} </p> {/* Display Sold */} <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span> {getProductSold(product)} </p> {/* Display Created At */} <p className="text-sm text-gray-600"> <span className="font-semibold">Created at:</span> {formatDate(product.created_at)} </p> {/* Display Has Color */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Color:</span> {product.has_color ? "Yes" : "No"} </p> {/* Display Has Size */} <p className="text-sm text-gray-600"> <span className="font-semibold">Has Size:</span> {product.has_size ? "Yes" : "No"} </p> {/* Display Brand */} <p className="text-sm text-gray-600"> <span className="font-semibold">Brand:</span> {brandMap[product.brand_id] || `ID: ${product.brand_id}`} </p> {/* Display Categories */} <p className="text-sm text-gray-600"> <span className="font-semibold">Category:</span>{" "} {product.categories.map((category) => category.name).join(", ")} </p> {/* Display First Color's First Size Information */} {colorSizeInfo && ( <div className="mt-2 space-y-1"> <p className="text-sm text-gray-600"> <span className="font-semibold">Color:</span> {colorSizeInfo.colorName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Size:</span> {colorSizeInfo.sizeName} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Price:</span> $ {colorSizeInfo.price.toLocaleString()} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Quantity:</span> {colorSizeInfo.qty} </p> <p className="text-sm text-gray-600"> <span className="font-semibold">Sold:</span> {colorSizeInfo.sold} </p> </div> )} </div> {/* Action Buttons */} <div className="flex space-x-2"> <button className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white transition duration-300 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400" onClick={() => handleEditClick(product)} aria-label={`Edit ${product.name}`} > <Edit className="mr-1 inline-block" size={16} /> Edit </button> <button className="bg-red-500 hover:bg-red-600 focus:ring-red-400 flex items-center rounded-md px-4 py-2 text-white transition duration-300 focus:outline-none focus:ring-2" onClick={() => handleDeleteClick(product)} aria-label={`Delete ${product.name}`} > <Trash2 className="mr-1 inline-block" size={16} /> Delete </button> </div> </div> </div> ); })} </div> )} {/* Updated Pagination Controls */} {!isLoading && totalPages > 1 && ( <div className="mt-8"> <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} /> </div> )} </main> {/* Add Product Dialog */} {isAddProductDialogOpen && ( <AddProductDialog isOpen={isAddProductDialogOpen} onClose={() => setIsAddProductDialogOpen(false)} /> )} {/* Edit Product Dialog */} {isEditProductDialogOpen && productToEdit && ( <EditProduct isOpen={isEditProductDialogOpen} onClose={() => { setIsEditProductDialogOpen(false); setProductToEdit(null); fetchProducts(); // Refresh the product list after editing }} // @ts-ignore product={productToEdit} /> )} {/* Delete Confirmation Modal */} {isDeleteConfirmOpen && ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"> <div className="w-11/12 max-w-md rounded-lg bg-white p-8 shadow-lg"> <h2 className="mb-4 text-xl font-semibold text-gray-800"> Confirm Delete </h2> <p className="mb-8 text-gray-600"> Are you sure you want to delete{" "} <span className="font-semibold"> {productToDelete?.name ?? "this product"} </span> ? </p> <div className="flex justify-end space-x-4"> <button className="bg-red-500 hover:bg-red-600 focus:ring-red-400 flex items-center rounded-md px-4 py-2 text-white transition duration-300 focus:outline-none focus:ring-2 disabled:opacity-50" onClick={handleDeleteConfirm} disabled={isDeleting} aria-label="Confirm Delete" > <Trash2 className="mr-1 inline-block" size={16} /> {isDeleting ? "Deleting..." : "Yes, Delete"} </button> <button className="rounded-md bg-gray-300 px-4 py-2 text-gray-700 transition duration-300 hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400 disabled:opacity-50" onClick={() => setIsDeleteConfirmOpen(false)} disabled={isDeleting} aria-label="Cancel Delete" > Cancel </button> </div> </div> </div> )} {/* Toast Notifications */} <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick pauseOnFocusLoss draggable pauseOnHover theme="light" /> </div> ); }; export default React.memo(ProductsPage);5. Additional Recommendations
Use Tailwind Plugins for Enhanced Features
Consider integrating Tailwind CSS plugins to further enhance your design capabilities, such as:
-
Tailwind Forms: For better styling of form elements.
npm install @tailwindcss/forms// tailwind.config.js module.exports = { // ... plugins: [ require('@tailwindcss/forms'), // ... other plugins ], } -
Tailwind Typography: For better default styles for rich text content.
npm install @tailwindcss/typography// tailwind.config.js module.exports = { // ... plugins: [ require('@tailwindcss/typography'), // ... other plugins ], }
Optimize Animations
While background animations can enhance visuals, excessive animations may affect performance and distract users. Ensure animations are smooth and not overwhelming:
- Limit the Number of Animated Elements: Fewer animated circles can improve performance.
- Control Animation Speed: Adjust
animation-durationto ensure smoothness. - Use CSS Optimizations: Utilize
will-change,transform, and other properties to optimize rendering.
Testing and Feedback
- Cross-Browser Testing: Ensure your page behaves consistently across different browsers.
- Responsive Testing: Test on various screen sizes to ensure a seamless experience.
- User Feedback: Gather feedback from actual users to identify and address any UX issues.
Conclusion
By creating a dedicated
Paginationcomponent with enhanced features, refining the overall design using Tailwind CSS, adhering to good UI/UX practices, and ensuring the background animation is optimally integrated, your Products Page will offer a more intuitive, responsive, and visually appealing experience for users. Remember to continually test and iterate based on user feedback to maintain and improve the quality of your application.Feel free to reach out if you have any further questions or need additional assistance!