Skip to content

Commit

Permalink
[AC-3508] fix: update carousel index calculation (#327)
Browse files Browse the repository at this point in the history
  • Loading branch information
bang9 authored Aug 7, 2024
1 parent 33be7ee commit 09587e1
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/components/ui/SnapCarousel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,22 @@ export const SnapCarousel = ({
const ref = useRef<HTMLDivElement>(null);
const [activeIndex, setActiveState] = useState(0);
const itemLength = React.Children.toArray(children).length;
const cursorSize = useMemo(() => {
const containerWidth = (ref.current?.scrollWidth ?? 0) - startPadding;
return containerWidth / itemLength + gap;
}, [ref.current?.scrollWidth, itemLength, gap, startPadding]);

const itemWidth = useMemo(() => {
const total = ref.current?.scrollWidth ?? 0;
return total - (startPadding + endPadding + gap * (itemLength - 1)) / itemLength;
}, [ref.current?.scrollWidth, itemLength, gap, startPadding, endPadding]);

const onScroll = (e: React.UIEvent<HTMLDivElement>) => {
const idx = Math.round(e.currentTarget.scrollLeft / cursorSize);
const idx = Math.round(e.currentTarget.scrollLeft / itemWidth);
if (idx !== activeIndex) setActiveState(idx);
};

const scrollTo = (index: number) => {
if (ref.current) {
const nextIdx = Math.min(Math.max(0, index), itemLength - 1);
ref.current.scroll({
left: nextIdx * cursorSize,
left: nextIdx * itemWidth,
behavior: 'smooth',
});
}
Expand Down

0 comments on commit 09587e1

Please sign in to comment.