/**
 * ldesign v0.4.6
 * (c) 2023 ldesign
 * @license MIT
 */

import { h as helper } from '../_chunks/dep-b6ac6e96.js';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _typeof from '@babel/runtime/helpers/typeof';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { BrowseIcon, BrowseOffIcon, CloseCircleFilledIcon } from '@ldesign/icons-vue';
import camelCase from 'lodash/camelCase';
import kebabCase from 'lodash/kebabCase';
import { getUnicodeLength, getIEVersion, limitUnicodeMaxLength } from '../_common/js/utils/helper.js';
import { getCharacterLength, omit } from '../utils/helper.js';
import getConfigReceiverMixins, { getGlobalIconMixins } from '../config-provider/config-receiver.js';
import mixins from '../utils/mixins.js';
import { emitEvent } from '../utils/event.js';
import { renderTNodeJSX } from '../utils/render-tnode.js';
import log from '../_common/js/log/log.js';
import props from './props.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'lodash/isString';
import 'lodash/isNull';
import 'lodash/isUndefined';
import 'lodash/isNumber';
import 'lodash/isArray';
import 'vue';
import 'lodash/mergeWith';
import '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '../_chunks/dep-2cb61c79.js';
import 'dayjs';
import '@vue/composition-api';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function getValidAttrs(obj) {
  var newObj = {};
  Object.keys(obj).forEach(function (key) {
    if (typeof obj[key] !== "undefined") newObj[key] = obj[key];
  });
  return newObj;
}
var _Input = mixins(getConfigReceiverMixins("input"), getGlobalIconMixins()).extend({
  name: "TInput",
  inheritAttrs: false,
  props: _objectSpread(_objectSpread({}, props), {}, {
    showInput: {
      type: Boolean,
      "default": true
    },
    keepWrapperWidth: {
      type: Boolean,
      "default": false
    }
  }),
  inject: {
    tFormItem: {
      "default": void 0
    }
  },
  data: function data() {
    return {
      formDisabled: void 0,
      isHover: false,
      focused: false,
      renderType: this.type,
      inputValue: this.value,
      composingRef: false,
      composingRefValue: this.value,
      resizeObserver: null,
      preValue: this.value
    };
  },
  computed: {
    tDisabled: function tDisabled() {
      return this.formDisabled || this.disabled;
    },
    tPlaceholder: function tPlaceholder() {
      var _this$placeholder;
      return (_this$placeholder = this.placeholder) !== null && _this$placeholder !== void 0 ? _this$placeholder : this.t(this.global.placeholder);
    },
    showClear: function showClear() {
      return (this.value && !this.disabled && this.clearable && !this.readonly || this.showClearIconOnEmpty) && this.isHover;
    },
    inputAttrs: function inputAttrs() {
      var _this$autocomplete;
      return getValidAttrs({
        autofocus: this.autofocus,
        disabled: this.tDisabled,
        readonly: this.readonly,
        autocomplete: (_this$autocomplete = this.autocomplete) !== null && _this$autocomplete !== void 0 ? _this$autocomplete : this.global.autocomplete,
        placeholder: this.tPlaceholder,
        name: this.name || void 0,
        type: this.renderType,
        unselectable: this.readonly ? "on" : "off"
      });
    },
    inputClasses: function inputClasses() {
      var _ref;
      return [this.componentName, (_ref = {}, _defineProperty(_ref, this.commonSizeClassName[this.size], this.size !== "medium"), _defineProperty(_ref, this.commonStatusClassName.disabled, this.tDisabled), _defineProperty(_ref, this.commonStatusClassName.focused, this.focused), _defineProperty(_ref, "".concat(this.classPrefix, "-is-").concat(this.tStatus), this.tStatus && this.tStatus !== "default"), _defineProperty(_ref, "".concat(this.classPrefix, "-align-").concat(this.align), this.align !== "left"), _defineProperty(_ref, "".concat(this.classPrefix, "-is-disabled"), this.tDisabled), _defineProperty(_ref, "".concat(this.classPrefix, "-is-readonly"), this.readonly), _defineProperty(_ref, "".concat(this.componentName, "--focused"), this.focused), _ref)];
    },
    inputWrapClass: function inputWrapClass() {
      var _ref2;
      var wrapClass = "".concat(this.componentName, "__wrap");
      return ["".concat(wrapClass), (_ref2 = {}, _defineProperty(_ref2, "".concat(wrapClass, "--focused"), this.focused), _defineProperty(_ref2, "".concat(this.componentName, "--auto-width"), this.autoWidth && !this.keepWrapperWidth), _ref2)];
    },
    limitNumber: function limitNumber() {
      var maxlength = this.maxlength,
        maxcharacter = this.maxcharacter,
        value = this.value;
      if (typeof value === "number") return String(value);
      if (maxlength && maxcharacter) log.warn("Input", "Pick one of maxlength and maxcharacter please.");
      if (maxlength) {
        var length = value !== null && value !== void 0 && value.length ? getUnicodeLength(value) : 0;
        return "".concat(length, "/").concat(maxlength);
      }
      if (maxcharacter) return "".concat(getCharacterLength(value || ""), "/").concat(maxcharacter);
      return "";
    },
    innerStatus: function innerStatus() {
      if (this.limitNumber) {
        var _this$limitNumber$spl = this.limitNumber.split("/"),
          _this$limitNumber$spl2 = _slicedToArray(_this$limitNumber$spl, 2),
          current = _this$limitNumber$spl2[0],
          total = _this$limitNumber$spl2[1];
        return Number(current) > Number(total) ? "error" : "";
      }
      return "";
    },
    tStatus: function tStatus() {
      return this.status || this.innerStatus;
    },
    isIE: function isIE() {
      return getIEVersion() <= 11;
    }
  },
  watch: {
    autofocus: {
      handler: function handler(val) {
        var _this = this;
        if (val === true) {
          this.$nextTick(function () {
            var input = _this.$refs.inputRef;
            input === null || input === void 0 ? void 0 : input.focus();
          });
        }
      },
      immediate: true
    },
    value: {
      handler: function handler(val) {
        this.inputValue = this.format ? this.format(val) : val;
        this.preValue = this.inputValue;
        var newVal = this.getValueByLimitNumber(val);
        if (newVal !== val && this.type !== "number") emitEvent(this, "change", newVal, {
          trigger: "initial"
        });
      },
      immediate: true
    },
    type: {
      handler: function handler(val) {
        this.renderType = val;
      },
      immediate: true
    }
  },
  created: function created() {
    var _this2 = this;
    this.composing = false;
    if (this.autoWidth) this.addListeners();
    if (this.maxlength || this.maxcharacter) {
      this.$watch(function () {
        return _this2.innerStatus;
      }, function () {
        return _this2.onValidateChange();
      });
    }
    this.innerStatus && this.onValidateChange();
  },
  mounted: function mounted() {
    this.addTableResizeObserver(this.$refs.inputPreRef);
  },
  beforeDestroy: function beforeDestroy() {
    var _this$resizeObserver, _this$resizeObserver2;
    (_this$resizeObserver = this.resizeObserver) === null || _this$resizeObserver === void 0 ? void 0 : _this$resizeObserver.unobserve(this.$refs.inputPreRef);
    (_this$resizeObserver2 = this.resizeObserver) === null || _this$resizeObserver2 === void 0 ? void 0 : _this$resizeObserver2.disconnect();
  },
  methods: {
    addListeners: function addListeners() {
      var _this3 = this;
      this.$watch(function () {
        return _this3.value + _this3.placeholder;
      }, function () {
        if (!_this3.autoWidth) return;
        _this3.$nextTick(function () {
          _this3.updateInputWidth();
        });
      }, {
        immediate: true
      });
    },
    addTableResizeObserver: function addTableResizeObserver(element) {
      var _this4 = this;
      if (typeof window.ResizeObserver === "undefined" || !element || this.isIE) return;
      this.resizeObserver = new window.ResizeObserver(function () {
        _this4.updateInputWidth();
      });
      this.resizeObserver.observe(element);
    },
    renderIcon: function renderIcon(h, icon, iconType) {
      if (typeof icon === "function") return icon(h);
      if (this.$scopedSlots[kebabCase(iconType)]) return this.$scopedSlots[kebabCase(iconType)](h);
      if (this.$scopedSlots[camelCase(iconType)]) return this.$scopedSlots[camelCase(iconType)](h);
      return null;
    },
    setInputValue: function setInputValue() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
      var input = this.$refs.inputRef;
      if (!input) return;
      var sV = String(v);
      if (input.value !== sV) input.value = sV;
    },
    focus: function focus() {
      this.$refs.inputRef.focus();
    },
    blur: function blur() {
      this.$refs.inputRef.blur();
    },
    handleKeydown: function handleKeydown(e) {
      if (this.tDisabled) return;
      var value = e.currentTarget.value;
      if (/enter/i.test(e.key) || /enter/i.test(e.code)) emitEvent(this, "enter", value, {
        e: e
      });else emitEvent(this, "keydown", value, {
        e: e
      });
    },
    handleKeyUp: function handleKeyUp(e) {
      if (this.tDisabled) return;
      var value = e.currentTarget.value;
      if (e.key === "Process") return;
      emitEvent(this, "keyup", value, {
        e: e
      });
    },
    handleKeypress: function handleKeypress(e) {
      if (this.tDisabled) return;
      var value = e.currentTarget.value;
      emitEvent(this, "keypress", value, {
        e: e
      });
    },
    handlePaste: function handlePaste(e) {
      if (this.tDisabled) return;
      var clipData = e.clipboardData || window.clipboardData;
      emitEvent(this, "paste", {
        e: e,
        pasteValue: clipData === null || clipData === void 0 ? void 0 : clipData.getData("text/plain")
      });
    },
    onHandleMousewheel: function onHandleMousewheel(e) {
      emitEvent(this, "wheel", {
        e: e
      });
    },
    emitPassword: function emitPassword() {
      var renderType = this.renderType;
      var toggleType = renderType === "password" ? "text" : "password";
      this.renderType = toggleType;
    },
    emitClear: function emitClear(e) {
      emitEvent(this, "change", "", {
        e: e,
        trigger: "clear"
      });
      emitEvent(this, "clear", {
        e: e
      });
    },
    emitFocus: function emitFocus(e) {
      this.inputValue = this.value;
      if (this.tDisabled) return;
      this.focused = true;
      emitEvent(this, "focus", this.value, {
        e: e
      });
    },
    formatAndEmitBlur: function formatAndEmitBlur(e) {
      var _this$tFormItem;
      if (this.format) this.inputValue = this.format(this.value);
      this.focused = false;
      (_this$tFormItem = this.tFormItem) === null || _this$tFormItem === void 0 ? void 0 : _this$tFormItem.validate("blur");
      emitEvent(this, "blur", this.value, {
        e: e
      });
    },
    compositionstartHandler: function compositionstartHandler(e) {
      var _this$onCompositionst;
      this.composingRef = true;
      var value = e.currentTarget.value;
      this.composingRefValue = value;
      this.$emit("compositionstart", value, {
        e: e
      });
      (_this$onCompositionst = this.onCompositionstart) === null || _this$onCompositionst === void 0 ? void 0 : _this$onCompositionst.call(this, value, {
        e: e
      });
    },
    compositionendHandler: function compositionendHandler(e) {
      var _this$onCompositionen;
      var value = e.currentTarget.value;
      if (this.composingRef) {
        this.composingRef = false;
        this.handleInput(e);
      }
      this.composingRefValue = "";
      this.$emit("compositionend", value, {
        e: e
      });
      (_this$onCompositionen = this.onCompositionend) === null || _this$onCompositionen === void 0 ? void 0 : _this$onCompositionen.call(this, value, {
        e: e
      });
    },
    onRootClick: function onRootClick(e) {
      var _this$$refs$inputRef, _this$onClick;
      (_this$$refs$inputRef = this.$refs.inputRef) === null || _this$$refs$inputRef === void 0 ? void 0 : _this$$refs$inputRef.focus();
      this.$emit("click", {
        e: e
      });
      (_this$onClick = this.onClick) === null || _this$onClick === void 0 ? void 0 : _this$onClick.call(this, {
        e: e
      });
    },
    handleInput: function handleInput(e) {
      var _this5 = this;
      this.preValue = this.inputValue + e.data;
      var val = e.currentTarget.value;
      var preCursorPos;
      if (this.composingRef) {
        this.composingRefValue = val;
      } else {
        if (this.type !== "number") val = this.getValueByLimitNumber(val);
        emitEvent(this, "change", val, {
          e: e,
          trigger: "input"
        });
        if (!this.isIE) {
          var inputRef = this.$refs.inputRef;
          preCursorPos = inputRef.selectionStart;
          setTimeout(function () {
            inputRef.selectionEnd = preCursorPos;
          });
        }
        this.$nextTick(function () {
          _this5.setInputValue(_this5.value);
        });
      }
    },
    onInputMouseenter: function onInputMouseenter(e) {
      this.isHover = true;
      emitEvent(this, "mouseenter", {
        e: e
      });
    },
    onInputMouseleave: function onInputMouseleave(e) {
      this.isHover = false;
      emitEvent(this, "mouseleave", {
        e: e
      });
    },
    updateInputWidth: function updateInputWidth() {
      var pre = this.$refs.inputPreRef;
      if (!pre) return;
      var _pre$getBoundingClien = pre.getBoundingClientRect(),
        width = _pre$getBoundingClien.width;
      if (this.$refs.inputRef) this.$refs.inputRef.style.width = "".concat(width, "px");
    },
    getValueByLimitNumber: function getValueByLimitNumber(inputValue) {
      var allowInputOverMax = this.allowInputOverMax,
        maxlength = this.maxlength,
        maxcharacter = this.maxcharacter;
      if (!(maxlength || maxcharacter) || allowInputOverMax || !inputValue) return inputValue;
      if (maxlength) {
        return limitUnicodeMaxLength(inputValue, maxlength);
      }
      if (maxcharacter) {
        var r = getCharacterLength(inputValue, maxcharacter);
        if (_typeof(r) === "object") return r.characters;
      }
    },
    onValidateChange: function onValidateChange() {
      var _this$onValidate;
      var error = this.innerStatus ? "exceed-maximum" : void 0;
      (_this$onValidate = this.onValidate) === null || _this$onValidate === void 0 ? void 0 : _this$onValidate.call(this, {
        error: error
      });
      this.$emit("validate", {
        error: error
      });
    }
  },
  render: function render(h) {
    var _ref3;
    var inputEvents = {
      focus: this.emitFocus,
      blur: this.formatAndEmitBlur,
      keydown: this.handleKeydown,
      keyup: this.handleKeyUp,
      keypress: this.handleKeypress,
      paste: this.handlePaste,
      compositionstart: this.compositionstartHandler,
      compositionend: this.compositionendHandler,
      change: function change() {}
    };
    var wrapperAttrs = omit(this.$attrs, Object.keys(this.inputAttrs));
    var wrapperEvents = omit(this.$listeners, [].concat(_toConsumableArray(Object.keys(inputEvents)), ["input", "paste"]));
    var prefixIcon = this.renderIcon(h, this.prefixIcon, "prefix-icon");
    var suffixIcon = this.renderIcon(h, this.suffixIcon, "suffix-icon");
    var passwordIcon = this.renderIcon(h, void 0, "password-icon");
    var label = renderTNodeJSX(this, "label");
    var suffix = renderTNodeJSX(this, "suffix");
    var limitNode = this.limitNumber && this.showLimitNumber ? h("div", {
      "class": "".concat(this.classPrefix, "-input__limit-number")
    }, [this.limitNumber]) : null;
    var labelContent = label ? h("div", {
      "class": "".concat(this.componentName, "__prefix")
    }, [label]) : null;
    var suffixContent = suffix || limitNode ? h("div", {
      "class": "".concat(this.componentName, "__suffix")
    }, [suffix, limitNode]) : null;
    var _this$useGlobalIcon = this.useGlobalIcon({
        BrowseIcon: BrowseIcon,
        BrowseOffIcon: BrowseOffIcon,
        CloseCircleFilledIcon: CloseCircleFilledIcon
      }),
      BrowseIcon$1 = _this$useGlobalIcon.BrowseIcon,
      BrowseOffIcon$1 = _this$useGlobalIcon.BrowseOffIcon,
      CloseCircleFilledIcon$1 = _this$useGlobalIcon.CloseCircleFilledIcon;
    if (this.type === "password") {
      if (this.renderType === "password") suffixIcon = h(BrowseOffIcon$1, {
        "class": "".concat(this.componentName, "__suffix-clear"),
        "nativeOn": {
          "click": this.emitPassword
        }
      });else if (this.renderType === "text") suffixIcon = h(BrowseIcon$1, {
        "class": "".concat(this.componentName, "__suffix-clear"),
        "nativeOn": {
          "click": this.emitPassword
        }
      });
    }
    if (this.showClear) {
      if (this.type === "password") {
        passwordIcon = h(CloseCircleFilledIcon$1, {
          "class": "".concat(this.componentName, "__suffix-clear"),
          "nativeOn": {
            "click": this.emitClear
          }
        });
      } else {
        suffixIcon = h(CloseCircleFilledIcon$1, {
          "class": "".concat(this.componentName, "__suffix-clear"),
          "nativeOn": {
            "click": this.emitClear
          }
        });
      }
    }
    var classes = [this.inputClasses, this.inputClass, (_ref3 = {}, _defineProperty(_ref3, "".concat(this.componentName, "--prefix"), prefixIcon || labelContent), _defineProperty(_ref3, "".concat(this.componentName, "--suffix"), suffixIcon || suffixContent), _ref3)];
    var inputNode = h("div", {
      "class": classes,
      "attrs": _objectSpread({}, wrapperAttrs),
      "on": _objectSpread(_objectSpread({}, wrapperEvents), {}, {
        "click": this.onRootClick,
        "mouseenter": this.onInputMouseenter,
        "mouseleave": this.onInputMouseleave,
        "wheel": this.onHandleMousewheel
      })
    }, [prefixIcon ? h("span", {
      "class": ["".concat(this.componentName, "__prefix"), "".concat(this.componentName, "__prefix-icon")]
    }, [prefixIcon]) : null, labelContent, this.showInput && h("input", helper([{}, {
      "attrs": this.inputAttrs
    }, {}, {
      "on": inputEvents
    }, {
      "ref": "inputRef",
      "class": "".concat(this.componentName, "__inner"),
      "domProps": {
        "value": this.composingRef ? this.composingRefValue : this.inputValue
      },
      "on": {
        "input": this.handleInput
      }
    }])), this.autoWidth && h("span", {
      "ref": "inputPreRef",
      "class": "".concat(this.classPrefix, "-input__input-pre")
    }, [this.preValue || this.tPlaceholder]), suffixContent, passwordIcon ? h("span", {
      "class": ["".concat(this.componentName, "__suffix"), "".concat(this.componentName, "__suffix-icon"), "".concat(this.componentName, "__clear")]
    }, [passwordIcon]) : null, suffixIcon ? h("span", {
      "class": ["".concat(this.componentName, "__suffix"), "".concat(this.componentName, "__suffix-icon"), _defineProperty({}, "".concat(this.componentName, "__clear"), this.showClear)]
    }, [suffixIcon]) : null]);
    var tips = renderTNodeJSX(this, "tips");
    return h("div", {
      "class": this.inputWrapClass
    }, [inputNode, tips && h("div", {
      "class": "".concat(this.componentName, "__tips ").concat(this.componentName, "__tips--").concat(this.tStatus || "default")
    }, [tips])]);
  }
});

export { _Input as default };
//# sourceMappingURL=input.js.map
