Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3704 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { Typography } from '@mui/material';
import Delete from '@mui/icons-material/Delete';
import { DragAndDropContainer, PreviewContainer, CloseButton } from './FilePicker.styles';

const FILE_TYPES = {
  image: 'image/jpeg, image/png, image/jpg',
  file: 'application/pdf, application/vnd.openxmlformats-officedocument.presentationml.presentation',
  video: 'video/mp4, video/mpeg, video/webm, video/quicktime',
  audio: 'audio/mpeg, audio/mp3, audio/wav, audio/ogg',
  all: 'image/jpeg, image/png, image/jpg, application/pdf, application/vnd.openxmlformats-officedocument.presentationml.presentation, video/mp4, video/mpeg, video/webm, video/quicktime, audio/mpeg, audio/mp3, audio/wav, audio/ogg'
};

export function FilePicker({
  type = 'image',
  multiple = false,
  maxFiles = 1,
  description = 'Arrastra el archivo aqui, o haga click para seleccionar',
  onChange = () => {}
}) {
  const [files, setFiles] = useState([]);
  const [errors, setErrors] = useState([]);

  const { getRootProps, getInputProps } = useDropzone({
    accept: FILE_TYPES[type] ?? FILE_TYPES.image,
    multiple,
    maxFiles,
    onDropAccepted: (files) => {
      setFiles(files);
      onChange(multiple ? files : files[0]);
    },
    onDropRejected: (rejections) => {
      if (rejections.length === 0) return;
      const errors = rejections.map((rejection) => rejection.errors[0].message);
      setErrors(errors);
    }
  });

  const removeFile = () => {
    setFiles([]);
    setErrors([]);
  };

  const filePreviewTest = (preview) => {
    const src = URL.createObjectURL(preview);
    const fileType = preview.type.split('/')[0];

    switch (fileType) {
      case 'image':
        return <img src={src} alt={preview.name} />;
      case 'video':
        return <video src={src} width='400' height='300' controls muted />;
      case 'application':
        return <object data={src} type='application/pdf' width='400' height='200' />;
      case 'audio':
        return <audio src={src} controls muted />;
      default:
        return <img src={src} alt={preview.name} />;
    }
  };

  if (files.length > 0) {
    return (
      <PreviewContainer>
        {files.map((file) => filePreviewTest(file))}
        <CloseButton onClick={removeFile}>
          <Delete />
        </CloseButton>
      </PreviewContainer>
    );
  }

  return (
    <>
      <DragAndDropContainer {...getRootProps()}>
        <input {...getInputProps()} />
        <p>{description}</p>
      </DragAndDropContainer>

      {errors.map((error, index) => (
        <Typography key={index} variant='caption' color='red'>
          {error}
        </Typography>
      ))}
    </>
  );
}