Skip to content

Commit

Permalink
feat: add auto play on select
Browse files Browse the repository at this point in the history
  • Loading branch information
remvze committed Oct 7, 2023
1 parent 856b3e6 commit 17d1b23
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
17 changes: 14 additions & 3 deletions src/components/sound/sound.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface SoundProps {
}

export function Sound({ label, src }: SoundProps) {
const { isPlaying } = usePlay();
const { isPlaying, play } = usePlay();
const [isSelected, setIsSelected] = useLocalStorage(
`${label}-is-selected`,
false,
Expand All @@ -30,11 +30,22 @@ export function Sound({ label, src }: SoundProps) {
}
}, [isSelected, sound, isPlaying]);

const toggle = useCallback(() => {
setIsSelected(prev => !prev);
const select = useCallback(() => {
setIsSelected(true);
play();
}, [setIsSelected, play]);

const unselect = useCallback(() => {
setIsSelected(false);
setVolume(0.5);
}, [setIsSelected, setVolume]);

const toggle = useCallback(() => {
if (isSelected) return unselect();

select();
}, [isSelected, unselect, select]);

return (
<div
className={cn(styles.sound, isSelected && styles.selected)}
Expand Down
15 changes: 10 additions & 5 deletions src/contexts/play.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ export const PlayContext = createContext({
toggle: () => {},
});

export const usePlay = () => useContext(PlayContext);
export const usePlay = (): {
isPlaying: boolean;
pause: () => void;
play: () => void;
toggle: () => void;
} => useContext(PlayContext);

interface PlayProviderProps {
children: React.ReactNode;
Expand All @@ -18,10 +23,10 @@ export function PlayProvider({ children }: PlayProviderProps) {

const play = useCallback(() => setIsPlaying(true), []);
const pause = useCallback(() => setIsPlaying(false), []);
const toggle = useCallback(
() => (isPlaying ? pause() : play()),
[isPlaying, play, pause],
);
const toggle = useCallback(() => {
if (isPlaying) pause();
else play();
}, [isPlaying, play, pause]);

return (
<PlayContext.Provider value={{ isPlaying, pause, play, toggle }}>
Expand Down

0 comments on commit 17d1b23

Please sign in to comment.