Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { CKEditor } from 'ckeditor4-react'
import { connect, useSelector } from 'react-redux'

import { axios, CKEDITOR_OPTIONS } from '../../utils'
import {
  closeShareModal,
  openShareModal,
  setModalType
} from '../../redux/share-modal/shareModal.actions'
import { addNotification } from '../../redux/notification/notification.actions'
import { addFeed, fetchFeeds } from '../../redux/feed/feed.actions'

import { shareModalTypes } from '../../redux/share-modal/shareModal.types'
import { feedTypes } from '../../redux/feed/feed.types'

import Spinner from '../UI/Spinner'
import ConfirmModal from './ConfirmModal'
import FormErrorFeedback from '../UI/FormErrorFeedback'
import DropzoneComponent from '../dropzone/DropzoneComponent'
import Modal from 'components/UI/Modal'

const ShareModal = ({
  postUrl,
  isOpen,
  modalType,
  lastModalType,
  setModalType,
  feedType,
  fetchFeeds,
  currentPage,
  timelineUrl,
  feedSharedId,
  closeShareModal, // Redux action
  addNotification, // Redux action
  addFeed, // Redux action
  openShareModal // Redux action
}) => {
  const [loading, setLoading] = useState(false)
  const [isCKEditorLoading, setIsCKEditorLoading] = useState(true)
  const [showConfirmModal, setShowConfirmModal] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)

  const {
    register,
    unregister,
    errors,
    handleSubmit,
    setValue,
    watch,
    getValues,
    clearErrors,
    setError,
    reset
  } = useForm({
    defaultValues: {
      description: '',
      share_width: 'p'
    }
  })

  useEffect(() => {
    register('description', {
      required: { value: 'true', message: 'El campo es requerido' }
    })
    register('posted_or_shared')
    if (
      modalType !== shareModalTypes.POST &&
      modalType !== shareModalTypes.SHARE
    ) {
      register('file', {
        required: { value: 'true', message: 'El campo es requerido' }
      })
    } else {
      if (!getValues('file')) unregister('file')
    }
  }, [modalType])

  const recomendationText = () => {
    switch (modalType) {
      case shareModalTypes.IMAGE:
        return 'Tamaño recomendado: 720x720'
      case shareModalTypes.FILE:
        return 'solo documentos PDF'
      case shareModalTypes.VIDEO:
        return 'Video de extensión mp4, mpeg, webm, mov'
      default:
        return ''
    }
  }
  useEffect(() => {
    const postedOrShared = modalType === shareModalTypes.SHARE ? 's' : 'p'
    setValue('posted_or_shared', postedOrShared)
    if (getValues('file') || getValues('description')) {
      if (modalType !== lastModalType) {
        closeShareModal()
        handleShowConfirmModal()
      }
    }
  }, [modalType])

  const hideDuplicatedModal = () => {
    setTimeout(() => {
      const modals = document.getElementsByClassName('modal')
      if (modals.length > 1 && modals[0].style.display !== 'none') {
        const currentModal = modals[0]
        currentModal.style.display = 'none'
        for (let index = 0; index < modals.length; index++) {
          const element = modals[index]
          element.removeAttribute('tabindex')
        }
      }
    }, 3000)
  }

  useEffect(() => {
    clearErrors()
    hideDuplicatedModal()
  }, [isOpen])

  const handleShowConfirmModal = () => {
    setShowConfirmModal(!showConfirmModal)
  }

  const handleModalAccept = () => {
    setShowConfirmModal(false)
    setValue('description', '')
    setValue('file', '')
    openShareModal(postUrl, modalType, feedType)
    clearErrors()
  }

  const handleModalCancel = () => {
    setShowConfirmModal(false)
    closeShareModal()
    setModalType(lastModalType)
    openShareModal(postUrl, lastModalType, feedType)
  }

  const onSubmit = (data) => {
    setLoading(true)
    const currentFormData = new FormData()

    Object.entries(data).forEach(([key, value]) =>
      currentFormData.append(key, value)
    )

    axios
      .post(postUrl, currentFormData)
      .then((response) => {
        const { data, success } = response.data

        if (!success) {
          if (data.description || data.file || data.share_width) {
            Object.entries(data).map(([key, value]) =>
              setError(key, { type: 'required', message: value })
            )
          } else {
            addNotification({ style: 'danger', msg: data })
          }
          return
        }

        const newFeed = data

        addNotification({
          style: 'success',
          msg: 'La publicación ha sido compartida'
        })
        reset()
        clearErrors()
        closeShareModal()

        if (feedSharedId) {
          addFeed(newFeed, feedSharedId)
        } else {
          addFeed(newFeed)
        }

        if (currentPage && timelineUrl) {
          fetchFeeds(timelineUrl, currentPage)
        }
      })
      .finally(() => setLoading(false))
  }

  const onUploadedHandler = (files) => {
    setValue('file', files)
    clearErrors('file')
  }

  const dropZoneRender = () => {
    if (
      modalType !== shareModalTypes.POST &&
      modalType !== shareModalTypes.SHARE
    ) {
      return (
        <DropzoneComponent
          modalType={modalType}
          onUploaded={onUploadedHandler}
          settedFile={getValues('file')}
          recomendationText={recomendationText()}
        />
      )
    }
  }

  const SharedWithSelectRender = () => {
    if (feedType === feedTypes.DASHBOARD) {
      return (
        <>
          <select
            name='shared_with'
            className='form-control'
            ref={register({ required: 'El campo es requerido' })}
          >
            <option disabled='disabled' value='' style={{ display: 'none' }}>
              {labels.share_with}
            </option>
            <option value='p'>{labels.public}</option>
            <option value='c'>{labels.connections}</option>
          </select>
          {errors.shared_with && (
            <FormErrorFeedback>{errors.shared_with.message}</FormErrorFeedback>
          )}
        </>
      )
    }
  }

  return (
    <>
      <Modal
        title={labels.share_a_post}
        labelAccept={labels.send}
        labelReject={labels.cancel}
        show={isOpen}
        onClose={closeShareModal}
        onReject={closeShareModal}
        onAccept={handleSubmit(onSubmit)}
      >
        {SharedWithSelectRender()}

        <CKEditor
          data={watch('description')}
          onChange={(e) => {
            const text = e.editor.getData()
            setValue('description', text)
          }}
          config={CKEDITOR_OPTIONS}
          name='description'
          onDialogShow={() => {
            const modal = document.querySelector('.fade.modal.show')
            modal.removeAttribute('tabindex')
          }}
          onBeforeLoad={() => {
            setIsCKEditorLoading(false)
          }}
        />

        {isCKEditorLoading && <Spinner />}

        {errors.description && (
          <FormErrorFeedback>{errors.description.message}</FormErrorFeedback>
        )}

        {dropZoneRender()}

        {errors.file && (
          <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
        )}

        {loading && <Spinner />}
      </Modal>
      <ConfirmModal
        show={showConfirmModal}
        onClose={handleModalCancel}
        onAccept={handleModalAccept}
        message='¿No se ha compartido tu publicación , desea descartarlo?'
      />
    </>
  )
}

const mapStateToProps = (state) => ({
  isOpen: state.shareModal.isOpen,
  postUrl: state.shareModal.postUrl,
  modalType: state.shareModal.modalType,
  lastModalType: state.shareModal.lastModalType,
  feedType: state.shareModal.feedType,
  feedSharedId: state.shareModal.feedSharedId
})

const mapDispatchToProps = {
  addNotification: (notification) => addNotification(notification),
  closeShareModal: () => closeShareModal(),
  openShareModal: (postUrl, modalType, feedType) =>
    openShareModal(postUrl, modalType, feedType),
  setModalType: (modalType) => setModalType(modalType),
  addFeed: (feed, feedSharedId) => addFeed(feed, feedSharedId),
  fetchFeeds: (url, page) => fetchFeeds(url, page)
}

export default connect(mapStateToProps, mapDispatchToProps)(ShareModal)