97 lines
2.5 KiB
TypeScript
97 lines
2.5 KiB
TypeScript
import { useRef, useState, type ReactNode } from "react";
|
|
import { type Swiper as SwiperType } from "swiper";
|
|
import { FreeMode } from "swiper/modules";
|
|
import { Swiper, SwiperSlide } from "swiper/react";
|
|
|
|
import "swiper/css";
|
|
import "swiper/css/free-mode";
|
|
|
|
import defaultStarIcon from "&/images/guaranteesSlider/eclat.png";
|
|
import CarouselControls from "@/front/Components/Shared/CarouselControls";
|
|
|
|
interface ScrollCarouselProps<T> {
|
|
items: T[];
|
|
renderItem: (item: T, index: number) => ReactNode;
|
|
spaceBetween?: number;
|
|
showStar?: boolean;
|
|
starIcon?: string;
|
|
starClassName?: string;
|
|
controlsColor?: string;
|
|
controlsDotColor?: string;
|
|
}
|
|
|
|
export default function ScrollCarousel<T>({
|
|
items,
|
|
renderItem,
|
|
spaceBetween = 32,
|
|
showStar = false,
|
|
starIcon = defaultStarIcon,
|
|
starClassName = "-top-6 -right-6 w-12 lg:w-16",
|
|
controlsColor,
|
|
controlsDotColor,
|
|
}: Readonly<ScrollCarouselProps<T>>) {
|
|
const swiperRef = useRef<SwiperType | null>(null);
|
|
const [activeIndex, setActiveIndex] = useState(0);
|
|
|
|
const goToIndex = (index: number) => {
|
|
const swiper = swiperRef.current;
|
|
if (!swiper) return;
|
|
|
|
setActiveIndex(index);
|
|
swiper.slideTo(index);
|
|
};
|
|
|
|
const handlePrev = () => {
|
|
goToIndex(Math.max(activeIndex - 1, 0));
|
|
};
|
|
|
|
const handleNext = () => {
|
|
goToIndex(Math.min(activeIndex + 1, items.length - 1));
|
|
};
|
|
|
|
return (
|
|
<div>
|
|
<Swiper
|
|
modules={[FreeMode]}
|
|
freeMode
|
|
slidesPerView="auto"
|
|
spaceBetween={spaceBetween}
|
|
className="!overflow-visible w-full"
|
|
wrapperClass="!items-end"
|
|
onSwiper={(swiper) => {
|
|
swiperRef.current = swiper;
|
|
}}
|
|
onSlideChange={(swiper) => {
|
|
setActiveIndex(swiper.activeIndex);
|
|
}}
|
|
>
|
|
{showStar && (
|
|
<img
|
|
src={starIcon}
|
|
alt=""
|
|
className={`pointer-events-none absolute z-10 ${starClassName}`}
|
|
/>
|
|
)}
|
|
{items.map((item, index) => (
|
|
<SwiperSlide
|
|
// eslint-disable-next-line @eslint-react/no-array-index-key
|
|
key={index}
|
|
className="!w-auto"
|
|
>
|
|
{renderItem(item, index)}
|
|
</SwiperSlide>
|
|
))}
|
|
</Swiper>
|
|
|
|
<CarouselControls
|
|
total={items.length}
|
|
activeIndex={activeIndex}
|
|
onPrev={handlePrev}
|
|
onNext={handleNext}
|
|
onSelect={goToIndex}
|
|
{...(controlsColor ? { color: controlsColor } : {})}
|
|
{...(controlsDotColor ? { dotColor: controlsDotColor } : {})}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|