import { defineComponent, toRefs, computed, unref, provide, reactive, onMounted, nextTick, onBeforeUnmount, resolveComponent, openBlock, createElementBlock, normalizeClass, createElementVNode, normalizeStyle, createVNode, withCtx, toDisplayString, createBlock, Fragment, renderList, createCommentVNode, Transition, withDirectives, vModelText, createSlots, resolveDynamicComponent, renderSlot } from 'vue';
import '../../../directives/index.mjs';
import '../../../hooks/index.mjs';
import { PsInput } from '../../input/index.mjs';
import { PsTooltip } from '../../tooltip/index.mjs';
import { PsScrollbar } from '../../scrollbar/index.mjs';
import { PsTag } from '../../tag/index.mjs';
import { PsIcon } from '../../icon/index.mjs';
import '../../popper/index.mjs';
import '../../../utils/index.mjs';
import { CircleClose, ArrowUp } from '@element-plus/icons-vue';
import Option from './option.mjs';
import PsSelectMenu from './select-dropdown.mjs';
import { useSelectStates, useSelect } from './useSelect.mjs';
import { selectKey } from './token.mjs';
import _export_sfc from '../../../_virtual/plugin-vue_export-helper.mjs';
import ClickOutside from '../../../directives/click-outside/index.mjs';
import { isValidComponentSize } from '../../../utils/vue/validator.mjs';
import { useTooltipContentProps } from '../../tooltip/src/tooltip.mjs';
import { tagProps } from '../../tag/src/tag.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { useLocale } from '../../../hooks/use-locale/index.mjs';
import { useFocus } from '../../../hooks/use-focus/index.mjs';
import { addResizeListener, removeResizeListener } from '../../../utils/dom/resize-event.mjs';
import { getComponentSize } from '../../../utils/vue/size.mjs';
import { useDeprecateAppendToBody } from '../../popper/src/deprecation.mjs';

