Spaces:
Running on Zero
Running on Zero
File size: 1,538 Bytes
ef6e870 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | export function useScrollCarousel() {
let canScrollLeft = $state(false);
let canScrollRight = $state(false);
let scrollContainer = $state<HTMLDivElement | undefined>();
function scrollToCenter(element: HTMLElement) {
if (!scrollContainer) return;
const containerRect = scrollContainer.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
const elementCenter = elementRect.left + elementRect.width / 2;
const containerCenter = containerRect.left + containerRect.width / 2;
const scrollOffset = elementCenter - containerCenter;
scrollContainer.scrollBy({ left: scrollOffset, behavior: 'smooth' });
}
function scrollLeft() {
if (!scrollContainer) return;
scrollContainer.scrollBy({ left: -250, behavior: 'smooth' });
}
function scrollRight() {
if (!scrollContainer) return;
scrollContainer.scrollBy({ left: 250, behavior: 'smooth' });
}
function updateScrollButtons() {
if (!scrollContainer) return;
const { scrollLeft: sl, scrollWidth, clientWidth } = scrollContainer;
canScrollLeft = sl > 0;
canScrollRight = sl < scrollWidth - clientWidth - 1;
}
$effect(() => {
if (scrollContainer) {
updateScrollButtons();
}
});
return {
get canScrollLeft() {
return canScrollLeft;
},
get canScrollRight() {
return canScrollRight;
},
get scrollContainer() {
return scrollContainer;
},
set scrollContainer(el: HTMLDivElement | undefined) {
scrollContainer = el;
},
scrollToCenter,
scrollLeft,
scrollRight,
updateScrollButtons
};
}
|