And more circles that moves randomly... @import…
- User
And more circles that moves randomly... @import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
@tailwind base; @tailwind components; @tailwind utilities;
@layer base { body { @apply relative z-1 bg-whiten font-satoshi text-base font-normal text-body; } } /* 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: #e9eaff; background: -webkit-linear-gradient(to left, #f0f0ff, #e9eaff); background: linear-gradient(to left, #f0f0ff, #e9eaff); 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 */
@layer components { }
@layer utilities { /* Chrome, Safari and Opera */ .no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } .chat-height { @apply h-[calc(100vh_-_8.125rem)] lg:h-[calc(100vh_-_5.625rem)]; } .inbox-height { @apply h-[calc(100vh_-_8.125rem)] lg:h-[calc(100vh_-_5.625rem)]; }}
/* third-party libraries CSS */
.tableCheckbox:checked ~ div span { @apply opacity-100; }
.tableCheckbox:checked ~ div { @apply border-primary bg-primary; }
.apexcharts-legend-text { @apply !text-body dark:!text-bodydark; }
.apexcharts-text { @apply !fill-body dark:!fill-bodydark; }
.apexcharts-xcrosshairs { @apply !fill-stroke dark:!fill-strokedark; }
.apexcharts-gridline { @apply !stroke-stroke dark:!stroke-strokedark; }
.apexcharts-series.apexcharts-pie-series path { @apply dark:!stroke-transparent; }
.apexcharts-legend-series { @apply !inline-flex gap-1.5; }
.apexcharts-tooltip.apexcharts-theme-light { @apply dark:!border-strokedark dark:!bg-boxdark; }
.apexcharts-tooltip.apexcharts-theme-light .apexcharts-tooltip-title { @apply dark:!border-strokedark dark:!bg-meta-4; }
.apexcharts-xaxistooltip, .apexcharts-yaxistooltip { @apply dark:!border-meta-4 dark:!bg-meta-4 dark:!text-bodydark1; }
.flatpickr-wrapper { @apply w-full; }
.flatpickr-months .flatpickr-prev-month:hover svg, .flatpickr-months .flatpickr-next-month:hover svg { @apply !fill-primary; }
.flatpickr-calendar.arrowTop:before { @apply dark:!border-b-boxdark; }
.flatpickr-calendar.arrowTop:after { @apply dark:!border-b-boxdark; }
.flatpickr-calendar { @apply !p-6 dark:!bg-boxdark dark:!text-bodydark dark:!shadow-8 2xsm:!w-auto; }
.flatpickr-day { @apply dark:!text-bodydark dark:hover:!border-meta-4 dark:hover:!bg-meta-4; }
.flatpickr-months .flatpickr-prev-month, .flatpickr-months .flatpickr-next-month { @apply !top-7 dark:!fill-white dark:!text-white; }
.flatpickr-months .flatpickr-prev-month.flatpickr-prev-month, .flatpickr-months .flatpickr-next-month.flatpickr-prev-month { @apply !left-7; }
.flatpickr-months .flatpickr-prev-month.flatpickr-next-month, .flatpickr-months .flatpickr-next-month.flatpickr-next-month { @apply !right-7; }
span.flatpickr-weekday, .flatpickr-months .flatpickr-month { @apply dark:!fill-white dark:!text-white; }
.flatpickr-day.inRange { box-shadow: -5px 0 0 #f3f4f6, 5px 0 0 #f3f4f6 !important; @apply dark:!shadow-7; }
.flatpickr-day.inRange, .flatpickr-day.prevMonthDay.inRange, .flatpickr-day.nextMonthDay.inRange, .flatpickr-day.today.inRange, .flatpickr-day.prevMonthDay.today.inRange, .flatpickr-day.nextMonthDay.today.inRange, .flatpickr-day:hover, .flatpickr-day.prevMonthDay:hover, .flatpickr-day.nextMonthDay:hover, .flatpickr-day:focus, .flatpickr-day.prevMonthDay:focus, .flatpickr-day.nextMonthDay:focus { @apply !border-[#F3F4F6] !bg-[#F3F4F6] dark:!border-meta-4 dark:!bg-meta-4; }
.flatpickr-day.selected, .flatpickr-day.startRange, .flatpickr-day.selected, .flatpickr-day.endRange { @apply dark:!text-white; }
.flatpickr-day.selected, .flatpickr-day.startRange, .flatpickr-day.endRange, .flatpickr-day.selected.inRange, .flatpickr-day.startRange.inRange, .flatpickr-day.endRange.inRange, .flatpickr-day.selected:focus, .flatpickr-day.startRange:focus, .flatpickr-day.endRange:focus, .flatpickr-day.selected:hover, .flatpickr-day.startRange:hover, .flatpickr-day.endRange:hover, .flatpickr-day.selected.prevMonthDay, .flatpickr-day.startRange.prevMonthDay, .flatpickr-day.endRange.prevMonthDay, .flatpickr-day.selected.nextMonthDay, .flatpickr-day.startRange.nextMonthDay, .flatpickr-day.endRange.nextMonthDay { background: #3c50e0; @apply !border-primary !bg-primary hover:!border-primary hover:!bg-primary; }
.flatpickr-day.selected.startRange + .endRange:not(:nth-child(7n + 1)), .flatpickr-day.startRange.startRange + .endRange:not(:nth-child(7n + 1)), .flatpickr-day.endRange.startRange + .endRange:not(:nth-child(7n + 1)) { box-shadow: -10px 0 0 #3c50e0; }
.map-btn .jvm-zoom-btn { @apply flex h-7.5 w-7.5 items-center justify-center rounded border border-stroke bg-white px-0 pb-0.5 pt-0 text-2xl leading-none text-body hover:border-primary hover:bg-primary hover:text-white dark:border-strokedark dark:bg-meta-4 dark:text-bodydark dark:hover:border-primary dark:hover:bg-primary dark:hover:text-white; }
.mapOne .jvm-zoom-btn { @apply !bottom-0 !left-auto !top-auto; }
.mapOne .jvm-zoom-btn.jvm-zoomin { @apply !right-10; }
.mapOne .jvm-zoom-btn.jvm-zoomout { @apply !right-0; }
.taskCheckbox:checked ~ .box span { @apply opacity-100; }
.taskCheckbox:checked ~ p { @apply line-through; }
.taskCheckbox:checked ~ .box { @apply border-primary bg-primary dark:border-primary; }
.custom-input-date::-webkit-calendar-picker-indicator { background: transparent; }
input[type="search"]::-webkit-search-cancel-button { @apply appearance-none; }
.custom-input-date::-webkit-calendar-picker-indicator { background-position: center; background-repeat: no-repeat; background-size: 20px; }
[x-cloak] { display: none !important; } "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(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 remains the same 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)} 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-transparent 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); Also improve the background color match the product background with the animation background... make it splash and glassmorph... beautiful ux and ui...
- Assistant
Absolutely! Enhancing your background with a splash effect and incorporating glassmorphism can significantly improve the visual appeal and user experience of your product page. Below, I'll guide you through integrating these effects seamlessly into your existing setup using Tailwind CSS.
Overview of Enhancements:
- Glassmorphism Effect: This involves using a semi-transparent background with a blur effect to create a "frosted glass" appearance.
- Splash Animation: Enhancing the existing circle animations to create a more dynamic and visually appealing background that complements the product display.
Step 1: Update the Background Animation with Glassmorphism
First, let's adjust your background and the product card to incorporate glassmorphism.
1.1. Modify the Background (
.areaand.circles)Enhance the
.areawith a subtle gradient and adjust the.circlesto be semi-transparent and blurred to create a glass-like effect./* Updated Background Animation */ .area { background: rgba(255, 255, 255, 0.1); /* Semi-transparent background */ backdrop-filter: blur(10px); /* Blur effect for glassmorphism */ background: -webkit-linear-gradient(to left, #f0f0ff, #e9eaff, rgba(255, 255, 255, 0.1)); background: linear-gradient(to left, #f0f0ff, #e9eaff, rgba(255, 255, 255, 0.1)); width: 100%; height: 100vh; position: fixed; top: 0; left: 0; z-index: -1; } .circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.1); /* More transparent circles */ animation: animate 25s linear infinite; bottom: -150px; filter: blur(5px); /* Blur the circles for a dreamy effect */ }1.2. Enhance the Product Card with Glassmorphism
Apply glassmorphism to the product cards to make them stand out against the animated background.
In your React component (
ProductsPage), update the product card classes:<div key={product.id} className={`overflow-hidden rounded-lg bg-white/30 backdrop-filter backdrop-blur-lg shadow-lg ${ viewMode === "list" ? "flex" : "" } transition-transform hover:scale-105`} > {/* ... rest of the product card content */} </div>Explanation:
bg-white/30: Sets a white background with 30% opacity.backdrop-filter backdrop-blur-lg: Applies a blur effect to the background behind the card.shadow-lg: Adds a large shadow for depth.
1.3. Adjust Text and Elements for Readability
Ensure that text and other elements within the glassmorphic cards remain readable against the semi-transparent backgrounds.
/* Optional: Enhance text readability */ @layer components { .product-title { @apply text-gray-900 font-semibold; } .product-description { @apply text-gray-700; } /* Adjust other text elements as needed */ }Step 2: Enhance the Splash Animation
To make the background animation more dynamic and visually appealing, let's refine the existing circles and add more variety.
2.1. Update Circle Colors and Sizes
Assign different colors and sizes to the circles to create a more vibrant splash effect.
.circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.1); /* Base transparent color */ animation: animate 25s linear infinite; bottom: -150px; filter: blur(5px); border-radius: 50%; } /* Assign varied colors and sizes */ .circles li:nth-child(1) { left: 25%; width: 80px; height: 80px; background: rgba(255, 255, 255, 0.1); animation-delay: 0s; } .circles li:nth-child(2) { left: 10%; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.08); animation-delay: 2s; } .circles li:nth-child(3) { left: 70%; width: 60px; height: 60px; background: rgba(255, 255, 255, 0.05); animation-delay: 4s; } /* Continue for other circles with varied settings */2.2. Introduce More Complex Animations
Enhance the
@keyframes animateto include scaling and varying opacity for a more dynamic effect.@keyframes animate { 0% { transform: translateY(0) rotate(0deg) scale(1); opacity: 1; border-radius: 0; } 50% { opacity: 0.7; transform: translateY(-500px) rotate(360deg) scale(1.5); } 100% { transform: translateY(-1000px) rotate(720deg) scale(1); opacity: 0; border-radius: 50%; } }Step 3: Optimize the React Component for Enhanced UI
Ensure that the product cards and other UI elements complement the new background and glassmorphism effects.
3.1. Update the Product Card Structure
Ensure that the product cards have enough spacing and appropriate layering.
<div key={product.id} className={`overflow-hidden rounded-lg bg-white/30 backdrop-filter backdrop-blur-lg shadow-lg ${ viewMode === "list" ? "flex" : "" } transition-transform hover:scale-105`} > {/* Product Image */} <div className={`${ viewMode === "list" ? "w-1/3" : "w-full" } relative pb-[100%]`} > {/* Image component remains the same */} </div> {/* Product Details */} <div className={`p-6 ${viewMode === "list" ? "w-2/3" : ""}`}> <h2 className="mb-2 text-2xl font-semibold text-gray-900 product-title"> {product.name} </h2> <p className="mb-4 text-sm text-gray-700 product-description" style={{ direction: "rtl" }} dangerouslySetInnerHTML={{ __html: product.description.replace(/\n/g, "<br />"), }} /> {/* ... rest of the product details */} </div> </div>Enhancements:
- Padding: Increased padding (
p-6) for better spacing within the card. - Text Classes: Applied custom classes (
product-title,product-description) for consistent styling.
3.2. Adjust Buttons and Interactive Elements
Ensure that buttons and interactive elements remain prominent and accessible against the new background.
{/* Example: Add Product Button */} <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 glass-effect" onClick={() => setIsAddProductDialogOpen(true)} aria-label="Add New Product" > <Plus className="mr-2" size={20} /> Add Product </button>Optional Glass Effect for Buttons: If you wish to apply a subtle glass effect to buttons:
@layer components { .glass-effect { background: rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.3); } }Apply
glass-effectclass to desired buttons:<button className="flex items-center rounded-md bg-white/30 px-4 py-2 text-blue-600 transition duration-300 hover:bg-white/40 focus:outline-none focus:ring-2 focus:ring-blue-400 glass-effect" onClick={() => setIsAddProductDialogOpen(true)} aria-label="Add New Product" > <Plus className="mr-2" size={20} /> Add Product </button>Step 4: Final CSS Integration
Ensure all new classes and styles are properly integrated within your Tailwind CSS setup.
4.1. Update
tailwind.config.js(if necessary)If you’re using custom classes or need to extend Tailwind’s capabilities, update the
tailwind.config.jsaccordingly.// tailwind.config.js module.exports = { // ... theme: { extend: { // Add custom colors, spacing, etc., if needed }, }, plugins: [], };4.2. Ensure Proper Layering with Tailwind
Place your custom CSS within appropriate layers to maintain Tailwind’s scalability.
/* styles/global.css */ @import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"); @tailwind base; @tailwind components; @tailwind utilities; /* Custom Components */ @layer components { .glass-effect { @apply bg-white/20 backdrop-blur-lg border border-white/30; } .product-title { @apply text-gray-900 font-semibold; } .product-description { @apply text-gray-700; } /* Add more custom component styles as needed */ } /* Custom Utilities */ @layer utilities { /* Existing utilities... */ }Step 5: Test and Refine
After implementing the above changes, thoroughly test your application to ensure:
- Responsiveness: Ensure that the glassmorphism and animations look good on all screen sizes.
- Performance: Glassmorphism and animations can be performance-intensive. Optimize images and animations to maintain smooth performance.
- Accessibility: Ensure sufficient contrast between text and backgrounds for readability. Use tools like Lighthouse to assess accessibility.
Complete Updated Code Snippets
Enhanced CSS (
styles/global.css)@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"); @tailwind base; @tailwind components; @tailwind utilities; @layer base { body { @apply relative z-1 bg-white font-satoshi text-base font-normal text-body; } } /* 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: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); background: -webkit-linear-gradient(to left, #f0f0ff, #e9eaff, rgba(255, 255, 255, 0.1)); background: linear-gradient(to left, #f0f0ff, #e9eaff, rgba(255, 255, 255, 0.1)); width: 100%; height: 100vh; position: fixed; top: 0; left: 0; z-index: -1; } .circles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; } .circles li { position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.1); animation: animate 25s linear infinite; bottom: -150px; filter: blur(5px); border-radius: 50%; } .circles li:nth-child(1) { left: 25%; width: 80px; height: 80px; background: rgba(255, 255, 255, 0.1); animation-delay: 0s; } .circles li:nth-child(2) { left: 10%; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.08); animation-delay: 2s; } .circles li:nth-child(3) { left: 70%; width: 60px; height: 60px; background: rgba(255, 255, 255, 0.05); animation-delay: 4s; } /* ... retain other nth-child styles with varied settings */ @keyframes animate { 0% { transform: translateY(0) rotate(0deg) scale(1); opacity: 1; border-radius: 0; } 50% { opacity: 0.7; transform: translateY(-500px) rotate(360deg) scale(1.5); } 100% { transform: translateY(-1000px) rotate(720deg) scale(1); opacity: 0; border-radius: 50%; } } /* End Background Animation */ @layer components { .glass-effect { @apply bg-white/20 backdrop-blur-lg border border-white/30; } .product-title { @apply text-gray-900 font-semibold; } .product-description { @apply text-gray-700; } /* Add more custom component styles as needed */ } @layer utilities { /* Existing utilities... */ /* Chrome, Safari and Opera */ .no-scrollbar::-webkit-scrollbar { display: none; } .no-scrollbar { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } /* ... rest of your utilities */ }Enhanced React Component (
ProductsPage.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, 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"; 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-transparent"> <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-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 glass-effect" 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 glass-effect" 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 glass-effect" 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 glass-effect" 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 glass-effect`} 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 glass-effect`} 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/30 backdrop-filter backdrop-blur-lg shadow-lg ${ 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-6 ${viewMode === "list" ? "w-2/3" : ""}`}> <h2 className="mb-2 text-2xl font-semibold text-gray-900 product-title"> {product.name} </h2> <p className="mb-4 text-sm text-gray-700 product-description" 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 glass-effect" 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 glass-effect" 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 }} 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/80 backdrop-filter backdrop-blur-lg p-8 shadow-lg"> <h2 className="mb-4 text-xl font-semibold text-gray-800"> Confirm Delete </h2> <p className="mb-8 text-gray-700"> 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 glass-effect" 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 glass-effect" 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);Additional Recommendations
-
Performance Optimization:
- Image Optimization: Ensure that all images are optimized for web to prevent performance issues, especially with the backdrop blur effects.
- Animation Performance: Limit the number and complexity of animated elements to maintain smooth performance across devices.
-
Responsiveness:
- Test the layout on various screen sizes to ensure that the glassmorphism and splash effects adapt gracefully.
- Adjust paddings, margins, and grid layouts as necessary for different devices.
-
Accessibility:
- Maintain sufficient contrast between text and backgrounds.
- Ensure that interactive elements like buttons are easily navigable via keyboard and screen readers.
-
Tailwind CSS Configuration:
- Custom Colors and Shadows: Define any additional custom colors or shadow levels in your
tailwind.config.jsto maintain consistency across your UI. - Variants: Utilize Tailwind’s variant utilities to handle hover, focus, and active states more effectively.
- Custom Colors and Shadows: Define any additional custom colors or shadow levels in your
-
Testing:
- Utilize tools like Lighthouse and aXe to audit the accessibility and performance of your application.
- Perform cross-browser testing to ensure compatibility.
-
Enhance the Splash with More Elements:
- Consider adding more animated elements like gradients, shapes, or even subtle particle effects to make the background more engaging.
Conclusion
By implementing glassmorphism and enhancing the splash animation, your product page will benefit from a modern, visually appealing design that captivates users and provides a seamless browsing experience. Tailwind CSS makes it straightforward to apply these styles, ensuring consistency and responsiveness across your application. Remember to balance aesthetics with performance and accessibility to maintain a high-quality user experience.
Feel free to further customize and experiment with the styles to perfectly align with your brand and design vision!