From 039c0b115e8d177ab6bc7c932d4b45490cfe89b0 Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Sun, 12 Jun 2022 13:07:46 +0300 Subject: [PATCH] Vote with arrow keys --- app/modules/plus-server/usePlusVoting.ts | 44 +++++++++++++++++++----- app/routes/plus/voting/index.tsx | 10 ++---- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/app/modules/plus-server/usePlusVoting.ts b/app/modules/plus-server/usePlusVoting.ts index f7479353f..ea62cf784 100644 --- a/app/modules/plus-server/usePlusVoting.ts +++ b/app/modules/plus-server/usePlusVoting.ts @@ -21,16 +21,16 @@ export function usePlusVoting(usersForVotingFromServer: UsersForVoting) { const [usersForVoting, setUsersForVoting] = React.useState(); const [votes, setVotes] = React.useState([]); - useLoadInitialStateFromLocalStorageEffect({ - usersForVotingFromServer, - setUsersForVoting, - setVotes, - }); - const vote = React.useCallback( - ({ score, userId }: PlusVote) => { + (type: "upvote" | "downvote") => { setVotes((votes) => { - const newVotes = [...votes, { userId, score }]; + const userId = usersForVoting?.[votes.length]?.user.id; + if (!userId) return votes; + + const newVotes = [ + ...votes, + { userId, score: type === "upvote" ? 1 : -1 }, + ]; votesToLocalStorage({ usersForVoting, votes: newVotes }); @@ -50,6 +50,14 @@ export function usePlusVoting(usersForVotingFromServer: UsersForVoting) { }); }, [usersForVoting]); + useLoadInitialStateFromLocalStorageEffect({ + usersForVotingFromServer, + setUsersForVoting, + setVotes, + }); + + useVoteWithArrowKeysEffect(vote); + const currentUser = usersForVoting?.[votes.length]; const progress: [currentAmount: number, targetAmount: number] | undefined = @@ -105,6 +113,26 @@ function useLoadInitialStateFromLocalStorageEffect({ }, [month, year, usersForVotingFromServer, setUsersForVoting, setVotes]); } +function useVoteWithArrowKeysEffect( + vote: (type: "upvote" | "downvote") => void +) { + React.useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if (e.code === "ArrowRight") { + vote("upvote"); + } else if (e.code === "ArrowLeft") { + vote("downvote"); + } + }; + + window.addEventListener("keydown", handleKeyDown); + + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [vote]); +} + function previousUser({ usersForVoting, votes, diff --git a/app/routes/plus/voting/index.tsx b/app/routes/plus/voting/index.tsx index 72b5a8c3a..494d4e650 100644 --- a/app/routes/plus/voting/index.tsx +++ b/app/routes/plus/voting/index.tsx @@ -139,16 +139,10 @@ function Voting(data: Extract) { />

{discordFullName(currentUser.user)}

- -