Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { useDispatch, useSelector } from 'react-redux'

import { axios } from '@utils'
import { useShareModal } from '@hooks'
import { addFeed } from '@store/feed/feed.actions'
import { feedTypes } from '@store/feed/feed.types'
import { addNotification } from '@store/notification/notification.actions'
import { shareModalTypes } from '@store/share-modal/shareModal.types'

import Modal from '@components/UI/modal/Modal'
import Select from '@components/UI/inputs/Select'
import Ckeditor from '@components/common/ckeditor/Ckeditor'
import DropzoneComponent from '@components/dropzone/DropzoneComponent'
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback'
import ConfirmModal from './ConfirmModal'

const recomendationText = {
  [shareModalTypes.IMAGE]: 'Tamaño recomendado: 720x720',
  [shareModalTypes.FILE]: 'solo documentos PDF',
  [shareModalTypes.VIDEO]: 'Video de extensión mp4, mpeg, webm, mov'
}

const ShareModal = () => {
  const [showConfirm, setShowConfirm] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const {
    show,
    modalType,
    feedType,
    feedSharedId,
    postUrl,
    closeModal,
    openModal
  } = useShareModal()

  const {
    control,
    formState: { errors, isSubmitting },
    handleSubmit,
    reset,
    watch
  } = useForm({
    defaultValues: {
      posted_or_shared: modalType === shareModalTypes.SHARE ? 's' : 'p',
      share_width: 'p',
      description: ''
    }
  })
  const description = watch('description')
  const file = watch('file')

  const toggleConfirm = () => setShowConfirm(!showConfirm)

  const onSubmit = handleSubmit(async (feed) => {
    try {
      const form = new FormData()
      Object.entries(feed).forEach(([key, value]) => form.append(key, value))

      const response = await axios.post(postUrl, form)
      const { data, success } = response.data

      if (!success) {
        const errorMessage =
          typeof data === 'string'
            ? data
            : 'Ha ocurrido un error al publicar, inténtalo de nuevo más tarde.'
        throw new Error(errorMessage)
      }

      const newFeed = data

      dispatch(
        addNotification({
          style: 'success',
          msg: 'La publicación ha sido compartida'
        })
      )
      dispatch(addFeed(newFeed, feedSharedId))
      reset()
      closeModal()
    } catch (error) {
      console.error(error)
      dispatch(addNotification({ style: 'danger', msg: error.message }))
    }
  })

  const handleClose = () => {
    if (description || file) toggleConfirm()
    closeModal()
  }

  const handleConfirm = () => {
    reset()
    toggleConfirm()
    closeModal()
  }

  const handleCancel = () => {
    toggleConfirm()
    openModal({ url: postUrl, modalType, feedType })
  }

  return (
    <>
      <Modal
        show={show}
        title={labels.share_a_post}
        labelAccept={labels.send}
        labelReject={labels.cancel}
        loading={isSubmitting}
        onAccept={onSubmit}
        onClose={handleClose}
      >
        {feedType === feedTypes.DASHBOARD && (
          <Select
            name='shared_with'
            defaultValue='p'
            control={control}
            options={[
              { name: labels.public, value: 'p' },
              { name: labels.connections, value: 'c' }
            ]}
          />
        )}

        <Ckeditor
          name='description'
          control={control}
          rules={{ required: 'La descripción es requerida' }}
          error={errors.description?.message}
        />

        {![shareModalTypes.POST, shareModalTypes.SHARE].includes(modalType) && (
          <Controller
            name='file'
            control={control}
            rules={{ required: 'El archivo es requerido' }}
            render={({ field: { value, onChange } }) => (
              <DropzoneComponent
                type={modalType}
                onUploaded={(file) => onChange(file)}
                settedFile={value}
                recomendationText={recomendationText[modalType] ?? ''}
              />
            )}
          />
        )}

        {errors.file && (
          <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
        )}
      </Modal>
      <ConfirmModal
        show={showConfirm}
        onAccept={handleConfirm}
        onClose={handleCancel}
        message='¿Estás seguro de que quieres salir sin publicar tu post?'
      />
    </>
  )
}

export default ShareModal