-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathCollections.jsx
More file actions
656 lines (610 loc) · 22.3 KB
/
Copy pathCollections.jsx
File metadata and controls
656 lines (610 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import { useContext, useEffect, useState, useRef, useCallback } from 'react';
import { useFocusTrap, useEscapeKey } from '../hooks/useDialogA11y';
import { shopDataContext } from '../context/ShopContext';
import Card from '../components/Card';
import Footer from '../components/Footer';
import { RiPriceTag3Line, RiArrowUpDownLine } from 'react-icons/ri';
import { FaStar, FaSearch, FaFilter, FaTimes } from 'react-icons/fa';
import { LoadingState, EmptyState, ErrorState } from '../components/StateComponents';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// Add slide animation style
const slideAnimationStyle = `
@keyframes slideInRight {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
`;
// Filter Content Component
const FilterContent = ({
activeFilters,
clearAllFilters,
priceRange,
setPriceRange,
minPrice,
maxPrice,
categories,
category,
toggleCategory,
subCategories,
subCategory,
toggleSubCategory,
ratings,
selectedRatings,
toggleRating,
}) => {
return (
<div className="space-y-8">
{activeFilters > 0 && (
<button
type="button"
onClick={clearAllFilters}
className="w-full text-sm px-4 py-2.5 bg-red-500/10 text-red-400 hover:bg-red-500/20 rounded-xl transition-all border border-red-500/20"
>
Clear all filters
</button>
)}
{/* Price Range Filter */}
<div className="mb-6">
<h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-3 flex items-center gap-2">
<RiPriceTag3Line className="text-cyan-400" />
Price Range
</h3>
<div className="px-1">
<label htmlFor="collections-price-range" className="sr-only">
Maximum price filter
</label>
<input
id="collections-price-range"
type="range"
min={minPrice}
max={maxPrice}
value={priceRange[1]}
onChange={(e) =>
setPriceRange([priceRange[0], parseInt(e.target.value, 10)])
}
className="w-full h-2 bg-slate-300 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer slider-thumb"
aria-valuemin={minPrice}
aria-valuemax={maxPrice}
aria-valuenow={priceRange[1]}
aria-label={`Maximum price ₹${priceRange[1]}`}
/>
<div className="flex justify-between mt-3">
<span className="text-slate-700 dark:text-gray-400 text-sm font-medium">
₹{priceRange[0]}
</span>
<span className="text-slate-900 dark:text-white text-sm font-semibold">
₹{priceRange[1]}
</span>
</div>
</div>
</div>
{/* Category Filter */}
<div className="mb-6">
<h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-3">
Category
</h3>
<div className="space-y-2">
{categories.map((cat, i) => (
<button
key={i}
type="button"
onClick={() => toggleCategory(cat)}
aria-pressed={category.includes(cat)}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 ${
category.includes(cat)
? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/30'
: 'bg-white/5 text-gray-300 hover:bg-white/10 border border-gray-700/50'
}`}
>
{cat}
</button>
))}
</div>
</div>
{/* Sub-Category Filter - Pill Style */}
<div>
<h3 className="font-semibold mb-3 text-slate-900 dark:text-white">
Sub Categories
</h3>
<div className="flex flex-wrap gap-2">
{subCategories.map((sub, i) => (
<button
key={i}
type="button"
onClick={() => toggleSubCategory(sub)}
aria-pressed={subCategory.includes(sub)}
className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 ${
subCategory.includes(sub)
? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/30'
: 'bg-white/5 text-gray-300 hover:bg-white/10 border border-gray-700/50'
}`}
>
{sub}
</button>
))}
</div>
</div>
{/* Rating Filter - Clean Cards */}
<div>
<h3 className="text-base font-semibold text-white mb-4">Rating</h3>
<div className="space-y-2">
{ratings.map((rating, i) => (
<button
key={i}
type="button"
onClick={() => toggleRating(rating)}
aria-pressed={selectedRatings.includes(rating)}
aria-label={`${rating} stars and up`}
className={`w-full text-left px-4 py-3 rounded-xl transition-all duration-300 flex items-center gap-2 ${
selectedRatings.includes(rating)
? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/20'
: 'bg-white/5 text-gray-300 hover:bg-white/10 border border-gray-700/50'
}`}
>
<div className="flex items-center gap-1">
{[...Array(5)].map((_, starIndex) => (
<FaStar
key={starIndex}
className={`text-sm ${
starIndex < rating
? 'text-yellow-400'
: 'text-slate-400 dark:text-gray-600'
}`}
/>
))}
</div>
<span className="text-sm font-medium">& up</span>
</button>
))}
</div>
</div>
</div>
);
};
function Collections() {
const [showFilter, setShowFilter] = useState(false);
const {
product,
pagination,
loadingProducts,
productsError,
getProducts,
search,
showSearch,
compareList,
toggleCompare,
} = useContext(shopDataContext);
const minPrice =
product.length > 0
? Math.min(...product.map((item) => item.price))
: 0;
const maxPrice =
product.length > 0
? Math.max(...product.map((item) => item.price))
: 2000;
const [filterProduct, setFilterProduct] = useState([]);
const [category, setCategory] = useState([]);
const [subCategory, setSubCategory] = useState([]);
const [sortType, setSortType] = useState('relevant');
const [priceRange, setPriceRange] = useState([0, 0]);
const [selectedRatings, setSelectedRatings] = useState([]);
const [activeFilters, setActiveFilters] = useState(0);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (product.length > 0) {
setPriceRange([minPrice, maxPrice]);
}
}, [product, minPrice, maxPrice]);
const contentRef = useRef(null);
const filterRef = useRef(null);
const filterDrawerRef = useRef(null);
const closeFilterDrawer = useCallback(() => setShowFilter(false), []);
useFocusTrap(showFilter, filterDrawerRef);
useEscapeKey(showFilter, closeFilterDrawer);
// Extract unique categories and subcategories
const categories = [...new Set(product.map((item) => item.category))].filter(
Boolean
);
const subCategories = [
...new Set(product.map((item) => item.subCategory)),
].filter(Boolean);
const ratings = [5, 4, 3, 2];
const toggleCategory = (cat) => {
if (category.includes(cat)) {
setCategory((prev) => prev.filter((item) => item !== cat));
} else {
setCategory((prev) => [...prev, cat]);
}
};
const toggleSubCategory = (sub) => {
if (subCategory.includes(sub)) {
setSubCategory((prev) => prev.filter((item) => item !== sub));
} else {
setSubCategory((prev) => [...prev, sub]);
}
};
const toggleRating = (rating) => {
if (selectedRatings.includes(rating)) {
setSelectedRatings((prev) => prev.filter((item) => item !== rating));
} else {
setSelectedRatings((prev) => [...prev, rating]);
}
};
const applyFilter = useCallback(() => {
let productCopy = product.slice();
if (showSearch && search) {
productCopy = productCopy.filter((item) =>
item.name.toLowerCase().includes(search.toLowerCase())
);
}
if (category.length > 0) {
productCopy = productCopy.filter((item) =>
category.includes(item.category)
);
}
if (subCategory.length > 0) {
productCopy = productCopy.filter((item) =>
subCategory.includes(item.subCategory)
);
}
productCopy = productCopy.filter(
(item) => item.price >= priceRange[0] && item.price <= priceRange[1]
);
if (selectedRatings.length > 0) {
productCopy = productCopy.filter((item) => {
const itemRating = item.rating || 0;
return selectedRatings.some((rating) => itemRating >= rating);
});
}
setFilterProduct(productCopy);
const filterCount =
category.length +
subCategory.length +
selectedRatings.length +
(
priceRange[0] > minPrice ||
priceRange[1] < maxPrice
? 1
: 0
);
setActiveFilters(filterCount);
}, [product, showSearch, search, category, subCategory, priceRange, selectedRatings,minPrice,
maxPrice,]);
const sortProduct = useCallback(() => {
setFilterProduct((prev) => {
let sorted = [...prev];
switch (sortType) {
case 'low-high':
sorted.sort((a, b) => a.price - b.price);
break;
case 'high-low':
sorted.sort((a, b) => b.price - a.price);
break;
case 'rating':
sorted.sort((a, b) => (b.rating || 0) - (a.rating || 0));
break;
default:
break;
}
return sorted;
});
}, [sortType]);
const clearAllFilters = () => {
setCategory([]);
setSubCategory([]);
setSelectedRatings([]);
setPriceRange([minPrice, maxPrice]);
setSortType('relevant');
};
// Inject style element on mount
useEffect(() => {
if (
typeof document !== 'undefined' &&
!document.head.querySelector('[data-collections-style]')
) {
const styleEl = document.createElement('style');
styleEl.setAttribute('data-collections-style', 'true');
styleEl.textContent = slideAnimationStyle;
document.head.appendChild(styleEl);
}
}, []);
useEffect(() => {
// Initial loading simulation
const timer = setTimeout(() => {
setIsLoading(false);
setFilterProduct(product);
}, 1500);
return () => clearTimeout(timer);
}, [product]);
useEffect(() => {
sortProduct();
}, [sortType, sortProduct]);
useEffect(() => {
applyFilter();
}, [category, subCategory, search, showSearch, priceRange, selectedRatings, applyFilter]);
useEffect(() => {
// Animations
if (!isLoading) {
gsap.fromTo(
'.collection-item',
{ opacity: 0, y: 30 },
{
opacity: 1,
y: 0,
duration: 0.8,
stagger: 0.1,
ease: 'power2.out',
scrollTrigger: {
trigger: contentRef.current,
start: 'top 80%',
toggleActions: 'play none none none',
},
}
);
gsap.fromTo(
filterRef.current,
{ x: -50, opacity: 0 },
{
x: 0,
opacity: 1,
duration: 0.8,
ease: 'power2.out',
}
);
}
}, [filterProduct, isLoading]);
return (
<>
<main
className="min-h-screen bg-gradient-to-br from-slate-100 via-white to-sky-100 dark:from-gray-900 dark:via-[#0f172a] dark:to-[#0c4a6e] pt-24 pb-20 overflow-x-hidden"
aria-labelledby="collections-page-title"
>
{/* Main Content */}
<div className="max-w-7xl mx-auto px-4 lg:px-8 flex flex-col lg:flex-row gap-8">
{/* Filter Sidebar - Desktop Only */}
<div
ref={filterRef}
className="hidden lg:block lg:w-80 bg-white/90 dark:bg-gray-800/50 backdrop-blur-md rounded-2xl border border-slate-200 dark:border-gray-700 p-6 sticky top-24 h-fit"
aria-label="Product filters"
>
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
<FaFilter className="text-cyan-400" />
Filters {activeFilters > 0 && `(${activeFilters})`}
</h2>
</div>
<FilterContent
activeFilters={activeFilters}
clearAllFilters={clearAllFilters}
priceRange={priceRange}
setPriceRange={setPriceRange}
minPrice={minPrice}
maxPrice={maxPrice}
categories={categories}
category={category}
toggleCategory={toggleCategory}
subCategories={subCategories}
subCategory={subCategory}
toggleSubCategory={toggleSubCategory}
ratings={ratings}
selectedRatings={selectedRatings}
toggleRating={toggleRating}
/>
</div>
{/* Products Section */}
<div className="flex-1 min-w-0" ref={contentRef}>
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6 p-5 bg-white/90 dark:bg-gray-800/50 rounded-2xl backdrop-blur-md border border-slate-200 dark:border-gray-700">
<h1
id="collections-page-title"
className="text-3xl font-extrabold text-slate-900 dark:text-white tracking-tight"
>
ALL{' '}
<span className="text-cyan-500 dark:text-cyan-400">
COLLECTIONS
</span>
</h1>
<div className="flex items-center gap-3">
{/* Mobile Filter Toggle */}
<button
type="button"
onClick={() => setShowFilter(!showFilter)}
className="lg:hidden flex items-center gap-2 px-4 py-2 bg-slate-200 dark:bg-gray-700 rounded-lg text-slate-800 dark:text-white text-sm font-medium"
aria-expanded={showFilter}
aria-controls="collections-filter-drawer"
>
<FaFilter className="text-sm" aria-hidden="true" />
Filters {activeFilters > 0 && `(${activeFilters})`}
</button>
{/* Sort Dropdown */}
<div className="relative">
<label htmlFor="collections-sort" className="sr-only">
Sort products
</label>
<select
id="collections-sort"
value={sortType}
onChange={(e) => setSortType(e.target.value)}
className="appearance-none bg-white dark:bg-gray-700 text-slate-900 dark:text-white px-4 py-2 rounded-lg pr-9 focus:outline-none focus:ring-2 focus:ring-cyan-500 border border-slate-300 dark:border-gray-600 text-sm"
>
<option value="relevant">Sort by: Relevant</option>
<option value="low-high">Price: Low to High</option>
<option value="high-low">Price: High to Low</option>
<option value="rating">Top Rated</option>
</select>
<RiArrowUpDownLine className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-500 dark:text-gray-400 pointer-events-none text-sm" />
</div>
</div>
</div>
{/* Product Grid */}
{productsError ? (
<ErrorState
title="Failed to Load Products"
message={productsError}
onRetry={() => getProducts(1)}
/>
) : (isLoading || loadingProducts) && filterProduct.length === 0 ? (
<LoadingState type="card" count={8} message="Discovering amazing items for you..." />
) : filterProduct.length > 0 ? (
<>
<p className="sr-only" role="status" aria-live="polite">
Showing {filterProduct.length} product
{filterProduct.length === 1 ? '' : 's'}
</p>
<div
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5"
role="list"
aria-label="Product results"
>
{filterProduct.map((item, _index) => (
<div
key={item._id}
className="collection-item"
role="listitem"
>
<Card
id={item._id}
name={item.name}
price={item.price}
image={item.image1}
reviewCount={item.reviewCount || 0}
showQuickActions={true}
onCompare={() => toggleCompare(item)}
isCompared={compareList?.some(
(p) => p._id === item._id
)}
/>
</div>
))}
</div>
{/* Load More Button */}
{pagination.page < pagination.pages && (
<div className="text-center mt-12">
<button
onClick={() => getProducts(pagination.page + 1)}
disabled={loadingProducts}
className="px-8 py-3 bg-slate-200 dark:bg-gray-700 hover:bg-slate-300 dark:hover:bg-gray-600 text-slate-800 dark:text-white rounded-lg transition-colors font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
>
{loadingProducts ? 'Loading...' : 'Load More Products'}
</button>
</div>
)}
</>
) : (
<EmptyState
icon={FaSearch}
title="No products found"
description="Try adjusting your filters to find what you're looking for."
actionText="Clear All Filters"
onAction={clearAllFilters}
/>
)}
</div>
</div>
{/* Floating Filter Drawer - Slides from Right with Blur Overlay */}
{showFilter && (
<div
className="fixed inset-0 z-50 backdrop-blur-sm bg-black/60 transition-all duration-300"
onClick={closeFilterDrawer}
role="presentation"
>
<div
id="collections-filter-drawer"
ref={filterDrawerRef}
role="dialog"
aria-modal="true"
aria-labelledby="filter-drawer-title"
className="absolute top-0 right-0 h-full w-full max-w-md bg-gray-900/95 backdrop-blur-xl border-l border-gray-700/50 shadow-2xl overflow-y-auto transform transition-transform duration-300"
onClick={(e) => e.stopPropagation()}
style={{
animation: 'slideInRight 0.3s ease-out',
}}
>
<div className="sticky top-0 bg-gray-900/95 backdrop-blur-xl border-b border-gray-700/50 p-6 z-10">
<div className="flex items-center justify-between">
<h2
id="filter-drawer-title"
className="text-2xl font-bold text-white flex items-center gap-3"
>
<FaFilter className="text-cyan-400" />
Filters
{activeFilters > 0 && (
<span className="px-2.5 py-1 bg-cyan-500 text-white text-sm rounded-full">
{activeFilters}
</span>
)}
</h2>
<button
type="button"
onClick={closeFilterDrawer}
className="p-2 text-gray-400 hover:text-white hover:bg-white/5 rounded-full transition-all"
aria-label="Close filters"
>
<FaTimes className="text-xl" aria-hidden="true" />
</button>
</div>
</div>
<div className="p-6">
<FilterContent
activeFilters={activeFilters}
clearAllFilters={clearAllFilters}
priceRange={priceRange}
setPriceRange={setPriceRange}
minPrice={minPrice}
maxPrice={maxPrice}
categories={categories}
category={category}
toggleCategory={toggleCategory}
subCategories={subCategories}
subCategory={subCategory}
toggleSubCategory={toggleSubCategory}
ratings={ratings}
selectedRatings={selectedRatings}
toggleRating={toggleRating}
/>
</div>
{/* Action Buttons */}
<div className="sticky bottom-0 bg-gray-900/95 backdrop-blur-xl border-t border-gray-700/50 p-6 space-y-3">
<button
onClick={() => setShowFilter(false)}
className="w-full px-4 py-3 bg-[#2563EB] hover:bg-[#1d4ed8] text-white rounded-xl transition-all duration-300 font-semibold"
>
View {filterProduct.length} Products
</button>
{activeFilters > 0 && (
<button
onClick={() => {
clearAllFilters();
setShowFilter(false);
}}
className="w-full px-4 py-3 bg-white/5 hover:bg-white/10 text-gray-300 rounded-xl transition-all duration-300 font-medium"
>
Clear All
</button>
)}
</div>
</div>
</div>
)}
</main>
{/* Footer */}
<Footer />
</>
);
}
export default Collections;