Certainly! I'll help you enhance your ProductsPage component by implementing the following improvements:
-
Search Stability:
- Enhanced debouncing to prevent excessive API calls.
- Added loading indicators and error handling for better user feedback.
-
Improved Pagination:
- Added first and last page buttons.
- Displayed the total number of products.
- Enhanced the overall pagination design for better usability.
-
UI Enhancements:
- Updated the font family, sizes, and colors for a more modern look.
- Implemented a moving gradient background with animated bubbles for a visually appealing effect.
- Ensured responsive design and accessibility considerations.
-
Overall UI/UX Practices:
- Improved spacing, alignment, and component responsiveness.
- Ensured buttons and interactive elements have appropriate hover and focus states.
To achieve the moving gradient background with animated bubbles, we'll use CSS animations within a custom component. This approach avoids adding extra dependencies and keeps the implementation lightweight.
Step-by-Step Enhancements
-
Update Font and Colors:
- Use the Inter font for a clean look.
- Adjust Tailwind CSS classes to enhance text sizes and colors.
-
Moving Gradient Background with Bubbles:
- Create a
BackgroundAnimation component that handles the animated background using CSS.
- Use Tailwind's
absolute and z- utilities to layer the background appropriately.
-
Enhanced Pagination:
- Include First, Last, Previous, Next, and specific page numbers with ellipsis for better navigation.
- Display the total number of products fetched from the API.
-
General UI/UX Improvements:
- Use consistent padding and margins.
- Improve button designs with better hover effects and responsive adjustments.
- Ensure modals/dialogs are accessible and properly styled.
Updated Code
Below is the updated pages/products.tsx file incorporating all the requested enhancements:
// 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,
ChevronLeft,
ChevronRight,
ChevronDoubleLeft,
ChevronDoubleRight,
} 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,
Category,
Color,
Size,
} from "@/components/types";
// Background Animation Component
const BackgroundAnimation: React.FC = () => {
return (
<div className="absolute inset-0 -z-10 overflow-hidden">
<div className="w-full h-full bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 animate-gradient bg-size-200 bg-pos-0"></div>
<div className="absolute inset-0 flex items-center justify-center">
{/* Bubbles */}
{Array.from({ length: 20 }).map((_, index) => (
<div
key={index}
className="absolute bg-white bg-opacity-20 rounded-full animate-bubble"
style={{
width: `${Math.random() * 20 + 10}px`,
height: `${Math.random() * 20 + 10}px`,
top: `${Math.random() * 100}%`,
left: `${Math.random() * 100}%`,
animationDuration: `${Math.random() * 20 + 10}s`,
animationDelay: `${Math.random() * 10}s`,
}}
/>
))}
</div>
<style jsx>{`
@keyframes gradientAnimation {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.animate-gradient {
animation: gradientAnimation 15s ease infinite;
}
@keyframes bubbleAnimation {
0% {
transform: translateY(0) scale(1);
opacity: 0.5;
}
100% {
transform: translateY(-200px) scale(1.5);
opacity: 0;
}
}
.animate-bubble {
animation: bubbleAnimation linear infinite;
}
.bg-size-200 {
background-size: 200% 200%;
}
.bg-pos-0 {
background-position: 0% 50%;
}
`}</style>
</div>
);
};
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 to prevent excessive API calls
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(); // Retrieve the token from localStorage
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}`, // Include the token here
},
},
);
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 for easy lookup
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(); // Retrieve the token from localStorage
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}`, // Include the token here
},
},
);
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 API returns total products
} 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(); // the token from localStorage
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}`, // Include the token here
},
},
);
if (!response.ok) {
throw new Error("Failed to delete product");
}
setProducts((prevProducts) =>
prevProducts.filter((p) => p.id !== productToDelete.id),
);
setTotalProducts((prevTotal) => prevTotal - 1);
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), // Ensuring 'sold' is absolute
};
}
}
}
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" });
}, []);
// Generate an array of page numbers to display
const generatePageNumbers = () => {
const pages = [];
const siblingCount = 1;
const totalPageNumbers = siblingCount * 2 + 5;
if (totalPages <= totalPageNumbers) {
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
const leftSiblingIndex = Math.max(currentPage - siblingCount, 1);
const rightSiblingIndex = Math.min(
currentPage + siblingCount,
totalPages,
);
const shouldShowLeftEllipsis = leftSiblingIndex > 2;
const shouldShowRightEllipsis = rightSiblingIndex < totalPages - 1;
if (!shouldShowLeftEllipsis && shouldShowRightEllipsis) {
const leftItemCount = 3 + 2 * siblingCount;
for (let i = 1; i <= leftItemCount; i++) {
pages.push(i);
}
pages.push("...");
pages.push(totalPages);
} else if (shouldShowLeftEllipsis && !shouldShowRightEllipsis) {
pages.push(1);
pages.push("...");
const rightRange = totalPages - (2 + 2 * siblingCount);
for (let i = rightRange; i <= totalPages; i++) {
pages.push(i);
}
} else if (shouldShowLeftEllipsis && shouldShowRightEllipsis) {
pages.push(1);
pages.push("...");
for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) {
pages.push(i);
}
pages.push("...");
pages.push(totalPages);
}
}
return pages;
};
return (
<div className="relative min-h-screen font-inter bg-gray-100">
<BackgroundAnimation />
<Head>
<title>Products - Naay Store</title>
<link rel="icon" href="/favicon.ico" />
{/* Link to Inter font */}
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap"
rel="stylesheet"
/>
</Head>
<main className="container mx-auto px-4 py-8 relative z-10">
{/* 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-4xl font-bold text-white drop-shadow-lg">
All Products
</h1>
<button
className="flex items-center rounded-md bg-green-600 px-4 py-2 text-white shadow-lg transition duration-300 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500"
onClick={() => setIsAddProductDialogOpen(true)}
>
<Plus className="mr-2" size={20} />
Add Product
</button>
</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 focus:outline-none focus:ring-2 focus:ring-green-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 bg-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-green-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 bg-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-green-500"
value={sortOrder}
onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")}
>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
<button
className={`rounded-md p-2 ${
viewMode === "grid"
? "bg-green-600 text-white shadow-lg"
: "bg-gray-200 text-gray-700"
} transition duration-300 focus:outline-none focus:ring-2 focus:ring-green-500`}
onClick={() => setViewMode("grid")}
aria-label="Grid View"
>
<Grid className="h-5 w-5" />
</button>
<button
className={`rounded-md p-2 ${
viewMode === "list"
? "bg-green-600 text-white shadow-lg"
: "bg-gray-200 text-gray-700"
} transition duration-300 focus:outline-none focus:ring-2 focus:ring-green-500`}
onClick={() => setViewMode("list")}
aria-label="List View"
>
<List className="h-5 w-5" />
</button>
</div>
</div>
{/* Total Products */}
<div className="mb-4 text-lg text-white drop-shadow-lg">
Total Products: <span className="font-semibold">{totalProducts}</span>
</div>
{/* Product List */}
{isLoading ? (
<div className="flex justify-center">
<LoadingSpinner />
</div>
) : filteredProducts.length === 0 ? (
<div className="mt-8 text-center text-white">
No products found.
</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 bg-opacity-90 shadow-md backdrop-blur-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-600 px-4 py-2 text-white shadow-lg transition duration-300 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
onClick={() => handleEditClick(product)}
>
<Edit className="mr-1 inline-block" size={16} />
Edit
</button>
<button
className="flex items-center rounded-md bg-red-600 px-4 py-2 text-white shadow-lg transition duration-300 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
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">
{/* First Page Button */}
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-gray-300 transition"
onClick={() => handlePageChange(1)}
disabled={currentPage === 1}
aria-label="First Page"
>
<ChevronDoubleLeft className="inline-block" />
</button>
{/* Previous Page Button */}
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-gray-300 transition"
onClick={() => handlePageChange(Math.max(currentPage - 1, 1))}
disabled={currentPage === 1}
aria-label="Previous Page"
>
<ChevronLeft className="inline-block" />
</button>
{/* Page Numbers */}
{generatePageNumbers().map((number, index) => {
if (number === "...") {
return (
<span key={`ellipsis-${index}`} className="text-gray-500">
...
</span>
);
}
return (
<button
key={number}
className={`rounded-md px-3 py-1 text-sm transition ${
currentPage === number
? "bg-green-600 text-white"
: "bg-gray-200 text-gray-700 hover:bg-gray-300"
} focus:outline-none focus:ring-2 focus:ring-green-500`}
onClick={() => handlePageChange(number as number)}
>
{number}
</button>
);
})}
{/* Next Page Button */}
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-gray-300 transition"
onClick={() =>
handlePageChange(Math.min(currentPage + 1, totalPages))
}
disabled={currentPage === totalPages}
aria-label="Next Page"
>
<ChevronRight className="inline-block" />
</button>
{/* Last Page Button */}
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-gray-300 transition"
onClick={() => handlePageChange(totalPages)}
disabled={currentPage === totalPages}
aria-label="Last Page"
>
<ChevronDoubleRight className="inline-block" />
</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
}}
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">
<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="flex items-center rounded-md bg-red-600 px-4 py-2 text-white shadow-lg transition duration-300 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
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-500"
onClick={() => setIsDeleteConfirmOpen(false)}
disabled={isDeleting}
>
Cancel
</button>
</div>
</div>
</div>
)}
{/* Toast Notifications */}
<ToastContainer />
<style jsx global>{`
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap");
body {
font-family: "Inter", sans-serif;
}
/* Scrollbar styling for webkit browsers */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
`}</style>
</div>
);
};
export default React.memo(ProductsPage);
Key Enhancements Explained
-
Moving Gradient Background with Bubbles:
BackgroundAnimation Component: This component creates an animated gradient background with floating bubbles. The gradient smoothly transitions between colors, and the bubbles have randomized sizes, positions, and animation durations to create a dynamic effect.
- CSS Keyframes:
gradientAnimation: Animates the gradient background.
bubbleAnimation: Animates the bubbles' upward movement and fading.
-
Improved Fonts and Colors:
- Inter Font: The Inter font is integrated via Google Fonts for a modern and clean typography.
- Color Palette: Updated colors to use more vibrant and consistent shades, enhancing readability and visual appeal.
-
Enhanced Pagination:
- First and Last Buttons: Added buttons to quickly navigate to the first and last pages.
- Ellipsis in Pagination: When there are many pages, ellipses (
...) are displayed to indicate skipped page numbers, improving usability.
- Total Products Display: Shows the total number of products fetched, giving users a clear understanding of the dataset size.
-
UI/UX Improvements:
- Responsive Design: Ensured that the layout adapts gracefully across different screen sizes.
- Button Enhancements: Buttons have improved hover effects, focus states, and consistent styling.
- Accessibility: Added
aria-labels to buttons for better accessibility support.
- Backdrop Blur: Applied a slight
backdrop-blur to the product cards for a modern look against the animated background.
-
Search Stability:
- Debouncing: Maintained debounce logic to reduce unnecessary API calls during search.
- Loading States: Displayed a loading spinner while fetching data.
- Error Handling: Enhanced error messages using
react-toastify for better user feedback.
-
Additional Styling:
- Global Styles: Added global styles for the Inter font and customized scrollbars for webkit browsers.
Tailwind CSS Configuration
To fully support the custom animations and styles, ensure your tailwind.config.js includes the necessary configurations. Here's a basic setup:
// tailwind.config.js
module.exports = {
content: [
// Paths to your components/pages
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
fontFamily: {
inter: ["Inter", "sans-serif"],
},
// If you want to define additional colors or other themes
},
},
plugins: [],
};
Final Notes
- Dependencies: Ensure that all custom components like
AddProductDialog, EditProduct, and LoadingSpinner are correctly implemented and styled.
- API Responses: The code assumes that the API returns a
total field in the ApiResponse for the total number of products. Adjust accordingly if the structure differs.
- Accessibility: Further enhancements can include more ARIA attributes and focus management, especially within modals/dialogs.
- Performance: The
React.memo wrapper helps prevent unnecessary re-renders. Additionally, lazy loading images and optimizing API calls contribute to better performance.
By implementing these enhancements, your ProductsPage should now offer a more stable, user-friendly, and visually appealing experience.