'use strict';

var neetoCist = require('@bigbinary/neeto-cist');
var ramda = require('ramda');
var initializers = require('@bigbinary/neeto-commons-frontend/initializers');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var classnames = require('classnames');
var FileUpload$1 = require('@bigbinary/neeto-icons/FileUpload');
var reactI18next = require('react-i18next');
var jsxRuntime = require('react/jsx-runtime');
var path = require('path');
var i18next = require('i18next');
var injectCss = require('./inject-css-B6qYtOJe.js');
var FileGeneric = require('@bigbinary/neeto-icons/FileGeneric');
var Check = require('@bigbinary/neeto-icons/Check');
var Close = require('@bigbinary/neeto-icons/Close');
var framerMotion = require('framer-motion');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var activestorage = require('@rails/activestorage');
var reactDropzone = require('react-dropzone');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var formik = require('formik');

var FILE_MIME_TYPES = {
  pdf: ["application/pdf"],
  doc: ["application/msword", "application/wps-writer"],
  docx: ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  xls: ["application/vnd.ms-excel"],
  xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  csv: ["text/csv"],
  txt: ["text/plain"],
  rtf: ["application/rtf", "text/rtf"],
  html: ["text/html"],
  htm: ["text/html"],
  md: ["text/markdown", "text/x-markdown"],
  zip: ["application/zip"],
  mp3: ["audio/mpeg"],
  wma: ["audio/x-ms-wma", "video/x-ms-asf"],
  mp4: ["video/mp4"],
  mpg: ["video/mpeg"],
  mpeg: ["video/mpeg"],
  flv: ["video/x-flv"],
  avi: ["video/x-msvideo"],
  jpg: ["image/jpeg"],
  jpeg: ["image/jpeg"],
  png: ["image/png"],
  gif: ["image/gif"],
  json: ["application/json"],
  epub: ["application/epub+zip"],
  aac: ["audio/aac"],
  svg: ["image/svg+xml"],
  ico: ["image/vnd.microsoft.icon"]
};
var ERROR_CODES = {
  FILE_TOO_LARGE: "file-too-large",
  FILE_INVALID_TYPE: "file-invalid-type",
  TOO_MANY_FILES: "too-many-files"
};
var DIRECT_UPLOAD_URL = "/api/direct_uploads";
var MAX_FILE_SIZE = (initializers.globalProps === null || initializers.globalProps === void 0 ? void 0 : initializers.globalProps.endUserUploadedFileSizeLimitInMb) || 10;

function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var DropZone = function DropZone(_ref) {
  var isDragActive = _ref.isDragActive,
    getRootProps = _ref.getRootProps,
    getInputProps = _ref.getInputProps,
    multipleFilesAllowed = _ref.multipleFilesAllowed,
    maxFileSize = _ref.maxFileSize,
    allowedFileTypes = _ref.allowedFileTypes,
    hasFileSizeLimit = _ref.hasFileSizeLimit;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var shouldAllowSingleFileUpload = !multipleFilesAllowed;
  var shouldShowFileSizeLimit = hasFileSizeLimit && maxFileSize;
  return /*#__PURE__*/jsxRuntime.jsx("div", _objectSpread$2(_objectSpread$2({}, getRootProps({
    className: classnames(["neeto-molecules-file-upload__dropzone"], {
      "neeto-molecules-file-upload__dropzone--drag-active": isDragActive
    })
  })), {}, {
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-molecules-file-upload__dropzone-inner",
      "data-testid": "file-upload-body",
      children: [/*#__PURE__*/jsxRuntime.jsx(FileUpload$1, {
        className: "neeto-molecules-file-upload__upload-icon",
        size: "36"
      }), /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "neeto-molecules-file-upload__dropzone-content",
        children: [/*#__PURE__*/jsxRuntime.jsxs("label", {
          className: "neeto-molecules-file-upload__upload-label",
          htmlFor: "file-upload",
          children: [/*#__PURE__*/jsxRuntime.jsx("span", {
            className: "neeto-molecules-file-upload__choose-file",
            children: t("neetoMolecules.fileUpload.filesDropzone.chooseFileOrDragHere")
          }), /*#__PURE__*/jsxRuntime.jsx("input", _objectSpread$2(_objectSpread$2({}, getInputProps()), {}, {
            "data-testid": "image-browse-button"
          }))]
        }), /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "neeto-molecules-file-upload__dropzone-helper-block",
          children: [shouldAllowSingleFileUpload && /*#__PURE__*/jsxRuntime.jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-testid": "upload-only-one-file-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.oneFileAllowed")
          }), shouldShowFileSizeLimit && /*#__PURE__*/jsxRuntime.jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-testid": "maximum-allowed-size-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.maxFileSize", {
              size: maxFileSize,
              unit: "MB"
            })
          }), allowedFileTypes && /*#__PURE__*/jsxRuntime.jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-testid": "allowed-files-types-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.allowedFileTypes", {
              types: allowedFileTypes
            })
          })]
        })]
      })]
    })
  }));
};

