'use client' import { useCallback, useEffect, useRef, useState } from 'react' import Image from './Image' export type CarouselImage = { src: string alt?: string caption?: string } interface ImageCarouselProps { images: CarouselImage[] /** Tailwind aspect class for the slide box. */ aspect?: string /** `cover` crops to fill, `contain` letterboxes. */ fit?: 'cover' | 'contain' showArrows?: boolean showDots?: boolean showCounter?: boolean } const Arrow = ({ dir }: { dir: 'left' | 'right' }) => ( ) export default function ImageCarousel({ images, aspect = 'aspect-[16/9]', fit = 'cover', showArrows = true, showDots = true, showCounter = true, }: ImageCarouselProps) { const trackRef = useRef(null) const [index, setIndex] = useState(0) const count = images?.length ?? 0 const multiple = count > 1 const goTo = useCallback( (i: number) => { const track = trackRef.current if (!track) return const clamped = Math.max(0, Math.min(count - 1, i)) track.scrollTo({ left: clamped * track.clientWidth, behavior: 'smooth' }) }, [count] ) // Keep the dot/counter state in sync with native swipe + trackpad scrolling. useEffect(() => { const track = trackRef.current if (!track) return let raf = 0 const onScroll = () => { cancelAnimationFrame(raf) raf = requestAnimationFrame(() => { const width = track.clientWidth || 1 setIndex(Math.round(track.scrollLeft / width)) }) } track.addEventListener('scroll', onScroll, { passive: true }) return () => { track.removeEventListener('scroll', onScroll) cancelAnimationFrame(raf) } }, []) if (count === 0) return null const onKeyDown = (event: React.KeyboardEvent) => { if (!multiple) return if (event.key === 'ArrowLeft') { event.preventDefault() goTo(index - 1) } else if (event.key === 'ArrowRight') { event.preventDefault() goTo(index + 1) } } const activeCaption = images[index]?.caption return (
{/* WAI-ARIA carousel pattern: the region is focusable so arrow keys work. */} {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
{images.map((image, i) => (
{image.alt
))}
{multiple && showArrows && ( <> )} {multiple && showCounter && (
{index + 1} / {count}
)}
{multiple && showDots && (
{images.map((image, i) => (
)} {activeCaption && (
{activeCaption}
)}
) }