Rev 6630 | Rev 7070 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useRef, useState, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { axios, debounce } from '../../../utils'
import useOutsideClick from '../../../hooks/useOutsideClick'
import { addNotification } from '../../../redux/notification/notification.actions'
import ReactionIcon from '@mui/icons-material/Recommend'
import FunIcon from '../icons/Fun'
import LoveItIcon from '../icons/LoveIt'
import SupportIcon from '../icons/Support'
import InterestIcon from '../icons/Interest'
import RecommendIcon from '../icons/Recommned'
const reactionsOptions = [
{
type: 'r',
icon: RecommendIcon,
label: 'Me gusta',
},
{
type: 's',
icon: SupportIcon,
label: 'Dar apoyo',
},
{
type: 'l',
icon: LoveItIcon,
label: 'Me encanta',
},
{
type: 'i',
icon: InterestIcon,
label: 'Me interesa',
},
{
type: 'f',
icon: FunIcon,
label: 'Me divierte',
},
]
const defaultReaction = {
label: 'Reaccionar',
icon: ReactionIcon,
type: 'default',
}
const ReactionsButton = ({
currentReaction,
onChange,
withLabel,
reactionTypesUrl,
deleteUrl,
}) => {
const [settedReaction, setSettedReaction] = useState(defaultReaction)
const [showReactions, setShowReactions] = useState(false)
const rectionBtn = useRef(null)
const dispatch = useDispatch()
const { icon: Icon } = settedReaction
useOutsideClick(rectionBtn, () => setShowReactions(false))
const saveReaction = async (type) => {
await axios.post(reactionTypesUrl[type]).then((res) => {
const { success, data } = res.data
if (!success) {
dispatch(addNotification({ style: 'danger', msg: data }))
}
onChange(data.reactions)
setSettedReaction(reactionsOptions[type])
})
}
const deleteReaction = async () => {
await axios.post(deleteUrl).then((res) => {
const { success, data } = res.data
if (!success) {
dispatch(addNotification({ style: 'danger', msg: data }))
return
}
onChange(data.reactions)
setSettedReaction(defaultReaction)
})
}
const onHover = debounce(() => setShowReactions(true), 500)
const onUnhover = debounce(() => setShowReactions(false), 500)
useEffect(() => {
const currentOption = reactionsOptions.find(
(reaction) => reaction.icon === currentReaction
)
if (!currentOption) {
setSettedReaction(defaultReaction)
return
}
setSettedReaction(currentOption)
}, [currentReaction])
return (
<>
<button
className="btn position-relative"
onMouseOver={onHover}
onMouseOut={onUnhover}
ref={rectionBtn}
onClick={() =>
settedReaction.type !== 'default'
? deleteReaction()
: saveReaction(reactionsOptions[0].type)
}
>
<Icon />
{withLabel && settedReaction.label}
<div className={`reactions ${showReactions ? 'active' : ''}`}>
{reactionsOptions.map((reaction) => {
const { icon: Icon, color, type, label } = reaction
return (
<button
key={type}
onClick={(e) => {
e.stopPropagation()
saveReaction(type)
}}
title={label}
>
<Icon style={{ color }} />
</button>
)
})}
</div>
</button>
</>
)
}
export default ReactionsButton