var getAcceptedFileTypes = function getAcceptedFileTypes(allowedFileTypes) {
  var accepted = {};
  allowedFileTypes.split(", ").forEach(function (type) {
    var mimeTypes = FILE_MIME_TYPES[type] || ["application/octet-stream"];
    var extension = ".".concat(type);
    if (neetoCist.isNotPresent(type) || neetoCist.isNotPresent(mimeTypes)) return;
    mimeTypes.forEach(function (mimeType) {
      if (accepted[mimeType]) accepted[mimeType].push(extension);else accepted[mimeType] = [extension];
    });
  });
  return accepted;
};
var convertBytesToMb = function convertBytesToMb(bytes) {
  return ((bytes - 10) / (1028 * 1024)).toFixed(2);
};
var renderErrorMessage = function renderErrorMessage(errorObject, maxFileSize, isMultiple) {
  var error = errorObject.errors[0];
  var file = errorObject.file;
  if (error) {
    var code = error.code;
    if (code === ERROR_CODES.FILE_TOO_LARGE) {
      return i18next.t("neetoMolecules.fileUpload.filesDropzone.errors.fileTooLarge", {
        fileName: file.name,
        maxSize: "".concat(Math.round(maxFileSize / 1048576), "MB")
      });
    } else if (code === ERROR_CODES.FILE_INVALID_TYPE) {
      return i18next.t("neetoMolecules.fileUpload.filesDropzone.errors.fileInvalidType", {
        fileType: path.extname(file.name)
      });
    } else if (code === ERROR_CODES.TOO_MANY_FILES && !isMultiple) {
      return i18next.t("neetoMolecules.fileUpload.filesDropzone.errors.tooManyFiles", {
        maxFiles: 1
      });
    }
  }
  return i18next.t("neetoMolecules.fileUpload.filesDropzone.errors.defaultError", {
    fileName: file.name
  });
};
var convertMbToBytes = function convertMbToBytes(mb) {
  return mb * 1028 * 1024 + 10;
};

var ErrorMessages = function ErrorMessages(_ref) {
  var fileRejections = _ref.fileRejections,
    maxFileSizeInBytes = _ref.maxFileSizeInBytes;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var hasMultipleFileErrors = fileRejections.some(function (_ref2) {
    var errors = _ref2.errors;
    return errors[0].code === ERROR_CODES.TOO_MANY_FILES;
  });
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [hasMultipleFileErrors && /*#__PURE__*/jsxRuntime.jsx("p", {
      className: "neeto-molecules-input__error-text",
      "data-testid": "form-file-upload-input-error",
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        className: "neeto-molecules-input__error-text-style-handle",
        children: t("neetoMolecules.fileUpload.filesDropzone.errors.tooManyFiles", {
          maxFiles: 1
        })
      })
    }), fileRejections.filter(function (_ref3) {
      var errors = _ref3.errors;
      return errors[0].code !== ERROR_CODES.TOO_MANY_FILES;
    }).map(function (file, index) {
      return /*#__PURE__*/jsxRuntime.jsx("p", {
        className: "neeto-molecules-input__error-text",
        "data-testid": "form-file-upload-input-error",
        children: /*#__PURE__*/jsxRuntime.jsx("span", {
          className: "neeto-molecules-input__error-text-style-handle",
          children: renderErrorMessage(file, maxFileSizeInBytes, false)
        })
      }, index);
    })]
  });
};

