Skip to content

Commit 30cae9d

Browse files
bpas247taion
andcommitted
refactor(carousel): group relevant logic together
Groups the relevant logic for the individual carousel intervals closer together, improving the overall readability of the code. Co-authored-by: Jimmy Jia <tesrin@gmail.com>
1 parent c8edc2c commit 30cae9d

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

src/Carousel.tsx

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -251,12 +251,6 @@ function CarouselFunc(uncontrolledProps: CarouselProps, ref) {
251251
activeIndex || 0,
252252
);
253253

254-
const intervals = useRef<number[]>([]);
255-
256-
const intervalRef = useCommittedRef(
257-
intervals.current[activeIndex as number] ?? interval,
258-
);
259-
260254
if (!isSliding && activeIndex !== renderedActiveIndex) {
261255
if (nextDirectionRef.current) {
262256
setDirection(nextDirectionRef.current);
@@ -278,13 +272,19 @@ function CarouselFunc(uncontrolledProps: CarouselProps, ref) {
278272
});
279273

280274
let numChildren = 0;
275+
let activeChildInterval: number | undefined;
276+
281277
// Iterate to grab all of the children's interval values
282278
// (and count them, too)
283279
forEach(children, (child, index) => {
284-
intervals.current[index] = child.props.interval as number;
285-
numChildren++;
280+
++numChildren;
281+
if (index === activeIndex) {
282+
activeChildInterval = child.props.interval as number | undefined;
283+
}
286284
});
287285

286+
const activeChildIntervalRef = useCommittedRef(activeChildInterval);
287+
288288
const prev = useCallback(
289289
(event) => {
290290
if (isSliding) {
@@ -505,15 +505,15 @@ function CarouselFunc(uncontrolledProps: CarouselProps, ref) {
505505

506506
intervalHandleRef.current = window.setInterval(
507507
document.visibilityState ? nextWhenVisible : next,
508-
intervalRef.current,
508+
activeChildIntervalRef.current || interval || undefined,
509509
);
510510

511511
return () => {
512512
if (intervalHandleRef.current !== null) {
513513
clearInterval(intervalHandleRef.current);
514514
}
515515
};
516-
}, [shouldPlay, next, intervalRef, interval, nextWhenVisible]);
516+
}, [shouldPlay, next, activeChildIntervalRef, interval, nextWhenVisible]);
517517

518518
const indicatorOnClicks = useMemo(
519519
() =>

test/CarouselSpec.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ describe('<Carousel>', () => {
340340
);
341341

342342
const total = intervals.reduce((sum, current) => sum + current, 0);
343-
clock.tick(total * 1.7);
343+
clock.tick(total * 1.1);
344344

345345
expect(onSelectSpy).to.have.been.calledThrice;
346346
expect(onSelectSpy.firstCall).to.have.been.calledWith(1);

0 commit comments

Comments
 (0)