Skip to content
Snippets Groups Projects
FileField.tsx 2.18 KiB
Newer Older
import { Button, ButtonGroup } from "@mui/material";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import DownloadIcon from "@mui/icons-material/Download";
import { ChangeEventHandler, useRef } from "react";
import { CWFile } from "@/types";
import { getFileDownloadUrl, getFileNameFromURL } from "@/utils";
import { ButtonTooltip } from "./ButtonTooltip";

interface FileFieldProps {
  label: string;
  value?: CWFile;
  disabled?: boolean;
  onChange?: (file: CWFile) => void;
}

export function FileField({
  label,
  value,
  disabled = false,
  onChange,
}: FileFieldProps) {
  const ref = useRef<HTMLInputElement>(null);

  const chooseFile = () => {
    ref.current?.click();
  };

  const onFileChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    if (e.target.files && e.target.files.length > 0 && onChange) {
      const file = e.target.files[0];
      onChange({
        data: file,
        updateKey: value?.updateKey !== undefined ? value.updateKey + 1 : 0,
      });
  function getFileName() {
    if (value?.data) {
      return `${value.data.name}`;
      return `${getFileNameFromURL(value?.downloadUrl)}`;
  const filePresent = value?.downloadUrl || value?.data;

  return (
    <ButtonGroup variant={filePresent ? "outlined" : "text"}>
      <Button
        fullWidth
        startIcon={<FileUploadIcon />}
        disabled={disabled}
        onClick={chooseFile}
        component="label"
        role={undefined}
      >
        {label}
        {filePresent
          ? ` (${getFileName()}): Modifier le fichier`
          : " : Choisir un fichier"}
        <input
          type="file"
          style={{ display: "none" }}
          ref={ref}
          onChange={onFileChange}
        />
      </Button>
      <ButtonTooltip
        title={
          filePresent ? "Télécharger le fichier" : "Aucun fichier en ligne"
        }
      >
          startIcon={<DownloadIcon />}
          disabled={disabled || !filePresent}
          href={getFileDownloadUrl(value)}
          download={getFileName()}
          Télécharger
      </ButtonTooltip>
    </ButtonGroup>