var css = ".neeto-ui-theme--dark,.neeto-ui-theme--light,:root{--neeto-molecules-file-upload-dropzone-color:var(--neeto-ui-gray-800),1;--neeto-molecules-file-upload-dropzone-help-text-color:var(--neeto-ui-gray-700),1;--neeto-molecules-file-upload-dropzone-icon-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-dropzone-background-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-dropzone-hover-background-color:var(--neeto-ui-gray-100,1);--neeto-molecules-file-upload-dropzone-border-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-border-radius:var(--neeto-ui-rounded-md);--neeto-molecules-file-upload-transition:var(--neeto-ui-transition);--neeto-molecules-file-upload-list-item-border-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-list-item-background-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-preview-icon-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-progress-ring-background-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-success-background-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-success-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-cancel-background-color:var(--neeto-ui-error-500),1;--neeto-molecules-file-upload-cancel-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-error-color:var(--neeto-ui-error-500),1;--neeto-molecules-file-upload-error-background-color:var(--neeto-ui-white),1}.neeto-molecules-file-upload__dropzone{background-color:rgba(var(--neeto-molecules-file-upload-dropzone-background-color));border:2px dashed rgba(var(--neeto-molecules-file-upload-dropzone-border-color));border-radius:var(--neeto-molecules-file-upload-border-radius);color:rgba(var(--neeto-molecules-file-upload-dropzone-color));padding:1.5em;transition:var(--neeto-molecules-file-upload-transition)}@media (prefers-reduced-motion:reduce){.neeto-molecules-file-upload__dropzone{transition:none}}.neeto-molecules-file-upload__dropzone:hover{background-color:rgba(var(--neeto-molecules-file-upload-dropzone-hover-background-color))}.neeto-molecules-file-upload__dropzone-inner{text-align:center}.neeto-molecules-file-upload__upload-icon{color:rgba(var(--neeto-molecules-file-upload-dropzone-icon-color));display:block;margin-bottom:1.25em;margin-inline-end:auto;margin-inline-start:auto}.neeto-molecules-file-upload__upload-label{display:flex;font-size:1rem;gap:.3125em;justify-content:center}.neeto-molecules-file-upload__choose-file{font-weight:500}.neeto-molecules-file-upload__dropzone-helper-block{margin-top:.5em}.neeto-molecules-file-upload__dropzone-helper-text{color:rgba(var(--neeto-molecules-file-upload-dropzone-help-text-color));display:block;font-size:.75rem;line-height:1.2;margin-bottom:.5rem}.neeto-molecules-file-upload__uploaded-list{list-style:none;margin:1.25em 0;padding:0}.neeto-molecules-file-upload__uploaded-list-item{align-items:center;background-color:rgba(var(--neeto-molecules-file-upload-list-item-background-color));border:1px solid rgba(var(--neeto-molecules-file-upload-list-item-border-color));display:flex;gap:.75em;list-style:none;margin-bottom:-.0625rem;padding:.5em .75em}.neeto-molecules-file-upload__uploaded-list-item:first-of-type{border-start-end-radius:var(--neeto-molecules-file-upload-border-radius);border-start-start-radius:var(--neeto-molecules-file-upload-border-radius)}.neeto-molecules-file-upload__uploaded-list-item:last-of-type{border-end-end-radius:var(--neeto-molecules-file-upload-border-radius);border-end-start-radius:var(--neeto-molecules-file-upload-border-radius)}.neeto-molecules-file-upload__file-preview{color:rgba(var(--neeto-molecules-file-upload-preview-icon-color));position:relative}.neeto-molecules-file-upload__file-preview .neeto-molecules-progress{align-items:center;display:flex;height:100%;inset-inline-start:0;justify-content:center;position:absolute;top:0;width:100%}.neeto-molecules-file-upload__file-preview .neeto-molecules-progress__circle-wrapper{color:rgba(var(--neeto-molecules-file-upload-progress-ring-background-color));position:relative}.neeto-molecules-file-upload__file-info{word-wrap:break-word;display:flex;flex-direction:column;flex-grow:1;min-width:0;overflow-wrap:break-word}.neeto-molecules-file-upload__file-info-name{font-size:.875em;margin-bottom:.3125em}.neeto-molecules-file-upload__file-info-size{color:rgba(var(--neeto-molecules-file-upload-dropzone-help-text-color));font-size:.75em}.neeto-molecules-file-upload__actions{flex-shrink:0;margin-inline-start:auto;position:relative}.neeto-molecules-file-upload__success-indicator{align-items:center;border-radius:100%;display:inline-flex;height:1.75em;justify-content:center;width:1.75em}.neeto-molecules-file-upload__success-indicator.neeto-molecules-file-upload__success-indicator--active{background-color:rgba(var(--neeto-molecules-file-upload-success-background-color));color:rgba(var(--neeto-molecules-file-upload-success-color))}.neeto-molecules-file-upload__button--red{align-items:center;background-color:rgba(var(--neeto-molecules-file-upload-cancel-background-color));border-radius:100%;color:rgba(var(--neeto-molecules-file-upload-cancel-color));display:inline-flex;height:1.75em;justify-content:center;width:1.75em}.neeto-molecules-file-upload__remove-button{inset-inline-start:0;opacity:0;position:absolute;top:0;transition:var(--neeto-molecules-file-upload-transition);visibility:hidden}@media (prefers-reduced-motion:reduce){.neeto-molecules-file-upload__remove-button{transition:none}}.neeto-molecules-file-upload__actions:hover .neeto-molecules-file-upload__remove-button{opacity:1;visibility:visible}.neeto-molecules-invisible{visibility:hidden}.neeto-molecules-input__error-text{font-size:.875rem;line-height:1.2;margin-top:.5em}.neeto-molecules-input__error-text-style-handle{background-color:rgba(var(--neeto-molecules-file-upload-error-background-color));border-radius:.1875rem;color:rgba(var(--neeto-molecules-file-upload-error-color));display:inline-block;font-size:.875rem;line-height:1.2;padding:.1875rem .375rem}";
injectCss.n(css,{});

