"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;exports.__esModule = true;exports.FileUploaderFileDataTids = exports.FileUploaderFile = void 0;var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _react = _interopRequireWildcard(require("react"));
var _globalObject = require("@skbkontur/global-object");

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

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





var _fileUtils = require("../../internal/FileUploaderControl/fileUtils");
var _utils = require("../../lib/utils");
var _TextWidthHelper = require("../../internal/TextWidthHelper/TextWidthHelper");
var _stringUtils = require("../../lib/stringUtils");
var _Emotion = require("../../lib/theming/Emotion");
var _ThemeContext = require("../../lib/theming/ThemeContext");
var _keyListener = require("../../lib/events/keyListener");
var _identifiers = require("../../lib/events/keyboard/identifiers");

var _Hint = require("../Hint");
var _Tooltip = require("../Tooltip");
var _getDOMRect = require("../../lib/dom/getDOMRect");
var _useFileUploaderSize = require("../../internal/FileUploaderControl/hooks/useFileUploaderSize");

var _FileUploaderFileStatusIcon = require("../../internal/FileUploaderControl/FileUploaderFile/icons/FileUploaderFileStatusIcon");
var _FileUploaderFileTypeIcon = require("../../internal/FileUploaderControl/FileUploaderFile/icons/FileUploaderFileTypeIcon");
var _FileUploaderFile = require("../../internal/FileUploaderControl/FileUploaderFile/FileUploaderFile.styles");




var _LoadingIcon = require("../../internal/icons2022/LoadingIcon");var _excluded = ["file", "showSize", "previewImg", "error", "warning", "multiple", "disabled", "hovered", "focused", "size", "view", "withValidationTooltip", "validationTooltipPosition", "withWarningIcon", "onRemove", "showFilenameHint", "fileTypeIcon"];






































var splitFileNameAndExtension = function splitFileNameAndExtension(filename) {
  var lastDotIndex = filename.lastIndexOf('.');
  if (lastDotIndex === -1) {
    return { name: filename, extension: '' };
  }
  var name = filename.substring(0, lastDotIndex);
  var extension = filename.substring(lastDotIndex + 1);
  return { name: name, extension: extension };
};

var getTruncatedName = function getTruncatedName(fileNameWidth, fileNameElementWidth, name, isTileView) {if (isTileView === void 0) {isTileView = false;}
  if (!fileNameWidth && !fileNameElementWidth) {
    return null;
  }

  if (fileNameWidth <= fileNameElementWidth) {
    return name;
  }

  var charWidth = Math.ceil(fileNameWidth / name.length);
  var maxCharsCountInSpan = Math.ceil(fileNameElementWidth / charWidth);

  if (isTileView) {
    var splitFileName = splitFileNameAndExtension(name);
    return (0, _stringUtils.truncate)(splitFileName.name, maxCharsCountInSpan) + "." + splitFileName.extension;
  }

  return (0, _stringUtils.truncate)(name, maxCharsCountInSpan);
};

var calcTruncatedName = function calcTruncatedName(
textHelperRef,
fileNameElementRef,
name,
isTileView)
{var _textHelperRef$curren;if (isTileView === void 0) {isTileView = false;}
  var fileNameWidth = ((_textHelperRef$curren = textHelperRef.current) == null ? void 0 : _textHelperRef$curren.getTextWidth()) || 0;
  var fileNameElementWidth = isTileView ?
  // даем возможность занять 2 строки с погрешностью в 50%
  (0, _getDOMRect.getDOMRect)(fileNameElementRef.current).width * 1.5 :
  (0, _getDOMRect.getDOMRect)(fileNameElementRef.current).width;

  return getTruncatedName(fileNameWidth, fileNameElementWidth, name, isTileView);
};

var FileUploaderFileDataTids = exports.FileUploaderFileDataTids = {
  file: 'FileUploader__file',
  fileTooltip: 'FileUploader__fileTooltip',
  fileName: 'FileUploader__fileName',
  fileSize: 'FileUploader__fileSize',
  fileIcon: 'FileUploader__fileIcon',
  fileTypeIcon: 'FileUploader__fileTypeIcon'
};

