ldc-bien-etre-animal/resources/ts/front/Components/Shared/ImageCarousel.tsx
2026-09-04 13:38:48 +02:00

99 lines
2.8 KiB
TypeScript

import { useRef, useState } from "react";
import CarouselControls from "@/front/Components/Shared/CarouselControls";
interface CarouselItem {
image: string;
imageWebp?: string;
rotation?: number;
}
interface ImageCarouselProps {
items: CarouselItem[];
gap?: string;
}
export default function ImageCarousel({
items,
gap = "gap-12",
}: Readonly<ImageCarouselProps>) {
const scrollRef = useRef<HTMLDivElement>(null);
const [activeIndex, setActiveIndex] = useState(0);
const scrollToIndex = (index: number) => {
const container = scrollRef.current;
if (!container) return;
if (index === 0) {
container.scrollTo({ left: 0, behavior: "smooth" });
setActiveIndex(index);
return;
}
const card = container.children[index] as HTMLElement | undefined;
if (!card) return;
container.scrollTo({
left: card.offsetLeft,
behavior: "smooth",
});
setActiveIndex(index);
};
const goPrev = () => {
if (activeIndex === 0) return;
scrollToIndex(activeIndex - 1);
};
const goNext = () => {
if (activeIndex === items.length - 1) return;
scrollToIndex(activeIndex + 1);
};
return (
<div className="flex w-full flex-col items-center gap-4 lg:gap-14">
<div
ref={scrollRef}
className={`flex h-[440px] w-full items-center overflow-x-auto overflow-y-visible scroll-smooth px-6 py-6 lg:h-[490px] lg:items-start lg:px-16 ${gap}`}
style={{ scrollbarWidth: "none" }}
>
{items.map((item, index) => (
<div
key={item.image}
className={`flex shrink-0 items-center justify-center overflow-hidden rounded-[10px] bg-white p-8 shadow-[0px_4px_15px_rgba(49,39,131,0.5)] transition-all duration-300 lg:rounded-[20px] lg:p-4 lg:shadow-[0px_4px_15px_rgba(0,0,0,0.15)] ${
index === activeIndex
? "h-[315px] w-[266px] lg:h-[450px] lg:w-[350px]"
: "h-[315px] w-[266px] lg:h-[400px] lg:w-[300px]"
}`}
style={{ transform: `rotate(${String(item.rotation ?? 0)}deg)` }}
>
<picture>
{item.imageWebp && (
<source srcSet={item.imageWebp} type="image/webp" />
)}
<img
src={item.image}
alt=""
className="h-auto w-full max-w-[200px] object-contain"
/>
</picture>
</div>
))}
<div className="w-6 shrink-0 lg:w-16" aria-hidden="true" />
</div>
<div className="flex w-full justify-center px-6">
<CarouselControls
total={items.length}
activeIndex={activeIndex}
onPrev={goPrev}
onNext={goNext}
onSelect={scrollToIndex}
color="text-bleu border-bleu hover:bg-bleu/10"
dotColor="bg-bleu"
/>
</div>
</div>
);
}