var Progress = function Progress(_ref) {
  var percents = _ref.percents,
    _ref$stroke = _ref.stroke,
    stroke = _ref$stroke === void 0 ? "currentColor" : _ref$stroke,
    _ref$emptyStroke = _ref.emptyStroke,
    emptyStroke = _ref$emptyStroke === void 0 ? stroke : _ref$emptyStroke,
    _ref$emptyStrokeOpaci = _ref.emptyStrokeOpacity,
    emptyStrokeOpacity = _ref$emptyStrokeOpaci === void 0 ? 0.25 : _ref$emptyStrokeOpaci,
    _ref$duration = _ref.duration,
    duration = _ref$duration === void 0 ? 0.5 : _ref$duration,
    _ref$delay = _ref.delay,
    delay = _ref$delay === void 0 ? 0 : _ref$delay,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 100 : _ref$size,
    _ref$strokeWidth = _ref.strokeWidth,
    strokeWidth = _ref$strokeWidth === void 0 ? 12 : _ref$strokeWidth;
  var shouldReduceMotion = framerMotion.useReducedMotion();
  var radius = 45;
  var circumference = Math.ceil(2 * Math.PI * radius);
  var fillPercents = Math.abs(Math.ceil(circumference / 100 * (percents - 100)));
  var transition = {
    duration: shouldReduceMotion ? 0 : duration,
    delay: shouldReduceMotion ? 0 : delay
  };
  var variants = {
    hidden: {
      strokeDashoffset: circumference,
      transition: transition
    },
    show: {
      strokeDashoffset: fillPercents,
      transition: transition
    }
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "neeto-molecules-progress__circle",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-molecules-progress__circle-wrapper",
      style: {
        height: size
      },
      children: [/*#__PURE__*/jsxRuntime.jsx("svg", {
        height: size,
        version: "1.1",
        viewBox: "0 0 100 100",
        width: size,
        xmlns: "http://www.w3.org/2000/svg",
        children: /*#__PURE__*/jsxRuntime.jsx("circle", {
          strokeWidth: strokeWidth,
          className: "circle",
          cx: "50",
          cy: "50",
          fill: "transparent",
          r: radius,
          stroke: emptyStroke,
          strokeOpacity: emptyStrokeOpacity
        })
      }), /*#__PURE__*/jsxRuntime.jsx("svg", {
        height: size,
        viewBox: "0 0 100 100",
        width: size,
        style: {
          position: "absolute",
          transform: "rotate(-90deg)",
          overflow: "visible",
          top: 0
        },
        children: /*#__PURE__*/jsxRuntime.jsx(framerMotion.motion.circle, {
          stroke: stroke,
          strokeWidth: strokeWidth,
          variants: variants,
          animate: "show",
          cx: "50",
          cy: "50",
          fill: "transparent",
          initial: "hidden",
          r: radius,
          strokeDasharray: circumference,
          strokeDashoffset: fillPercents
        })
      })]
    })
  });
};

