"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;exports.__esModule = true;exports.FileUploaderDataTids = exports.FileUploader = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));var _react = _interopRequireWildcard(require("react"));
var _globalObject = require("@skbkontur/global-object");







var _fileUtils = require("../../internal/FileUploaderControl/fileUtils");
var _Emotion = require("../../lib/theming/Emotion");

var _useMemoObject = require("../../hooks/useMemoObject");
var _FileUploaderControlContext = require("../../internal/FileUploaderControl/FileUploaderControlContext");
var _useControlLocale = require("../../internal/FileUploaderControl/hooks/useControlLocale");
var _useUpload = require("../../internal/FileUploaderControl/hooks/useUpload");
var _useDrop3 = require("../../hooks/useDrop");
var _ThemeContext = require("../../lib/theming/ThemeContext");

var _withFileUploaderControlProvider = require("../../internal/FileUploaderControl/withFileUploaderControlProvider");
var _keyListener = require("../../lib/events/keyListener");

var _FileUploaderFile = require("../../internal/FileUploaderControl/FileUploaderFile/FileUploaderFile");
var _FileUploaderFileList = require("../../internal/FileUploaderControl/FileUploaderFileList/FileUploaderFileList");

var _CommonWrapper = require("../../internal/CommonWrapper");

var _FileUploaderFileValidationResult = require("../../internal/FileUploaderControl/FileUploaderFileValidationResult");
var _useFileUploaderSize = require("../../internal/FileUploaderControl/hooks/useFileUploaderSize");

var _forwardRefAndName = require("../../lib/forwardRefAndName");
var _FocusControlWrapper = require("../../internal/FocusControlWrapper");
var _ThemeHelpers = require("../../lib/theming/ThemeHelpers");


var _UploadIcon = require("./UploadIcon");
var _FileUploader2 = require("./FileUploader.styles");var _excluded = ["disabled", "error", "warning", "withValidationTooltip", "validationTooltipPosition", "withWarningIcon", "multiple", "uploaderText", "uploaderIcon", "view", "uploadButtonPosition", "validationSummary", "validationSummaryStart", "width", "hideFiles", "onBlur", "onFocus", "onChange", "request", "validateBeforeUpload", "onRequestSuccess", "onRequestError", "size", "renderFile"];

var stopPropagation = function stopPropagation(e) {return e.stopPropagation();};













































































































var FileUploaderDataTids = exports.FileUploaderDataTids = {
  root: 'FileUploader__root',
  content: 'FileUploader__content',
  link: 'FileUploader__link',
  input: 'FileUploader__input'
};

var defaultRenderFile = function defaultRenderFile(
_file,
_fileNode,
props) {return /*#__PURE__*/(
    _react.default.createElement(_FileUploaderFile.FileUploaderFile, props));};

