function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { __rest } from "tslib";
import React, { createElement, forwardRef, useContext, useState, useRef, useImperativeHandle } from "react";
import classNames from 'classnames';
import { isWeb } from '@uni/env';
import { Text, TextInput } from "@alifd/meet-react-component-one";
import View from '../view';
import Icon from '../icon';
import Form from '../form';
import { getValueFromEvents, isStrictByteDanceMicroApp, isStrictWechatMiniProgram, stopPropagation, isNumber, isMiniappPlatform, get } from '../utils';
import { useValue } from '../utils/hooks';
var ICON_NAME_MAP = {
  warning: 'warning-filling',
  error: 'warning-filling',
  success: 'success-filling',
  loading: 'loading'
};

var Input = function Input(props, ref) {
  var _classNames, _classNames3, _classNames4;

  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$type = props.type,
      type = _props$type === void 0 ? 'normal' : _props$type,
      valueProp = props.value,
      _props$defaultValue = props.defaultValue,
      defaultValue = _props$defaultValue === void 0 ? '' : _props$defaultValue,
      _props$keyboardType = props.keyboardType,
      keyboardType = _props$keyboardType === void 0 ? 'text' : _props$keyboardType,
      placeholder = props.placeholder,
      _props$htmlType = props.htmlType,
      htmlType = _props$htmlType === void 0 ? '' : _props$htmlType,
      _props$isPassword = props.isPassword,
      isPasswordProp = _props$isPassword === void 0 ? false : _props$isPassword,
      stateProp = props.state,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$readOnly = props.readOnly,
      readOnly = _props$readOnly === void 0 ? false : _props$readOnly,
      _props$hasClear = props.hasClear,
      hasClear = _props$hasClear === void 0 ? false : _props$hasClear,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      _props$useOriginalRef = props.useOriginalRef,
      useOriginalRef = _props$useOriginalRef === void 0 ? false : _props$useOriginalRef,
      _props$highlightable = props.highlightable,
      highlightable = _props$highlightable === void 0 ? false : _props$highlightable,
      _props$showLimitHint = props.showLimitHint,
      showLimitHint = _props$showLimitHint === void 0 ? true : _props$showLimitHint,
      _props$rows = props.rows,
      rows = _props$rows === void 0 ? 3 : _props$rows,
      maxLength = props.maxLength,
      focused = props.focused,
      autoFocus = props.autoFocus,
      alignProp = props.align,
      _props$onFocus = props.onFocus,
      onFocus = _props$onFocus === void 0 ? function () {} : _props$onFocus,
      _props$onBlur = props.onBlur,
      onBlur = _props$onBlur === void 0 ? function () {} : _props$onBlur,
      _props$onChange = props.onChange,
      onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
      _props$onConfirm = props.onConfirm,
      onConfirm = _props$onConfirm === void 0 ? function () {} : _props$onConfirm,
      _props$onClear = props.onClear,
      onClear = _props$onClear === void 0 ? function () {} : _props$onClear,
      onCompositionStart = props.onCompositionStart,
      onCompositionEnd = props.onCompositionEnd,
      className = props.className,
      controlled = props.controlled,
      _props$addonAfter = props.addonAfter,
      addonAfter = _props$addonAfter === void 0 ? null : _props$addonAfter,
      _props$addonBefore = props.addonBefore,
      addonBefore = _props$addonBefore === void 0 ? null : _props$addonBefore,
      _props$innerAfter = props.innerAfter,
      innerAfter = _props$innerAfter === void 0 ? null : _props$innerAfter,
      _props$innerBefore = props.innerBefore,
      innerBefore = _props$innerBefore === void 0 ? null : _props$innerBefore,
      enableNative = props.enableNative,
      compositionProp = props.composition,
      others = __rest(props, ["prefix", "size", "type", "value", "defaultValue", "keyboardType", "placeholder", "htmlType", "isPassword", "state", "disabled", "readOnly", "hasClear", "multiline", "useOriginalRef", "highlightable", "showLimitHint", "rows", "maxLength", "focused", "autoFocus", "align", "onFocus", "onBlur", "onChange", "onConfirm", "onClear", "onCompositionStart", "onCompositionEnd", "className", "controlled", "addonAfter", "addonBefore", "innerAfter", "innerBefore", "enableNative", "composition"]);

  var inputRef = useRef(null);
  var composition = useRef(false);
  var isPassword = isPasswordProp || htmlType === 'password';
  var clsPrefix = "".concat(prefix, "input");

  var _useContext = useContext(Form.ItemContext),
      validateState = _useContext.validateState,
      contentAlign = _useContext.contentAlign,
      hasFeedback = _useContext.hasFeedback;

  var _useValue = useValue(props, '', {
    fitValue: function fitValue(v) {
      if (isNumber(maxLength) && maxLength > 0) {
        return "".concat(v).length > maxLength ? "".concat(v).substr(0, maxLength) : v;
      }

      return v;
    }
  }),
      _useValue2 = _slicedToArray(_useValue, 4),
      value = _useValue2[0],
      setValue = _useValue2[1],
      isControlled = _useValue2[2],
      setPropValue = _useValue2[3];

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isFocused = _useState2[0],
      setFocusState = _useState2[1];

  var align = alignProp || contentAlign;
  var state = stateProp || validateState;
  var editable = !disabled && !readOnly;
  var showClear = hasClear && (isWeb && isFocused || isMiniappPlatform) && !!value && editable;
  var hasIcon = showClear || state !== 'normal';
  var clses = {
    input: classNames(clsPrefix, "".concat(clsPrefix, "--").concat(size), "".concat(clsPrefix, "--").concat(type), (_classNames = {}, _defineProperty(_classNames, "".concat(clsPrefix, "--hasIcon"), hasIcon), _defineProperty(_classNames, "".concat(clsPrefix, "--").concat(type, "-highlighted"), highlightable && isFocused), _classNames), className),
    textInputWrapper: classNames("".concat(clsPrefix, "-textinput-wrapper"), _defineProperty({}, "".concat(clsPrefix, "-textinput-wrapper--multiline"), multiline)),
    textInput: classNames("".concat(clsPrefix, "-textinput"), "".concat(clsPrefix, "-textinput--").concat(size), "".concat(clsPrefix, "-textinput--").concat(type), "".concat(clsPrefix, "-textinput--").concat(align), (_classNames3 = {}, _defineProperty(_classNames3, "".concat(clsPrefix, "-textinput--").concat(type, "-readonly"), readOnly), _defineProperty(_classNames3, "".concat(clsPrefix, "-textinput--").concat(type, "-disabled"), disabled), _defineProperty(_classNames3, "".concat(clsPrefix, "-textinput--").concat(size, "-multiline"), multiline), _defineProperty(_classNames3, "".concat(clsPrefix, "-textinput--wechat"), isStrictWechatMiniProgram), _defineProperty(_classNames3, "".concat(clsPrefix, "-textinput--not-bw"), !isStrictByteDanceMicroApp && !isStrictWechatMiniProgram), _classNames3)),
    icon: classNames("".concat(clsPrefix, "-icon"), "".concat(clsPrefix, "-icon--").concat(size), (_classNames4 = {}, _defineProperty(_classNames4, "".concat(clsPrefix, "-icon--loading"), state === 'loading'), _defineProperty(_classNames4, "".concat(clsPrefix, "-icon--warning"), state === 'warning'), _defineProperty(_classNames4, "".concat(clsPrefix, "-icon--success"), state === 'success'), _defineProperty(_classNames4, "".concat(clsPrefix, "-icon--error"), state === 'error'), _classNames4)),
    clear: classNames("".concat(clsPrefix, "-icon"), "".concat(clsPrefix, "-icon--").concat(size), _defineProperty({}, "".concat(clsPrefix, "-icon--clear"), hasClear)),
    limitHint: classNames("".concat(clsPrefix, "-limit-hint"), "".concat(clsPrefix, "-limit-hint--").concat(type), "".concat(clsPrefix, "-limit-hint--").concat(size)),
    addonBefore: "".concat(clsPrefix, "-addon-before--").concat(size),
    addonAfter: "".concat(clsPrefix, "-addon-after--").concat(size)
  };

  var handleFocus = function handleFocus(e) {
    setFocusState(true);
    onFocus(e);
  };

  var handleBlur = function handleBlur(e) {
    if (isWeb) {
      if (inputRef && inputRef.current && inputRef.current._nativeNode !== document.activeElement) {
        setFocusState(false);
        onBlur(e);
      }
    } else {
      setFocusState(false);
      onBlur(e);
    }
  };

  var handleConfirm = function handleConfirm(e) {
    return onConfirm(getValueFromEvents(e), e);
  };

  var triggerChange = function triggerChange(v, e) {
    var _a, _b, _c, _d;

    onChange(v, e);

    if (isWeb) {
      var r;

      try {
        if (isNumber((_a = e === null || e === void 0 ? void 0 : e.target) === null || _a === void 0 ? void 0 : _a.selectionStart) && isNumber((_b = e === null || e === void 0 ? void 0 : e.target) === null || _b === void 0 ? void 0 : _b.selectionEnd)) {
          r = [e.target.selectionStart, e.target.selectionEnd];
        }

        if (Array.isArray(r) && ((_d = (_c = inputRef === null || inputRef === void 0 ? void 0 : inputRef.current) === null || _c === void 0 ? void 0 : _c._nativeNode) === null || _d === void 0 ? void 0 : _d.setSelectionRange)) {
          setTimeout(function () {
            inputRef.current._nativeNode.setSelectionRange(r[0], r[1]);
          }, 32);
        }
      } catch (err) {}
    }
  };

  var handleChange = function handleChange(v, e) {
    if (isControlled) {
      if (composition.current) {
        setPropValue(v);
      }
    } else {
      setValue(v);
    }

    if (composition.current) {
      return;
    }

    triggerChange(v, e);
  };

  var handleClear = function handleClear(e) {
    if (disabled || readOnly) {
      return;
    }

    if (e && e.preventDefault) {
      e.preventDefault();
    }

    if (onClear) {
      onClear(e);
    }

    handleChange('', e);

    if (inputRef && inputRef.current) {
      inputRef.current.focus();
    }
  };

  var handleCompositionStart = function handleCompositionStart(e) {
    composition.current = true;

    if (onCompositionStart) {
      onCompositionStart(e);
    }
  };

  var handleCompositionEnd = function handleCompositionEnd(e) {
    composition.current = false;

    if (onCompositionEnd) {
      onCompositionEnd(e);
    }

    triggerChange(getValueFromEvents(e), e);
  };

  var clearEvt = _defineProperty({}, isWeb ? 'onTouchEnd' : 'onClick', handleClear);

  if (compositionProp) {
    others.onCompositionStart = handleCompositionStart;
    others.onCompositionEnd = handleCompositionEnd;
  }

  useImperativeHandle(ref, function () {
    return Object.assign(get(inputRef, 'current') || {});
  });
  return /*#__PURE__*/React.createElement(View, {
    className: clses.input
  }, addonBefore ? /*#__PURE__*/React.createElement(View, {
    className: clses.addonBefore
  }, addonBefore) : null, readOnly ? /*#__PURE__*/React.createElement(Text, {
    className: clses.textInput,
    numberOfLines: multiline ? 'auto' : 1
  }, value, "\xA0") : /*#__PURE__*/React.createElement(View, {
    className: clses.textInputWrapper
  }, innerBefore, /*#__PURE__*/React.createElement(TextInput, _extends({
    ref: inputRef,
    autoHeight: true
  }, others, {
    editable: editable,
    value: value,
    keyboardType: keyboardType,
    multiline: multiline,
    maxLength: maxLength,
    numberOfLines: rows,
    className: clses.textInput
  }, isPassword ? {
    type: 'password'
  } : null, {
    secureTextEntry: isPassword,
    password: isPassword,
    onFocus: handleFocus,
    onBlur: handleBlur,
    onConfirm: handleConfirm,
    placeholder: placeholder,
    controlled: controlled,
    autoFocus: autoFocus || focused,
    onInput: function onInput(e) {
      return handleChange(getValueFromEvents(e), e);
    },
    onChange: function onChange(e) {
      return stopPropagation(e);
    },
    placeholderColor: undefined,
    "placeholder-class": "".concat(clsPrefix, "-placeholder"),
    enableNative: enableNative,
    showCount: false
  })), isNumber(maxLength) && maxLength > 0 && showLimitHint ? /*#__PURE__*/React.createElement(Text, {
    className: clses.limitHint
  }, value.length || 0, "/", maxLength) : null), !multiline ? /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-items ").concat(clsPrefix, "-items--").concat(size)
  }, showClear ? /*#__PURE__*/React.createElement(View, _extends({
    className: "".concat(clsPrefix, "-icon-wrapper")
  }, clearEvt), /*#__PURE__*/React.createElement(Icon, {
    name: "delete-filling",
    className: clses.clear
  })) : null, !showClear && state !== 'normal' && hasFeedback ? /*#__PURE__*/React.createElement(Icon, {
    className: clses.icon,
    name: ICON_NAME_MAP[state]
  }) : null, innerAfter, addonAfter ? /*#__PURE__*/React.createElement(View, {
    className: clses.addonAfter
  }, addonAfter) : null) : null);
};

Input.displayName = 'Input';
export default /*#__PURE__*/forwardRef(Input);