"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const aria = require("../../../constants/aria.js");
const event$1 = require("../../../constants/event.js");
const event = require("../../../utils/dom/event.js");
const index = require("../../../hooks/use-namespace/index.js");
const index$2 = require("../../select/index.js");
const index$1 = require("../../../../node_modules/@vueuse/core/index.js");
const Vue = require("vue");
const pick = require("../../../../../lodash-es/pick.js");
const useSelect = (props, { attrs, emit }, { select, tree, key }) => {
  const ns = index.useNamespace("tree-select");
  Vue.watch(() => props.data, () => {
    if (props.filterable) Vue.nextTick(() => {
      var _a, _b;
      (_b = tree.value) == null ? void 0 : _b.filter((_a = select.value) == null ? void 0 : _a.states.inputValue);
    });
  }, { flush: "post" });
  const focusLastNode = (listNode) => {
    var _a, _b;
    const lastNode = listNode.at(-1);
    if (lastNode.expanded && lastNode.childNodes.at(-1)) focusLastNode([lastNode.childNodes.at(-1)]);
    else {
      (_b = (_a = tree.value.el$) == null ? void 0 : _a.querySelector(`[data-key="${listNode.at(-1).key}"]`)) == null ? void 0 : _b.focus({ preventScroll: true });
      return;
    }
  };
  Vue.onMounted(() => {
    index$1.useEventListener(() => {
      var _a;
      return (_a = select.value) == null ? void 0 : _a.$el;
    }, "keydown", async (evt) => {
      const code = event.getEventCode(evt);
      const { dropdownMenuVisible } = select.value;
      if ([aria.EVENT_CODE.down, aria.EVENT_CODE.up].includes(code) && dropdownMenuVisible) {
        await Vue.nextTick();
        setTimeout(() => {
          var _a, _b, _c;
          if (aria.EVENT_CODE.up === code) {
            const listNode = tree.value.store.root.childNodes;
            focusLastNode(listNode);
            return;
          }
          (_c = (_b = (_a = select.value.optionsArray[select.value.states.hoveringIndex].$el) == null ? void 0 : _a.parentNode) == null ? void 0 : _b.parentNode) == null ? void 0 : _c.focus({ preventScroll: true });
        });
      }
    }, { capture: true });
  });
  return {
    ...pick.default(Vue.toRefs(props), Object.keys(index$2.ElSelect.props)),
    ...attrs,
    class: Vue.computed(() => attrs.class),
    style: Vue.computed(() => attrs.style),
    "onUpdate:modelValue": (value) => emit(event$1.UPDATE_MODEL_EVENT, value),
    valueKey: key,
    popperClass: Vue.computed(() => {
      const classes = [ns.e("popper")];
      if (props.popperClass) classes.push(props.popperClass);
      return classes.join(" ");
    }),
    filterMethod: (keyword = "") => {
      var _a;
      if (props.filterMethod) props.filterMethod(keyword);
      else if (props.remoteMethod) props.remoteMethod(keyword);
      else (_a = tree.value) == null ? void 0 : _a.filter(keyword);
    }
  };
};
exports.useSelect = useSelect;
