Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 5820 | Rev 6017 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

/* eslint-disable react/prop-types */
import React, { useEffect, useState } from 'react'
import parse from 'html-react-parser'
import { axios } from '../../utils'
import { useDispatch } from 'react-redux'
import { setIntlLabels } from '../../redux/intl/intl.action'
import withReactions from '../components/feed/withReaction'
import { addNotification } from '../../redux/notification/notification.actions'

import HomeNews from '../components/home-section/HomeNews'
import InputOption from '../templates/linkedin/Feed/InputOption'
import withExternalShare from '../templates/linkedin/Feed/withExternalShare'
import FeedCommentSection from '../components/feed/feed-comment/FeedCommentSection'

import ChatOutlinedIcon from '@mui/icons-material/ChatOutlined'
import SendOutlinedIcon from '@mui/icons-material/SendOutlined'
import AccessTimeIcon from '@mui/icons-material/AccessTime'
import RecommendIcon from '@mui/icons-material/Recommend'
import FavoriteIcon from '@mui/icons-material/FavoriteTwoTone'
import VolunteerActivismIcon from '@mui/icons-material/VolunteerActivism'
import EmojiEmotionsIcon from '@mui/icons-material/EmojiEmotions'
import TungstenIcon from '@mui/icons-material/Tungsten'

import '../templates/linkedin/Feed/Feed.scss'

export default function PostView({ post, labels }) {
  const [externalShare, setExternalShare] = useState(post.total_share_external)
  const [ownerReactions, setOwnerReaction] = useState(post.reactions)
  const [currentReaction, setCurrentReaction] = useState(post.my_reaction)
  const [totalReactions, setTotalReactions] = useState(0)
  const [comments, setComments] = useState([])
  const [isReadMoreActive, setIsReadMoreActive] = useState(false)
  const [showComments, setShowComments] = useState(false)
  const dispatch = useDispatch()

  const reactionsOptions = [
    {
      type: 'r',
      icon: <RecommendIcon style={{ color: '#7405f9' }} />,
    },
    {
      type: 's',
      icon: <VolunteerActivismIcon style={{ color: '#6495ED' }} />,
    },
    {
      type: 'l',
      icon: <FavoriteIcon style={{ color: '#DF704D' }} />,
    },
    {
      type: 'i',
      icon: (
        <TungstenIcon
          style={{ color: '#F5BB5C', transform: 'rotate(180deg)' }}
        />
      ),
    },
    {
      type: 'f',
      icon: <EmojiEmotionsIcon style={{ color: '#FF7F50' }} />,
    },
  ]

  const readMoreHandler = () => setIsReadMoreActive(!isReadMoreActive)

  const displayCommentSection = () => {
    setShowComments(!showComments)
  }

  const getComments = async () => {
    await axios.get(post.comments_url).then(({ data: response }) => {
      if (!response.success) {
        addNotification({ style: 'danger', msg: response.data })
        return
      }

      setComments(response.data)
    })
  }

  const handleExternalShare = (value) => setExternalShare(value)

  const ExternalShareButton = withExternalShare(
    InputOption,
    post.share_external_url,
    {
      Icon: SendOutlinedIcon,
      color: 'gray',
      title: 'Enviar',
      shareUrl: post.share_increment_external_counter_url,
      setValue: handleExternalShare,
    }
  )

  const htmlParsedText = (fullStringText) => {
    const fullText = parse(fullStringText)
    if (fullStringText.length > 500) {
      const shortenedString = fullStringText.substr(0, 500)
      const shortenedText = parse(`${shortenedString}... `)
      return (
        <>
          {isReadMoreActive ? fullText : shortenedText}
          <span className="cursor-pointer" onClick={readMoreHandler}>
            {isReadMoreActive ? ' Leer menos' : ' Leer más'}
          </span>
        </>
      )
    }
    return <p>{fullText}</p>
  }

  const saveReaction = (type) => {
    const reactionTypesUrl = {
      r: post.save_reaction_recommended_url,
      s: post.save_reaction_support_url,
      l: post.save_reaction_love_url,
      i: post.save_reaction_interest_url,
      f: post.save_reaction_fun_url,
    }

    axios.post(reactionTypesUrl[type]).then((res) => {
      const { success, data } = res.data

      if (!success) {
        dispatch(addNotification({ style: 'danger', msg: data }))
      }

      setOwnerReaction(data.reactions)
      setCurrentReaction(type)
    })
  }

  const deleteReaction = () => {
    axios.post(post.delete_reaction_url).then((res) => {
      const { success, data } = res.data

      if (!success) {
        dispatch(addNotification({ style: 'danger', msg: data }))
        return
      }

      setOwnerReaction(data.reactions)
      setCurrentReaction('')
    })
  }

  const WithReactionIcon = withReactions(InputOption, {
    onSelect: saveReaction,
    onDelete: deleteReaction,
    myReaction: currentReaction,
  })

  useEffect(() => {
    dispatch(setIntlLabels(labels))
  }, [])

  useEffect(() => {
    if (showComments && !comments.length) getComments()
  }, [showComments])

  useEffect(() => {
    const feedReactions = ownerReactions.reduce(
      (acc, reaction) => acc + Number(reaction.total),
      0
    )
    setTotalReactions(feedReactions)
  }, [ownerReactions])

  return (
    <div className="container">
      <div className="d-flex flex-column flex-md-row" style={{ gap: '1rem' }}>
        <div className="col-12 col-md-8 p-0">
          <div className="feed">
            <div className="feed__body">
              {post.image && (
                <img
                  src={`/storage/type/post/code/${post.uuid}/filename/${post.image}`}
                  className="Entradas"
                  loading="lazy"
                />
              )}
            </div>
            <div className="feed__body">
              <div className="feed__header">
                <div className="feed__info">
                  <h2>{post.title}</h2>
                  <div className="time__elapse">
                    <p>{post.addedOn}</p>
                    <AccessTimeIcon className="time__elapse-icon" />
                  </div>
                </div>
              </div>
              {post.description && htmlParsedText(post.description)}
            </div>
            <div className="d-flex justify-content-between align-items-center">
              <div className="reactions-counter">
                {reactionsOptions
                  .filter((option) =>
                    ownerReactions.find(
                      (reaction) => reaction.reaction === option.type
                    )
                  )
                  .map((reaction) => reaction.icon)}
                <span>{totalReactions} reacciones</span>
              </div>
              {externalShare && (
                <span>{`${externalShare} ${labels.SENDS.toLowerCase()}`}</span>
              )}
            </div>
            <div className="feed__buttons">
              <WithReactionIcon />
              <InputOption
                Icon={ChatOutlinedIcon}
                title={labels.COMMENTS}
                color="gray"
                onClick={displayCommentSection}
              />
              <ExternalShareButton />
            </div>
            <div className="px-2 pb-2">
              <FeedCommentSection
                isShow={showComments}
                currentComments={comments}
                addUrl={post.comments_add_url}
              />
            </div>
          </div>
        </div>
        <div className="col-12 col-md-4 p-0">
          <HomeNews currentPost={post.uuid} />
        </div>
      </div>
    </div>
  )
}