Integrated React-query in Gallery for handling api calling #264

Merged
pramod.mahajan merged 2 commits from query-Gallary into react-query-v2 2025-07-18 09:58:51 +00:00
4 changed files with 430 additions and 363 deletions

View File

@ -2,84 +2,115 @@ import { useState, useCallback } from "react";
// import { ImageGalleryAPI } from "../repositories/ImageGalleyRepository"; // import { ImageGalleryAPI } from "../repositories/ImageGalleyRepository";
import { ImageGalleryAPI } from "../repositories/ImageGalleryAPI"; import { ImageGalleryAPI } from "../repositories/ImageGalleryAPI";
// const PAGE_SIZE = 10;
// const useImageGallery = (selectedProjectId) => {
// const [images, setImages] = useState([]);
// const [allImagesData, setAllImagesData] = useState([]);
// const [pageNumber, setPageNumber] = useState(1);
// const [hasMore, setHasMore] = useState(true);
// const [loading, setLoading] = useState(false);
// const [loadingMore, setLoadingMore] = useState(false);
// const fetchImages = useCallback(async (page = 1, filters = {}, reset = false) => {
// if (!selectedProjectId) return;
// try {
// if (page === 1) {
// setLoading(true);
// } else {
// setLoadingMore(true);
// }
// const res = await ImageGalleryAPI.ImagesGet(
// selectedProjectId,
// filters,
// page,
// PAGE_SIZE
// );
// const newBatches = res.data || [];
// const receivedCount = newBatches.length;
// setImages((prev) => {
// if (page === 1 || reset) return newBatches;
// const uniqueNew = newBatches.filter(
// (batch) => !prev.some((b) => b.batchId === batch.batchId)
// );
// return [...prev, ...uniqueNew];
// });
// setAllImagesData((prev) => {
// if (page === 1 || reset) return newBatches;
// const uniqueAll = newBatches.filter(
// (batch) => !prev.some((b) => b.batchId === batch.batchId)
// );
// return [...prev, ...uniqueAll];
// });
// setHasMore(receivedCount === PAGE_SIZE);
// } catch (error) {
// console.error("Error fetching images:", error);
// if (page === 1) {
// setImages([]);
// setAllImagesData([]);
// }
// setHasMore(false);
// } finally {
// setLoading(false);
// setLoadingMore(false);
// }
// }, [selectedProjectId]);
// const resetGallery = useCallback(() => {
// setImages([]);
// setAllImagesData([]);
// setPageNumber(1);
// setHasMore(true);
// }, []);
// return {
// images,
// allImagesData,
// pageNumber,
// setPageNumber,
// hasMore,
// loading,
// loadingMore,
// fetchImages,
// resetGallery,
// };
// };
// export default useImageGallery;
import { useInfiniteQuery } from "@tanstack/react-query";
const PAGE_SIZE = 10; const PAGE_SIZE = 10;
const useImageGallery = (selectedProjectId) => { const useImageGallery = (selectedProjectId, filters) => {
const [images, setImages] = useState([]); const hasFilters = filters && Object.values(filters).some(
const [allImagesData, setAllImagesData] = useState([]); value => Array.isArray(value) ? value.length > 0 : value !== null && value !== ""
const [pageNumber, setPageNumber] = useState(1); );
const [hasMore, setHasMore] = useState(true);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const fetchImages = useCallback(async (page = 1, filters = {}, reset = false) => {
if (!selectedProjectId) return;
try {
if (page === 1) {
setLoading(true);
} else {
setLoadingMore(true);
}
return useInfiniteQuery({
queryKey: ["imageGallery", selectedProjectId, hasFilters ? filters : null],
enabled: !!selectedProjectId,
getNextPageParam: (lastPage, allPages) => {
if (!lastPage?.data?.length) return undefined;
return allPages.length + 1;
},
queryFn: async ({ pageParam = 1 }) => {
const res = await ImageGalleryAPI.ImagesGet( const res = await ImageGalleryAPI.ImagesGet(
selectedProjectId, selectedProjectId,
filters, hasFilters ? filters : undefined,
page, pageParam,
PAGE_SIZE PAGE_SIZE
); );
return res;
const newBatches = res.data || []; },
const receivedCount = newBatches.length; });
setImages((prev) => {
if (page === 1 || reset) return newBatches;
const uniqueNew = newBatches.filter(
(batch) => !prev.some((b) => b.batchId === batch.batchId)
);
return [...prev, ...uniqueNew];
});
setAllImagesData((prev) => {
if (page === 1 || reset) return newBatches;
const uniqueAll = newBatches.filter(
(batch) => !prev.some((b) => b.batchId === batch.batchId)
);
return [...prev, ...uniqueAll];
});
setHasMore(receivedCount === PAGE_SIZE);
} catch (error) {
console.error("Error fetching images:", error);
if (page === 1) {
setImages([]);
setAllImagesData([]);
}
setHasMore(false);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, [selectedProjectId]);
const resetGallery = useCallback(() => {
setImages([]);
setAllImagesData([]);
setPageNumber(1);
setHasMore(true);
}, []);
return {
images,
allImagesData,
pageNumber,
setPageNumber,
hasMore,
loading,
loadingMore,
fetchImages,
resetGallery,
};
}; };
export default useImageGallery; export default useImageGallery;

View File

@ -16,32 +16,20 @@ import { setProjectId } from "../../slices/localVariablesSlice";
const SCROLL_THRESHOLD = 5; const SCROLL_THRESHOLD = 5;
const ImageGallery = () => { const ImageGallery = () => {
const selectedProjectId = useSelector((store) => store.localVariables.projectId); const selectedProjectId = useSelector(
(store) => store.localVariables.projectId
);
const dispatch = useDispatch();
const { projectNames } = useProjectName();
const dispatch = useDispatch() // Auto-select a project on mount
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
useEffect(() => { useEffect(() => {
if(selectedProjectId == null){ if (!selectedProjectId && projectNames?.length) {
dispatch(setProjectId(projectNames[0]?.id)); dispatch(setProjectId(projectNames[0].id));
} }
},[]) }, [selectedProjectId, projectNames, dispatch]);
const {
images,
allImagesData,
pageNumber,
setPageNumber,
hasMore,
loading,
loadingMore,
fetchImages,
resetGallery,
} = useImageGallery(selectedProjectId);
const { openModal } = useModal();
const yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
// Filter states
const [selectedFilters, setSelectedFilters] = useState({ const [selectedFilters, setSelectedFilters] = useState({
building: [], building: [],
floor: [], floor: [],
@ -52,7 +40,6 @@ const ImageGallery = () => {
startDate: "", startDate: "",
endDate: "", endDate: "",
}); });
const [appliedFilters, setAppliedFilters] = useState({ const [appliedFilters, setAppliedFilters] = useState({
buildingIds: null, buildingIds: null,
floorIds: null, floorIds: null,
@ -63,7 +50,6 @@ const ImageGallery = () => {
startDate: null, startDate: null,
endDate: null, endDate: null,
}); });
const [collapsedFilters, setCollapsedFilters] = useState({ const [collapsedFilters, setCollapsedFilters] = useState({
dateRange: false, dateRange: false,
building: false, building: false,
@ -73,7 +59,6 @@ const ImageGallery = () => {
workCategory: false, workCategory: false,
workArea: false, workArea: false,
}); });
const [isFilterPanelOpen, setIsFilterPanelOpen] = useState(false); const [isFilterPanelOpen, setIsFilterPanelOpen] = useState(false);
const [hoveredImage, setHoveredImage] = useState(null); const [hoveredImage, setHoveredImage] = useState(null);
@ -81,133 +66,113 @@ const ImageGallery = () => {
const loaderRef = useRef(null); const loaderRef = useRef(null);
const filterPanelRef = useRef(null); const filterPanelRef = useRef(null);
const filterButtonRef = useRef(null); const filterButtonRef = useRef(null);
const { openModal } = useModal();
const {
data,
fetchNextPage,
hasNextPage,
isLoading,
isFetchingNextPage,
refetch,
} = useImageGallery(selectedProjectId, appliedFilters);
const images = data?.pages.flatMap((page) => page.data) || [];
useEffect(() => { useEffect(() => {
const handleClickOutside = (event) => { const handleClick = (e) => {
if ( if (
filterPanelRef.current && filterPanelRef.current &&
!filterPanelRef.current.contains(event.target) && !filterPanelRef.current.contains(e.target) &&
filterButtonRef.current && filterButtonRef.current &&
!filterButtonRef.current.contains(event.target) !filterButtonRef.current.contains(e.target)
) { ) {
setIsFilterPanelOpen(false); setIsFilterPanelOpen(false);
} }
}; };
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
if (isFilterPanelOpen) { useEffect(() => {
document.addEventListener("mousedown", handleClickOutside); if (selectedProjectId) refetch();
} else { }, [selectedProjectId, appliedFilters, refetch]);
document.removeEventListener("mousedown", handleClickOutside);
}
return () => { useEffect(() => {
document.removeEventListener("mousedown", handleClickOutside); const handler = (data) => {
if (data.projectId === selectedProjectId) refetch();
}; };
}, [isFilterPanelOpen]); eventBus.on("image_gallery", handler);
return () => eventBus.off("image_gallery", handler);
}, [selectedProjectId, refetch]);
useEffect(() => { useEffect(() => {
if (!selectedProjectId) { if (!loaderRef.current) return;
resetGallery();
return;
}
resetGallery(); const observer = new IntersectionObserver(
fetchImages(1, appliedFilters, true); ([entry]) => {
}, [selectedProjectId, appliedFilters]); if (entry.isIntersecting && hasNextPage && !isFetchingNextPage && !isLoading) {
fetchNextPage();
useEffect(() => {
const handleExternalEvent = (data) => {
if (selectedProjectId === data.projectId) {
resetGallery();
fetchImages(1, appliedFilters, true);
} }
}; },
{ rootMargin: "200px", threshold: 0.1 }
);
eventBus.on("image_gallery", handleExternalEvent); observer.observe(loaderRef.current);
return () => { return () => {
eventBus.off("image_gallery", handleExternalEvent); if (loaderRef.current) {
}; observer.unobserve(loaderRef.current);
}, [appliedFilters, fetchImages, selectedProjectId]); }
};
}, [hasNextPage, isFetchingNextPage, isLoading, fetchNextPage]);
useEffect(() => {
if (!loaderRef.current) return;
const observer = new IntersectionObserver( // Utility: derive filter options
(entries) => { const getUniqueValues = useCallback(
if (entries[0].isIntersecting && hasMore && !loadingMore && !loading) { (idKey, nameKey) => {
setPageNumber((prevPageNumber) => prevPageNumber + 1); const m = new Map();
images.forEach((batch) => {
const id = idKey === "floorIds" ? batch.floorIds : batch[idKey];
if (id && batch[nameKey] && !m.has(id)) {
m.set(id, batch[nameKey]);
} }
}, });
{ return [...m.entries()].sort((a, b) => a[1].localeCompare(b[1]));
root: null, },
rootMargin: "200px", [images]
threshold: 0.1, );
}
);
observer.observe(loaderRef.current); const getUploadedBy = useCallback(() => {
const m = new Map();
return () => { images.forEach((batch) => {
if (loaderRef.current) { batch.documents.forEach((doc) => {
observer.unobserve(loaderRef.current); const name = `${doc.uploadedBy?.firstName || ""} ${
} doc.uploadedBy?.lastName || ""
}; }`.trim();
}, [hasMore, loadingMore, loading]); if (doc.uploadedBy?.id && name && !m.has(doc.uploadedBy.id)) {
m.set(doc.uploadedBy.id, name);
useEffect(() => {
if (pageNumber > 1) {
fetchImages(pageNumber, appliedFilters);
}
}, [pageNumber]);
const getUniqueValuesWithIds = useCallback((idKey, nameKey) => {
const map = new Map();
allImagesData.forEach(batch => {
let id = idKey === "floorIds" ? batch.floorIds : batch[idKey];
const name = batch[nameKey];
if (id && name && !map.has(id)) {
map.set(id, name);
}
});
return Array.from(map.entries()).sort((a, b) => a[1].localeCompare(b[1]));
}, [allImagesData]);
const getUniqueUploadedByUsers = useCallback(() => {
const uniqueUsersMap = new Map();
allImagesData.forEach(batch => {
batch.documents.forEach(doc => {
if (doc.uploadedBy && doc.uploadedBy.id) {
const fullName = `${doc.uploadedBy.firstName || ""} ${doc.uploadedBy.lastName || ""}`.trim();
if (fullName) {
uniqueUsersMap.set(doc.uploadedBy.id, fullName);
}
} }
}); });
}); });
return Array.from(uniqueUsersMap.entries()).sort((a, b) => a[1].localeCompare(b[1])); return [...m.entries()].sort((a, b) => a[1].localeCompare(b[1]));
}, [allImagesData]); }, [images]);
const buildings = getUniqueValuesWithIds("buildingId", "buildingName"); const buildings = getUniqueValues("buildingId", "buildingName");
const floors = getUniqueValuesWithIds("floorIds", "floorName"); const floors = getUniqueValues("floorIds", "floorName");
const activities = getUniqueValuesWithIds("activityId", "activityName"); const activities = getUniqueValues("activityId", "activityName");
const workAreas = getUniqueValuesWithIds("workAreaId", "workAreaName"); const workAreas = getUniqueValues("workAreaId", "workAreaName");
const uploadedByUsers = getUniqueUploadedByUsers(); const workCategories = getUniqueValues("workCategoryId", "workCategoryName");
const workCategories = getUniqueValuesWithIds("workCategoryId", "workCategoryName"); const uploadedByUsers = getUploadedBy();
const toggleFilter = useCallback((type, itemId, itemName) => { const toggleFilter = useCallback((type, id, name) => {
setSelectedFilters((prev) => { setSelectedFilters((prev) => {
const current = prev[type]; const arr = prev[type];
const isSelected = current.some((item) => item[0] === itemId); const exists = arr.some(([x]) => x === id);
const updated = exists
const newArray = isSelected ? arr.filter(([x]) => x !== id)
? current.filter((item) => item[0] !== itemId) : [...arr, [id, name]];
: [...current, [itemId, itemName]]; return { ...prev, [type]: updated };
return {
...prev,
[type]: newArray,
};
}); });
}, []); }, []);
@ -220,48 +185,33 @@ const ImageGallery = () => {
}, []); }, []);
const toggleCollapse = useCallback((type) => { const toggleCollapse = useCallback((type) => {
setCollapsedFilters((prev) => ({ setCollapsedFilters((prev) => ({ ...prev, [type]: !prev[type] }));
...prev,
[type]: !prev[type],
}));
}, []); }, []);
const handleApplyFilters = useCallback(() => { const handleApplyFilters = useCallback(() => {
const payload = { const payload = {
buildingIds: selectedFilters.building.length ? selectedFilters.building.map((item) => item[0]) : null, buildingIds: selectedFilters.building.map(([x]) => x) || null,
floorIds: selectedFilters.floor.length ? selectedFilters.floor.map((item) => item[0]) : null, floorIds: selectedFilters.floor.map(([x]) => x) || null,
workAreaIds: selectedFilters.workArea.length ? selectedFilters.workArea.map((item) => item[0]) : null, activityIds: selectedFilters.activity.map(([x]) => x) || null,
workCategoryIds: selectedFilters.workCategory.length ? selectedFilters.workCategory.map((item) => item[0]) : null, uploadedByIds: selectedFilters.uploadedBy.map(([x]) => x) || null,
activityIds: selectedFilters.activity.length ? selectedFilters.activity.map((item) => item[0]) : null, workCategoryIds: selectedFilters.workCategory.map(([x]) => x) || null,
uploadedByIds: selectedFilters.uploadedBy.length ? selectedFilters.uploadedBy.map((item) => item[0]) : null, workAreaIds: selectedFilters.workArea.map(([x]) => x) || null,
startDate: selectedFilters.startDate || null, startDate: selectedFilters.startDate || null,
endDate: selectedFilters.endDate || null, endDate: selectedFilters.endDate || null,
}; };
const changed = Object.keys(payload).some((key) => {
const areFiltersChanged = Object.keys(payload).some(key => { const oldVal = appliedFilters[key],
const oldVal = appliedFilters[key]; newVal = payload[key];
const newVal = payload[key]; return Array.isArray(oldVal)
if (Array.isArray(oldVal) && Array.isArray(newVal)) { ? oldVal.length !== newVal.length ||
if (oldVal.length !== newVal.length) return true; oldVal.some((x) => !newVal.includes(x))
const oldSet = new Set(oldVal); : oldVal !== newVal;
const newSet = new Set(newVal);
for (const item of newSet) {
if (!oldSet.has(item)) return true;
}
return false;
}
if ((oldVal === null && newVal === "") || (oldVal === "" && newVal === null)) return false;
return oldVal !== newVal;
}); });
if (changed) setAppliedFilters(payload);
if (areFiltersChanged) {
setAppliedFilters(payload);
resetGallery();
}
}, [selectedFilters, appliedFilters]); }, [selectedFilters, appliedFilters]);
const handleClearAllFilters = useCallback(() => { const handleClear = useCallback(() => {
const initialStateSelected = { setSelectedFilters({
building: [], building: [],
floor: [], floor: [],
activity: [], activity: [],
@ -270,10 +220,8 @@ const ImageGallery = () => {
workArea: [], workArea: [],
startDate: "", startDate: "",
endDate: "", endDate: "",
}; });
setSelectedFilters(initialStateSelected); setAppliedFilters({
const initialStateApplied = {
buildingIds: null, buildingIds: null,
floorIds: null, floorIds: null,
activityIds: null, activityIds: null,
@ -282,69 +230,70 @@ const ImageGallery = () => {
workAreaIds: null, workAreaIds: null,
startDate: null, startDate: null,
endDate: null, endDate: null,
}; });
setAppliedFilters(initialStateApplied);
resetGallery();
}, []); }, []);
const scrollLeft = useCallback((key) => { const scrollLeft = useCallback(
imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" }); (key) =>
}, []); imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" }),
[]
);
const scrollRight = useCallback(
(key) =>
imageGroupRefs.current[key]?.scrollBy({ left: 200, behavior: "smooth" }),
[]
);
const scrollRight = useCallback((key) => { const renderCategory = (label, items, type) => (
imageGroupRefs.current[key]?.scrollBy({ left: 200, behavior: "smooth" }); <div
}, []); className={`dropdown my-2 ${collapsedFilters[type] ? "collapsed" : ""}`}
>
const renderFilterCategory = (label, items, type) => ( <div
<div className={`dropdown my-2 ${collapsedFilters[type] ? "collapsed" : ""}`}> className="dropdown-header bg-label-primary"
<div className="dropdown-header bg-label-primary" onClick={() => toggleCollapse(type)}> onClick={() => toggleCollapse(type)}
>
<strong>{label}</strong> <strong>{label}</strong>
<div className="header-controls"> <div className="header-controls">
{type === "dateRange" && (selectedFilters.startDate || selectedFilters.endDate) && ( {((type === "dateRange" &&
(selectedFilters.startDate || selectedFilters.endDate)) ||
(type !== "dateRange" && selectedFilters[type]?.length > 0)) && (
<button <button
className="clear-button" className="clear-button"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setSelectedFilters((prev) => ({ ...prev, startDate: "", endDate: "" })); setSelectedFilters((prev) => ({
...prev,
[type]: type === "dateRange" ? "" : [],
...(type === "dateRange" && { startDate: "", endDate: "" }),
}));
}} }}
> >
Clear Clear
</button> </button>
)} )}
{type !== "dateRange" && selectedFilters[type]?.length > 0 && ( <span className="collapse-icon">
<button {collapsedFilters[type] ? "+" : "-"}
className="clear-button" </span>
onClick={(e) => {
e.stopPropagation();
setSelectedFilters((prev) => ({ ...prev, [type]: [] }));
}}
>
Clear
</button>
)}
<span className="collapse-icon">{collapsedFilters[type] ? '+' : '-'}</span>
</div> </div>
</div> </div>
{!collapsedFilters[type] && ( {!collapsedFilters[type] && (
<div className="dropdown-content"> <div className="dropdown-content">
{type === "dateRange" ? ( {type === "dateRange" ? (
<div className="date-range-inputs"> <DateRangePicker
<DateRangePicker onRangeChange={setDateRange}
onRangeChange={setDateRange} endDateMode="today"
endDateMode="today" startDate={selectedFilters.startDate}
startDate={selectedFilters.startDate} endDate={selectedFilters.endDate}
endDate={selectedFilters.endDate} />
/>
</div>
) : ( ) : (
items.map(([itemId, itemName]) => ( items.map(([id, name]) => (
<label key={itemId}> <label key={id}>
<input <input
type="checkbox" type="checkbox"
checked={selectedFilters[type].some((item) => item[0] === itemId)} checked={selectedFilters[type].some(([x]) => x === id)}
onChange={() => toggleFilter(type, itemId, itemName)} onChange={() => toggleFilter(type, id, name)}
/> />
{itemName} {name}
</label> </label>
)) ))
)} )}
@ -354,105 +303,193 @@ const ImageGallery = () => {
); );
return ( return (
<div className={`gallery-container container-fluid ${isFilterPanelOpen ? "filter-panel-open-end" : ""}`}> <div
<Breadcrumb data={[{ label: "Home", link: "/" }, { label: "Gallary", link: null }]} /> className={`gallery-container container-fluid ${
isFilterPanelOpen ? "filter-panel-open-end" : ""
}`}
>
<Breadcrumb data={[{ label: "Home", link: "/" }, { label: "Gallery" }]} />
<div className="main-content"> <div className="main-content">
<button <button
className={`filter-button btn-primary ${isFilterPanelOpen ? "closed-icon" : ""}`} className={`filter-button btn-primary ${
onClick={() => setIsFilterPanelOpen(!isFilterPanelOpen)} isFilterPanelOpen ? "closed-icon" : ""
}`}
onClick={() => setIsFilterPanelOpen((p) => !p)}
ref={filterButtonRef} ref={filterButtonRef}
> >
{isFilterPanelOpen ? <i className="fa-solid fa-times fs-5"></i> : <i className="fa-solid fa-filter ms-1 fs-5"></i>} {isFilterPanelOpen ? (
<i className="fa-solid fa-times fs-5" />
) : (
<i className="fa-solid fa-filter ms-1 fs-5" />
)}
</button> </button>
<div className="activity-section"> <div className="activity-section">
{loading && pageNumber === 1 ? ( {isLoading ? (
<div className="spinner-container"><div className="spinner" /></div> <div className="text-center">
) : images.length > 0 ? ( <p>Loading...</p>
</div>
) : images.length ? (
images.map((batch) => { images.map((batch) => {
const firstDoc = batch.documents[0]; const doc = batch.documents[0];
const userName = `${firstDoc?.uploadedBy?.firstName || ""} ${firstDoc?.uploadedBy?.lastName || ""}`.trim(); const userName = `${doc.uploadedBy?.firstName || ""} ${
const date = formatUTCToLocalTime(firstDoc?.uploadedAt); doc.uploadedBy?.lastName || ""
const showScrollButtons = batch.documents.length > SCROLL_THRESHOLD; }`.trim();
const date = formatUTCToLocalTime(doc.uploadedAt);
const hasArrows = batch.documents.length > SCROLL_THRESHOLD;
return ( return (
<div key={batch.batchId} className="grouped-section"> <div key={batch.batchId} className="grouped-section">
<div className="group-heading"> <div className="group-heading">
<div className="d-flex flex-column"> {/* Uploader Info */}
<div className="d-flex align-items-center mb-1"> <div className="d-flex align-items-center mb-1">
<Avatar size="xs" firstName={firstDoc?.uploadedBy?.firstName} lastName={firstDoc?.uploadedBy?.lastName} className="me-2" /> <Avatar
<div className="d-flex flex-column align-items-start"> size="xs"
<strong className="user-name-text">{userName}</strong> firstName={doc.uploadedBy?.firstName}
<span className="me-2">{date}</span> lastName={doc.uploadedBy?.lastName}
</div> className="me-2"
/>
<div className="d-flex flex-column align-items-start">
<strong className="user-name-text">{userName}</strong>
<span className="text-muted small">{date}</span>
</div> </div>
</div> </div>
<div className="location-line">
<div>{batch.buildingName} &gt; {batch.floorName} &gt; <strong>{batch.workAreaName || "Unknown"} &gt; {batch.activityName}</strong></div> {/* Location Info */}
<div className="location-line text-secondary">
<div className="d-flex align-items-center flex-wrap gap-1 text-secondary">
{" "}
<span className="d-flex align-items-center">
<span>{batch.buildingName}</span>
<i className="bx bx-chevron-right " />
</span>
<span className="d-flex align-items-center">
<span>{batch.floorName}</span>
<i className="bx bx-chevron-right m" />
</span>
<span className="d-flex align-items-center ">
<span>{batch.workAreaName || "Unknown"}</span>
<i className="bx bx-chevron-right " />
<span>{batch.activityName}</span>
</span>
</div>
{batch.workCategoryName && ( {batch.workCategoryName && (
<div className="work-category-display ms-2"> <span className="badge bg-label-primary ms-2">
<span className="badge bg-label-primary rounded-pill d-flex align-items-center gap-1"> {batch.workCategoryName}
{batch.workCategoryName} </span>
</span>
</div>
)} )}
</div> </div>
</div> </div>
<div className="image-group-wrapper">
{showScrollButtons && <button className="scroll-arrow left-arrow" onClick={() => scrollLeft(batch.batchId)}>&#8249;</button>}
<div className="image-group-horizontal" ref={(el) => (imageGroupRefs.current[batch.batchId] = el)}>
{batch.documents.map((doc, idx) => {
const hoverDate = moment(doc.uploadedAt).format("DD-MM-YYYY");
const hoverTime = moment(doc.uploadedAt).format("hh:mm A");
<div className="image-group-wrapper">
{hasArrows && (
<button
className="scroll-arrow left-arrow"
onClick={() => scrollLeft(batch.batchId)}
>
</button>
)}
<div
className="image-group-horizontal"
ref={(el) => (imageGroupRefs.current[batch.batchId] = el)}
>
{batch.documents.map((d, i) => {
const hoverDate = moment(d.uploadedAt).format(
"DD-MM-YYYY"
);
const hoverTime = moment(d.uploadedAt).format(
"hh:mm A"
);
return ( return (
<div key={doc.id} className="image-card" onClick={() => openModal(<ImagePop batch={batch} initialIndex={idx} />)} onMouseEnter={() => setHoveredImage(doc)} onMouseLeave={() => setHoveredImage(null)}> <div
key={d.id}
className="image-card"
onClick={() =>
openModal(
<ImagePop batch={batch} initialIndex={i} />
)
}
onMouseEnter={() => setHoveredImage(d)}
onMouseLeave={() => setHoveredImage(null)}
>
<div className="image-wrapper"> <div className="image-wrapper">
<img src={doc.url} alt={`Image ${idx + 1}`} /> <img src={d.url} alt={`Image ${i + 1}`} />
</div> </div>
{hoveredImage === doc && ( {hoveredImage === d && (
<div className="image-hover-description"> <div className="image-hover-description">
<p><strong>Date:</strong> {hoverDate}</p> <p>
<p><strong>Time:</strong> {hoverTime}</p> <strong>Date:</strong> {hoverDate}
<p><strong>Activity:</strong> {batch.activityName}</p> </p>
<p>
<strong>Time:</strong> {hoverTime}
</p>
<p>
<strong>Activity:</strong>{" "}
{batch.activityName}
</p>
</div> </div>
)} )}
</div> </div>
); );
})} })}
</div> </div>
{showScrollButtons && <button className="scroll-arrow right-arrow" onClick={() => scrollRight(batch.batchId)}>&#8250;</button>} {hasArrows && (
<button
className="scroll-arrow right-arrow"
onClick={() => scrollRight(batch.batchId)}
>
<i className="bx bx-chevron-right"></i>
</button>
)}
</div> </div>
</div> </div>
); );
}) })
) : ( ) : (
!loading && <p style={{ textAlign: "center", color: "#777", marginTop: "50px" }}>No images match the selected filters.</p> <p className="text-center text-muted mt-5">
No images match the selected filters.
</p>
)} )}
<div ref={loaderRef} style={{ height: '50px', margin: '20px 0', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <div ref={loaderRef}>
{loadingMore && hasMore && <div className="spinner" />} {isFetchingNextPage && hasNextPage && <p>Loading...</p>}
{!hasMore && !loading && images.length > 0 && <p style={{ color: '#aaa' }}>You've reached the end of the images.</p>} {!hasNextPage && !isLoading && images.length > 0 && (
<p className="text-muted">
You've reached the end of the images.
</p>
)}
</div> </div>
</div> </div>
</div> </div>
<div className={`offcanvas offcanvas-end ${isFilterPanelOpen ? "show" : ""}`} tabIndex="-1" id="filterOffcanvas" aria-labelledby="filterOffcanvasLabel" ref={filterPanelRef}> <div
className={`offcanvas offcanvas-end ${isFilterPanelOpen ? "show" : ""}`}
ref={filterPanelRef}
>
<div className="offcanvas-header"> <div className="offcanvas-header">
<h5 className="offcanvas-title" id="filterOffcanvasLabel">Filters</h5> <h5>Filters</h5>
<button type="button" className="btn-close" onClick={() => setIsFilterPanelOpen(false)} aria-label="Close" /> <button
className="btn-close"
onClick={() => setIsFilterPanelOpen(false)}
/>
</div> </div>
<div className="filter-actions mt-auto mx-2"> <div className="filter-actions mt-auto mx-2">
<button className="btn btn-secondary btn-xs" onClick={handleClearAllFilters}>Clear All</button> <button className="btn btn-secondary btn-xs" onClick={handleClear}>
<button className="btn btn-primary btn-xs" onClick={handleApplyFilters}>Apply Filters</button> Clear All
</button>
<button
className="btn btn-primary btn-xs"
onClick={handleApplyFilters}
>
Apply Filters
</button>
</div> </div>
<div className="offcanvas-body d-flex flex-column"> <div className="offcanvas-body d-flex flex-column">
{renderFilterCategory("Date Range", [], "dateRange")} {renderCategory("Date Range", [], "dateRange")}
{renderFilterCategory("Building", buildings, "building")} {renderCategory("Building", buildings, "building")}
{renderFilterCategory("Floor", floors, "floor")} {renderCategory("Floor", floors, "floor")}
{renderFilterCategory("Work Area", workAreas, "workArea")} {renderCategory("Work Area", workAreas, "workArea")}
{renderFilterCategory("Activity", activities, "activity")} {renderCategory("Activity", activities, "activity")}
{renderFilterCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")} {renderCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")}
{renderFilterCategory("Work Category", workCategories, "workCategory")} {renderCategory("Work Category", workCategories, "workCategory")}
</div> </div>
</div> </div>
</div> </div>

View File

@ -42,14 +42,23 @@
} }
/* Image Styles */ /* Image Styles */
.modal-image {
max-width: 100%; .image-container {
max-height: 70vh; aspect-ratio: 1 / 1; /* Square shape: width and height are equal */
width: auto; width: 100%; /* or set a fixed width like 300px */
max-width: 400px; /* Optional: limit how large it grows */
border-radius: 10px; border-radius: 10px;
object-fit: contain; overflow: hidden;
margin-bottom: 20px; display: flex;
flex-shrink: 0; justify-content: center;
align-items: center;
background-color: #f5f5f5;
}
.modal-image {
width: 100%;
height: 100%;
object-fit: cover;
} }
/* Scrollable Container for Text Details */ /* Scrollable Container for Text Details */

View File

@ -54,44 +54,34 @@ const ImagePop = ({ batch, initialIndex = 0 }) => {
return ( return (
<div className="image-modal-overlay"> <div className="image-modal-overlay">
<div className="image-modal-content"> <div className="image-modal-content">
{/* Close button */}
<button className="close-button" onClick={closeModal}> <i className='bx bx-x close-button' onClick={closeModal}></i>
×
</button>
{/* Previous button, only shown if there's a previous image */}
{hasPrev && ( {hasPrev && (
<button className="nav-button prev-button" onClick={handlePrev}> <button className="nav-button prev-button" onClick={handlePrev}>
&#8249; {/* Unicode for single left angle quotation mark */} <i className='bx bx-chevron-left'></i>
</button> </button>
)} )}
{/* The main image display */} <div className="image-container">
<img src={image.url} alt="Preview" className="modal-image" /> <img src={image.url} alt="Preview" className="modal-image" />
</div>
{/* Next button, only shown if there's a next image */}
{hasNext && ( {hasNext && (
<button className="nav-button next-button" onClick={handleNext}> <button className="nav-button next-button" onClick={handleNext}>
&#8250; {/* Unicode for single right angle quotation mark */} <i className='bx bx-chevron-right'></i>
</button> </button>
)} )}
{/* Image details */}
<div className="image-details"> <div className="image-details">
<p>
<strong>👤 Uploaded By:</strong> {fullName} <div className="flex alig-items-center"> <i className='bx bxs-user'></i> <span className="text-muted">Uploaded By : </span> <span className="text-secondary">{fullName}</span></div>
</p> <div className="flex alig-items-center"> <i class='bx bxs-calendar' ></i> <span className="text-muted">Date : </span> <span className="text-secondary"> {date}</span></div>
<p> <div className="flex alig-items-center"> <i class='bx bx-map' ></i> <span className="text-muted">Uploaded By : </span> <span className="text-secondary">{buildingName} <i className='bx bx-chevron-right'></i> {floorName} <i className='bx bx-chevron-right'></i>
<strong>📅 Date:</strong> {date} {workAreaName || "Unknown"} <i className='bx bx-chevron-right'></i> {activityName}</span></div>
</p> <div className="flex alig-items-center"> <i className='bx bx-comment-dots'></i> <span className="text-muted">comment : </span> <span className="text-secondary">{batchComment}</span></div>
<p>
<strong>🏢 Location:</strong> {buildingName} &gt; {floorName} &gt;{" "}
{workAreaName || "Unknown"} &gt; {activityName}
</p>
<p>
{/* Display the comment from the batch object */}
<strong>📝 Comments:</strong> {batchComment || "N/A"}
</p>
</div> </div>
</div> </div>
</div> </div>