From b76ced7554df2b117cba78e8905c238452df75e0 Mon Sep 17 00:00:00 2001 From: brymut Date: Sat, 5 Jul 2025 15:01:47 +0300 Subject: [PATCH] enhance(carousel): Close carousel on browser back navigation --- components/carousel.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/components/carousel.js b/components/carousel.js index 1b5ed6dd0..12d2c0cd3 100644 --- a/components/carousel.js +++ b/components/carousel.js @@ -5,6 +5,7 @@ import ArrowRight from '@/svgs/arrow-right-line.svg' import styles from './carousel.module.css' import { useShowModal } from './modal' import { Dropdown } from 'react-bootstrap' +import { useRouter } from 'next/router' function useSwiping ({ moveLeft, moveRight }) { const [touchStartX, setTouchStartX] = useState(null) @@ -56,8 +57,16 @@ function useArrowKeys ({ moveLeft, moveRight }) { export default function Carousel ({ close, mediaArr, src, originalSrc, setOptions }) { const [index, setIndex] = useState(mediaArr.findIndex(([key]) => key === src)) const [currentSrc, canGoLeft, canGoRight] = useMemo(() => { + if (index === -1) return [src, false, false] return [mediaArr[index][0], index > 0, index < mediaArr.length - 1] - }, [mediaArr, index]) + }, [mediaArr, index, src]) + + useEffect(() => { + if (!setOptions || !mediaArr[index]) return + setOptions({ + overflow: + }) + }, [index, mediaArr, setOptions]) const moveLeft = useCallback(() => { setIndex(i => Math.max(0, i - 1)) @@ -106,15 +115,25 @@ function CarouselOverflow ({ originalSrc, rel }) { export function CarouselProvider ({ children }) { const media = useRef(new Map()) const showModal = useShowModal() + const router = useRouter() const showCarousel = useCallback(({ src }) => { + const url = router.asPath.split('#')[0] + if (window.location.hash !== '#carousel') { + router.push(url, url + '#carousel', { shallow: true }) + } showModal((close, setOptions) => { return }, { fullScreen: true, - overflow: + overflow: , + onClose: () => { + if (window.location.hash === '#carousel') { + router.back() + } + } }) - }, [showModal, media.current]) + }, [showModal, media.current, router]) const addMedia = useCallback(({ src, originalSrc, rel }) => { media.current.set(src, { src, originalSrc, rel })