var _FileUploader = (0, _forwardRefAndName.forwardRefAndName)('FileUploader', function (props, ref) {var _files$, _files$2, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _cx;
  var theme = (0, _react.useContext)(_ThemeContext.ThemeContext);

  var
    disabled =
























    props.disabled,error = props.error,warning = props.warning,_props$withValidation = props.withValidationTooltip,withValidationTooltip = _props$withValidation === void 0 ? false : _props$withValidation,validationTooltipPosition = props.validationTooltipPosition,_props$withWarningIco = props.withWarningIcon,withWarningIcon = _props$withWarningIco === void 0 ? false : _props$withWarningIco,_props$multiple = props.multiple,multiple = _props$multiple === void 0 ? false : _props$multiple,uploaderText = props.uploaderText,uploaderIcon = props.uploaderIcon,_props$view = props.view,view = _props$view === void 0 ? 'row' : _props$view,_props$uploadButtonPo = props.uploadButtonPosition,uploadButtonPosition = _props$uploadButtonPo === void 0 ? 'start' : _props$uploadButtonPo,_props$validationSumm = props.validationSummary,validationSummary = _props$validationSumm === void 0 ? 'auto' : _props$validationSumm,_props$validationSumm2 = props.validationSummaryStart,validationSummaryStart = _props$validationSumm2 === void 0 ? 5 : _props$validationSumm2,_props$width = props.width,width = _props$width === void 0 ? theme.fileUploaderWidth : _props$width,_props$hideFiles = props.hideFiles,hideFiles = _props$hideFiles === void 0 ? false : _props$hideFiles,onBlur = props.onBlur,onFocus = props.onFocus,onChange = props.onChange,request = props.request,validateBeforeUpload = props.validateBeforeUpload,onRequestSuccess = props.onRequestSuccess,onRequestError = props.onRequestError,_props$size = props.size,size = _props$size === void 0 ? 'small' : _props$size,_props$renderFile = props.renderFile,renderFile = _props$renderFile === void 0 ? defaultRenderFile : _props$renderFile,inputProps = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);

  var _useContext = (0, _react.useContext)(_FileUploaderControlContext.FileUploaderControlContext),files = _useContext.files,setFiles = _useContext.setFiles,removeFile = _useContext.removeFile,reset = _useContext.reset,setFileValidationResult = _useContext.setFileValidationResult;

  var versionGTE5_5 = (0, _ThemeHelpers.isThemeGTE)(theme, '5.5');
  var locale = (0, _useControlLocale.useControlLocale)(versionGTE5_5);

  var inputRef = (0, _react.useRef)(null);
  var fileDivRef = (0, _react.useRef)(null);

  var isAsync = !!request;
  var isSingleMode = !multiple;

  var _useState = (0, _react.useState)(false),hovered = _useState[0],setHovered = _useState[1];
  var upload = (0, _useUpload.useUpload)(request, onRequestSuccess, onRequestError);

  var tryValidateAndUpload = (0, _react.useCallback)(
    function (files) {
      files.forEach( /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(file) {var validationMessage;return _regenerator.default.wrap(function _callee$(_context) {while (1) switch (_context.prev = _context.next) {case 0:_context.t0 =
                validateBeforeUpload;if (!_context.t0) {_context.next = 5;break;}_context.next = 4;return validateBeforeUpload(file);case 4:_context.t0 = _context.sent;case 5:validationMessage = _context.t0;

                if (!validationMessage) {
                  isAsync && upload(file);
                } else if (typeof validationMessage === 'object') {
                  setFileValidationResult(
                    file.id,
                    _FileUploaderFileValidationResult.FileUploaderFileValidationResult.error(validationMessage.message),
                    validationMessage.status
                  );
                } else {
                  setFileValidationResult(
                    file.id,
                    _FileUploaderFileValidationResult.FileUploaderFileValidationResult.error(validationMessage),
                    _fileUtils.FileUploaderFileStatus.Error
                  );
                }case 7:case "end":return _context.stop();}}, _callee);}));return function (_x) {return _ref.apply(this, arguments);};}()
      );
    },
    [validateBeforeUpload, isAsync, upload, setFileValidationResult]
  );

  var isTileView = view === 'tile';
  var jsViewStyles = versionGTE5_5 && isTileView ? _FileUploader2.jsTileStyles : _FileUploader2.jsRowStyles;

  var sizeClassName = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: jsViewStyles.sizeSmall(theme),
    medium: jsViewStyles.sizeMedium(theme),
    large: jsViewStyles.sizeLarge(theme)
  });

  var uploadButtonTileWithFileClassName = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: _FileUploader2.jsTileStyles.uploadButtonTileWithFileSmall(theme),
    medium: _FileUploader2.jsTileStyles.uploadButtonTileWithFileMedium(theme),
    large: _FileUploader2.jsTileStyles.uploadButtonTileWithFileLarge(theme)
  });

  var uploadButtonIconGapClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: jsViewStyles.uploadButtonIconGapSmall(theme),
    medium: jsViewStyles.uploadButtonIconGapMedium(theme),
    large: jsViewStyles.uploadButtonIconGapLarge(theme)
  });

  var sizeIconClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: versionGTE5_5 ? _FileUploader2.jsStyles.iconSmall5_5(theme) : _FileUploader2.jsStyles.iconSmall(theme),
    medium: versionGTE5_5 ? _FileUploader2.jsStyles.iconMedium5_5(theme) : _FileUploader2.jsStyles.iconMedium(theme),
    large: versionGTE5_5 ? _FileUploader2.jsStyles.iconLarge5_5(theme) : _FileUploader2.jsStyles.iconLarge(theme)
  });

  var sizeWrapperClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: _FileUploader2.jsTileStyles.uploadButtonWrapperSmall(theme),
    medium: _FileUploader2.jsTileStyles.uploadButtonWrapperMedium(theme),
    large: _FileUploader2.jsTileStyles.uploadButtonWrapperLarge(theme)
  });

  var sizeWrapperEmptyFileClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: _FileUploader2.jsTileStyles.uploadButtonWrapperEmptyFileSmall(theme),
    medium: _FileUploader2.jsTileStyles.uploadButtonWrapperEmptyFileMedium(theme),
    large: _FileUploader2.jsTileStyles.uploadButtonWrapperEmptyFileLarge(theme)
  });

  var contentInnerClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
    small: _FileUploader2.jsStyles.contentInnerSmall(theme),
    medium: _FileUploader2.jsStyles.contentInnerMedium(theme),
    large: _FileUploader2.jsStyles.contentInnerLarge(theme)
  });

  /** common part **/
  var handleChange = (0, _react.useCallback)(
    function (newFiles) {
      if (!newFiles || !newFiles.length) {
        return;
      }

      var filesArray = Array.from(newFiles);

      if (isSingleMode) {
        filesArray = [filesArray[0]];
      }

      var attachedFiles = filesArray.map(_fileUtils.getAttachedFile);

      if (isSingleMode && attachedFiles.length && files.length) {
        removeFile(files[0].id);
      }

      if (attachedFiles.length) {
        setFiles(attachedFiles);
        tryValidateAndUpload(attachedFiles);
      }
    },
    [tryValidateAndUpload, setFiles, isSingleMode, files, removeFile]
  );

  var handleDrop = (0, _react.useCallback)(
    function (event) {
      if (disabled) {
        return;
      }

      var dataTransfer = event.dataTransfer;
      if (dataTransfer) {var _dataTransfer$files;
        if (isSingleMode && dataTransfer.files.length > 1) {
          dataTransfer.dropEffect = 'none';
          return;
        }
        if (((_dataTransfer$files = dataTransfer.files) == null ? void 0 : _dataTransfer$files.length) > 0) {
          inputRef.current && (inputRef.current.files = dataTransfer.files);
          handleChange(dataTransfer.files);
        }
      }
    },
    [handleChange, disabled]
  );

  var _useDrop = (0, _useDrop3.useDrop)({ onDrop: handleDrop }),isDraggable = _useDrop.isDraggable,labelRef = _useDrop.ref;
  var _useDrop2 = (0, _useDrop3.useDrop)(),isWindowDraggable = _useDrop2.isDraggable,windowRef = _useDrop2.ref;

  if ((0, _globalObject.isBrowser)(_globalObject.globalObject)) {
    windowRef.current = _globalObject.globalObject.document;
  }

  var focus = (0, _react.useCallback)(function () {var _inputRef$current;
    _keyListener.keyListener.isTabPressed = true;
    (_inputRef$current = inputRef.current) == null || _inputRef$current.focus();
  }, []);

  var blur = (0, _react.useCallback)(function () {var _inputRef$current2;
    (_inputRef$current2 = inputRef.current) == null || _inputRef$current2.blur();
  }, []);

  var removeFileFromNativeInput = (0, _react.useCallback)(
    function (fileId) {
      var dataTransfer = new DataTransfer();
      files.
      filter(function (f) {return f.id !== fileId;}).
      forEach(function (file) {
        dataTransfer.items.add(file.originalFile);
      });
      inputRef.current && (inputRef.current.files = dataTransfer.files);
    },
    [files]
  );

  var handleRemoveFile = (0, _react.useCallback)(
    function (fileId) {
      removeFile(fileId);
      removeFileFromNativeInput(fileId);
    },
    [removeFileFromNativeInput, removeFile]
  );

  var handleReset = (0, _react.useCallback)(function () {
    reset();
    var dataTransfer = new DataTransfer();
    inputRef.current && (inputRef.current.files = dataTransfer.files);
  }, [reset, handleRemoveFile]);

  (0, _react.useImperativeHandle)(
    ref,
    function () {return {
        focus: focus,
        blur: blur,
        reset: handleReset,
        removeFile: handleRemoveFile,
        getRootNode: function getRootNode() {return rootNodeRef.current;}
      };},
    [ref, blur, focus, handleReset, handleRemoveFile]
  );

  var _useState2 = (0, _react.useState)(false),focusedByTab = _useState2[0],setFocusedByTab = _useState2[1];
  var handleInputChange = function handleInputChange(event) {
    onChange == null || onChange(event);
    handleChange(event.target.files);
    setHovered(false);
  };

  var handleFocus = function handleFocus(e) {
    if (!disabled) {
      // focus event fires before keyDown eventlistener
      // so we should check tabPressed in async way
      _globalObject.globalObject.requestAnimationFrame == null || _globalObject.globalObject.requestAnimationFrame(function () {
        if (_keyListener.keyListener.isTabPressed) {
          setFocusedByTab(true);
        }
      });
      onFocus == null || onFocus(e);
    }
  };

  var handleBlur = function handleBlur(e) {
    setFocusedByTab(false);
    if (!disabled) {
      onBlur == null || onBlur(e);
    }
  };

  var hasFiles = files.length > 0;
  var hasOneFile = files.length === 1;
  var hasOneFileForSingle = isSingleMode && hasOneFile && !hideFiles;

  var hasError = !!error || ((_files$ = files[0]) == null ? void 0 : _files$.status) === _fileUtils.FileUploaderFileStatus.Error;
  var hasWarning = !!warning || ((_files$2 = files[0]) == null ? void 0 : _files$2.status) === _fileUtils.FileUploaderFileStatus.Warning;

  var uploadButtonClassNames = (0, _Emotion.cx)(
    _FileUploader2.jsStyles.uploadButton(theme),
    jsViewStyles.uploadButton(),
    sizeClassName,
    versionGTE5_5 && hasOneFileForSingle && jsViewStyles.uploadButtonWithFile(theme),
    focusedByTab && _FileUploader2.jsStyles.uploadButtonFocus(theme),
    disabled && (_ref2 = {}, _ref2[
    _FileUploader2.jsStyles.disabled(theme)] = true, _ref2[
    _FileUploader2.jsStyles.disabledBackground(theme)] = !versionGTE5_5 || !hasFiles, _ref2),

    (focusedByTab || !hasOneFileForSingle || !versionGTE5_5) && (_ref3 = {}, _ref3[
    _FileUploader2.jsStyles.warningButton(theme)] = hasWarning, _ref3[
    _FileUploader2.jsStyles.errorButton(theme)] = hasError, _ref3),

    versionGTE5_5 &&
    hasOneFileForSingle && (_ref4 = {}, _ref4[
    uploadButtonTileWithFileClassName] = isTileView, _ref4[
    _FileUploader2.jsStyles.warningFile(theme)] = (!isTileView || hovered) && hasWarning, _ref4[
    _FileUploader2.jsStyles.errorFile(theme)] = (!isTileView || hovered) && hasError, _ref4),

    !disabled &&
    hovered && (_ref5 = {}, _ref5[
    _FileUploader2.jsStyles.hovered(theme)] = true, _ref5[
    _FileUploader2.jsStyles.hoveredBorderColor(theme)] = !versionGTE5_5, _ref5),

    isDraggable && !disabled && _FileUploader2.jsStyles.dragOver(theme)
  );

  var canDrop = isWindowDraggable && !disabled;
  var uploadButtonWrapperClassNames = (0, _Emotion.cx)(
    isTileView && (_ref6 = {}, _ref6[
    sizeWrapperClass] = true, _ref6[
    sizeWrapperEmptyFileClass] = !hasOneFileForSingle, _ref6),

    jsViewStyles.uploadButtonWrapper(),
    canDrop && _FileUploader2.jsStyles.windowDragOver(theme)
  );

  var uploadButtonIconClassNames = (0, _Emotion.cx)(
    _FileUploader2.jsStyles.icon(theme),
    sizeIconClass,
    disabled && _FileUploader2.jsStyles.iconDisabled(theme),
    !versionGTE5_5 && _FileUploader2.jsStyles.iconRight(),
    versionGTE5_5 && uploadButtonIconGapClass
  );

  var rootClassNames = (0, _Emotion.cx)(
    _FileUploader2.jsStyles.root(theme),
    versionGTE5_5 && (_ref7 = {}, _ref7[
    _FileUploader2.jsStyles.root5_5()] = true, _ref7[
    _FileUploader2.jsRowStyles.root()] = !isTileView, _ref7)

  );

  var contentClassNames = (0, _Emotion.cx)(jsViewStyles.content(), (_cx = {}, _cx[
  jsViewStyles.contentWithFiles()] = hasOneFileForSingle, _cx[
  contentInnerClass] = !isTileView && (!files.length || !isSingleMode), _cx)
  );

  var afterLinkTextClassNames = (0, _Emotion.cx)(
    _FileUploader2.globalClasses.afterLinkText,
    hasOneFileForSingle ? _FileUploader2.jsStyles.afterLinkText_HasFiles() : _FileUploader2.jsStyles.afterLinkText(),
    !versionGTE5_5 && _FileUploader2.jsStyles.afterLinkTextColor(theme)
  );

  var linkClassNames = (0, _Emotion.cx)(
    _FileUploader2.jsStyles.link(theme),
    !disabled && hovered && _FileUploader2.jsStyles.linkHovered(theme),
    disabled && _FileUploader2.jsStyles.linkDisabled(theme)
  );

  (0, _react.useEffect)(function () {
    if (!files || !files.length || !inputRef.current) {
      return;
    }

    var dataTransfer = new DataTransfer();
    files.forEach(function (file) {return dataTransfer.items.add(file.originalFile);});
    inputRef.current.files = dataTransfer.files;
  }, []);

  var rootNodeRef = (0, _react.useRef)(null);

  var icon = uploaderIcon != null ? uploaderIcon : /*#__PURE__*/_react.default.createElement(_UploadIcon.UploadIcon, { size: size, view: view });
  var chooseFileText = uploaderText != null ? uploaderText : locale.chooseFile;
  var chooseFileLocale = "" + chooseFileText + String.fromCharCode(0xa0); /* &nbsp; */
  var hideUploaderText = versionGTE5_5 && isTileView && uploaderText === '';
  var renderChooseFileText = function renderChooseFileText() {return (
      !hideUploaderText && /*#__PURE__*/
      _react.default.createElement("span", { "data-tid": FileUploaderDataTids.link, className: linkClassNames },
      versionGTE5_5 && !hasOneFileForSingle && chooseFileLocale,
      !versionGTE5_5 && (hasOneFileForSingle ? locale.choosedFile : locale.chooseFile),
      versionGTE5_5 ? null : String.fromCharCode(0xa0) /* &nbsp; */
      ));};


  var renderFileList = function renderFileList() {
    var propsVersionGTE5_5 = {
      withValidationTooltip: withValidationTooltip,
      validationSummary: validationSummary,
      validationSummaryStart: validationSummaryStart,
      withWarningIcon: withWarningIcon,
      disabled: disabled
    };

    return (
      !hideFiles &&
      !isSingleMode &&
      !!files.length && /*#__PURE__*/
      _react.default.createElement(_FileUploaderFileList.FileUploaderFileList, (0, _extends2.default)({
        renderFile: renderFile,
        size: size,
        view: view,
        onRemove: handleRemoveFile,
        validationTooltipPosition: validationTooltipPosition },
      versionGTE5_5 && propsVersionGTE5_5)
      ));


  };

  var fileProps = {
    file: files[0],
    size: size,
    view: view,
    onRemove: handleRemoveFile,
    error: error,
    warning: warning,
    withValidationTooltip: withValidationTooltip,
    validationTooltipPosition: validationTooltipPosition,
    withWarningIcon: withWarningIcon,
    hovered: hovered,
    disabled: disabled
  };

  var fileElement = renderFile(files[0], /*#__PURE__*/_react.default.createElement(_FileUploaderFile.FileUploaderFile, fileProps), fileProps);

  return /*#__PURE__*/(
    _react.default.createElement(_CommonWrapper.CommonWrapper, props, /*#__PURE__*/
    _react.default.createElement("div", {
      "data-tid": FileUploaderDataTids.root,
      className: rootClassNames,
      style: (0, _useMemoObject.useMemoObject)({ width: isTileView && !multiple ? theme.fileUploaderTileWidth : width }),
      ref: rootNodeRef },

    (!versionGTE5_5 || uploadButtonPosition === 'end') && renderFileList(), /*#__PURE__*/
    _react.default.createElement("div", { className: uploadButtonWrapperClassNames }, /*#__PURE__*/
    _react.default.createElement("label", {
      onMouseEnter: function onMouseEnter() {return setHovered(true);},
      onMouseLeave: function onMouseLeave() {return setHovered(false);},
      ref: labelRef,
      className: uploadButtonClassNames },

    versionGTE5_5 && !hasOneFileForSingle && /*#__PURE__*/_react.default.createElement("div", { className: uploadButtonIconClassNames }, icon), /*#__PURE__*/
    _react.default.createElement("div", { "data-tid": FileUploaderDataTids.content, className: contentClassNames },
    renderChooseFileText(), /*#__PURE__*/
    _react.default.createElement("div", { className: afterLinkTextClassNames },
    hasOneFileForSingle ? /*#__PURE__*/
    _react.default.createElement("div", { ref: fileDivRef, className: _FileUploader2.jsStyles.singleFile() },
    fileElement
    ) :

    !versionGTE5_5 && /*#__PURE__*/
    _react.default.createElement(_react.default.Fragment, null,
    locale.orDragHere, "\xA0", /*#__PURE__*/
    _react.default.createElement("div", { className: uploadButtonIconClassNames }, icon)
    )


    )
    ), /*#__PURE__*/
    _react.default.createElement(_FocusControlWrapper.FocusControlWrapper, { onBlurWhenDisabled: function onBlurWhenDisabled() {return setFocusedByTab(false);} }, /*#__PURE__*/
    _react.default.createElement("input", (0, _extends2.default)({},
    inputProps, {
      "data-tid": FileUploaderDataTids.input,
      ref: inputRef,
      tabIndex: disabled ? -1 : 0,
      type: "file",
      disabled: disabled,
      multiple: multiple,
      className: _FileUploader2.jsStyles.visuallyHidden(),
      onClick: stopPropagation,
      onChange: handleInputChange,
      onFocus: handleFocus,
      onBlur: handleBlur })
    )
    )
    )
    ),
    versionGTE5_5 && uploadButtonPosition === 'start' && renderFileList()
    )
    ));

});



/**
 * `FileUploader` — контрол для выбора пользователем файла на компьютере и отображения статуса его отправки на сервер.
 *
 * Можно использовать для синхронной отправки данных, например, в форме. Или же можно использовать в асинхронном режиме.
 */
var FileUploader = exports.FileUploader = (0, _withFileUploaderControlProvider.withFileUploaderControlProvider)( /*#__PURE__*/
  _react.default.memo(_FileUploader)
);

FileUploader.displayName = 'FileUploader';