/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var iconsVue = require('@ldesign/icons-vue');
var camelCase = require('lodash/camelCase');
var kebabCase = require('lodash/kebabCase');
var helper = require('../../chunks/helper2.js');
var log = require('../../chunks/log.js');
var utils_helper = require('../../utils/helper.js');
var components_configProvider_configReceiver = require('../config-provider/config-receiver.js');
var utils_mixins = require('../../utils/mixins.js');
var utils_event = require('../../utils/event.js');
var utils_renderNode = require('../../utils/render-node.js');
var components_input_props = require('./props.js');
require('../../chunks/_commonjsHelpers-2e6815bd.js');
require('vue');
require('lodash/mergeWith');
require('lodash');
require('../config-provider/context.js');
require('../../chunks/zh_CN.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var camelCase__default = /*#__PURE__*/_interopDefaultLegacy(camelCase);
var kebabCase__default = /*#__PURE__*/_interopDefaultLegacy(kebabCase);

function getValidAttrs(obj) {
  const newObj = {};
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] !== "undefined") newObj[key] = obj[key];
  });
  return newObj;
}
var _Input = utils_mixins["default"](components_configProvider_configReceiver["default"]("input"), components_configProvider_configReceiver.getGlobalIconMixins()).extend({
  name: "LInput",
  inheritAttrs: false,
  props: {
    ...components_input_props["default"],
    showInput: {
      type: Boolean,
      default: true
    },
    keepWrapperWidth: {
      type: Boolean,
      default: false
    }
  },
  inject: {
    tFormItem: {
      default: void 0
    }
  },
  data() {
    return {
      formDisabled: void 0,
      isHover: false,
      focused: false,
      renderType: this.type,
      inputValue: this.value,
      composingRef: false,
      composingRefValue: this.value
    };
  },
  computed: {
    tDisabled() {
      return this.formDisabled || this.disabled;
    },
    tPlaceholder() {
      return this.placeholder ?? this.t(this.global.placeholder);
    },
    showClear() {
      return (this.value && !this.disabled && this.clearable && !this.readonly || this.showClearIconOnEmpty) && this.isHover;
    },
    inputAttrs() {
      return getValidAttrs({
        autofocus: this.autofocus,
        disabled: this.tDisabled,
        readonly: this.readonly,
        autocomplete: this.autocomplete ?? this.global.autocomplete,
        placeholder: this.tPlaceholder,
        name: this.name || void 0,
        type: this.renderType,
        unselectable: this.readonly ? "on" : "off"
      });
    },
    inputClasses() {
      return [this.componentName, this.commonSizeClassName[this.size] || "", {
        [this.commonStatusClassName.disabled]: this.tDisabled,
        [this.commonStatusClassName.focused]: this.focused,
        [`${this.classPrefix}-is-${this.tStatus}`]: this.tStatus,
        [`${this.classPrefix}-align-${this.align}`]: this.align !== "left",
        [`${this.classPrefix}-is-disabled`]: this.tDisabled,
        [`${this.classPrefix}-is-readonly`]: this.readonly,
        [`${this.componentName}--focused`]: this.focused,
        [`${this.componentName}--auto-width`]: this.autoWidth && !this.keepWrapperWidth
      }];
    },
    inputWrapClass() {
      const wrapClass = `${this.componentName}__wrap`;
      return [`${wrapClass}`, {
        [`${wrapClass}--focused`]: this.focused
      }];
    },
    limitNumber() {
      const {
        maxlength,
        maxcharacter,
        value
      } = this;
      if (typeof value === "number") return String(value);
      if (maxlength && maxcharacter) log.log.warn("Input", "Pick one of maxlength and maxcharacter please.");
      if (maxlength) {
        const length = value !== null && value !== void 0 && value.length ? helper.getUnicodeLength(value) : 0;
        return `${length}/${maxlength}`;
      }
      if (maxcharacter) return `${utils_helper.getCharacterLength(value || "")}/${maxcharacter}`;
      return "";
    },
    innerStatus() {
      if (this.limitNumber) {
        const [current, total] = this.limitNumber.split("/");
        return Number(current) > Number(total) ? "error" : "";
      }
      return "";
    },
    tStatus() {
      return this.status || this.innerStatus;
    }
  },
  watch: {
    autofocus: {
      handler(val) {
        if (val === true) {
          this.$nextTick(() => {
            const input = this.$refs.inputRef;
            input === null || input === void 0 ? void 0 : input.focus();
          });
        }
      },
      immediate: true
    },
    value: {
      handler(val) {
        this.inputValue = this.format ? this.format(val) : val;
      },
      immediate: true
    },
    type: {
      handler(val) {
        this.renderType = val;
      },
      immediate: true
    }
  },
  created() {
    this.composing = false;
    if (this.autoWidth) this.addListeners();
    if (this.maxlength || this.maxcharacter) {
      this.$watch(() => this.innerStatus, () => this.onValidateChange());
    }
    this.innerStatus && this.onValidateChange();
  },
  methods: {
    addListeners() {
      this.$watch(() => this.value + this.placeholder, () => {
        if (!this.autoWidth) return;
        this.$nextTick(() => {
          this.updateInputWidth();
        });
      }, {
        immediate: true
      });
    },
    mouseEvent(v) {
      this.isHover = v;
    },
    renderIcon(h, icon, iconType) {
      if (typeof icon === "function") return icon(h);
      if (this.$scopedSlots[kebabCase__default["default"](iconType)]) return this.$scopedSlots[kebabCase__default["default"](iconType)](null);
      if (this.$scopedSlots[camelCase__default["default"](iconType)]) return this.$scopedSlots[camelCase__default["default"](iconType)](null);
      return null;
    },
    setInputValue() {
      let v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
      const input = this.$refs.inputRef;
      if (!input) return;
      const sV = String(v);
      if (input.value !== sV) input.value = sV;
    },
    focus() {
      this.$refs.inputRef.focus();
    },
    blur() {
      this.$refs.inputRef.blur();
    },
    handleKeydown(e) {
      if (this.tDisabled) return;
      const code = e.code || e.key;
      const {
        currentTarget: {
          value
        }
      } = e;
      if (code === "Enter" || code === "NumpadEnter") utils_event.emitEvent(this, "enter", value, {
        e
      });else utils_event.emitEvent(this, "keydown", value, {
        e
      });
    },
    handleKeyUp(e) {
      if (this.tDisabled) return;
      const {
        currentTarget: {
          value
        }
      } = e;
      if (e.key === "Process") return;
      utils_event.emitEvent(this, "keyup", value, {
        e
      });
    },
    handleKeypress(e) {
      if (this.tDisabled) return;
      const {
        currentTarget: {
          value
        }
      } = e;
      utils_event.emitEvent(this, "keypress", value, {
        e
      });
    },
    onHandlePaste(e) {
      if (this.tDisabled) return;
      const clipData = e.clipboardData || window.clipboardData;
      utils_event.emitEvent(this, "paste", {
        e,
        pasteValue: clipData === null || clipData === void 0 ? void 0 : clipData.getData("text/plain")
      });
    },
    onHandleMousewheel(e) {
      utils_event.emitEvent(this, "wheel", {
        e
      });
    },
    emitPassword() {
      const {
        renderType
      } = this;
      const toggleType = renderType === "password" ? "text" : "password";
      this.renderType = toggleType;
    },
    emitClear(e) {
      utils_event.emitEvent(this, "clear", {
        e
      });
      utils_event.emitEvent(this, "change", "", {
        e
      });
    },
    emitFocus(e) {
      this.inputValue = this.value;
      if (this.tDisabled) return;
      this.focused = true;
      utils_event.emitEvent(this, "focus", this.value, {
        e
      });
    },
    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");
      utils_event.emitEvent(this, "blur", this.value, {
        e
      });
    },
    compositionstartHandler(e) {
      var _this$onCompositionst;
      this.composingRef = true;
      const {
        currentTarget: {
          value
        }
      } = e;
      this.composingRefValue = value;
      this === null || this === void 0 ? void 0 : (_this$onCompositionst = this.onCompositionstart) === null || _this$onCompositionst === void 0 ? void 0 : _this$onCompositionst.call(this, value, {
        e
      });
    },
    compositionendHandler(e) {
      var _this$onCompositionen;
      const {
        currentTarget: {
          value
        }
      } = e;
      if (this.composingRef) {
        this.composingRef = false;
        this.handleInput(e);
      }
      this.composingRefValue = "";
      this === null || this === void 0 ? void 0 : (_this$onCompositionen = this.onCompositionend) === null || _this$onCompositionen === void 0 ? void 0 : _this$onCompositionen.call(this, value, {
        e
      });
    },
    onRootClick(e) {
      var _this$$refs$inputRef;
      (_this$$refs$inputRef = this.$refs.inputRef) === null || _this$$refs$inputRef === void 0 ? void 0 : _this$$refs$inputRef.focus();
      this.$emit("click", e);
    },
    handleInput(e) {
      let {
        currentTarget: {
          value: val
        }
      } = e;
      if (this.composingRef) {
        this.composingRefValue = val;
      } else {
        if (this.type !== "number") val = this.getValueByLimitNumber(val);
        utils_event.emitEvent(this, "change", val, {
          e
        });
        this.$nextTick(() => {
          this.setInputValue(this.value);
        });
      }
    },
    onInputMouseenter(e) {
      var _this$onMouseenter;
      this.mouseEvent(true);
      (_this$onMouseenter = this.onMouseenter) === null || _this$onMouseenter === void 0 ? void 0 : _this$onMouseenter.call(this, {
        e
      });
    },
    onInputMouseleave(e) {
      var _this$onMouseleave;
      this.mouseEvent(false);
      (_this$onMouseleave = this.onMouseleave) === null || _this$onMouseleave === void 0 ? void 0 : _this$onMouseleave.call(this, {
        e
      });
    },
    updateInputWidth() {
      const pre = this.$refs.inputPreRef;
      if (!pre) return;
      const width = pre.offsetWidth;
      if (this.$refs.inputRef) this.$refs.inputRef.style.width = `${width}px`;
    },
    getValueByLimitNumber(inputValue) {
      const {
        allowInputOverMax,
        maxlength,
        maxcharacter
      } = this;
      if (!(maxlength || maxcharacter) || allowInputOverMax || !inputValue) return inputValue;
      if (maxlength) {
        return helper.limitUnicodeMaxLength(inputValue, maxlength);
      }
      if (maxcharacter) {
        const r = utils_helper.getCharacterLength(inputValue, maxcharacter);
        if (typeof r === "object") return r.characters;
      }
    },
    onValidateChange() {
      var _this$onValidate;
      const error = this.innerStatus ? "exceed-maximum" : void 0;
      (_this$onValidate = this.onValidate) === null || _this$onValidate === void 0 ? void 0 : _this$onValidate.call(this, {
        error
      });
      this.$emit("validate", {
        error
      });
    }
  },
  render(h) {
    const inputEvents = getValidAttrs({
      focus: this.emitFocus,
      blur: this.formatAndEmitBlur,
      keydown: this.handleKeydown,
      keyup: this.handleKeyUp,
      keypress: this.handleKeypress,
      paste: this.onHandlePaste,
      change: () => {}
    });
    const wrapperAttrs = utils_helper.omit(this.$attrs, Object.keys(this.inputAttrs));
    const wrapperEvents = utils_helper.omit(this.$listeners, [...Object.keys(inputEvents), "input", "paste"]);
    const prefixIcon = this.renderIcon(h, this.prefixIcon, "prefix-icon");
    let suffixIcon = this.renderIcon(h, this.suffixIcon, "suffix-icon");
    let passwordIcon = this.renderIcon(h, void 0, "password-icon");
    const label = utils_renderNode.renderLNodeJSX(this, "label");
    const suffix = utils_renderNode.renderLNodeJSX(this, "suffix");
    const limitNode = this.limitNumber && this.showLimitNumber ? h("div", {
      "class": `${this.classPrefix}-input__limit-number`
    }, [this.limitNumber]) : null;
    const labelContent = label ? h("div", {
      "class": `${this.componentName}__prefix`
    }, [label]) : null;
    const suffixContent = suffix || limitNode ? h("div", {
      "class": `${this.componentName}__suffix`
    }, [suffix, limitNode]) : null;
    const {
      BrowseIcon,
      BrowseOffIcon,
      CloseCircleFilledIcon
    } = this.useGlobalIcon({
      BrowseIcon: iconsVue.BrowseIcon,
      BrowseOffIcon: iconsVue.BrowseOffIcon,
      CloseCircleFilledIcon: iconsVue.CloseCircleFilledIcon
    });
    if (this.type === "password") {
      if (this.renderType === "password") suffixIcon = h(BrowseOffIcon, {
        "class": `${this.componentName}__suffix-clear`,
        "nativeOn": {
          "click": this.emitPassword
        }
      });else if (this.renderType === "text") suffixIcon = h(BrowseIcon, {
        "class": `${this.componentName}__suffix-clear`,
        "nativeOn": {
          "click": this.emitPassword
        }
      });
    }
    if (this.showClear) {
      if (this.type === "password") {
        passwordIcon = h(CloseCircleFilledIcon, {
          "class": `${this.componentName}__suffix-clear`,
          "nativeOn": {
            "click": this.emitClear
          }
        });
      } else {
        suffixIcon = h(CloseCircleFilledIcon, {
          "class": `${this.componentName}__suffix-clear`,
          "nativeOn": {
            "click": this.emitClear
          }
        });
      }
    }
    const classes = [this.inputClasses, this.inputClass, {
      [`${this.componentName}--prefix`]: prefixIcon || labelContent,
      [`${this.componentName}--suffix`]: suffixIcon || suffixContent
    }];
    const inputNode = h("div", {
      "class": classes,
      "on": {
        "click": this.onRootClick,
        ...wrapperEvents,
        "mouseenter": this.onInputMouseenter,
        "mouseleave": this.onInputMouseleave,
        "wheel": this.onHandleMousewheel
      },
      "attrs": {
        ...wrapperAttrs
      }
    }, [prefixIcon ? h("span", {
      "class": [`${this.componentName}__prefix`, `${this.componentName}__prefix-icon`]
    }, [prefixIcon]) : null, labelContent, this.showInput && h("input", {
      "attrs": {
        ...this.inputAttrs
      },
      "on": {
        ...inputEvents,
        "input": this.handleInput,
        "compositionstart": this.compositionstartHandler,
        "compositionend": this.compositionendHandler
      },
      "ref": "inputRef",
      "class": `${this.componentName}__inner`,
      "domProps": {
        "value": this.composingRef ? this.composingRefValue : this.inputValue
      }
    }), this.autoWidth && h("span", {
      "ref": "inputPreRef",
      "class": `${this.classPrefix}-input__input-pre`
    }, [this.value || this.tPlaceholder]), suffixContent, passwordIcon ? h("span", {
      "class": [`${this.componentName}__suffix`, `${this.componentName}__suffix-icon`, `${this.componentName}__clear`]
    }, [passwordIcon]) : null, suffixIcon ? h("span", {
      "class": [`${this.componentName}__suffix`, `${this.componentName}__suffix-icon`, {
        [`${this.componentName}__clear`]: this.showClear
      }]
    }, [suffixIcon]) : null]);
    const tips = utils_renderNode.renderLNodeJSX(this, "tips");
    return h("div", {
      "class": this.inputWrapClass
    }, [inputNode, tips && h("div", {
      "class": `${this.componentName}__tips ${this.componentName}__tips--${this.tStatus || "default"}`
    }, [tips])]);
  }
});

exports["default"] = _Input;
//# sourceMappingURL=input.js.map