const COMPONENT_NAME = "PsSelect";
const _sfc_main = defineComponent({
  name: COMPONENT_NAME,
  componentName: COMPONENT_NAME,
  components: {
    PsInput,
    PsSelectMenu,
    PsOption: Option,
    PsTag,
    PsScrollbar,
    PsTooltip,
    PsIcon
  },
  directives: { ClickOutside },
  props: {
    name: String,
    id: String,
    modelValue: {
      type: [Array, String, Number, Boolean, Object],
      default: void 0
    },
    autocomplete: {
      type: String,
      default: "off"
    },
    automaticDropdown: Boolean,
    size: {
      type: String,
      validator: isValidComponentSize
    },
    effect: {
      type: String,
      default: "light"
    },
    disabled: Boolean,
    clearable: Boolean,
    filterable: Boolean,
    allowCreate: Boolean,
    loading: Boolean,
    popperClass: {
      type: String,
      default: ""
    },
    remote: Boolean,
    loadingText: String,
    noMatchText: String,
    noDataText: String,
    remoteMethod: Function,
    filterMethod: Function,
    multiple: Boolean,
    multipleLimit: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String
    },
    defaultFirstOption: Boolean,
    reserveKeyword: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: "value"
    },
    collapseTags: Boolean,
    collapseTagsTooltip: {
      type: Boolean,
      default: false
    },
    popperAppendToBody: {
      type: Boolean,
      default: void 0
    },
    teleported: useTooltipContentProps.teleported,
    persistent: {
      type: Boolean,
      default: true
    },
    clearIcon: {
      type: [String, Object],
      default: CircleClose
    },
    fitInputWidth: {
      type: Boolean,
      default: false
    },
    suffixIcon: {
      type: [String, Object],
      default: ArrowUp
    },
    tagType: { ...tagProps.type, default: "info" },
    offset: {
      type: Number,
      default: 12
    },
    placement: {
      type: String,
      default: "bottom-start"
    },
    showArrow: {
      type: Boolean,
      default: true
    }
  },
  setup(props, ctx) {
    const nsSelect = useNamespace("select");
    const nsInput = useNamespace("input");
    const { t } = useLocale();
    const states = useSelectStates(props);
    const {
      optionsArray,
      selectSize,
      readonly,
      handleResize,
      collapseTagSize,
      debouncedOnInputChange,
      debouncedQueryChange,
      deletePrevTag,
      deleteTag,
      deleteSelected,
      handleOptionSelect,
      scrollToOption,
      setSelected,
      resetInputHeight,
      managePlaceholder,
      showClose,
      selectDisabled,
      iconComponent,
      iconReverse,
      showNewOption,
      emptyText,
      toggleLastOptionHitState,
      resetInputState,
      handleComposition,
      onOptionCreate,
      onOptionDestroy,
      handleMenuEnter,
      handleFocus,
      blur,
      handleBlur,
      handleClearClick,
      handleClose,
      toggleMenu,
      selectOption,
      getValueKey,
      navigateOptions,
      dropMenuVisible,
      reference,
      input,
      tooltipRef,
      tags,
      selectWrapper,
      scrollbar,
      queryChange,
      groupQueryChange
    } = useSelect(props, states, ctx);
    const { focus } = useFocus(reference);
    const {
      inputWidth,
      selected,
      inputLength,
      filteredOptionsCount,
      visible,
      softFocus,
      selectedLabel,
      hoverIndex,
      query,
      inputHovering,
      currentPlaceholder,
      menuVisibleOnFocus,
      isOnComposition,
      isSilentBlur,
      options,
      cachedOptions,
      optionsCount,
      prefixWidth,
      tagInMultiLine
    } = toRefs(states);
    const wrapperKls = computed(() => {
      const classList = [nsSelect.b()];
      const _selectSize = unref(selectSize);
      if (_selectSize) {
        classList.push(nsSelect.m(_selectSize));
      }
      if (props.disabled) {
        classList.push(nsSelect.m("disabled"));
      }
      return classList;
    });
    const selectTagsStyle = computed(() => ({
      maxWidth: `${unref(inputWidth) - 32}px`,
      width: "100%"
    }));
    provide(selectKey, reactive({
      props,
      options,
      optionsArray,
      cachedOptions,
      optionsCount,
      filteredOptionsCount,
      hoverIndex,
      handleOptionSelect,
      onOptionCreate,
      onOptionDestroy,
      selectWrapper,
      selected,
      setSelected,
      queryChange,
      groupQueryChange
    }));
    onMounted(() => {
      states.cachedPlaceHolder = currentPlaceholder.value = props.placeholder || t("el.select.placeholder");
      if (props.multiple && Array.isArray(props.modelValue) && props.modelValue.length > 0) {
        currentPlaceholder.value = "";
      }
      addResizeListener(selectWrapper.value, handleResize);
      if (reference.value && reference.value.$el) {
        const input2 = reference.value.input;
        states.initialInputHeight = input2.getBoundingClientRect().height || getComponentSize(selectSize.value);
      }
      if (props.remote && props.multiple) {
        resetInputHeight();
      }
      nextTick(() => {
        const refEl = reference.value && reference.value.$el;
        if (!refEl)
          return;
        inputWidth.value = refEl.getBoundingClientRect().width;
        if (ctx.slots.prefix) {
          const prefix = refEl.querySelector(`.${nsInput.e("prefix")}`);
          prefixWidth.value = Math.max(prefix.getBoundingClientRect().width + 5, 30);
        }
      });
      setSelected();
    });
    onBeforeUnmount(() => {
      removeResizeListener(selectWrapper.value, handleResize);
    });
    const popperPaneRef = computed(() => {
      var _a, _b;
      return (_b = (_a = tooltipRef.value) == null ? void 0 : _a.popperRef) == null ? void 0 : _b.contentRef;
    });
    const { compatTeleported } = useDeprecateAppendToBody(COMPONENT_NAME, "popperAppendToBody");
    return {
      tagInMultiLine,
      prefixWidth,
      selectSize,
      readonly,
      handleResize,
      collapseTagSize,
      debouncedOnInputChange,
      debouncedQueryChange,
      deletePrevTag,
      deleteTag,
      deleteSelected,
      handleOptionSelect,
      scrollToOption,
      inputWidth,
      selected,
      inputLength,
      filteredOptionsCount,
      visible,
      softFocus,
      selectedLabel,
      hoverIndex,
      query,
      inputHovering,
      currentPlaceholder,
      menuVisibleOnFocus,
      isOnComposition,
      isSilentBlur,
      options,
      resetInputHeight,
      managePlaceholder,
      showClose,
      selectDisabled,
      iconComponent,
      iconReverse,
      showNewOption,
      emptyText,
      toggleLastOptionHitState,
      resetInputState,
      handleComposition,
      handleMenuEnter,
      handleFocus,
      blur,
      handleBlur,
      handleClearClick,
      handleClose,
      toggleMenu,
      selectOption,
      getValueKey,
      navigateOptions,
      dropMenuVisible,
      focus,
      reference,
      input,
      tooltipRef,
      popperPaneRef,
      tags,
      selectWrapper,
      scrollbar,
      wrapperKls,
      selectTagsStyle,
      compatTeleported,
      nsSelect
    };
  }
});
const _hoisted_1 = { class: "select-trigger" };
const _hoisted_2 = ["disabled", "autocomplete"];
const _hoisted_3 = { style: { "height": "100%", "display": "flex", "justify-content": "center", "align-items": "center" } };
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_ps_tag = resolveComponent("ps-tag");
  const _component_ps_tooltip = resolveComponent("ps-tooltip");
  const _component_ps_icon = resolveComponent("ps-icon");
  const _component_ps_input = resolveComponent("ps-input");
  return openBlock(), createElementBlock("div", {
    ref: "selectWrapper",
    class: normalizeClass(_ctx.wrapperKls)
  }, [
    createElementVNode("div", _hoisted_1, [
      _ctx.multiple ? (openBlock(), createElementBlock("div", {
        key: 0,
        ref: "tags",
        class: normalizeClass(_ctx.nsSelect.e("tags")),
        style: normalizeStyle(_ctx.selectTagsStyle)
      }, [
        _ctx.collapseTags && _ctx.selected.length ? (openBlock(), createElementBlock("span", {
          key: 0,
          class: normalizeClass([
            _ctx.nsSelect.b("tags-wrapper"),
            { "has-prefix": _ctx.prefixWidth && _ctx.selected.length }
          ])
        }, [
          createVNode(_component_ps_tag, {
            closable: !_ctx.selectDisabled && !_ctx.selected[0].isDisabled,
            size: _ctx.collapseTagSize,
            hit: _ctx.selected[0].hitState,
            type: _ctx.tagType,
            "disable-transitions": ""
          }, {
            default: withCtx(() => [
              createElementVNode("span", {
                class: normalizeClass(_ctx.nsSelect.e("tags-text")),
                style: normalizeStyle({ maxWidth: _ctx.inputWidth - 123 + "px" })
              }, toDisplayString(_ctx.selected[0].currentLabel), 7)
            ]),
            _: 1
          }, 8, ["closable", "size", "hit", "type"]),
          _ctx.selected.length > 1 ? (openBlock(), createBlock(_component_ps_tag, {
            key: 0,
            closable: false,
            size: _ctx.collapseTagSize,
            type: _ctx.tagType,
            "disable-transitions": ""
          }, {
            default: withCtx(() => [
              _ctx.collapseTagsTooltip ? (openBlock(), createBlock(_component_ps_tooltip, {
                key: 0,
                disabled: _ctx.dropMenuVisible,
                "fallback-placements": ["bottom", "top", "right", "left"],
                effect: _ctx.effect,
                placement: "bottom",
                teleported: false
              }, {
                default: withCtx(() => [
                  createElementVNode("span", {
                    class: normalizeClass(_ctx.nsSelect.e("tags-text"))
                  }, "+ " + toDisplayString(_ctx.selected.length - 1), 3)
                ]),
                content: withCtx(() => [
                  createElementVNode("div", {
                    class: normalizeClass(_ctx.nsSelect.e("collapse-tags"))
                  }, [
                    (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.selected, (item, idx) => {
                      return openBlock(), createElementBlock("div", {
                        key: idx,
                        class: normalizeClass(_ctx.nsSelect.e("collapse-tag"))
                      }, [
                        (openBlock(), createBlock(_component_ps_tag, {
                          key: _ctx.getValueKey(item),
                          class: "in-tooltip",
                          closable: !_ctx.selectDisabled && !item.isDisabled,
                          size: _ctx.collapseTagSize,
                          hit: item.hitState,
                          type: _ctx.tagType,
                          "disable-transitions": "",
                          style: { margin: "2px" }
                        }, {
                          default: withCtx(() => [
                            createElementVNode("span", {
                              class: normalizeClass(_ctx.nsSelect.e("tags-text")),
                              style: normalizeStyle({
                                maxWidth: _ctx.inputWidth - 75 + "px"
                              })
                            }, toDisplayString(item.currentLabel), 7)
                          ]),
                          _: 2
                        }, 1032, ["closable", "size", "hit", "type"]))
                      ], 2);
                    }), 128))
                  ], 2)
                ]),
                _: 1
              }, 8, ["disabled", "effect"])) : (openBlock(), createElementBlock("span", {
                key: 1,
                class: normalizeClass(_ctx.nsSelect.e("tags-text"))
              }, "+ " + toDisplayString(_ctx.selected.length - 1), 3))
            ]),
            _: 1
          }, 8, ["size", "type"])) : createCommentVNode("v-if", true)
        ], 2)) : createCommentVNode("v-if", true),
        createCommentVNode(" <div> "),
        !_ctx.collapseTags ? (openBlock(), createBlock(Transition, {
          key: 1,
          onAfterLeave: _ctx.resetInputHeight
        }, {
          default: withCtx(() => [
            createElementVNode("span", {
              class: normalizeClass([
                _ctx.nsSelect.b("tags-wrapper"),
                { "has-prefix": _ctx.prefixWidth && _ctx.selected.length }
              ])
            }, [
              (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.selected, (item) => {
                return openBlock(), createBlock(_component_ps_tag, {
                  key: _ctx.getValueKey(item),
                  closable: !_ctx.selectDisabled && !item.isDisabled,
                  size: _ctx.collapseTagSize,
                  hit: item.hitState,
                  type: _ctx.tagType,
                  "disable-transitions": ""
                }, {
                  default: withCtx(() => [
                    createElementVNode("span", {
                      class: normalizeClass(_ctx.nsSelect.e("tags-text")),
                      style: normalizeStyle({ maxWidth: _ctx.inputWidth - 75 + "px" })
                    }, toDisplayString(item.currentLabel), 7)
                  ]),
                  _: 2
                }, 1032, ["closable", "size", "hit", "type"]);
              }), 128))
            ], 2)
          ]),
          _: 1
        }, 8, ["onAfterLeave"])) : createCommentVNode("v-if", true),
        createCommentVNode(" </div> "),
        _ctx.filterable ? withDirectives((openBlock(), createElementBlock("input", {
          key: 2,
          ref: "input",
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => _ctx.query = $event),
          type: "text",
          class: normalizeClass([_ctx.nsSelect.e("input"), _ctx.nsSelect.is(_ctx.selectSize)]),
          disabled: _ctx.selectDisabled,
          autocomplete: _ctx.autocomplete,
          style: normalizeStyle({
            marginLeft: _ctx.prefixWidth && !_ctx.selected.length || _ctx.tagInMultiLine ? `${_ctx.prefixWidth}px` : "",
            flexGrow: 1,
            width: `${_ctx.inputLength / (_ctx.inputWidth - 32)}%`,
            maxWidth: `${_ctx.inputWidth - 42}px`
          })
        }, null, 14, _hoisted_2)), [
          [vModelText, _ctx.query]
        ]) : createCommentVNode("v-if", true)
      ], 6)) : createCommentVNode("v-if", true),
      createVNode(_component_ps_input, {
        id: _ctx.id,
        ref: "reference",
        modelValue: _ctx.selectedLabel,
        "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => _ctx.selectedLabel = $event),
        type: "text",
        placeholder: _ctx.currentPlaceholder,
        name: _ctx.name,
        autocomplete: _ctx.autocomplete,
        size: _ctx.selectSize,
        disabled: _ctx.selectDisabled,
        readonly: _ctx.readonly,
        "validate-event": false,
        class: normalizeClass([_ctx.nsSelect.is("focus", _ctx.visible)]),
        tabindex: _ctx.multiple && _ctx.filterable ? -1 : void 0
      }, createSlots({
        suffix: withCtx(() => [
          _ctx.iconComponent && !_ctx.showClose ? (openBlock(), createBlock(_component_ps_icon, {
            key: 0,
            class: normalizeClass([_ctx.nsSelect.e("caret"), _ctx.nsSelect.e("icon"), _ctx.iconReverse])
          }, {
            default: withCtx(() => [
              (openBlock(), createBlock(resolveDynamicComponent(_ctx.iconComponent)))
            ]),
            _: 1
          }, 8, ["class"])) : createCommentVNode("v-if", true),
          _ctx.showClose && _ctx.clearIcon ? (openBlock(), createBlock(_component_ps_icon, {
            key: 1,
            class: normalizeClass([_ctx.nsSelect.e("caret"), _ctx.nsSelect.e("icon")])
          }, {
            default: withCtx(() => [
              (openBlock(), createBlock(resolveDynamicComponent(_ctx.clearIcon)))
            ]),
            _: 1
          }, 8, ["class"])) : createCommentVNode("v-if", true)
        ]),
        _: 2
      }, [
        _ctx.$slots.prefix ? {
          name: "prefix",
          fn: withCtx(() => [
            createElementVNode("div", _hoisted_3, [
              renderSlot(_ctx.$slots, "prefix")
            ])
          ])
        } : void 0
      ]), 1032, ["id", "modelValue", "placeholder", "name", "autocomplete", "size", "disabled", "readonly", "class", "tabindex"])
    ])
  ], 2);
}
var Select = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render], ["__file", "/Users/meng/workspace/element-ps/packages/components/select/src/select.vue"]]);

export { Select as default };
//# sourceMappingURL=select.mjs.map
