Skip to content

Commit df72819

Browse files
committed
enhance(carousel): Close carousel on browser back navigation
1 parent f14c0ed commit df72819

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
function Carousel ({ close, mediaArr, src, 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
useEffect(() => {
6372
if (index === -1) return
@@ -113,15 +122,25 @@ function CarouselOverflow ({ originalSrc, rel }) {
113122
export function CarouselProvider ({ children }) {
114123
const media = useRef(new Map())
115124
const showModal = useShowModal()
125+
const router = useRouter()
116126

117127
const showCarousel = useCallback(({ src }) => {
128+
const url = router.asPath.split('#')[0]
129+
if (window.location.hash !== '#carousel') {
130+
router.push(url, url + '#carousel', { shallow: true })
131+
}
118132
showModal((close, setOptions) => {
119133
return <Carousel close={close} mediaArr={Array.from(media.current.entries())} src={src} setOptions={setOptions} />
120134
}, {
121135
fullScreen: true,
122-
overflow: <CarouselOverflow {...media.current.get(src)} />
136+
overflow: <CarouselOverflow {...media.current.get(src)} />,
137+
onClose: () => {
138+
if (window.location.hash === '#carousel') {
139+
router.back()
140+
}
141+
}
123142
})
124-
}, [showModal])
143+
}, [showModal, media.current, router])
125144

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

0 commit comments

Comments
 (0)