var FilePreview = function FilePreview(_ref) {
  var file = _ref.file,
    isUploading = _ref.isUploading,
    cancel = _ref.cancel,
    progress = _ref.progress;
  return /*#__PURE__*/jsxRuntime.jsxs("li", {
    className: "neeto-molecules-file-upload__uploaded-list-item",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-molecules-file-upload__file-preview",
      children: [/*#__PURE__*/jsxRuntime.jsx("a", {
        className: classnames({
          "neeto-molecules-invisible": isUploading
        }),
        href: file.url,
        rel: "noreferrer",
        target: "_blank",
        children: /*#__PURE__*/jsxRuntime.jsx(FileGeneric, {})
      }), isUploading && /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "neeto-molecules-progress",
        children: /*#__PURE__*/jsxRuntime.jsx(Progress, {
          percents: progress || 0,
          size: 20
        })
      })]
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-molecules-file-upload__file-info",
      children: [/*#__PURE__*/jsxRuntime.jsx("span", {
        className: "neeto-molecules-file-upload__file-info-name",
        "data-testid": "file-name",
        children: file.name
      }), /*#__PURE__*/jsxRuntime.jsx("span", {
        className: "neeto-molecules-file-upload__file-info-size",
        children: file.size ? "".concat(convertBytesToMb(file.size), " MB") : ""
      })]
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-molecules-file-upload__actions",
      children: [/*#__PURE__*/jsxRuntime.jsx("span", {
        className: classnames("neeto-molecules-file-upload__success-indicator", {
          "neeto-molecules-file-upload__success-indicator--active": file.url
        }),
        children: file.url && /*#__PURE__*/jsxRuntime.jsx(Check, {
          "data-testid": "file-upload-success"
        })
      }), /*#__PURE__*/jsxRuntime.jsx("button", {
        className: "neeto-molecules-file-upload__button--red neeto-molecules-file-upload__remove-button",
        type: "button",
        onClick: cancel,
        children: /*#__PURE__*/jsxRuntime.jsx(Close, {})
      })]
    })]
  }, file.url);
};

