Skip to content

Commit

Permalink
feat(spindle-hooks): add useCarousel hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
keiya01 committed Mar 31, 2022
1 parent 2de4b37 commit c186003
Show file tree
Hide file tree
Showing 9 changed files with 812 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/spindle-hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useCarousel } from './useCarousel';
1 change: 1 addition & 0 deletions packages/spindle-hooks/src/useCarousel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useCarousel } from './useCarousel';
58 changes: 58 additions & 0 deletions packages/spindle-hooks/src/useCarousel/useAutoSlide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { useCallback, useEffect, useState } from 'react';

const AUTO_SLIDE_SPEED = 4000; // ms

type Payload = {
onTimeOut: () => void;
shouldAutoPlaying?: boolean;
};

export function useAutoSlide({ onTimeOut, shouldAutoPlaying = true }: Payload) {
const [isAutoPlaying, setIsAutoPlaying] = useState(shouldAutoPlaying);
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);

const resetTimeOut = useCallback(() => {
if (timeoutId) {
clearTimeout(timeoutId);
}
}, [timeoutId]);

const activateAutoSlide = () => {
resetTimeOut();

const newTimeoutId = setTimeout(() => {
onTimeOut();
}, AUTO_SLIDE_SPEED);

setTimeoutId(newTimeoutId);
};

const resetAutoSlide = () => {
if (isAutoPlaying) {
activateAutoSlide();
}
};

const toggleAutoPlay = () => {
resetTimeOut();

if (!isAutoPlaying) {
activateAutoSlide();
}
setIsAutoPlaying((prev) => !prev);
};

useEffect(() => {
if (shouldAutoPlaying) {
activateAutoSlide();
}
}, []);

return {
isAutoPlaying,
setIsAutoPlaying,
resetAutoSlide,
resetTimeOut,
toggleAutoPlay,
};
}
Loading

0 comments on commit c186003

Please sign in to comment.