/**
 * Компонент файла `FileUploaderFile` из FileUploader для отрисовки загруженного файла.
 */
var FileUploaderFile = exports.FileUploaderFile = (0, _forwardRefAndName.forwardRefAndName)(
  'FileUploaderFile',
  function (props, ref) {var _cx, _cx2, _ref, _ref2;
    var
      file =

















      props.file,_props$showSize = props.showSize,showSize = _props$showSize === void 0 ? false : _props$showSize,previewImg = props.previewImg,error = props.error,warning = props.warning,multiple = props.multiple,_props$disabled = props.disabled,disabled = _props$disabled === void 0 ? false : _props$disabled,_props$hovered = props.hovered,hovered = _props$hovered === void 0 ? false : _props$hovered,_props$focused = props.focused,focused = _props$focused === void 0 ? false : _props$focused,size = props.size,_props$view = props.view,view = _props$view === void 0 ? 'row' : _props$view,withValidationTooltip = props.withValidationTooltip,validationTooltipPosition = props.validationTooltipPosition,withWarningIcon = props.withWarningIcon,onRemove = props.onRemove,_props$showFilenameHi = props.showFilenameHint,showFullFilename = _props$showFilenameHi === void 0 ? true : _props$showFilenameHi,fileTypeIcon = props.fileTypeIcon,rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
    var id = file.id,originalFile = file.originalFile,status = file.status,validationResult = file.validationResult;
    var name = originalFile.name,fileSize = originalFile.size;

    var _useState = (0, _react.useState)(hovered || false),hoveredFile = _useState[0],setHoveredFile = _useState[1];
    var _useState2 = (0, _react.useState)(focused || false),focusedByTab = _useState2[0],setFocusedByTab = _useState2[1];
    var _useState3 = (0, _react.useState)(null),truncatedFileName = _useState3[0],setTruncatedFileName = _useState3[1];

    var textHelperRef = (0, _react.useRef)(null);
    var fileNameElementRef = (0, _react.useRef)(null);

    var theme = (0, _react.useContext)(_ThemeContext.ThemeContext);

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

    var isLoading = status === _fileUtils.FileUploaderFileStatus.Loading;
    var isTileView = versionGTE5_5 && view === 'tile';
    var jsViewStyles = isTileView ? _FileUploaderFile.jsTileStyles : _FileUploaderFile.jsRowStyles;
    var validationTooltipPositionByView = validationTooltipPosition || (isTileView ? 'top center' : 'top left');

    var formattedSize = (0, _react.useMemo)(function () {return (0, _utils.formatBytes)(fileSize, 1);}, [fileSize]);

    (0, _react.useEffect)(function () {
      var truncatedName = calcTruncatedName(textHelperRef, fileNameElementRef, name, isTileView);

      setTruncatedFileName(truncatedName);
    });

    var handleRemove = (0, _react.useCallback)(
      function (event) {
        event.preventDefault();
        event.stopPropagation();
        onRemove(id);
      },
      [id, onRemove]
    );

    var isValid = validationResult.isValid,message = validationResult.message;

    var isError = file.status === _fileUtils.FileUploaderFileStatus.Error || error;
    var isWarning = file.status === _fileUtils.FileUploaderFileStatus.Warning || warning;
    var isInvalid = isError || !isValid;

    var sizeIconClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
      small: jsViewStyles.iconSmall(theme),
      medium: jsViewStyles.iconMedium(theme),
      large: jsViewStyles.iconLarge(theme)
    });

    var renderTooltipContent = (0, _react.useCallback)(function () {
      return !isValid && !error && message ? message : null;
    }, [isValid, error, message]);

    var sizeNameBlockClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
      small: _FileUploaderFile.jsStyles.contentSmall(theme),
      medium: _FileUploaderFile.jsStyles.contentMedium(theme),
      large: _FileUploaderFile.jsStyles.contentLarge(theme)
    });

    var sizeViewNameBlockClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
      small: jsViewStyles.contentSmall(theme),
      medium: jsViewStyles.contentMedium(theme),
      large: jsViewStyles.contentLarge(theme)
    });

    var validationTextClassName = (0, _Emotion.cx)((_cx = {}, _cx[
    _FileUploaderFile.jsStyles.validationTextWarning(theme)] = isWarning, _cx[
    _FileUploaderFile.jsStyles.validationTextError(theme)] = isError, _cx)
    );

    var contentClassNames = (0, _Emotion.cx)(
      _FileUploaderFile.jsStyles.content(),
      jsViewStyles.content(),
      !versionGTE5_5 && (error || !isValid) && _FileUploaderFile.jsStyles.error(theme)
    );
    var nameTextClassNames = (0, _Emotion.cx)(jsViewStyles.name(), isTileView && !disabled && validationTextClassName);

    var handleMouseEnter = (0, _react.useCallback)(function () {
      setHoveredFile(true);
    }, []);

    var handleMouseLeave = (0, _react.useCallback)(function () {
      setHoveredFile(false);
    }, []);

    var handleFocus = (0, _react.useCallback)(function () {
      // 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);
        }
      });
    }, []);

    var handleBlur = (0, _react.useCallback)(function () {
      setFocusedByTab(false);
    }, []);

    var handleIconKeyDown = (0, _react.useCallback)(
      function (e) {
        if ((0, _identifiers.isKeyEnter)(e)) {
          onRemove(id);
        }
      },
      [onRemove, id]
    );

    var iconClassNames = (0, _Emotion.cx)(_FileUploaderFile.jsStyles.icon(theme), (_cx2 = {}, _cx2[
    _FileUploaderFile.jsStyles.icon5_5(theme)] = versionGTE5_5, _cx2[
    _FileUploaderFile.jsStyles.iconMultiple()] = !versionGTE5_5 && multiple, _cx2[
    sizeIconClass] = versionGTE5_5, _cx2[
    _FileUploaderFile.jsTileStyles.iconAction(theme)] = isTileView, _cx2[
    _FileUploaderFile.jsTileStyles.iconActionShow()] = isTileView && !disabled && (hovered || hoveredFile || focused || focusedByTab), _cx2)
    );

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

    var sizeClassNames = (0, _Emotion.cx)(
      _FileUploaderFile.jsStyles.size(theme),
      versionGTE5_5 && (_ref = {}, _ref[
      sizeClassName] = true, _ref[
      jsViewStyles.size(theme)] = true, _ref[
      _FileUploaderFile.jsTileStyles.sizeDisabled(theme)] = isTileView && disabled, _ref)

    );

    var sizeFileTypeIconClass = (0, _useFileUploaderSize.useFileUploaderSize)(size, {
      small: jsViewStyles.fileTypeIconSmall(theme),
      medium: jsViewStyles.fileTypeIconMedium(theme),
      large: jsViewStyles.fileTypeIconLarge(theme)
    });

    var isTruncated = truncatedFileName !== name;

    var fileTypeIconClassName = (0, _Emotion.cx)(
      sizeFileTypeIconClass,
      disabled && _FileUploaderFile.jsStyles.disabledFileTypeIconSvg(theme),
      isTileView && (_ref2 = {}, _ref2[
      _FileUploaderFile.jsTileStyles.fileTypeIcon(theme)] = true, _ref2[
      _FileUploaderFile.jsTileStyles.fileTypeIconPreview()] = !!previewImg, _ref2[
      _FileUploaderFile.jsTileStyles.disabledFileTypeIcon(theme)] = disabled, _ref2[
      _FileUploaderFile.jsTileStyles.warningFileTypeIcon(theme)] = isWarning, _ref2[
      _FileUploaderFile.jsTileStyles.errorFileTypeIcon(theme)] = isError, _ref2),

      multiple && _FileUploaderFile.jsStyles.fileTypeIconMultiple()
    );

    var nameBlockClassNames = (0, _Emotion.cx)(
      sizeNameBlockClass,
      versionGTE5_5 && sizeViewNameBlockClass,
      _FileUploaderFile.jsStyles.nameBlock(),
      disabled && jsViewStyles.disabled(theme),
      jsViewStyles.nameBlock()
    );

    var fileType = (0, _fileUtils.getFileUploaderTypeIcon)(
      file.originalFile,
      isError,
      isWarning && !!withWarningIcon
    );
    var icon =
    isTileView && isLoading ? /*#__PURE__*/
    _react.default.createElement(_LoadingIcon.LoadingIcon, { size: size }) :

    fileTypeIcon != null ? fileTypeIcon : /*#__PURE__*/_react.default.createElement(_FileUploaderFileTypeIcon.FileUploaderFileTypeIcon, { type: fileType, size: size, view: view });


    var splitTruncatedFileName = truncatedFileName && splitFileNameAndExtension(truncatedFileName);

    return /*#__PURE__*/(
      _react.default.createElement(_CommonWrapper.CommonWrapper, rest, /*#__PURE__*/
      _react.default.createElement("div", {
        "data-tid": FileUploaderFileDataTids.file,
        className: _FileUploaderFile.jsStyles.root(),
        onMouseEnter: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        ref: ref }, /*#__PURE__*/

      _react.default.createElement(_Tooltip.Tooltip, {
        "data-tid": FileUploaderFileDataTids.fileTooltip,
        pos: versionGTE5_5 ? validationTooltipPositionByView : 'right middle',
        render: function render() {return withValidationTooltip || isTileView || !versionGTE5_5 ? renderTooltipContent() : null;} }, /*#__PURE__*/

      _react.default.createElement("div", { className: contentClassNames },
      versionGTE5_5 && /*#__PURE__*/
      _react.default.createElement("div", {
        "data-tid": FileUploaderFileDataTids.fileTypeIcon,
        className: fileTypeIconClassName,
        style: previewImg ? { backgroundImage: "url(" + previewImg + ")" } : undefined },

      (!isTileView || !previewImg) && icon
      ), /*#__PURE__*/

      _react.default.createElement("div", { className: nameBlockClassNames }, /*#__PURE__*/
      _react.default.createElement(_TextWidthHelper.TextWidthHelper, { ref: textHelperRef, text: name }), /*#__PURE__*/
      _react.default.createElement(_Hint.Hint, { maxWidth: '100%', text: showFullFilename && isTruncated ? name : null }, /*#__PURE__*/
      _react.default.createElement("span", {
        "data-tid": FileUploaderFileDataTids.fileName,
        ref: fileNameElementRef,
        className: nameTextClassNames },

      splitTruncatedFileName && /*#__PURE__*/
      _react.default.createElement(_react.default.Fragment, null,
      splitTruncatedFileName.name,
      splitTruncatedFileName.extension && /*#__PURE__*/_react.default.createElement("span", null, ".", splitTruncatedFileName.extension)
      )

      )
      ),
      !(withValidationTooltip || isTileView) && versionGTE5_5 && /*#__PURE__*/
      _react.default.createElement("span", { className: validationTextClassName }, renderTooltipContent())

      ),
      showSize && formattedSize && /*#__PURE__*/
      _react.default.createElement("span", { "data-tid": FileUploaderFileDataTids.fileSize, className: sizeClassNames },
      formattedSize
      ), /*#__PURE__*/

      _react.default.createElement("div", {
        className: iconClassNames,
        "data-tid": FileUploaderFileDataTids.fileIcon,
        tabIndex: 0,
        onClick: handleRemove,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onKeyDown: handleIconKeyDown }, /*#__PURE__*/

      _react.default.createElement(_FileUploaderFileStatusIcon.FileUploaderFileStatusIcon, {
        isTileView: isTileView,
        status: status,
        disabled: disabled,
        hovered: hovered || hoveredFile,
        focusedByTab: focused || focusedByTab,
        isInvalid: isInvalid,
        hasValidation: isError || isWarning,
        size: size }
      )
      )
      )
      )
      )
      ));

  }
);