Swipe-rij: actieve kaart afleiden i.p.v. via effect (race in trage omgeving en kort flikkeren)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,7 +24,11 @@ function scrollLeftFor(container: HTMLElement, index: number): number {
|
||||
*/
|
||||
export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: string) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(initialIndex);
|
||||
// The active card is derived for the current set of cards (key), so it is already correct in
|
||||
// the first render after the data or the filter changed (no effect, no flicker, no race).
|
||||
const key = `${initialIndex}|${itemCount}|${resetKey}`;
|
||||
const [active, setActive] = useState({ key, index: initialIndex });
|
||||
const activeIndex = active.key === key ? active.index : initialIndex;
|
||||
const reducedMotion = usePrefersReducedMotion();
|
||||
|
||||
const scrollToIndex = useCallback(
|
||||
@@ -39,9 +43,9 @@ export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: s
|
||||
} else {
|
||||
container.scrollLeft = left;
|
||||
}
|
||||
setActiveIndex(index);
|
||||
setActive({ key, index });
|
||||
},
|
||||
[reducedMotion],
|
||||
[reducedMotion, key],
|
||||
);
|
||||
|
||||
// Start position: featured card (or first) whenever the set of cards changes.
|
||||
@@ -50,7 +54,6 @@ export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: s
|
||||
if (container) {
|
||||
container.scrollLeft = scrollLeftFor(container, initialIndex);
|
||||
}
|
||||
setActiveIndex(initialIndex);
|
||||
}, [initialIndex, itemCount, resetKey]);
|
||||
|
||||
// Follow the scroll position for the dots (throttled to animation frames).
|
||||
@@ -63,13 +66,14 @@ export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: s
|
||||
const onScroll = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
setActiveIndex(
|
||||
activeIndexFromScroll(
|
||||
setActive({
|
||||
key,
|
||||
index: activeIndexFromScroll(
|
||||
container.scrollLeft,
|
||||
container.clientWidth,
|
||||
cardMetrics(container),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
container.addEventListener('scroll', onScroll, { passive: true });
|
||||
@@ -77,7 +81,7 @@ export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: s
|
||||
cancelAnimationFrame(frame);
|
||||
container.removeEventListener('scroll', onScroll);
|
||||
};
|
||||
}, [itemCount]);
|
||||
}, [itemCount, key]);
|
||||
|
||||
return { ref, activeIndex, scrollToIndex };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user