Change the design of Filter drower.

This commit is contained in:
Kartik sharma 2025-07-06 13:37:42 +05:30
parent 4adfbc8e8e
commit 9eb8418330
2 changed files with 101 additions and 132 deletions

View File

@ -10,15 +10,15 @@ import DateRangePicker from "../../components/common/DateRangePicker";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
const PAGE_SIZE = 10; const PAGE_SIZE = 10;
const SCROLL_THRESHOLD = 5; // Define how many images are visible before scroll buttons appear const SCROLL_THRESHOLD = 5;
const ImageGallery = () => { const ImageGallery = () => {
const [images, setImages] = useState([]); const [images, setImages] = useState([]);
const [allImagesData, setAllImagesData] = useState([]);
const [pageNumber, setPageNumber] = useState(1); const [pageNumber, setPageNumber] = useState(1);
const [hasMore, setHasMore] = useState(true); const [hasMore, setHasMore] = useState(true);
const selectedProjectId = useSelector((store) => store.localVariables.projectId); const selectedProjectId = useSelector((store) => store.localVariables.projectId);
const { openModal } = useModal(); const { openModal } = useModal();
const [initialImageCache, setInitialImageCache] = useState([]);
const yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD'); const yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
@ -60,9 +60,9 @@ const ImageGallery = () => {
const [loadingMore, setLoadingMore] = useState(false); const [loadingMore, setLoadingMore] = useState(false);
const imageGroupRefs = useRef({}); const imageGroupRefs = useRef({});
const loaderRef = useRef(null);
const filterPanelRef = useRef(null); const filterPanelRef = useRef(null);
const filterButtonRef = useRef(null); const filterButtonRef = useRef(null);
const loaderRef = useRef(null);
useEffect(() => { useEffect(() => {
const handleClickOutside = (event) => { const handleClickOutside = (event) => {
@ -75,15 +75,22 @@ const ImageGallery = () => {
setIsFilterPanelOpen(false); setIsFilterPanelOpen(false);
} }
}; };
document.addEventListener("mousedown", handleClickOutside);
if (isFilterPanelOpen) {
document.addEventListener("mousedown", handleClickOutside);
} else {
document.removeEventListener("mousedown", handleClickOutside);
}
return () => { return () => {
document.removeEventListener("mousedown", handleClickOutside); document.removeEventListener("mousedown", handleClickOutside);
}; };
}, []); }, [isFilterPanelOpen]);
useEffect(() => { useEffect(() => {
if (!selectedProjectId) { if (!selectedProjectId) {
setImages([]); setImages([]);
setAllImagesData([]);
setLoading(false); setLoading(false);
setHasMore(false); setHasMore(false);
return; return;
@ -94,7 +101,8 @@ const ImageGallery = () => {
setHasMore(true); setHasMore(true);
setLoading(true); setLoading(true);
fetchImages(1, appliedFilters); setAllImagesData([]);
fetchImages(1, appliedFilters, true);
}, [selectedProjectId, appliedFilters]); }, [selectedProjectId, appliedFilters]);
const fetchImages = useCallback(async (page, filters) => { const fetchImages = useCallback(async (page, filters) => {
@ -103,13 +111,6 @@ const ImageGallery = () => {
try { try {
if (page === 1) { if (page === 1) {
setLoading(true); setLoading(true);
const noFiltersApplied = Object.values(filters).every(
(val) => val === null || (Array.isArray(val) && val.length === 0)
);
if (noFiltersApplied) {
setInitialImageCache([]); // Reset cache before fetching
}
} else { } else {
setLoadingMore(true); setLoadingMore(true);
} }
@ -122,22 +123,23 @@ const ImageGallery = () => {
const uniqueNewBatches = newBatches.filter( const uniqueNewBatches = newBatches.filter(
(newBatch) => !prevImages.some((prevBatch) => prevBatch.batchId === newBatch.batchId) (newBatch) => !prevImages.some((prevBatch) => prevBatch.batchId === newBatch.batchId)
); );
const updatedImages = [...prevImages, ...uniqueNewBatches]; return [...prevImages, ...uniqueNewBatches];
});
const noFiltersApplied = Object.values(filters).every( setAllImagesData((prevAllImages) => {
(val) => val === null || (Array.isArray(val) && val.length === 0) const uniqueAllImages = newBatches.filter(
(newBatch) => !prevAllImages.some((prevBatch) => prevBatch.batchId === newBatch.batchId)
); );
if (page === 1 && noFiltersApplied) { return [...prevAllImages, ...uniqueAllImages];
setInitialImageCache(updatedImages);
}
return updatedImages;
}); });
setHasMore(receivedCount === PAGE_SIZE); setHasMore(receivedCount === PAGE_SIZE);
} catch (err) { } catch (err) {
console.error("Error fetching images:", err); console.error("Error fetching images:", err);
setImages([]); if (page === 1) {
setImages([]);
setAllImagesData([]);
}
setHasMore(false); setHasMore(false);
} finally { } finally {
setLoading(false); setLoading(false);
@ -145,19 +147,14 @@ const ImageGallery = () => {
} }
}, [selectedProjectId]); }, [selectedProjectId]);
const isNoFiltersApplied = (filters) =>
Object.values(filters).every(
(val) => val === null || (Array.isArray(val) && val.length === 0)
);
useEffect(() => { useEffect(() => {
const handleExternalEvent = (data) => { const handleExternalEvent = (data) => {
if (selectedProjectId == data.projectId) { if (selectedProjectId === data.projectId) {
setImages([]); setImages([]);
setAllImagesData([]);
setPageNumber(1); setPageNumber(1);
setHasMore(true); setHasMore(true);
fetchImages(1, appliedFilters); fetchImages(1, appliedFilters, true);
} }
}; };
@ -199,22 +196,28 @@ const ImageGallery = () => {
} }
}, [pageNumber, fetchImages, appliedFilters]); }, [pageNumber, fetchImages, appliedFilters]);
const getUniqueValuesWithIds = useCallback((idKey, nameKey, dataArray = initialImageCache) => { const getUniqueValuesWithIds = useCallback((idKey, nameKey) => {
const map = new Map(); const map = new Map();
dataArray.forEach(batch => { allImagesData.forEach(batch => {
const id = batch[idKey]; let id;
if (idKey === "floorIds") {
id = batch.floorIds;
} else {
id = batch[idKey];
}
const name = batch[nameKey]; const name = batch[nameKey];
if (id && name && !map.has(id)) { if (id && name && !map.has(id)) {
map.set(id, name); map.set(id, name);
} }
}); });
return Array.from(map.entries()); return Array.from(map.entries());
}, [initialImageCache]); }, [allImagesData]);
const getUniqueUploadedByUsers = useCallback(() => { const getUniqueUploadedByUsers = useCallback(() => {
const uniqueUsersMap = new Map(); const uniqueUsersMap = new Map();
images.forEach(batch => { allImagesData.forEach(batch => {
batch.documents.forEach(doc => { batch.documents.forEach(doc => {
if (doc.uploadedBy && doc.uploadedBy.id) { if (doc.uploadedBy && doc.uploadedBy.id) {
const fullName = `${doc.uploadedBy.firstName || ""} ${doc.uploadedBy.lastName || ""}`.trim(); const fullName = `${doc.uploadedBy.firstName || ""} ${doc.uploadedBy.lastName || ""}`.trim();
@ -225,15 +228,14 @@ const ImageGallery = () => {
}); });
}); });
return Array.from(uniqueUsersMap.entries()); return Array.from(uniqueUsersMap.entries());
}, [images]); }, [allImagesData]);
const buildings = getUniqueValuesWithIds("buildingId", "buildingName", initialImageCache); const buildings = getUniqueValuesWithIds("buildingId", "buildingName");
const floors = getUniqueValuesWithIds("floorIds", "floorName");
const floors = getUniqueValuesWithIds("floorId", "floorName", initialImageCache); const activities = getUniqueValuesWithIds("activityId", "activityName");
const activities = getUniqueValuesWithIds("activityId", "activityName", initialImageCache); const workAreas = getUniqueValuesWithIds("workAreaId", "workAreaName");
const workAreas = getUniqueValuesWithIds("workAreaId", "workAreaName", initialImageCache);
const uploadedByUsers = getUniqueUploadedByUsers(); const uploadedByUsers = getUniqueUploadedByUsers();
const workCategories = getUniqueValuesWithIds("workCategoryId", "workCategoryName", initialImageCache); const workCategories = getUniqueValuesWithIds("workCategoryId", "workCategoryName");
const toggleFilter = useCallback((type, itemId, itemName) => { const toggleFilter = useCallback((type, itemId, itemName) => {
setSelectedFilters((prev) => { setSelectedFilters((prev) => {
@ -310,18 +312,21 @@ const ImageGallery = () => {
} }
return false; return false;
} }
if ((oldVal === null && newVal === "") || (oldVal === "" && newVal === null)) {
return false;
}
return oldVal !== newVal; return oldVal !== newVal;
}); });
if (areFiltersChanged) { if (areFiltersChanged) {
setAppliedFilters(payload); setAppliedFilters(payload);
setImages([]); setImages([]);
setPageNumber(1); setPageNumber(1);
setHasMore(true); setHasMore(true);
} }
// Removed setIsFilterPanelOpen(false); to keep the drawer open
}, [selectedFilters, appliedFilters]); }, [selectedFilters, appliedFilters]);
const handleClearAllFilters = useCallback(() => { const handleClearAllFilters = useCallback(() => {
const initialStateSelected = { const initialStateSelected = {
building: [], building: [],
@ -351,40 +356,6 @@ const ImageGallery = () => {
setHasMore(true); setHasMore(true);
}, []); }, []);
const filteredBatches = images.filter((batch) => {
const firstDocUploadedAt = batch.documents[0]?.uploadedAt;
const uploadedAtMoment = firstDocUploadedAt ? moment(firstDocUploadedAt) : null;
const startDateMoment = appliedFilters.startDate
? moment(appliedFilters.startDate)
: null;
const endDateMoment = appliedFilters.endDate
? moment(appliedFilters.endDate)
: null;
const isWithinDateRange =
(!startDateMoment || (uploadedAtMoment && uploadedAtMoment.isSameOrAfter(startDateMoment, "day"))) &&
(!endDateMoment || (uploadedAtMoment && uploadedAtMoment.isSameOrBefore(endDateMoment, "day")));
const passesCategoryFilters =
(appliedFilters.buildingIds === null ||
appliedFilters.buildingIds.includes(batch.buildingId)) &&
(appliedFilters.floorIds === null ||
appliedFilters.floorIds.includes(batch.floorId)) &&
(appliedFilters.activityIds === null ||
appliedFilters.activityIds.includes(batch.activityId)) &&
(appliedFilters.workAreaIds === null ||
appliedFilters.workAreaIds.includes(batch.workAreaId)) &&
(appliedFilters.workCategoryIds === null ||
appliedFilters.workCategoryIds.includes(batch.workCategoryId));
const passesUploadedByFilter =
appliedFilters.uploadedByIds === null ||
batch.documents.some(doc => appliedFilters.uploadedByIds.includes(doc.uploadedBy?.id));
return isWithinDateRange && passesCategoryFilters && passesUploadedByFilter;
});
const scrollLeft = useCallback((key) => { const scrollLeft = useCallback((key) => {
imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" }); imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" });
}, []); }, []);
@ -430,7 +401,15 @@ const ImageGallery = () => {
{!collapsedFilters[type] && ( {!collapsedFilters[type] && (
<div className="dropdown-content"> <div className="dropdown-content">
{type === "dateRange" ? ( {type === "dateRange" ? (
null <div className="date-range-inputs">
<DateRangePicker
onRangeChange={setDateRange}
defaultStartDate={selectedFilters.startDate || yesterday}
defaultEndDate={selectedFilters.endDate || moment().format('YYYY-MM-DD')}
startDate={selectedFilters.startDate}
endDate={selectedFilters.endDate}
/>
</div>
) : ( ) : (
items.map((item) => { items.map((item) => {
const itemId = item[0]; const itemId = item[0];
@ -457,22 +436,33 @@ const ImageGallery = () => {
); );
return ( return (
<div className={`gallery-container ${isFilterPanelOpen ? "filter-panel-open" : ""}`}> <div className={`gallery-container ${isFilterPanelOpen ? "filter-panel-open-end" : ""}`}>
<div className="main-content"> <div className="main-content">
<button
className={`filter-button btn-primary ${isFilterPanelOpen ? "closed-icon" : ""}`}
onClick={() => setIsFilterPanelOpen(!isFilterPanelOpen)}
ref={filterButtonRef}
>
{isFilterPanelOpen ? (
<i className="fa-solid fa-times fs-5"></i>
) : (
<><i className="fa-solid fa-filter ms-1 fs-5"></i></>
)}
</button>
<div className="activity-section"> <div className="activity-section">
{loading && pageNumber === 1 ? ( {loading && pageNumber === 1 ? (
<div className="spinner-container"> <div className="spinner-container">
<div className="spinner" /> <div className="spinner" />
</div> </div>
) : filteredBatches.length > 0 ? ( ) : images.length > 0 ? (
filteredBatches.map((batch) => { images.map((batch) => {
const firstDoc = batch.documents[0]; const firstDoc = batch.documents[0];
const userName = `${firstDoc?.uploadedBy?.firstName || ""} ${firstDoc?.uploadedBy?.lastName || "" const userName = `${firstDoc?.uploadedBy?.firstName || ""} ${firstDoc?.uploadedBy?.lastName || ""
}`.trim(); }`.trim();
const date = moment(firstDoc?.uploadedAt).format("DD-MM-YYYY"); const date = moment(firstDoc?.uploadedAt).format("DD-MM-YYYY");
const time = moment(firstDoc?.uploadedAt).format("hh:mm A"); const time = moment(firstDoc?.uploadedAt).format("hh:mm A");
// Determine if scroll buttons should be shown for this batch
const showScrollButtons = batch.documents.length > SCROLL_THRESHOLD; const showScrollButtons = batch.documents.length > SCROLL_THRESHOLD;
return ( return (
@ -514,7 +504,6 @@ const ImageGallery = () => {
</div> </div>
<div className="image-group-wrapper"> <div className="image-group-wrapper">
{/* Render Left Scroll Button conditionally */}
{showScrollButtons && ( {showScrollButtons && (
<button <button
className="scroll-arrow left-arrow" className="scroll-arrow left-arrow"
@ -561,7 +550,6 @@ const ImageGallery = () => {
); );
})} })}
</div> </div>
{/* Render Right Scroll Button conditionally */}
{showScrollButtons && ( {showScrollButtons && (
<button <button
className="scroll-arrow right-arrow" className="scroll-arrow right-arrow"
@ -582,50 +570,33 @@ const ImageGallery = () => {
<div ref={loaderRef} style={{ height: '50px', margin: '20px 0', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <div ref={loaderRef} style={{ height: '50px', margin: '20px 0', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{loadingMore && hasMore && <div className="spinner" />} {loadingMore && hasMore && <div className="spinner" />}
{!hasMore && !loading && filteredBatches.length > 0 && ( {!hasMore && !loading && images.length > 0 && (
<p style={{ color: '#aaa' }}>You've reached the end of the images.</p> <p style={{ color: '#aaa' }}>You've reached the end of the images.</p>
)} )}
</div> </div>
</div> </div>
</div> </div>
<div className="filter-drawer-wrapper"> <div
<button className={`offcanvas offcanvas-end ${isFilterPanelOpen ? "show" : ""}`}
className={`filter-button btn-primary ${isFilterPanelOpen ? "" : "closed-icon"}`} tabIndex="-1"
onClick={() => setIsFilterPanelOpen(!isFilterPanelOpen)} id="filterOffcanvas"
ref={filterButtonRef} aria-labelledby="filterOffcanvasLabel"
> ref={filterPanelRef}
{isFilterPanelOpen ? ( >
<> <div className="offcanvas-header">
Filter <span className="ms-1">&#10006;</span> <h5 className="offcanvas-title" id="filterOffcanvasLabel">
</> Filters
) : ( </h5>
<> <button
<i className="fa-solid fa-filter ms-1 fs-5"></i> type="button"
</> className="btn-close"
)} onClick={() => setIsFilterPanelOpen(false)}
</button> aria-label="Close"
<div className={`filter-panel ${isFilterPanelOpen ? "open" : ""}`} ref={filterPanelRef}> ></button>
<div className={`dropdown ${collapsedFilters.dateRange ? 'collapsed' : ''}`}> </div>
<div className="dropdown-header" onClick={() => toggleCollapse('dateRange')}> <div className="offcanvas-body d-flex flex-column">
<strong>Date Range</strong> {renderFilterCategory("Date Range", [], "dateRange")}
<span className="collapse-icon">
{collapsedFilters.dateRange ? '+' : '-'}
</span>
</div>
{!collapsedFilters.dateRange && (
<div className="datepicker" >
<DateRangePicker
onRangeChange={setDateRange}
defaultStartDate={selectedFilters.startDate || yesterday}
defaultEndDate={selectedFilters.endDate || moment().format('YYYY-MM-DD')}
startDate={selectedFilters.startDate}
endDate={selectedFilters.endDate}
/>
</div>
)}
</div>
{renderFilterCategory("Building", buildings, "building")} {renderFilterCategory("Building", buildings, "building")}
{renderFilterCategory("Floor", floors, "floor")} {renderFilterCategory("Floor", floors, "floor")}
{renderFilterCategory("Work Area", workAreas, "workArea")} {renderFilterCategory("Work Area", workAreas, "workArea")}
@ -633,7 +604,7 @@ const ImageGallery = () => {
{renderFilterCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")} {renderFilterCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")}
{renderFilterCategory("Work Category", workCategories, "workCategory")} {renderFilterCategory("Work Category", workCategories, "workCategory")}
<div className="filter-actions"> <div className="filter-actions mt-auto">
<button className="btn btn-secondary btn-xs" onClick={handleClearAllFilters}> <button className="btn btn-secondary btn-xs" onClick={handleClearAllFilters}>
Clear All Clear All
</button> </button>

View File

@ -1,7 +1,5 @@
/* ImageGallery.css */
.gallery-container { .gallery-container {
display: grid; display: grid;
grid-template-columns: 1fr 50px;
gap: 4px; gap: 4px;
padding: 25px; padding: 25px;
font-family: sans-serif; font-family: sans-serif;
@ -69,7 +67,7 @@
transition: background-color 0.2s ease, box-shadow 0.2s ease, width 0.3s ease-in-out, transition: background-color 0.2s ease, box-shadow 0.2s ease, width 0.3s ease-in-out,
height 0.3s ease-in-out, border-radius 0.3s ease-in-out, padding 0.3s ease-in-out; height 0.3s ease-in-out, border-radius 0.3s ease-in-out, padding 0.3s ease-in-out;
position: absolute; position: absolute;
top: 0; top: 250px;
right: 0; right: 0;
height: 40px; height: 40px;
width: 40px; width: 40px;
@ -544,4 +542,4 @@ hr {
.datepicker { .datepicker {
margin-right: 135px; margin-right: 135px;
margin-top: 6px; margin-top: 6px;
} }