"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const utils = require("./utils.js");
const Cell = require("../cell/Cell.js");
const index_esm = require("../../../@vant/use/dist/index.esm.js");
const useId = require("../composables/use-id.js");
const useExpose = require("../composables/use-expose.js");
const index$1 = require("../icon/index.js");
const index = require("../cell/index.js");
const basic = require("../utils/basic.js");
const format = require("../utils/format.js");
const dom = require("../utils/dom.js");
const create = require("../utils/create.js");
const constant = require("../utils/constant.js");
const props = require("../utils/props.js");
const [name, bem] = create.createNamespace("field");
const fieldSharedProps = {
  id: String,
  name: String,
  leftIcon: String,
  rightIcon: String,
  autofocus: Boolean,
  clearable: Boolean,
  maxlength: props.numericProp,
  max: Number,
  min: Number,
  formatter: Function,
  clearIcon: props.makeStringProp("clear"),
  modelValue: props.makeNumericProp(""),
  inputAlign: String,
  placeholder: String,
  autocomplete: String,
  autocapitalize: String,
  autocorrect: String,
  errorMessage: String,
  enterkeyhint: String,
  clearTrigger: props.makeStringProp("focus"),
  formatTrigger: props.makeStringProp("onChange"),
  spellcheck: {
    type: Boolean,
    default: null
  },
  error: {
    type: Boolean,
    default: null
  },
  disabled: {
    type: Boolean,
    default: null
  },
  readonly: {
    type: Boolean,
    default: null
  },
  inputmode: String
};
const fieldProps = basic.extend({}, Cell.cellSharedProps, fieldSharedProps, {
  rows: props.numericProp,
  type: props.makeStringProp("text"),
  rules: Array,
  autosize: [Boolean, Object],
  labelWidth: props.numericProp,
  labelClass: props.unknownProp,
  labelAlign: String,
  showWordLimit: Boolean,
  errorMessageAlign: String,
  colon: {
    type: Boolean,
    default: null
  }
});
var stdin_default = Vue.defineComponent({
  name,
  props: fieldProps,
  emits: ["blur", "focus", "clear", "keypress", "clickInput", "endValidate", "startValidate", "clickLeftIcon", "clickRightIcon", "update:modelValue"],
  setup(props2, {
    emit,
    slots
  }) {
    const id = useId.useId();
    const state = Vue.reactive({
      status: "unvalidated",
      focused: false,
      validateMessage: ""
    });
    const inputRef = Vue.ref();
    const clearIconRef = Vue.ref();
    const customValue = Vue.ref();
    const {
      parent: form
    } = index_esm.useParent(constant.FORM_KEY);
    const getModelValue = () => {
      var _a;
      return String((_a = props2.modelValue) != null ? _a : "");
    };
    const getProp = (key) => {
      if (basic.isDef(props2[key])) {
        return props2[key];
      }
      if (form && basic.isDef(form.props[key])) {
        return form.props[key];
      }
    };
    const showClear = Vue.computed(() => {
      const readonly = getProp("readonly");
      if (props2.clearable && !readonly) {
        const hasValue = getModelValue() !== "";
        const trigger = props2.clearTrigger === "always" || props2.clearTrigger === "focus" && state.focused;
        return hasValue && trigger;
      }
      return false;
    });
    const formValue = Vue.computed(() => {
      if (customValue.value && slots.input) {
        return customValue.value();
      }
      return props2.modelValue;
    });
    const showRequiredMark = Vue.computed(() => {
      var _a;
      const required = getProp("required");
      if (required === "auto") {
        return (_a = props2.rules) == null ? void 0 : _a.some((rule) => rule.required);
      }
      return required;
    });
    const runRules = (rules) => rules.reduce((promise, rule) => promise.then(() => {
      if (state.status === "failed") {
        return;
      }
      let {
        value
      } = formValue;
      if (rule.formatter) {
        value = rule.formatter(value, rule);
      }
      if (!utils.runSyncRule(value, rule)) {
        state.status = "failed";
        state.validateMessage = utils.getRuleMessage(value, rule);
        return;
      }
      if (rule.validator) {
        if (utils.isEmptyValue(value) && rule.validateEmpty === false) {
          return;
        }
        return utils.runRuleValidator(value, rule).then((result) => {
          if (result && typeof result === "string") {
            state.status = "failed";
            state.validateMessage = result;
          } else if (result === false) {
            state.status = "failed";
            state.validateMessage = utils.getRuleMessage(value, rule);
          }
        });
      }
    }), Promise.resolve());
    const resetValidation = () => {
      state.status = "unvalidated";
      state.validateMessage = "";
    };
    const endValidate = () => emit("endValidate", {
      status: state.status,
      message: state.validateMessage
    });
    const validate = (rules = props2.rules) => new Promise((resolve) => {
      resetValidation();
      if (rules) {
        emit("startValidate");
        runRules(rules).then(() => {
          if (state.status === "failed") {
            resolve({
              name: props2.name,
              message: state.validateMessage
            });
            endValidate();
          } else {
            state.status = "passed";
            resolve();
            endValidate();
          }
        });
      } else {
        resolve();
      }
    });
    const validateWithTrigger = (trigger) => {
      if (form && props2.rules) {
        const {
          validateTrigger
        } = form.props;
        const defaultTrigger = basic.toArray(validateTrigger).includes(trigger);
        const rules = props2.rules.filter((rule) => {
          if (rule.trigger) {
            return basic.toArray(rule.trigger).includes(trigger);
          }
          return defaultTrigger;
        });
        if (rules.length) {
          validate(rules);
        }
      }
    };
    const limitValueLength = (value) => {
      var _a;
      const {
        maxlength
      } = props2;
      if (basic.isDef(maxlength) && utils.getStringLength(value) > +maxlength) {
        const modelValue = getModelValue();
        if (modelValue && utils.getStringLength(modelValue) === +maxlength) {
          return modelValue;
        }
        let selectionEnd = (_a = inputRef.value) == null ? void 0 : _a.selectionEnd;
        if (state.focused && selectionEnd) {
          const valueArr = [...value];
          const exceededLength = valueArr.length - +maxlength;
          selectionEnd = utils.getStringLength(value.slice(0, selectionEnd));
          valueArr.splice(selectionEnd - exceededLength, exceededLength);
          return valueArr.join("");
        }
        return utils.cutString(value, +maxlength);
      }
      return value;
    };
    const updateValue = (value, trigger = "onChange") => {
      var _a, _b;
      const originalValue = value;
      value = limitValueLength(value);
      const limitDiffLen = originalValue.length - value.length;
      if (props2.type === "number" || props2.type === "digit") {
        const isNumber = props2.type === "number";
        value = format.formatNumber(value, isNumber, isNumber);
        if (trigger === "onBlur" && value !== "" && (props2.min !== void 0 || props2.max !== void 0)) {
          const adjustedValue = format.clamp(+value, (_a = props2.min) != null ? _a : -Infinity, (_b = props2.max) != null ? _b : Infinity);
          if (+value !== adjustedValue) {
            value = adjustedValue.toString();
          }
        }
      }
      let formatterDiffLen = 0;
      if (props2.formatter && trigger === props2.formatTrigger) {
        const {
          formatter,
          maxlength
        } = props2;
        value = formatter(value);
        if (basic.isDef(maxlength) && utils.getStringLength(value) > +maxlength) {
          value = utils.cutString(value, +maxlength);
        }
        if (inputRef.value && state.focused) {
          const {
            selectionEnd
          } = inputRef.value;
          const bcoVal = utils.cutString(originalValue, selectionEnd);
          formatterDiffLen = formatter(bcoVal).length - bcoVal.length;
        }
      }
      if (inputRef.value && inputRef.value.value !== value) {
        if (state.focused) {
          let {
            selectionStart,
            selectionEnd
          } = inputRef.value;
          inputRef.value.value = value;
          if (basic.isDef(selectionStart) && basic.isDef(selectionEnd)) {
            const valueLen = value.length;
            if (limitDiffLen) {
              selectionStart -= limitDiffLen;
              selectionEnd -= limitDiffLen;
            } else if (formatterDiffLen) {
              selectionStart += formatterDiffLen;
              selectionEnd += formatterDiffLen;
            }
            inputRef.value.setSelectionRange(Math.min(selectionStart, valueLen), Math.min(selectionEnd, valueLen));
          }
        } else {
          inputRef.value.value = value;
        }
      }
      if (value !== props2.modelValue) {
        emit("update:modelValue", value);
      }
    };
    const onInput = (event) => {
      if (!event.target.composing) {
        updateValue(event.target.value);
      }
    };
    const blur = () => {
      var _a;
      return (_a = inputRef.value) == null ? void 0 : _a.blur();
    };
    const focus = () => {
      var _a;
      return (_a = inputRef.value) == null ? void 0 : _a.focus();
    };
    const adjustTextareaSize = () => {
      const input = inputRef.value;
      if (props2.type === "textarea" && props2.autosize && input) {
        utils.resizeTextarea(input, props2.autosize);
      }
    };
    const onFocus = (event) => {
      state.focused = true;
      emit("focus", event);
      Vue.nextTick(adjustTextareaSize);
      if (getProp("readonly")) {
        blur();
      }
    };
    const onBlur = (event) => {
      state.focused = false;
      updateValue(getModelValue(), "onBlur");
      emit("blur", event);
      if (getProp("readonly")) {
        return;
      }
      validateWithTrigger("onBlur");
      Vue.nextTick(adjustTextareaSize);
      dom.resetScroll();
    };
    const onClickInput = (event) => emit("clickInput", event);
    const onClickLeftIcon = (event) => emit("clickLeftIcon", event);
    const onClickRightIcon = (event) => emit("clickRightIcon", event);
    const onClear = (event) => {
      dom.preventDefault(event);
      emit("update:modelValue", "");
      emit("clear", event);
    };
    const showError = Vue.computed(() => {
      if (typeof props2.error === "boolean") {
        return props2.error;
      }
      if (form && form.props.showError && state.status === "failed") {
        return true;
      }
    });
    const labelStyle = Vue.computed(() => {
      const labelWidth = getProp("labelWidth");
      const labelAlign = getProp("labelAlign");
      if (labelWidth && labelAlign !== "top") {
        return {
          width: format.addUnit(labelWidth)
        };
      }
    });
    const onKeypress = (event) => {
      const ENTER_CODE = 13;
      if (event.keyCode === ENTER_CODE) {
        const submitOnEnter = form && form.props.submitOnEnter;
        if (!submitOnEnter && props2.type !== "textarea") {
          dom.preventDefault(event);
        }
        if (props2.type === "search") {
          blur();
        }
      }
      emit("keypress", event);
    };
    const getInputId = () => props2.id || `${id}-input`;
    const getValidationStatus = () => state.status;
    const renderInput = () => {
      const controlClass = bem("control", [getProp("inputAlign"), {
        error: showError.value,
        custom: !!slots.input,
        "min-height": props2.type === "textarea" && !props2.autosize
      }]);
      if (slots.input) {
        return Vue.createVNode("div", {
          "class": controlClass,
          "onClick": onClickInput
        }, [slots.input()]);
      }
      const inputAttrs = {
        id: getInputId(),
        ref: inputRef,
        name: props2.name,
        rows: props2.rows !== void 0 ? +props2.rows : void 0,
        class: controlClass,
        disabled: getProp("disabled"),
        readonly: getProp("readonly"),
        autofocus: props2.autofocus,
        placeholder: props2.placeholder,
        autocomplete: props2.autocomplete,
        autocapitalize: props2.autocapitalize,
        autocorrect: props2.autocorrect,
        enterkeyhint: props2.enterkeyhint,
        spellcheck: props2.spellcheck,
        "aria-labelledby": props2.label ? `${id}-label` : void 0,
        "data-allow-mismatch": "attribute",
        onBlur,
        onFocus,
        onInput,
        onClick: onClickInput,
        onChange: utils.endComposing,
        onKeypress,
        onCompositionend: utils.endComposing,
        onCompositionstart: utils.startComposing
      };
      if (props2.type === "textarea") {
        return Vue.createVNode("textarea", Vue.mergeProps(inputAttrs, {
          "inputmode": props2.inputmode
        }), null);
      }
      return Vue.createVNode("input", Vue.mergeProps(utils.mapInputType(props2.type, props2.inputmode), inputAttrs), null);
    };
    const renderLeftIcon = () => {
      const leftIconSlot = slots["left-icon"];
      if (props2.leftIcon || leftIconSlot) {
        return Vue.createVNode("div", {
          "class": bem("left-icon"),
          "onClick": onClickLeftIcon
        }, [leftIconSlot ? leftIconSlot() : Vue.createVNode(index$1.Icon, {
          "name": props2.leftIcon,
          "classPrefix": props2.iconPrefix
        }, null)]);
      }
    };
    const renderRightIcon = () => {
      const rightIconSlot = slots["right-icon"];
      if (props2.rightIcon || rightIconSlot) {
        return Vue.createVNode("div", {
          "class": bem("right-icon"),
          "onClick": onClickRightIcon
        }, [rightIconSlot ? rightIconSlot() : Vue.createVNode(index$1.Icon, {
          "name": props2.rightIcon,
          "classPrefix": props2.iconPrefix
        }, null)]);
      }
    };
    const renderWordLimit = () => {
      if (props2.showWordLimit && props2.maxlength) {
        const count = utils.getStringLength(getModelValue());
        return Vue.createVNode("div", {
          "class": bem("word-limit")
        }, [Vue.createVNode("span", {
          "class": bem("word-num")
        }, [count]), Vue.createTextVNode("/"), props2.maxlength]);
      }
    };
    const renderMessage = () => {
      if (form && form.props.showErrorMessage === false) {
        return;
      }
      const message = props2.errorMessage || state.validateMessage;
      if (message) {
        const slot = slots["error-message"];
        const errorMessageAlign = getProp("errorMessageAlign");
        return Vue.createVNode("div", {
          "class": bem("error-message", errorMessageAlign)
        }, [slot ? slot({
          message
        }) : message]);
      }
    };
    const renderLabel = () => {
      const labelWidth = getProp("labelWidth");
      const labelAlign = getProp("labelAlign");
      const colon = getProp("colon") ? ":" : "";
      if (slots.label) {
        return [slots.label(), colon];
      }
      if (props2.label) {
        return Vue.createVNode("label", {
          "id": `${id}-label`,
          "for": slots.input ? void 0 : getInputId(),
          "data-allow-mismatch": "attribute",
          "onClick": (event) => {
            dom.preventDefault(event);
            focus();
          },
          "style": labelAlign === "top" && labelWidth ? {
            width: format.addUnit(labelWidth)
          } : void 0
        }, [props2.label + colon]);
      }
    };
    const renderFieldBody = () => [Vue.createVNode("div", {
      "class": bem("body")
    }, [renderInput(), showClear.value && Vue.createVNode(index$1.Icon, {
      "ref": clearIconRef,
      "name": props2.clearIcon,
      "class": bem("clear")
    }, null), renderRightIcon(), slots.button && Vue.createVNode("div", {
      "class": bem("button")
    }, [slots.button()])]), renderWordLimit(), renderMessage()];
    useExpose.useExpose({
      blur,
      focus,
      validate,
      formValue,
      resetValidation,
      getValidationStatus
    });
    Vue.provide(index_esm.CUSTOM_FIELD_INJECTION_KEY, {
      customValue,
      resetValidation,
      validateWithTrigger
    });
    Vue.watch(() => props2.modelValue, () => {
      updateValue(getModelValue());
      resetValidation();
      validateWithTrigger("onChange");
      Vue.nextTick(adjustTextareaSize);
    });
    Vue.onMounted(() => {
      updateValue(getModelValue(), props2.formatTrigger);
      Vue.nextTick(adjustTextareaSize);
    });
    index_esm.useEventListener("touchstart", onClear, {
      target: Vue.computed(() => {
        var _a;
        return (_a = clearIconRef.value) == null ? void 0 : _a.$el;
      })
    });
    return () => {
      const disabled = getProp("disabled");
      const labelAlign = getProp("labelAlign");
      const LeftIcon = renderLeftIcon();
      const renderTitle = () => {
        const Label = renderLabel();
        if (labelAlign === "top") {
          return [LeftIcon, Label].filter(Boolean);
        }
        return Label || [];
      };
      return Vue.createVNode(index.Cell, {
        "size": props2.size,
        "class": bem({
          error: showError.value,
          disabled,
          [`label-${labelAlign}`]: labelAlign
        }),
        "center": props2.center,
        "border": props2.border,
        "isLink": props2.isLink,
        "clickable": props2.clickable,
        "titleStyle": labelStyle.value,
        "valueClass": bem("value"),
        "titleClass": [bem("label", [labelAlign, {
          required: showRequiredMark.value
        }]), props2.labelClass],
        "arrowDirection": props2.arrowDirection
      }, {
        icon: LeftIcon && labelAlign !== "top" ? () => LeftIcon : null,
        title: renderTitle,
        value: renderFieldBody,
        extra: slots.extra
      });
    };
  }
});
exports.default = stdin_default;
exports.fieldProps = fieldProps;
exports.fieldSharedProps = fieldSharedProps;
