require('./TextArea_1yvej8a.css');
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var index = require('../../utils/index.js');
var TextArea_styles = require('./TextArea.styles.js');
var TextArea_tokens = require('./TextArea.tokens.js');
var base$2 = require('./variations/_view/base.js');
var base$1 = require('./variations/_size/base.js');
var base$3 = require('./variations/_read-only/base.js');
var base$4 = require('./variations/_disabled/base.js');
var base$5 = require('./variations/_hint-view/base.js');
var base$6 = require('./variations/_hint-size/base.js');
var Hint = require('./ui/Hint/Hint.js');
var useOutsideClick = require('../../hooks/useOutsideClick.js');
var useAutoResize = require('./hooks/useAutoResize.js');
var useResizeObserver = require('../../hooks/useResizeObserver.js');
var setRefList = require('../../utils/setRefList.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var _excluded = ["id", "className", "style", "label", "labelPlacement", "titleCaption", "placeholder", "leftHelper", "leftHelperPlacement", "rightHelperPlacement", "helperText", "rightHelper", "contentRight", "headerSlot", "requiredPlacement", "hasRequiredIndicator", "hintTrigger", "hintText", "hintView", "hintSize", "hintTargetIcon", "hintPlacement", "hintHasArrow", "hintOffset", "hintWidth", "hintContentLeft", "appearance", "status", "view", "size", "readOnly", "disabled", "required", "clear", "optional", "optionalText", "hasDivider", "value", "defaultValue", "resize", "autoResize", "minAuto", "maxAuto", "height", "width", "rows", "cols", "onChange", "labelAriaHidden"];
var innerPlaceholderUp = TextArea_tokens.classes.innerPlaceholderUp,
  focusedOuterPlaceholderColor = TextArea_tokens.classes.focusedOuterPlaceholderColor,
  hidePlaceHolder = TextArea_tokens.classes.hidePlaceHolder,
  styledContainer = TextArea_tokens.classes.styledContainer,
  styledTextArea = TextArea_tokens.classes.styledTextArea,
  styledTextAreaWrapper = TextArea_tokens.classes.styledTextAreaWrapper,
  styledPlaceholder = TextArea_tokens.classes.styledPlaceholder,
  styledHelpers = TextArea_tokens.classes.styledHelpers,
  hasHeaderSlot = TextArea_tokens.classes.hasHeaderSlot,
  styledContentWrapper = TextArea_tokens.classes.styledContentWrapper;
var base = "bz0816o";
var getDimensionValue = function getDimensionValue(value) {
  if (value === undefined || value === null || value === '') return undefined;
  return Number.isNaN(Number(value)) ? String(value) : "".concat(value, "rem");
};

// TODO: Удалить после отказа от старых библиотек plasma-web / plasma-b2c
var fallbackStatusMap = {
  '': 'primary',
  success: 'positive',
  warning: 'warning',
  error: 'negative'
};
var HINT_DEFAULT_OFFSET = [0, 0];

// TODO: Перенести этот метод в файл applyDynamicLabel.ts
var getDynamicLabelClasses = function getDynamicLabelClasses(props, focused) {
  var readOnly = props.readOnly,
    label = props.label,
    labelPlacement = props.labelPlacement,
    rows = props.rows,
    value = props.value,
    size = props.size;

  // Добавить класс отвечающий за изменение цвета плейсхолдера при фокусе
  var withFocusedOuterUpPlaceholder = !readOnly && focused && (!label || labelPlacement === 'outer') ? focusedOuterPlaceholderColor : undefined;

  // Добавить класс отвечающий за поднятие и уменьшение плейсхолдера
  var withInnerPlaceholderUp = labelPlacement === 'inner' && label && !rows && size !== 'xs' && (!readOnly && (value || focused) || readOnly && value) ? innerPlaceholderUp : undefined;

  // Добавить класс отвечающий за скрытие плейсхолдера
  var withHidePlaceholder = value && !label || labelPlacement === 'inner' && (focused && !readOnly || value) && label && rows || labelPlacement === 'outer' && value || labelPlacement === 'inner' && size === 'xs' && value ? hidePlaceHolder : undefined;
  return [withFocusedOuterUpPlaceholder, withInnerPlaceholderUp, withHidePlaceholder];
};
var textAreaRoot = function textAreaRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (props, innerRef) {
    var id = props.id,
      className = props.className,
      style = props.style,
      label = props.label,
      _props$labelPlacement = props.labelPlacement,
      labelPlacement = _props$labelPlacement === void 0 ? 'inner' : _props$labelPlacement,
      titleCaption = props.titleCaption,
      placeholder = props.placeholder,
      leftHelper = props.leftHelper,
      _props$leftHelperPlac = props.leftHelperPlacement,
      leftHelperPlacement = _props$leftHelperPlac === void 0 ? 'inner' : _props$leftHelperPlac,
      _props$rightHelperPla = props.rightHelperPlacement,
      rightHelperPlacement = _props$rightHelperPla === void 0 ? 'inner' : _props$rightHelperPla,
      helperText = props.helperText,
      rightHelper = props.rightHelper,
      contentRight = props.contentRight,
      headerSlot = props.headerSlot,
      _props$requiredPlacem = props.requiredPlacement,
      requiredPlacement = _props$requiredPlacem === void 0 ? 'right' : _props$requiredPlacem,
      _props$hasRequiredInd = props.hasRequiredIndicator,
      hasRequiredIndicator = _props$hasRequiredInd === void 0 ? false : _props$hasRequiredInd,
      _props$hintTrigger = props.hintTrigger,
      hintTrigger = _props$hintTrigger === void 0 ? 'hover' : _props$hintTrigger,
      hintText = props.hintText,
      _props$hintView = props.hintView,
      hintView = _props$hintView === void 0 ? 'default' : _props$hintView,
      _props$hintSize = props.hintSize,
      hintSize = _props$hintSize === void 0 ? 'm' : _props$hintSize,
      hintTargetIcon = props.hintTargetIcon,
      _props$hintPlacement = props.hintPlacement,
      hintPlacement = _props$hintPlacement === void 0 ? 'auto' : _props$hintPlacement,
      hintHasArrow = props.hintHasArrow,
      _props$hintOffset = props.hintOffset,
      hintOffset = _props$hintOffset === void 0 ? HINT_DEFAULT_OFFSET : _props$hintOffset,
      hintWidth = props.hintWidth,
      hintContentLeft = props.hintContentLeft,
      appearance = props.appearance,
      status = props.status,
      view = props.view,
      size = props.size,
      readOnly = props.readOnly,
      disabled = props.disabled,
      _props$required = props.required,
      required = _props$required === void 0 ? false : _props$required,
      clear = props.clear,
      _props$optional = props.optional,
      optional = _props$optional === void 0 ? false : _props$optional,
      _props$optionalText = props.optionalText,
      optionalText = _props$optionalText === void 0 ? 'optional' : _props$optionalText,
      hasDivider = props.hasDivider,
      value = props.value,
      defaultValue = props.defaultValue,
      resize = props.resize,
      _props$autoResize = props.autoResize,
      autoResize = _props$autoResize === void 0 ? false : _props$autoResize,
      _props$minAuto = props.minAuto,
      minAuto = _props$minAuto === void 0 ? 0 : _props$minAuto,
      maxAuto = props.maxAuto,
      height = props.height,
      width = props.width,
      rows = props.rows,
      cols = props.cols,
      onChange = props.onChange,
      _props$labelAriaHidde = props.labelAriaHidden,
      labelAriaHidden = _props$labelAriaHidde === void 0 ? false : _props$labelAriaHidde,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(props, _excluded);
    var _useState = React.useState(false),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      isHintVisible = _useState2[0],
      setIsHintVisible = _useState2[1];
    var computedHeight = getDimensionValue(height);
    var _useState3 = React.useState('100%'),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      helperWidth = _useState4[0],
      setHelperWidth = _useState4[1];
    var innerWidth = getDimensionValue(width) || helperWidth;
    var _useState5 = React.useState(false),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      focused = _useState6[0],
      setFocused = _useState6[1];
    // TODO: перенести в общую переменную для value снаружи и внутри
    var _useState7 = React.useState(),
      _useState8 = _rollupPluginBabelHelpers.slicedToArray(_useState7, 2),
      uncontrolledValue = _useState8[0],
      setUncontrolledValue = _useState8[1];
    var outerRef = /*#__PURE__*/React.createRef();
    var hiddenRef = React.useRef(null);
    var hintRef = React.useRef(null);
    useOutsideClick.useOutsideClick(function () {
      setIsHintVisible(false);
    }, [hintRef]);
    var isInnerLeftHelperPlacement = leftHelperPlacement === 'inner';
    var isInnerRightHelperPlacement = rightHelperPlacement === 'inner';
    var leftHelperText = leftHelper || helperText;
    var innerOptional = required ? false : optional;
    var hasLeftHelper = Boolean(leftHelper || helperText);
    var hasRightHelper = Boolean(rightHelper);
    var hasHelper = isInnerLeftHelperPlacement && hasLeftHelper || isInnerRightHelperPlacement && hasRightHelper;
    var hasOuterLabel = Boolean(label && labelPlacement === 'outer');
    var hasInnerLabel = Boolean(label && labelPlacement === 'inner' && size !== 'xs');
    var hasPlaceholderOptional = innerOptional && !hasOuterLabel;
    var hasHeader = Boolean(headerSlot) && !(clear || appearance === 'clear');
    var overriddenView = status !== undefined ? fallbackStatusMap[status] : view;
    var textareaHelperId = id ? "".concat(id, "-helper") : undefined;
    var hasExplicitHeight = Boolean(computedHeight);
    var placeholderLabel = hasInnerLabel ? label : placeholder;
    var applyAutoResize = autoResize || Boolean(clear || appearance === 'clear' || appearance === 'viewMode');
    var clearClass = clear || appearance === 'clear' ? TextArea_tokens.classes.clear : undefined;
    var hasHintClass = hintText ? TextArea_tokens.classes.hasHint : undefined;
    var hasRightContentClass = contentRight ? TextArea_tokens.classes.hasRightContent : undefined;
    var hasDividerClass = hasDivider ? TextArea_tokens.classes.hasDivider : undefined;
    var requiredPlacementClass = requiredPlacement === 'right' ? TextArea_tokens.classes.requiredAlignRight : undefined;
    var handleHintShow = function handleHintShow() {
      return setIsHintVisible(true);
    };
    var handleHintHide = function handleHintHide() {
      return setIsHintVisible(false);
    };
    var handleHintClick = function handleHintClick(event) {
      var _hintRef$current;
      if (!hintText || hintTrigger !== 'click') {
        return;
      }
      event.stopPropagation();
      var targetIsPopover = event.target === hintRef.current;
      var rootHasTarget = (_hintRef$current = hintRef.current) === null || _hintRef$current === void 0 ? void 0 : _hintRef$current.contains(event.target);
      if (!targetIsPopover && !rootHasTarget) {
        setIsHintVisible(true);
      }
    };
    React.useLayoutEffect(function () {
      if (outerRef.current) {
        setUncontrolledValue(outerRef.current.value);
      }
    }, [outerRef]);
    React.useLayoutEffect(function () {
      if (!hiddenRef.current || !cols) {
        return;
      }
      var _hiddenRef$current$ge = hiddenRef.current.getBoundingClientRect(),
        elementWidth = _hiddenRef$current$ge.width;
      setHelperWidth("".concat(elementWidth / useAutoResize.ROOT_FONT_SIZE, "rem"));
    }, [cols]);
    useResizeObserver.useResizeObserver(outerRef, function (currentElement) {
      var inlineWidth = currentElement.style.width;
      if (inlineWidth) {
        var _currentElement$getBo = currentElement.getBoundingClientRect(),
          elementWidth = _currentElement$getBo.width;
        setHelperWidth("".concat(elementWidth / useAutoResize.ROOT_FONT_SIZE, "rem"));
      }
    });
    useAutoResize.useAutoResize(applyAutoResize, outerRef, value || uncontrolledValue, minAuto, maxAuto, resize, hiddenRef, size);
    var onFocusHandler = React.useCallback(function () {
      setFocused(true);
    }, []);
    var onBlurHandler = React.useCallback(function () {
      setFocused(false);
    }, []);
    var onChangeHandler = React.useCallback(function (event) {
      // INFO: Для крайне редких кейсов, когда value снаружи не контролируется
      if (value === undefined) {
        setUncontrolledValue(event === null || event === void 0 ? void 0 : event.target.value);
      }
      onChange === null || onChange === void 0 || onChange(event);
    }, [value, onChange]);
    var handleTextAreaFocus = function handleTextAreaFocus() {
      if (readOnly || disabled || !(outerRef !== null && outerRef !== void 0 && outerRef.current)) {
        return;
      }
      outerRef.current.focus();
    };
    var dynamicLabelClasses = getDynamicLabelClasses({
      size: size,
      readOnly: readOnly,
      label: label,
      labelPlacement: labelPlacement,
      value: value || uncontrolledValue || defaultValue,
      rows: rows,
      labelAriaHidden: labelAriaHidden
    }, focused);
    var optionalTextNode = innerOptional ? /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledOptionalText, {
      inheritFont: !hasOuterLabel
    }, Boolean(hasPlaceholderOptional && (placeholderLabel || label)) && '\xa0', optionalText) : null;
    return /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      view: overriddenView,
      size: size,
      disabled: disabled,
      readOnly: readOnly,
      style: _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({
        width: innerWidth,
        height: computedHeight
      }, hasExplicitHeight && _rollupPluginBabelHelpers.defineProperty({}, TextArea_tokens.privateTokens.inputActualHeight, '100%')), style),
      className: index.cx(clearClass, hasDividerClass, hasHintClass, className),
      onClick: handleTextAreaFocus,
      "data-root": true
    }, hintText && {
      hintView: hintView,
      hintSize: hintSize
    }), (hasOuterLabel || titleCaption) && /*#__PURE__*/React__default.default.createElement(TextArea_styles.OuterLabelWrapper, {
      isInnerLabel: labelPlacement === 'inner'
    }, hasOuterLabel && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledIndicatorWrapper, null, /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledLabel, {
      "aria-hidden": labelAriaHidden
    }, label), hintText && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledHintWrapper, null, /*#__PURE__*/React__default.default.createElement(Hint.HintComponent, {
      ref: hintRef,
      hintText: hintText,
      hintTrigger: hintTrigger,
      isHintVisible: isHintVisible,
      hintTargetIcon: hintTargetIcon,
      hintPlacement: hintPlacement,
      hintHasArrow: hintHasArrow,
      hintOffset: hintOffset,
      hintWidth: hintWidth,
      hintContentLeft: hintContentLeft,
      handleHintShow: handleHintShow,
      handleHintHide: handleHintHide,
      handleHintClick: handleHintClick
    })), required && hasRequiredIndicator && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledIndicator, {
      className: index.cx(TextArea_tokens.classes.outerLabelPlacement, requiredPlacementClass, hasHintClass)
    }), optionalTextNode), titleCaption && /*#__PURE__*/React__default.default.createElement(TextArea_styles.TitleCaption, null, titleCaption)), /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledContainer, {
      className: index.cx.apply(void 0, [styledContainer].concat(_rollupPluginBabelHelpers.toConsumableArray(dynamicLabelClasses))),
      hasExplicitHeight: hasExplicitHeight,
      onFocus: onFocusHandler,
      onBlur: onBlurHandler
    }, !hasOuterLabel && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, required && hasRequiredIndicator && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledIndicator, {
      className: index.cx(TextArea_tokens.classes.innerLabelPlacement, requiredPlacementClass)
    }), hintText && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledHintWrapper, {
      className: TextArea_tokens.classes.innerLabelPlacement
    }, /*#__PURE__*/React__default.default.createElement(Hint.HintComponent, {
      ref: hintRef,
      hintText: hintText,
      hintTrigger: hintTrigger,
      isHintVisible: isHintVisible,
      hintTargetIcon: hintTargetIcon,
      hintPlacement: hintPlacement,
      hintHasArrow: hintHasArrow,
      hintOffset: hintOffset,
      hintWidth: hintWidth,
      hintContentLeft: hintContentLeft,
      size: size,
      handleHintShow: handleHintShow,
      handleHintHide: handleHintHide,
      handleHintClick: handleHintClick,
      isInnerLabel: true
    }))), /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledTextAreaWrapper, {
      className: index.cx(styledTextAreaWrapper, hasHeader && hasHeaderSlot),
      hasHelper: hasHelper,
      hasHeader: hasHeader,
      hasExplicitHeight: hasExplicitHeight,
      isClear: clear || appearance === 'clear'
    }, headerSlot && !clear && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledHeaderSlot, null, headerSlot), contentRight && !hasHeader && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledContent, null, contentRight), hasHeader && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledContentWrapper, {
      className: styledContentWrapper,
      hasHeader: hasHeader
    }, contentRight && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledContent, {
      hasHeader: hasHeader
    }, contentRight), headerSlot && placeholderLabel && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledPlaceholder, {
      hasContentRight: Boolean(contentRight),
      className: styledPlaceholder,
      htmlFor: id
    }, placeholderLabel, !hasOuterLabel && optionalTextNode)), /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledTextArea, _rollupPluginBabelHelpers.extends({
      className: index.cx(styledTextArea, hasRightContentClass),
      id: id,
      hasContentRight: Boolean(contentRight),
      hasExplicitHeight: hasExplicitHeight,
      ref: setRefList.mergeRefs(outerRef, innerRef),
      disabled: disabled,
      required: required,
      placeholder: placeholderLabel,
      "aria-describedby": textareaHelperId,
      value: value,
      readOnly: readOnly,
      rows: rows,
      cols: cols,
      resize: resize,
      defaultValue: defaultValue,
      onChange: onChangeHandler
    }, rest)), Boolean(applyAutoResize || cols) && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledHiddenTextArea, {
      "aria-hidden": true,
      ref: hiddenRef,
      hasContentRight: Boolean(contentRight),
      value: value || uncontrolledValue || ' ',
      onChange: function onChange() {},
      defaultValue: defaultValue,
      cols: cols
    })), hasHelper && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledHelpers, {
      className: styledHelpers,
      id: textareaHelperId
    }, hasLeftHelper && isInnerLeftHelperPlacement && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledLeftHelper, {
      className: focused ? TextArea_tokens.classes.leftHelperFocus : ''
    }, leftHelperText), hasRightHelper && isInnerRightHelperPlacement && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledRightHelper, {
      "data-root": true
    }, rightHelper)), !hasHeader && placeholderLabel && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledPlaceholder, {
      hasContentRight: Boolean(contentRight),
      className: styledPlaceholder,
      htmlFor: id
    }, placeholderLabel, !hasOuterLabel && optionalTextNode)), !isInnerLeftHelperPlacement && hasLeftHelper || !isInnerRightHelperPlacement && hasRightHelper ? /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledOutsideHelpersWrapper, {
      id: textareaHelperId
    }, !isInnerLeftHelperPlacement && hasLeftHelper && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledLeftHelper, null, leftHelperText), !isInnerRightHelperPlacement && hasRightHelper && /*#__PURE__*/React__default.default.createElement(TextArea_styles.StyledRightHelper, {
      "data-root": true
    }, rightHelper)) : null);
  });
};
var textAreaConfig = {
  name: 'TextArea',
  tag: 'div',
  layout: textAreaRoot,
  base: base,
  variations: {
    size: {
      css: base$1.base
    },
    view: {
      css: base$2.base
    },
    readOnly: {
      css: base$3.base,
      attrs: true
    },
    disabled: {
      css: base$4.base,
      attrs: true
    },
    hintView: {
      css: base$5.base
    },
    hintSize: {
      css: base$6.base
    }
  },
  defaults: {
    size: 'm',
    view: 'primary'
  }
};

exports.getDynamicLabelClasses = getDynamicLabelClasses;
exports.textAreaConfig = textAreaConfig;
exports.textAreaRoot = textAreaRoot;
