"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const aria = require("../../../constants/aria.js");
const event = require("../../../constants/event.js");
const event$1 = require("../../../utils/dom/event.js");
const shared_esmBundler = require("../../../../../@vue/shared/dist/shared.esm-bundler.js");
const error = require("../../../utils/error.js");
const index = require("../../../hooks/use-namespace/index.js");
const index$1 = require("../../../hooks/use-id/index.js");
const index$7 = require("../../icon/index.js");
const useFormCommonProps = require("../../form/src/hooks/use-form-common-props.js");
const index$4 = require("../../tooltip/index.js");
const input = require("../../input/src/input.js");
const index$5 = require("../../input/index.js");
const autocomplete = require("./autocomplete.js");
const index$6 = require("../../scrollbar/index.js");
const index$3 = require("../../../../node_modules/@vueuse/core/index.js");
const index$8 = require("../../../../../@element-plus/icons-vue/dist/index.js");
const Vue = require("vue");
const pick = require("../../../../../lodash-es/pick.js");
const index$2 = require("../../../../node_modules/@vueuse/shared/index.js");
const _hoisted_1 = ["aria-expanded", "aria-owns"];
const _hoisted_2 = { key: 0 };
const _hoisted_3 = [
  "id",
  "aria-selected",
  "onClick"
];
const COMPONENT_NAME = "ElAutocomplete";
var autocomplete_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ Vue.defineComponent({
  name: COMPONENT_NAME,
  inheritAttrs: false,
  __name: "autocomplete",
  props: autocomplete.autocompleteProps,
  emits: autocomplete.autocompleteEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const passInputProps = Vue.computed(() => pick.default(props, Object.keys(input.inputProps)));
    const rawAttrs = Vue.useAttrs();
    const disabled = useFormCommonProps.useFormDisabled();
    const ns = index.useNamespace("autocomplete");
    const inputRef = Vue.ref();
    const regionRef = Vue.ref();
    const popperRef = Vue.ref();
    const listboxRef = Vue.ref();
    let readonly = false;
    let ignoreFocusEvent = false;
    const suggestions = Vue.ref([]);
    const highlightedIndex = Vue.ref(-1);
    const dropdownWidth = Vue.ref("");
    const activated = Vue.ref(false);
    const suggestionDisabled = Vue.ref(false);
    const loading = Vue.ref(false);
    const listboxId = index$1.useId();
    const styles = Vue.computed(() => rawAttrs.style);
    const suggestionVisible = Vue.computed(() => {
      return (suggestions.value.length > 0 || loading.value) && activated.value;
    });
    const suggestionLoading = Vue.computed(() => !props.hideLoading && loading.value);
    const refInput = Vue.computed(() => {
      if (inputRef.value) return Array.from(inputRef.value.$el.querySelectorAll("input"));
      return [];
    });
    const onSuggestionShow = () => {
      if (suggestionVisible.value) dropdownWidth.value = `${inputRef.value.$el.offsetWidth}px`;
    };
    const onHide = () => {
      highlightedIndex.value = -1;
    };
    const getData = async (queryString) => {
      if (suggestionDisabled.value) return;
      const cb = (suggestionList) => {
        loading.value = false;
        if (suggestionDisabled.value) return;
        if (shared_esmBundler.isArray(suggestionList)) {
          suggestions.value = suggestionList;
          highlightedIndex.value = props.highlightFirstItem ? 0 : -1;
        } else error.throwError(COMPONENT_NAME, "autocomplete suggestions must be an array");
      };
      loading.value = true;
      if (shared_esmBundler.isArray(props.fetchSuggestions)) cb(props.fetchSuggestions);
      else {
        const result = await props.fetchSuggestions(queryString, cb);
        if (shared_esmBundler.isArray(result)) cb(result);
      }
    };
    const debouncedGetData = index$2.useDebounceFn(getData, Vue.computed(() => props.debounce));
    const handleInput = (value) => {
      const valuePresented = !!value;
      emit(event.INPUT_EVENT, value);
      emit(event.UPDATE_MODEL_EVENT, value);
      suggestionDisabled.value = false;
      activated.value || (activated.value = valuePresented);
      if (!props.triggerOnFocus && !value) {
        suggestionDisabled.value = true;
        suggestions.value = [];
        return;
      }
      debouncedGetData(value);
    };
    const handleMouseDown = (event2) => {
      var _a;
      if (disabled.value) return;
      if (((_a = event2.target) == null ? void 0 : _a.tagName) !== "INPUT" || refInput.value.includes(document.activeElement)) activated.value = true;
    };
    const handleChange = (value) => {
      emit(event.CHANGE_EVENT, value);
    };
    const handleFocus = (evt) => {
      if (!ignoreFocusEvent) {
        activated.value = true;
        emit("focus", evt);
        const queryString = props.modelValue ?? "";
        if (props.triggerOnFocus && !readonly) debouncedGetData(String(queryString));
      } else ignoreFocusEvent = false;
    };
    const handleBlur = (evt) => {
      setTimeout(() => {
        var _a;
        if ((_a = popperRef.value) == null ? void 0 : _a.isFocusInsideContent()) {
          ignoreFocusEvent = true;
          return;
        }
        activated.value && close();
        emit("blur", evt);
      });
    };
    const handleClear = () => {
      activated.value = false;
      emit(event.UPDATE_MODEL_EVENT, "");
      emit("clear");
    };
    const handleKeyEnter = async () => {
      var _a;
      if ((_a = inputRef.value) == null ? void 0 : _a.isComposing) return;
      if (suggestionVisible.value && highlightedIndex.value >= 0 && highlightedIndex.value < suggestions.value.length) handleSelect(suggestions.value[highlightedIndex.value]);
      else {
        if (props.selectWhenUnmatched) {
          emit("select", { value: props.modelValue });
          suggestions.value = [];
          highlightedIndex.value = -1;
        }
        activated.value = true;
        debouncedGetData(String(props.modelValue));
      }
    };
    const handleKeyEscape = (evt) => {
      if (suggestionVisible.value) {
        evt.preventDefault();
        evt.stopPropagation();
        close();
      }
    };
    const close = () => {
      activated.value = false;
    };
    const focus = () => {
      var _a;
      (_a = inputRef.value) == null ? void 0 : _a.focus();
    };
    const blur = () => {
      var _a;
      (_a = inputRef.value) == null ? void 0 : _a.blur();
    };
    const handleSelect = async (item) => {
      emit(event.INPUT_EVENT, item[props.valueKey]);
      emit(event.UPDATE_MODEL_EVENT, item[props.valueKey]);
      emit("select", item);
      suggestions.value = [];
      highlightedIndex.value = -1;
    };
    const highlight = (index2) => {
      var _a, _b;
      if (!suggestionVisible.value || loading.value) return;
      if (index2 < 0) {
        if (!props.loopNavigation) {
          highlightedIndex.value = -1;
          return;
        }
        index2 = suggestions.value.length - 1;
      }
      if (index2 >= suggestions.value.length) index2 = props.loopNavigation ? 0 : suggestions.value.length - 1;
      const [suggestion, suggestionList] = getSuggestionContext();
      const highlightItem = suggestionList[index2];
      const scrollTop = suggestion.scrollTop;
      const { offsetTop, scrollHeight } = highlightItem;
      if (offsetTop + scrollHeight > scrollTop + suggestion.clientHeight) suggestion.scrollTop = offsetTop + scrollHeight - suggestion.clientHeight;
      if (offsetTop < scrollTop) suggestion.scrollTop = offsetTop;
      highlightedIndex.value = index2;
      (_b = (_a = inputRef.value) == null ? void 0 : _a.ref) == null ? void 0 : _b.setAttribute("aria-activedescendant", `${listboxId.value}-item-${highlightedIndex.value}`);
    };
    const getSuggestionContext = () => {
      const suggestion = regionRef.value.querySelector(`.${ns.be("suggestion", "wrap")}`);
      return [suggestion, suggestion.querySelectorAll(`.${ns.be("suggestion", "list")} li`)];
    };
    const stopHandle = index$3.onClickOutside(listboxRef, (event2) => {
      var _a;
      if ((_a = popperRef.value) == null ? void 0 : _a.isFocusInsideContent()) return;
      const hadIgnoredFocus = ignoreFocusEvent;
      ignoreFocusEvent = false;
      if (!suggestionVisible.value) return;
      if (hadIgnoredFocus) handleBlur(new FocusEvent("blur", event2));
      else close();
    });
    const handleKeydown = (e) => {
      switch (event$1.getEventCode(e)) {
        case aria.EVENT_CODE.up:
          e.preventDefault();
          highlight(highlightedIndex.value - 1);
          break;
        case aria.EVENT_CODE.down:
          e.preventDefault();
          highlight(highlightedIndex.value + 1);
          break;
        case aria.EVENT_CODE.enter:
        case aria.EVENT_CODE.numpadEnter:
          e.preventDefault();
          handleKeyEnter();
          break;
        case aria.EVENT_CODE.tab:
          close();
          break;
        case aria.EVENT_CODE.esc:
          handleKeyEscape(e);
          break;
        case aria.EVENT_CODE.home:
          e.preventDefault();
          highlight(0);
          break;
        case aria.EVENT_CODE.end:
          e.preventDefault();
          highlight(suggestions.value.length - 1);
          break;
        case aria.EVENT_CODE.pageUp:
          e.preventDefault();
          highlight(Math.max(0, highlightedIndex.value - 10));
          break;
        case aria.EVENT_CODE.pageDown:
          e.preventDefault();
          highlight(Math.min(suggestions.value.length - 1, highlightedIndex.value + 10));
          break;
      }
    };
    Vue.onBeforeUnmount(() => {
      stopHandle == null ? void 0 : stopHandle();
    });
    Vue.onMounted(() => {
      var _a;
      const inputElement = (_a = inputRef.value) == null ? void 0 : _a.ref;
      if (!inputElement) return;
      [
        {
          key: "role",
          value: "textbox"
        },
        {
          key: "aria-autocomplete",
          value: "list"
        },
        {
          key: "aria-controls",
          value: listboxId.value
        },
        {
          key: "aria-activedescendant",
          value: `${listboxId.value}-item-${highlightedIndex.value}`
        }
      ].forEach(({ key, value }) => inputElement.setAttribute(key, value));
      readonly = inputElement.hasAttribute("readonly");
    });
    __expose({
      highlightedIndex,
      activated,
      loading,
      inputRef,
      popperRef,
      suggestions,
      handleSelect,
      handleKeyEnter,
      focus,
      blur,
      close,
      highlight,
      getData
    });
    return (_ctx, _cache) => {
      return Vue.openBlock(), Vue.createBlock(Vue.unref(index$4.ElTooltip), {
        ref_key: "popperRef",
        ref: popperRef,
        visible: suggestionVisible.value,
        placement: __props.placement,
        "fallback-placements": ["bottom-start", "top-start"],
        "popper-class": [Vue.unref(ns).e("popper"), __props.popperClass],
        "popper-style": __props.popperStyle,
        teleported: __props.teleported,
        "append-to": __props.appendTo,
        "gpu-acceleration": false,
        pure: "",
        "manual-mode": "",
        effect: "light",
        trigger: "click",
        transition: `${Vue.unref(ns).namespace.value}-zoom-in-top`,
        persistent: "",
        role: "listbox",
        onBeforeShow: onSuggestionShow,
        onHide
      }, {
        content: Vue.withCtx(() => [Vue.createElementVNode("div", {
          ref_key: "regionRef",
          ref: regionRef,
          class: Vue.normalizeClass([Vue.unref(ns).b("suggestion"), Vue.unref(ns).is("loading", suggestionLoading.value)]),
          style: Vue.normalizeStyle({
            [__props.fitInputWidth ? "width" : "minWidth"]: dropdownWidth.value,
            outline: "none"
          }),
          role: "region"
        }, [
          _ctx.$slots.header ? (Vue.openBlock(), Vue.createElementBlock("div", {
            key: 0,
            class: Vue.normalizeClass(Vue.unref(ns).be("suggestion", "header")),
            onClick: _cache[0] || (_cache[0] = Vue.withModifiers(() => {
            }, ["stop"]))
          }, [Vue.renderSlot(_ctx.$slots, "header")], 2)) : Vue.createCommentVNode("v-if", true),
          Vue.createVNode(Vue.unref(index$6.ElScrollbar), {
            id: Vue.unref(listboxId),
            tag: "ul",
            "wrap-class": Vue.unref(ns).be("suggestion", "wrap"),
            "view-class": Vue.unref(ns).be("suggestion", "list"),
            role: "listbox"
          }, {
            default: Vue.withCtx(() => [suggestionLoading.value ? (Vue.openBlock(), Vue.createElementBlock("li", _hoisted_2, [Vue.renderSlot(_ctx.$slots, "loading", {}, () => [Vue.createVNode(Vue.unref(index$7.ElIcon), { class: Vue.normalizeClass(Vue.unref(ns).is("loading")) }, {
              default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index$8.Loading))]),
              _: 1
            }, 8, ["class"])])])) : (Vue.openBlock(true), Vue.createElementBlock(Vue.Fragment, { key: 1 }, Vue.renderList(suggestions.value, (item, index2) => {
              return Vue.openBlock(), Vue.createElementBlock("li", {
                id: `${Vue.unref(listboxId)}-item-${index2}`,
                key: index2,
                class: Vue.normalizeClass({ highlighted: highlightedIndex.value === index2 }),
                role: "option",
                "aria-selected": highlightedIndex.value === index2,
                onClick: ($event) => handleSelect(item)
              }, [Vue.renderSlot(_ctx.$slots, "default", { item }, () => [Vue.createTextVNode(Vue.toDisplayString(item[__props.valueKey]), 1)])], 10, _hoisted_3);
            }), 128))]),
            _: 3
          }, 8, [
            "id",
            "wrap-class",
            "view-class"
          ]),
          _ctx.$slots.footer ? (Vue.openBlock(), Vue.createElementBlock("div", {
            key: 1,
            class: Vue.normalizeClass(Vue.unref(ns).be("suggestion", "footer")),
            onClick: _cache[1] || (_cache[1] = Vue.withModifiers(() => {
            }, ["stop"]))
          }, [Vue.renderSlot(_ctx.$slots, "footer")], 2)) : Vue.createCommentVNode("v-if", true)
        ], 6)]),
        default: Vue.withCtx(() => [Vue.createElementVNode("div", {
          ref_key: "listboxRef",
          ref: listboxRef,
          class: Vue.normalizeClass([Vue.unref(ns).b(), _ctx.$attrs.class]),
          style: Vue.normalizeStyle(styles.value),
          role: "combobox",
          "aria-haspopup": "listbox",
          "aria-expanded": suggestionVisible.value,
          "aria-owns": Vue.unref(listboxId)
        }, [Vue.createVNode(Vue.unref(index$5.ElInput), Vue.mergeProps({
          ref_key: "inputRef",
          ref: inputRef
        }, Vue.mergeProps(passInputProps.value, _ctx.$attrs), {
          "model-value": __props.modelValue,
          disabled: Vue.unref(disabled),
          onInput: handleInput,
          onChange: handleChange,
          onFocus: handleFocus,
          onBlur: handleBlur,
          onClear: handleClear,
          onKeydown: handleKeydown,
          onMousedown: handleMouseDown
        }), Vue.createSlots({ _: 2 }, [
          _ctx.$slots.prepend ? {
            name: "prepend",
            fn: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "prepend")]),
            key: "0"
          } : void 0,
          _ctx.$slots.append ? {
            name: "append",
            fn: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "append")]),
            key: "1"
          } : void 0,
          _ctx.$slots.prefix ? {
            name: "prefix",
            fn: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "prefix")]),
            key: "2"
          } : void 0,
          _ctx.$slots.suffix ? {
            name: "suffix",
            fn: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "suffix")]),
            key: "3"
          } : void 0
        ]), 1040, ["model-value", "disabled"])], 14, _hoisted_1)]),
        _: 3
      }, 8, [
        "visible",
        "placement",
        "popper-class",
        "popper-style",
        "teleported",
        "append-to",
        "transition"
      ]);
    };
  }
});
exports.default = autocomplete_vue_vue_type_script_setup_true_lang_default;
