Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import React, { useEffect, useRef, useState } from 'react'
import { axios } from '../../../utils'
import { useForm } from 'react-hook-form'
import { connect, useSelector } from 'react-redux'

import { addNotification } from '../../redux/notification/notification.actions'

import ConfirmModal from '../modals/ConfirmModal'
import useOutsideClick from '../../hooks/useOutsideClick'
import FormErrorFeedback from '../UI/FormErrorFeedback'

const FeedComments = ({
  isShow = true,
  image = '/images/avatar.jpg',
  addUrl = '',
  currentComments = [],
  addNotification,
  updateTotalComments = function () {},
}) => {
  const { register, handleSubmit, errors, reset } = useForm()
  const [comments, setComments] = useState(currentComments)
  const labels = useSelector(({ intl }) => intl.labels)

  const submitCommet = (data) => {
    const currentFormData = new FormData()
    Object.entries(data).forEach(([key, value]) =>
      currentFormData.append(key, value)
    )

    axios.post(addUrl, currentFormData).then(({ data: response }) => {
      const { success, data: message, total_comments } = response

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

      updateTotalComments(total_comments)
      setComments((prevMessages) => [...prevMessages, message])
      reset()
    })
  }

  const deleteComment = (commentUnique, deleteCommentUrl) => {
    axios
      .post(deleteCommentUrl)
      .then(({ data: response }) => {
        const { success, data, total_comments } = response

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

        updateTotalComments(total_comments)
        setComments((prevComments) =>
          prevComments.filter((comment) => comment.unique !== commentUnique)
        )
        addNotification({ style: 'success', msg: data })
      })
      .catch((error) => addNotification({ style: 'danger', msg: error }))
  }

  useEffect(() => {
    setComments(currentComments)
  }, [currentComments])

  return (
    <div className={`comments-container ${isShow ? 'show' : 'hidden'}`}>
      <form
        className="feedCommentContainer"
        onSubmit={handleSubmit(submitCommet)}
      >
        <img src={image} alt="User profile image" />
        <input
          className="commentInput"
          type="text"
          name="comment"
          maxLength="256"
          placeholder={labels.write_a_comment}
          ref={register({ required: 'El campo es requerido' })}
        />
        <button className="shareIconContainer iconActive">
          <img src="/images/icons/send.png" className="fa img-icon" />
        </button>
      </form>
      {errors.comment && (
        <FormErrorFeedback>{errors.comment.message}</FormErrorFeedback>
      )}
      <FeedComments.List comments={comments} onDelete={deleteComment} />
    </div>
  )
}

const CommentsList = ({ comments, onDelete }) => {
  return (
    <ul className="comment-list">
      {comments.map((comment) => {
        return (
          <CommentsList.Item
            comment={comment}
            onDelete={onDelete}
            key={comment.unique}
          />
        )
      })}
    </ul>
  )
}

const CommentTemplate = ({ onDelete, comment }) => {
  const {
    unique,
    user_url,
    user_name,
    user_image = '/images/avatar.jpg',
    time_elapsed,
    comment: content,
    link_delete,
  } = comment
  const [showConfirmModal, setShowConfirmModal] = useState(false)
  const [displayOption, setDisplayOption] = useState(false)
  const deleteButton = useRef(null)
  const labels = useSelector(({ intl }) => intl.labels)
  useOutsideClick(deleteButton, () => setDisplayOption(false))

  const toggleModal = () => setShowConfirmModal(!showConfirmModal)

  return (
    <li>
      <div className="comment-container">
        <img src={user_image} alt="user-image" className="user-image" />
        <div className="comment-content">
          <div className="info">
            <a href={user_url}>
              <h3>{user_name}</h3>
            </a>
            <span>
              {time_elapsed}
              {comment.link_delete && (
                <>
                  <img
                    src="/images/icons/options.png"
                    className="cursor-pointer img-icon options-sm"
                    onClick={() => setDisplayOption(!displayOption)}
                  />
                  <div
                    className={`comments-options ${
                      displayOption ? 'active' : ''
                    }`}
                  >
                    <ul>
                      <li>
                        <button
                          className="option-btn"
                          onClick={toggleModal}
                          ref={deleteButton}
                        >
                          <i className="fa fa-trash-o mr-1" />
                          {labels.delete}
                        </button>
                      </li>
                    </ul>
                  </div>
                </>
              )}
            </span>
          </div>
          <p>{content}</p>
        </div>
      </div>
      <ConfirmModal
        show={showConfirmModal}
        onClose={toggleModal}
        onAccept={() => onDelete(unique, link_delete)}
        acceptLabel={labels.accept}
      />
    </li>
  )
}

FeedComments.List = CommentsList
CommentsList.Item = CommentTemplate

const mapDispatchToProps = {
  addNotification: (notification) => addNotification(notification),
}

export default connect(null, mapDispatchToProps)(FeedComments)