From 5c3311ca5f64e30920624f2648ca07436215535c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Wed, 23 Jul 2025 18:21:12 +0400 Subject: [PATCH] =?UTF-8?q?feat:=20ajoute=20composant=20VoteButtons=20r?= =?UTF-8?q?=C3=A9utilisable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/versions/vote-buttons.js | 136 ++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 components/versions/vote-buttons.js diff --git a/components/versions/vote-buttons.js b/components/versions/vote-buttons.js new file mode 100644 index 0000000..3b5d05e --- /dev/null +++ b/components/versions/vote-buttons.js @@ -0,0 +1,136 @@ +import {useState, useEffect} from 'react' +import PropTypes from 'prop-types' +import Box from '@mui/material/Box' +import IconButton from '@mui/material/IconButton' +import Typography from '@mui/material/Typography' +import ThumbUpIcon from '@mui/icons-material/ThumbUp' +import ThumbDownIcon from '@mui/icons-material/ThumbDown' +import {useSession} from 'next-auth/react' +import {handleVote, getUserVote} from '@/lib/directus.js' + +export default function VoteButtons({versionId, isDisabled = false, hasCountsVisible = false, voteCounts = null, onVoteResult = null}) { + const {data: session} = useSession() + const [currentVote, setCurrentVote] = useState(null) + + useEffect(() => { + const fetchVote = async () => { + if (session?.user && versionId) { + try { + const vote = await getUserVote({ + accessToken: session.user.accessToken, + userId: session.user.userId, + versionId + }) + setCurrentVote(vote) + } catch (error) { + console.error('Error fetching vote:', error) + } + } + } + + fetchVote() + }, [session, versionId]) + + const handleVoteClick = async voteValue => { + if (isDisabled) { + return + } + + try { + const newVoteValue = await handleVote({ + accessToken: session.user.accessToken, + userId: session.user.userId, + versionId, + voteValue + }) + setCurrentVote(newVoteValue) + + if (onVoteResult) { + onVoteResult({ + success: true, + message: newVoteValue === null ? 'Vote annulé' : 'Vote enregistré avec succès' + }) + } + } catch (error) { + if (onVoteResult) { + onVoteResult({ + success: false, + message: `Erreur lors du vote: ${error}` + }) + } + } + } + + if (!session?.user) { + return null + } + + return ( + + + handleVoteClick(1)} + > + + + {hasCountsVisible && voteCounts && ( + + {voteCounts.positive || 0} + + )} + + + + handleVoteClick(-1)} + > + + + {hasCountsVisible && voteCounts && ( + + {voteCounts.negative || 0} + + )} + + + ) +} + +VoteButtons.propTypes = { + versionId: PropTypes.string.isRequired, + isDisabled: PropTypes.bool, + hasCountsVisible: PropTypes.bool, + voteCounts: PropTypes.shape({ + positive: PropTypes.number, + negative: PropTypes.number + }), + onVoteResult: PropTypes.func +}