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";
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 [images, setImages] = useState([]);
const [allImagesData, setAllImagesData] = useState([]);
const [pageNumber, setPageNumber] = useState(1);
const [hasMore, setHasMore] = useState(true);
const selectedProjectId = useSelector((store) => store.localVariables.projectId);
const { openModal } = useModal();
const [initialImageCache, setInitialImageCache] = useState([]);
const yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
@ -60,9 +60,9 @@ const ImageGallery = () => {
const [loadingMore, setLoadingMore] = useState(false);
const imageGroupRefs = useRef({});
const loaderRef = useRef(null);
const filterPanelRef = useRef(null);
const filterButtonRef = useRef(null);
const loaderRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
@ -75,15 +75,22 @@ const ImageGallery = () => {
setIsFilterPanelOpen(false);
}
};
if (isFilterPanelOpen) {
document.addEventListener("mousedown", handleClickOutside);
} else {
document.removeEventListener("mousedown", handleClickOutside);
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
}, [isFilterPanelOpen]);
useEffect(() => {
if (!selectedProjectId) {
setImages([]);
setAllImagesData([]);
setLoading(false);
setHasMore(false);
return;
@ -94,7 +101,8 @@ const ImageGallery = () => {
setHasMore(true);
setLoading(true);
fetchImages(1, appliedFilters);
setAllImagesData([]);
fetchImages(1, appliedFilters, true);
}, [selectedProjectId, appliedFilters]);
const fetchImages = useCallback(async (page, filters) => {
@ -103,13 +111,6 @@ const ImageGallery = () => {
try {
if (page === 1) {
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 {
setLoadingMore(true);
}
@ -122,22 +123,23 @@ const ImageGallery = () => {
const uniqueNewBatches = newBatches.filter(
(newBatch) => !prevImages.some((prevBatch) => prevBatch.batchId === newBatch.batchId)
);
const updatedImages = [...prevImages, ...uniqueNewBatches];
return [...prevImages, ...uniqueNewBatches];
});
const noFiltersApplied = Object.values(filters).every(
(val) => val === null || (Array.isArray(val) && val.length === 0)
setAllImagesData((prevAllImages) => {
const uniqueAllImages = newBatches.filter(
(newBatch) => !prevAllImages.some((prevBatch) => prevBatch.batchId === newBatch.batchId)
);
if (page === 1 && noFiltersApplied) {
setInitialImageCache(updatedImages);
}
return updatedImages;
return [...prevAllImages, ...uniqueAllImages];
});
setHasMore(receivedCount === PAGE_SIZE);
} catch (err) {
console.error("Error fetching images:", err);
if (page === 1) {
setImages([]);
setAllImagesData([]);
}
setHasMore(false);
} finally {
setLoading(false);
@ -145,19 +147,14 @@ const ImageGallery = () => {
}
}, [selectedProjectId]);
const isNoFiltersApplied = (filters) =>
Object.values(filters).every(
(val) => val === null || (Array.isArray(val) && val.length === 0)
);
useEffect(() => {
const handleExternalEvent = (data) => {
if (selectedProjectId == data.projectId) {
if (selectedProjectId === data.projectId) {
setImages([]);
setAllImagesData([]);
setPageNumber(1);
setHasMore(true);
fetchImages(1, appliedFilters);
fetchImages(1, appliedFilters, true);
}
};
@ -199,22 +196,28 @@ const ImageGallery = () => {
}
}, [pageNumber, fetchImages, appliedFilters]);
const getUniqueValuesWithIds = useCallback((idKey, nameKey, dataArray = initialImageCache) => {
const getUniqueValuesWithIds = useCallback((idKey, nameKey) => {
const map = new Map();
dataArray.forEach(batch => {
const id = batch[idKey];
allImagesData.forEach(batch => {
let id;
if (idKey === "floorIds") {
id = batch.floorIds;
} else {
id = batch[idKey];
}
const name = batch[nameKey];
if (id && name && !map.has(id)) {
map.set(id, name);
}
});
return Array.from(map.entries());
}, [initialImageCache]);
}, [allImagesData]);
const getUniqueUploadedByUsers = useCallback(() => {
const uniqueUsersMap = new Map();
images.forEach(batch => {
allImagesData.forEach(batch => {
batch.documents.forEach(doc => {
if (doc.uploadedBy && doc.uploadedBy.id) {
const fullName = `${doc.uploadedBy.firstName || ""} ${doc.uploadedBy.lastName || ""}`.trim();
@ -225,15 +228,14 @@ const ImageGallery = () => {
});
});
return Array.from(uniqueUsersMap.entries());
}, [images]);
}, [allImagesData]);
const buildings = getUniqueValuesWithIds("buildingId", "buildingName", initialImageCache);
const floors = getUniqueValuesWithIds("floorId", "floorName", initialImageCache);
const activities = getUniqueValuesWithIds("activityId", "activityName", initialImageCache);
const workAreas = getUniqueValuesWithIds("workAreaId", "workAreaName", initialImageCache);
const buildings = getUniqueValuesWithIds("buildingId", "buildingName");
const floors = getUniqueValuesWithIds("floorIds", "floorName");
const activities = getUniqueValuesWithIds("activityId", "activityName");
const workAreas = getUniqueValuesWithIds("workAreaId", "workAreaName");
const uploadedByUsers = getUniqueUploadedByUsers();
const workCategories = getUniqueValuesWithIds("workCategoryId", "workCategoryName", initialImageCache);
const workCategories = getUniqueValuesWithIds("workCategoryId", "workCategoryName");
const toggleFilter = useCallback((type, itemId, itemName) => {
setSelectedFilters((prev) => {
@ -310,6 +312,9 @@ const ImageGallery = () => {
}
return false;
}
if ((oldVal === null && newVal === "") || (oldVal === "" && newVal === null)) {
return false;
}
return oldVal !== newVal;
});
@ -319,9 +324,9 @@ const ImageGallery = () => {
setPageNumber(1);
setHasMore(true);
}
// Removed setIsFilterPanelOpen(false); to keep the drawer open
}, [selectedFilters, appliedFilters]);
const handleClearAllFilters = useCallback(() => {
const initialStateSelected = {
building: [],
@ -351,40 +356,6 @@ const ImageGallery = () => {
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) => {
imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" });
}, []);
@ -430,7 +401,15 @@ const ImageGallery = () => {
{!collapsedFilters[type] && (
<div className="dropdown-content">
{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) => {
const itemId = item[0];
@ -457,22 +436,33 @@ const ImageGallery = () => {
);
return (
<div className={`gallery-container ${isFilterPanelOpen ? "filter-panel-open" : ""}`}>
<div className={`gallery-container ${isFilterPanelOpen ? "filter-panel-open-end" : ""}`}>
<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">
{loading && pageNumber === 1 ? (
<div className="spinner-container">
<div className="spinner" />
</div>
) : filteredBatches.length > 0 ? (
filteredBatches.map((batch) => {
) : images.length > 0 ? (
images.map((batch) => {
const firstDoc = batch.documents[0];
const userName = `${firstDoc?.uploadedBy?.firstName || ""} ${firstDoc?.uploadedBy?.lastName || ""
}`.trim();
const date = moment(firstDoc?.uploadedAt).format("DD-MM-YYYY");
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;
return (
@ -514,7 +504,6 @@ const ImageGallery = () => {
</div>
<div className="image-group-wrapper">
{/* Render Left Scroll Button conditionally */}
{showScrollButtons && (
<button
className="scroll-arrow left-arrow"
@ -561,7 +550,6 @@ const ImageGallery = () => {
);
})}
</div>
{/* Render Right Scroll Button conditionally */}
{showScrollButtons && (
<button
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' }}>
{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>
)}
</div>
</div>
</div>
<div className="filter-drawer-wrapper">
<button
className={`filter-button btn-primary ${isFilterPanelOpen ? "" : "closed-icon"}`}
onClick={() => setIsFilterPanelOpen(!isFilterPanelOpen)}
ref={filterButtonRef}
<div
className={`offcanvas offcanvas-end ${isFilterPanelOpen ? "show" : ""}`}
tabIndex="-1"
id="filterOffcanvas"
aria-labelledby="filterOffcanvasLabel"
ref={filterPanelRef}
>
{isFilterPanelOpen ? (
<>
Filter <span className="ms-1">&#10006;</span>
</>
) : (
<>
<i className="fa-solid fa-filter ms-1 fs-5"></i>
</>
)}
</button>
<div className={`filter-panel ${isFilterPanelOpen ? "open" : ""}`} ref={filterPanelRef}>
<div className={`dropdown ${collapsedFilters.dateRange ? 'collapsed' : ''}`}>
<div className="dropdown-header" onClick={() => toggleCollapse('dateRange')}>
<strong>Date Range</strong>
<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 className="offcanvas-header">
<h5 className="offcanvas-title" id="filterOffcanvasLabel">
Filters
</h5>
<button
type="button"
className="btn-close"
onClick={() => setIsFilterPanelOpen(false)}
aria-label="Close"
></button>
</div>
<div className="offcanvas-body d-flex flex-column">
{renderFilterCategory("Date Range", [], "dateRange")}
{renderFilterCategory("Building", buildings, "building")}
{renderFilterCategory("Floor", floors, "floor")}
{renderFilterCategory("Work Area", workAreas, "workArea")}
@ -633,7 +604,7 @@ const ImageGallery = () => {
{renderFilterCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")}
{renderFilterCategory("Work Category", workCategories, "workCategory")}
<div className="filter-actions">
<div className="filter-actions mt-auto">
<button className="btn btn-secondary btn-xs" onClick={handleClearAllFilters}>
Clear All
</button>

View File

@ -1,7 +1,5 @@
/* ImageGallery.css */
.gallery-container {
display: grid;
grid-template-columns: 1fr 50px;
gap: 4px;
padding: 25px;
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,
height 0.3s ease-in-out, border-radius 0.3s ease-in-out, padding 0.3s ease-in-out;
position: absolute;
top: 0;
top: 250px;
right: 0;
height: 40px;
width: 40px;