Skip to content

Commit 58be990

Browse files
committed
enhance(carousel): Close carousel on browser back navigation
1 parent 8337aad commit 58be990

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

components/carousel.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import ArrowRight from '@/svgs/arrow-right-line.svg'
55
import styles from './carousel.module.css'
66
import { useShowModal } from './modal'
77
import { Dropdown } from 'react-bootstrap'
8+
import { useRouter } from 'next/router'
89

910
function useSwiping ({ moveLeft, moveRight }) {
1011
const [touchStartX, setTouchStartX] = useState(null)
@@ -56,8 +57,16 @@ function useArrowKeys ({ moveLeft, moveRight }) {
5657
export default function Carousel ({ close, mediaArr, src, originalSrc, setOptions }) {
5758
const [index, setIndex] = useState(mediaArr.findIndex(([key]) => key === src))
5859
const [currentSrc, canGoLeft, canGoRight] = useMemo(() => {
60+
if (index === -1) return [src, false, false]
5961
return [mediaArr[index][0], index > 0, index < mediaArr.length - 1]
60-
}, [mediaArr, index])
62+
}, [mediaArr, index, src])
63+
64+
useEffect(() => {
65+
if (!setOptions || !mediaArr[index]) return
66+
setOptions({
67+
overflow: <CarouselOverflow {...mediaArr[index][1]} />
68+
})
69+
}, [index, mediaArr, setOptions])
6170

6271
const moveLeft = useCallback(() => {
6372
setIndex(i => Math.max(0, i - 1))
@@ -106,15 +115,25 @@ function CarouselOverflow ({ originalSrc, rel }) {
106115
export function CarouselProvider ({ children }) {
107116
const media = useRef(new Map())
108117
const showModal = useShowModal()
118+
const router = useRouter()
109119

110120
const showCarousel = useCallback(({ src }) => {
121+
const url = router.asPath.split('#')[0]
122+
if (window.location.hash !== '#carousel') {
123+
router.push(url, url + '#carousel', { shallow: true })
124+
}
111125
showModal((close, setOptions) => {
112126
return <Carousel close={close} mediaArr={Array.from(media.current.entries())} src={src} setOptions={setOptions} />
113127
}, {
114128
fullScreen: true,
115-
overflow: <CarouselOverflow {...media.current.get(src)} />
129+
overflow: <CarouselOverflow {...media.current.get(src)} />,
130+
onClose: () => {
131+
if (window.location.hash === '#carousel') {
132+
router.back()
133+
}
134+
}
116135
})
117-
}, [showModal, media.current])
136+
}, [showModal, media, router])
118137

119138
const addMedia = useCallback(({ src, originalSrc, rel }) => {
120139
media.current.set(src, { src, originalSrc, rel })

0 commit comments

Comments
 (0)