function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var useFileUpload = function useFileUpload(_ref) {
  var disabled = _ref.disabled,
    accept = _ref.accept,
    multiple = _ref.multiple,
    maxFileSize = _ref.maxFileSize,
    minFileSize = _ref.minFileSize,
    files = _ref.files,
    onChange = _ref.onChange,
    setError = _ref.setError,
    setTouched = _ref.setTouched,
    hasFileSizeLimit = _ref.hasFileSizeLimit;
  var _useState = React.useState({}),
    _useState2 = _slicedToArray(_useState, 2),
    uploadProgress = _useState2[0],
    setUploadProgress = _useState2[1];
  var _useState3 = React.useState(""),
    _useState4 = _slicedToArray(_useState3, 2),
    uploadError = _useState4[0],
    setUploadError = _useState4[1];
  var filesRef = React.useRef(files);
  filesRef.current = files;
  var cancel = React.useCallback(function (index) {
    return function () {
      setUploadProgress(ramda.assoc(files[index].name, null));
      var newFiles = files === null || files === void 0 ? void 0 : files.filter(function (_, idx) {
        return idx !== index;
      });
      onChange(newFiles);
    };
  }, [files]);
  React.useEffect(function () {
    uploadError && setError(uploadError);
  }, [uploadError]);
  var onDropAccepted = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(acceptedFiles) {
      var initialFiles, updatedFiles, newFiles, _updatedFiles;
      return _regenerator().w(function (_context) {
        while (1) switch (_context.n) {
          case 0:
            setTouched(false);
            setUploadError("");
            initialFiles = acceptedFiles.map(function (file) {
              return {
                name: file.name,
                size: file.size
              };
            });
            updatedFiles = multiple ? [].concat(_toConsumableArray(files || []), _toConsumableArray(initialFiles)) : initialFiles;
            onChange(updatedFiles);
            _context.n = 1;
            return new Promise(function (resolve) {
              var files = [];
              acceptedFiles.forEach(function (file) {
                setUploadProgress(ramda.assoc(file.name, 0));
                var upload = new activestorage.DirectUpload(file, DIRECT_UPLOAD_URL, {
                  directUploadWillStoreFileWithXHR: function directUploadWillStoreFileWithXHR(xhr) {
                    xhr.upload.addEventListener("progress", function (event) {
                      var percentComplete = Math.round(event.loaded / event.total * 100);
                      setUploadProgress(ramda.assoc(file.name, percentComplete));
                    });
                    xhr.upload.addEventListener("load", function () {
                      setUploadProgress(ramda.assoc(file.name, undefined));
                    });
                  }
                });
                upload.create(function (error, blob) {
                  if (error) {
                    return setUploadError(error);
                  }
                  files.push({
                    url: blob.blob_url,
                    name: blob.filename,
                    signedId: blob.signed_id
                  });
                  var isUploadCompleted = multiple ? acceptedFiles.length === files.length : files.length === 1;
                  if (isUploadCompleted) {
                    return resolve(files);
                  }
                  return "";
                });
              });
              return files;
            });
          case 1:
            newFiles = _context.v;
            if (multiple) {
              _updatedFiles = filesRef.current.map(function (file) {
                var uploadedFile = neetoCist.findBy({
                  name: file.name
                }, newFiles);
                return _objectSpread$1(_objectSpread$1({}, file), uploadedFile);
              });
              onChange(_updatedFiles);
            } else {
              onChange(newFiles);
            }
          case 2:
            return _context.a(2);
        }
      }, _callee);
    }));
    return function onDropAccepted(_x) {
      return _ref2.apply(this, arguments);
    };
  }();
  var onDropRejected = function onDropRejected(fileRejections) {
    fileRejections.forEach(function (fileObject) {
      setTouched(true);
      if (fileObject.errors[0].code === "too-many-files") {
        setUploadError(renderErrorMessage(fileObject, maxFileSize, multiple));
      } else {
        setUploadError(renderErrorMessage(fileObject, maxFileSize, multiple));
      }
    });
  };
  var _useDropzone = reactDropzone.useDropzone(_objectSpread$1({
      disabled: disabled,
      accept: accept,
      multiple: multiple,
      minSize: convertMbToBytes(minFileSize),
      onDropAccepted: onDropAccepted,
      onDropRejected: onDropRejected
    }, maxFileSize && hasFileSizeLimit && {
      maxSize: convertMbToBytes(maxFileSize)
    })),
    getRootProps = _useDropzone.getRootProps,
    getInputProps = _useDropzone.getInputProps,
    isDragActive = _useDropzone.isDragActive,
    fileRejections = _useDropzone.fileRejections;
  return {
    progress: uploadProgress,
    cancel: cancel,
    getRootProps: getRootProps,
    getInputProps: getInputProps,
    isDragActive: isDragActive,
    fileRejections: fileRejections
  };
};

