added files in git
This commit is contained in:
66
src/components/ImageViewer.jsx
Normal file
66
src/components/ImageViewer.jsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
export default function ImageViewer({ images, initialIndex = 0, onClose }) {
|
||||
const [index, setIndex] = useState(initialIndex);
|
||||
|
||||
const urls = images.map(u => (u.startsWith("http") ? u : `${API_URL}${u}`));
|
||||
|
||||
const next = useCallback(() => {
|
||||
setIndex(i => (i + 1) % urls.length);
|
||||
}, [urls.length]);
|
||||
|
||||
const prev = useCallback(() => {
|
||||
setIndex(i => (i - 1 + urls.length) % urls.length);
|
||||
}, [urls.length]);
|
||||
|
||||
const handleImgClick = useCallback(() => {
|
||||
next();
|
||||
}, [next]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKey = (e) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
if (e.key === "ArrowRight") next();
|
||||
if (e.key === "ArrowLeft") prev();
|
||||
};
|
||||
window.addEventListener("keydown", handleKey);
|
||||
return () => window.removeEventListener("keydown", handleKey);
|
||||
}, [onClose, next, prev]);
|
||||
|
||||
useEffect(() => {
|
||||
setIndex(initialIndex);
|
||||
}, [initialIndex]);
|
||||
|
||||
if (!urls.length) return null;
|
||||
|
||||
return (
|
||||
<div className="f-viewer-bg" onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<button className="f-viewer-close" onClick={onClose}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
|
||||
<div className="f-viewer">
|
||||
<img
|
||||
src={urls[index]}
|
||||
alt=""
|
||||
className="f-viewer-img"
|
||||
onClick={handleImgClick}
|
||||
/>
|
||||
|
||||
{urls.length > 1 && (
|
||||
<div className="f-viewer-dots">
|
||||
{urls.map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
className={`f-viewer-dot${i === index ? " active" : ""}`}
|
||||
onClick={() => setIndex(i)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user