var FileUpload = function FileUpload(_ref) {
  var _ref$allowedFileTypes = _ref.allowedFileTypes,
    allowedFileTypes = _ref$allowedFileTypes === void 0 ? "" : _ref$allowedFileTypes,
    _ref$multipleFilesAll = _ref.multipleFilesAllowed,
    multipleFilesAllowed = _ref$multipleFilesAll === void 0 ? true : _ref$multipleFilesAll,
    _ref$maxFileSize = _ref.maxFileSize,
    maxFileSize = _ref$maxFileSize === void 0 ? MAX_FILE_SIZE : _ref$maxFileSize,
    _ref$hasFileSizeLimit = _ref.hasFileSizeLimit,
    hasFileSizeLimit = _ref$hasFileSizeLimit === void 0 ? true : _ref$hasFileSizeLimit,
    _ref$isPreview = _ref.isPreview,
    isPreview = _ref$isPreview === void 0 ? false : _ref$isPreview,
    _ref$minFileSize = _ref.minFileSize,
    minFileSize = _ref$minFileSize === void 0 ? 0 : _ref$minFileSize,
    _ref$files = _ref.files,
    files = _ref$files === void 0 ? [] : _ref$files,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? neetoCist.noop : _ref$onChange,
    error = _ref.error,
    _ref$setError = _ref.setError,
    setError = _ref$setError === void 0 ? neetoCist.noop : _ref$setError,
    _ref$setTouched = _ref.setTouched,
    setTouched = _ref$setTouched === void 0 ? neetoCist.noop : _ref$setTouched;
  var _useFileUpload = useFileUpload({
      disabled: isPreview,
      accept: getAcceptedFileTypes(allowedFileTypes),
      multiple: multipleFilesAllowed,
      maxFileSize: maxFileSize,
      minFileSize: minFileSize,
      files: files,
      onChange: onChange,
      setError: setError,
      setTouched: setTouched,
      hasFileSizeLimit: hasFileSizeLimit
    }),
    progress = _useFileUpload.progress,
    cancel = _useFileUpload.cancel,
    getRootProps = _useFileUpload.getRootProps,
    getInputProps = _useFileUpload.getInputProps,
    isDragActive = _useFileUpload.isDragActive,
    fileRejections = _useFileUpload.fileRejections;
  var maxFileSizeInBytes = maxFileSize * 1000000;
  var isUploadingFile = function isUploadingFile(file) {
    return ramda.isNotNil(progress[file.name]) && (progress[file.name] !== 100 || !file.url);
  };
  var shouldShowError = error && ramda.isEmpty(fileRejections);
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsx(DropZone, {
      allowedFileTypes: allowedFileTypes,
      getInputProps: getInputProps,
      getRootProps: getRootProps,
      hasFileSizeLimit: hasFileSizeLimit,
      isDragActive: isDragActive,
      maxFileSize: maxFileSize,
      multipleFilesAllowed: multipleFilesAllowed
    }), !ramda.isEmpty(files) && /*#__PURE__*/jsxRuntime.jsx("ul", {
      className: "neeto-molecules-file-upload__uploaded-list",
      children: files === null || files === void 0 ? void 0 : files.map(function (file, idx) {
        return /*#__PURE__*/React.createElement(FilePreview, {
          file: file,
          cancel: cancel(idx),
          isUploading: isUploadingFile(file),
          key: idx,
          progress: progress[file.name]
        });
      })
    }), neetoCist.isNotEmpty(fileRejections) && /*#__PURE__*/jsxRuntime.jsx(ErrorMessages, {
      fileRejections: fileRejections,
      maxFileSizeInBytes: maxFileSizeInBytes
    }), shouldShowError && /*#__PURE__*/jsxRuntime.jsx("p", {
      className: "neeto-molecules-input__error-text",
      "data-testid": "form-file-upload-input-error",
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        className: "neeto-molecules-input__error-text-style-handle",
        children: error
      })
    })]
  });
};

var _excluded = ["name"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikFileUpload = function FormikFileUpload(_ref) {
  var name = _ref.name,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useField = formik.useField(name),
    _useField2 = _slicedToArray(_useField, 3);
    _useField2[0];
    var _useField2$ = _useField2[1],
    value = _useField2$.value,
    touched = _useField2$.touched,
    error = _useField2$.error,
    _useField2$2 = _useField2[2],
    setValue = _useField2$2.setValue,
    setTouched = _useField2$2.setTouched,
    setError = _useField2$2.setError;
  var errorToDisplay = touched && error ? error : "";
  return /*#__PURE__*/jsxRuntime.jsx(FileUpload, _objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, props), {}, {
    setError: setError,
    setTouched: setTouched
  })), {}, {
    error: errorToDisplay,
    files: value,
    onChange: setValue
  }));
};

exports.FileUpload = FileUpload;
exports.FormikFileUpload = FormikFileUpload;
//# sourceMappingURL=FileUpload.js.map
