import _ from "../combobox-with-popover/combobox-with-popover.js";
import v from "../input/input.js";
import L from "../chip/chip.js";
import W from "../validation-messages/validation-messages.js";
import { validationMessageValidator as M } from "../../common/validators/index.js";
import { extractNonListeners as B, returnFirstEl as d, extractVueListeners as O, hasSlotContent as T } from "../../common/utils/index.js";
import { POPOVER_APPEND_TO_VALUES as P } from "../popover/popover-constants.js";
import { CHIP_TOP_POSITION as F, CHIP_SIZES as k, MULTI_SELECT_SIZES as H } from "./combobox-multi-select-constants.js";
import { resolveComponent as p, createBlock as f, openBlock as u, mergeProps as g, createSlots as R, withCtx as r, createElementVNode as h, withModifiers as V, renderSlot as m, createElementBlock as b, toDisplayString as C, createVNode as y, normalizeClass as z, Fragment as E, renderList as D, toHandlers as K, withKeys as N, createTextVNode as A } from "vue";
import { _ as U } from "../../_plugin-vue_export-helper-CHgC5LLL.js";
const j = {
  compatConfig: { MODE: 3 },
  name: "DtRecipeComboboxMultiSelect",
  components: {
    DtRecipeComboboxWithPopover: _,
    DtInput: v,
    DtChip: L,
    DtValidationMessages: W
  },
  inheritAttrs: !1,
  props: {
    /**
     * String to use for the input label.
     */
    label: {
      type: String,
      required: !0
    },
    /**
     * Determines visibility of input label.
     * @values true, false
     */
    labelVisible: {
      type: Boolean,
      default: !0
    },
    /**
     * Description for the input
     */
    description: {
      type: String,
      default: ""
    },
    /**
     * Input placeholder
     */
    placeholder: {
      type: String,
      default: "Select one or start typing"
    },
    /**
     * Input validation messages
     */
    inputMessages: {
      type: Array,
      default: () => [],
      validator: (t) => M(t)
    },
    /**
     * Show input validation message
     */
    showInputMessages: {
      type: Boolean,
      default: !0
    },
    // @TODO: https://dialpad.atlassian.net/browse/DP-52324
    // type: {
    //   type: String,
    //   values: ['input', 'select'],
    //   default: 'select',
    // },
    /**
     * Determines if the list is loading
     */
    loading: {
      type: Boolean,
      default: !1
    },
    /**
     * The message when the list is loading
     */
    loadingMessage: {
      type: String,
      default: "loading..."
    },
    /**
     * Determines when to show the list element and also controls the aria-expanded attribute.
     * Leaving this null will have the combobox trigger on input focus by default.
     * If you set this value, the default trigger behavior will be disabled and you can
     * control it as you need.
     */
    showList: {
      type: Boolean,
      default: null
    },
    /**
     * Determines maximum height for the popover before overflow.
     * Possible units rem|px|em
     */
    listMaxHeight: {
      type: String,
      default: "300px"
    },
    /**
     * The selected items
     */
    selectedItems: {
      type: Array,
      default: function() {
        return [];
      }
    },
    /**
     * Would be the maximum number of selections you can make. 0 is unlimited
     */
    maxSelected: {
      type: Number,
      default: 0
    },
    /**
     * Max select message when the max selections is exceeded with the structure:
     * `[{"message": string, "type": VALIDATION_MESSAGE_TYPES }]`
     */
    maxSelectedMessage: {
      type: Array,
      default: function() {
        return [];
      }
    },
    /**
     * Displays the list when the combobox is focused, before the user has typed anything.
     * When this is enabled the list will not close after selection.
     */
    hasSuggestionList: {
      type: Boolean,
      default: !0
    },
    /**
     * Size of the chip, one of `xs`, `sm`, `md`
     */
    size: {
      type: String,
      default: "md",
      validator: (t) => Object.values(H).includes(t)
    },
    /**
     * Sets the element to which the popover is going to append to.
     * 'body' will append to the nearest body (supports shadow DOM).
     * @values 'body', 'parent', HTMLElement,
     */
    appendTo: {
      type: [HTMLElement, String],
      default: "body",
      validator: (t) => P.includes(t) || t instanceof HTMLElement
    },
    /**
     * Named transition when the content display is toggled.
     * @see DtLazyShow
     */
    transition: {
      type: String,
      default: "fade"
    },
    /**
     * Determines whether the combobox should collapse to a single when losing focus.
     * @type {boolean}
     */
    collapseOnFocusOut: {
      type: Boolean,
      default: !1
    },
    /**
     * Determines maximum width for the popover before overflow.
     * Possible units rem|px|em
     */
    listMaxWidth: {
      type: String,
      default: ""
    },
    /**
    * Amount of reserved space (in px) on the right side of the input
    * before the chips and the input caret jump to the next line.
    * default is 64
    */
    reservedRightSpace: {
      type: Number,
      default: 64
    },
    /**
     * Determines the maximum width of a single chip. If the text within this chip exceeds the value
     * it will be truncated with ellipses.
     * Possible units rem|px|em
     */
    chipMaxWidth: {
      type: String,
      default: ""
    },
    /**
     * Additional class name for the input element.
     * Can accept String, Object, and Array, i.e. has the
     * same API as Vue's built-in handling of the class attribute.
     */
    inputClass: {
      type: [String, Object, Array],
      default: ""
    },
    /**
     * Additional class name for the input wrapper element.
     * Can accept all of String, Object, and Array, i.e. has the
     * same api as Vue's built-in handling of the class attribute.
     */
    inputWrapperClass: {
      type: [String, Object, Array],
      default: ""
    },
    /**
     * When true, disables the underlying input.
     */
    disabled: {
      type: Boolean,
      default: !1
    }
  },
  emits: [
    /**
     * Native input event
     *
     * @event input
     * @type {String }
     */
    "input",
    /**
     * Event fired when item selected
     *
     * @event select
     * @type {Number}
     */
    "select",
    /**
     * Event fired when item removed
     *
     * @event remove
     * @type {String}
     */
    "remove",
    /**
     * Event fired when max selected items limit is reached
     *
     * @event max-selected
     * @type {Object}
     */
    "max-selected",
    /**
     * Native keyup event
     *
     * @event keyup
     * @type {KeyboardEvent}
      */
    "keyup",
    /**
     * Native keydown event
     *
     * @event keydown
     * @type {KeyboardEvent}
      */
    "keydown",
    /**
     * Event fired when combobox item is highlighted
     *
     * @event combobox-highlight
     * @type {Object}
     */
    "combobox-highlight"
  ],
  data() {
    return {
      value: "",
      popoverOffset: [0, 4],
      showValidationMessages: !1,
      resizeWindowObserver: null,
      initialInputHeight: null,
      CHIP_SIZES: k,
      hasSlotContent: T,
      inputFocused: !1,
      hideInputText: !1
    };
  },
  computed: {
    inputPlaceHolder() {
      var t;
      return ((t = this.selectedItems) == null ? void 0 : t.length) > 0 ? "" : this.placeholder;
    },
    chipListeners() {
      return {
        keydown: (t) => {
          this.onChipKeyDown(t), this.$emit("keydown", t);
        }
      };
    },
    inputListeners() {
      return {
        ...O(this.$attrs),
        onInput: (t) => {
          this.$emit("input", t), this.hasSuggestionList && this.showComboboxList();
        },
        onKeydown: (t) => {
          this.onInputKeyDown(t);
        },
        onKeyup: (t) => {
          this.$emit("keyup", t);
        },
        onClick: () => {
          this.hasSuggestionList && this.showComboboxList();
        }
      };
    },
    chipWrapperClass() {
      return {
        [`d-recipe-combobox-multi-select__chip-wrapper-${this.size}--collapsed`]: !this.inputFocused && this.collapseOnFocusOut
      };
    }
  },
  watch: {
    selectedItems: {
      deep: !0,
      handler: async function() {
        await this.initSelectedItems();
      }
    },
    chipMaxWidth: {
      async handler() {
        await this.initSelectedItems();
      }
    },
    async label() {
      await this.$nextTick(), this.setChipsTopPosition();
    },
    async description() {
      await this.$nextTick(), this.setChipsTopPosition();
    },
    size: {
      async handler() {
        await this.$nextTick();
        const t = this.getInput();
        this.revertInputPadding(t), this.initialInputHeight = t.getBoundingClientRect().height, this.setInputPadding(), this.setChipsTopPosition();
      }
    }
  },
  async mounted() {
    this.setInitialInputHeight(), this.resizeWindowObserver = new ResizeObserver(async () => {
      this.setChipsTopPosition(), this.setInputPadding();
    }), this.resizeWindowObserver.observe(document.body), await this.initSelectedItems();
  },
  beforeUnmount() {
    var t;
    (t = this.resizeWindowObserver) == null || t.unobserve(document.body);
  },
  methods: {
    extractNonListeners: B,
    comboboxHighlight(t) {
      this.$emit("combobox-highlight", t);
    },
    async initSelectedItems() {
      await this.$nextTick(), this.setInputPadding(), this.setChipsTopPosition(), this.setInputMinWidth(), this.checkMaxSelected();
    },
    onChipRemove(t) {
      var e;
      this.$emit("remove", t), (e = this.$refs.input) == null || e.focus();
    },
    onComboboxSelect(t) {
      this.loading || (this.value = "", this.$emit("select", t));
    },
    showComboboxList() {
      var t;
      this.showList == null && ((t = this.$refs.comboboxWithPopover) == null || t.showComboboxList());
    },
    closeComboboxList() {
      var t;
      this.showList == null && ((t = this.$refs.comboboxWithPopover) == null || t.closeComboboxList());
    },
    getChips() {
      return !this.selectedItems.length || !this.$refs.chips ? null : this.selectedItems.map((e) => this.$refs.chips.find((i) => {
        var o, s, a;
        return ((a = (s = (o = d(i.$el)) == null ? void 0 : o.querySelector(".d-chip__label")) == null ? void 0 : s.textContent) == null ? void 0 : a.trim()) === e;
      })).filter(Boolean).map((e) => d(e.$el));
    },
    getChipButtons() {
      const t = this.getChips();
      return t && t.map((e) => d(e).querySelector("button"));
    },
    getLastChipButton() {
      const t = this.getChipButtons();
      return t && t[t.length - 1];
    },
    getLastChip() {
      const t = this.getChips();
      return t && t[t.length - 1];
    },
    getFirstChip() {
      const t = this.getChips();
      return t && t[0];
    },
    getInput() {
      var t;
      return (t = this.$refs.input) == null ? void 0 : t.$refs.input;
    },
    onChipKeyDown(t) {
      var i;
      const e = (i = t.code) == null ? void 0 : i.toLowerCase();
      e === "arrowleft" ? this.navigateBetweenChips(t.target, !0) : e === "arrowright" && (t.target.id === this.getLastChipButton().id ? this.moveFromChipToInput() : this.navigateBetweenChips(t.target, !1));
    },
    onInputKeyDown(t) {
      var i;
      const e = (i = t.code) == null ? void 0 : i.toLowerCase();
      if (this.selectedItems.length > 0 && t.target.selectionStart === 0) {
        if (t.target.selectionEnd !== t.target.selectionStart)
          return;
        (e === "backspace" || e === "arrowleft") && this.moveFromInputToChip();
      }
    },
    moveFromInputToChip() {
      var t;
      this.getLastChipButton().focus(), (t = this.$refs.input) == null || t.blur(), this.closeComboboxList();
    },
    moveFromChipToInput() {
      var t;
      this.getLastChipButton().blur(), (t = this.$refs.input) == null || t.focus(), this.showComboboxList();
    },
    navigateBetweenChips(t, e) {
      var o;
      const i = this.getChipButtons().indexOf(t), n = e ? i - 1 : i + 1;
      n < 0 || n >= ((o = this.$refs.chips) == null ? void 0 : o.length) || (this.getChipButtons()[i].blur(), this.getChipButtons()[n].focus(), this.closeComboboxList());
    },
    setChipsTopPosition() {
      const t = this.getInput();
      if (!t) return;
      const e = this.$refs.inputSlotWrapper, i = t.getBoundingClientRect().top - e.getBoundingClientRect().top, n = this.$refs.chipsWrapper;
      n.style.top = i - F[this.size] + "px";
    },
    setInputPadding() {
      const t = this.getLastChip(), e = this.getInput(), i = this.$refs.chipsWrapper;
      if (!e || (this.revertInputPadding(e), this.popoverOffset = [0, 4], !t) || this.collapseOnFocusOut && !this.inputFocused) return;
      const n = t.offsetLeft + this.getFullWidth(t), o = e.getBoundingClientRect().width - n;
      o > this.reservedRightSpace ? e.style.paddingLeft = n + "px" : e.style.paddingLeft = "4px";
      const s = i.getBoundingClientRect().height - 4, a = t.getBoundingClientRect().height - 4, c = o > this.reservedRightSpace ? t.offsetTop + 2 : s + a - 9;
      e.style.paddingTop = `${c}px`;
    },
    revertInputPadding(t) {
      t.style.paddingLeft = "", t.style.paddingTop = "", t.style.paddingBottom = "";
    },
    getFullWidth(t) {
      const e = window.getComputedStyle(t);
      return t.offsetWidth + parseInt(e.marginLeft) + parseInt(e.marginRight);
    },
    setInputMinWidth() {
      const t = this.getFirstChip(), e = this.getInput();
      e && (t ? e.style.minWidth = this.getFullWidth(t) + 4 + "px" : e.style.minWidth = "");
    },
    checkMaxSelected() {
      this.maxSelected !== 0 && (this.selectedItems.length > this.maxSelected ? (this.showValidationMessages = !0, this.$emit("max-selected")) : this.showValidationMessages = !1);
    },
    setInitialInputHeight() {
      const t = this.getInput();
      t && (this.initialInputHeight = t.getBoundingClientRect().height);
    },
    async handleInputFocusIn() {
      this.inputFocused = !0, this.collapseOnFocusOut && (this.hideInputText = !1, await this.$nextTick(), this.setInputPadding());
    },
    async handleInputFocusOut() {
      if (this.inputFocused = !1, this.collapseOnFocusOut) {
        this.hideInputText = !0;
        const t = this.getInput();
        if (!t || !t.style.paddingTop)
          return;
        this.revertInputPadding(t);
      }
    }
  }
}, q = { ref: "header" }, Z = {
  key: 1,
  class: "d-recipe-combobox-multi-select__list--loading"
}, G = { ref: "footer" };
function J(t, e, i, n, o, s) {
  const a = p("dt-chip"), c = p("dt-input"), x = p("dt-validation-messages"), I = p("dt-recipe-combobox-with-popover");
  return u(), f(I, g({
    ref: "comboboxWithPopover",
    label: i.label,
    "show-list": i.showList,
    "max-height": i.listMaxHeight,
    "max-width": i.listMaxWidth,
    "popover-offset": o.popoverOffset,
    "has-suggestion-list": i.hasSuggestionList,
    "content-width": "anchor",
    "append-to": i.appendTo,
    transition: i.transition
  }, s.extractNonListeners(t.$attrs), {
    onSelect: s.onComboboxSelect,
    onHighlight: s.comboboxHighlight
  }), R({
    input: r(({ onInput: w }) => [
      h("span", {
        ref: "inputSlotWrapper",
        class: "d-recipe-combobox-multi-select__input-wrapper",
        onFocusin: e[1] || (e[1] = (...l) => s.handleInputFocusIn && s.handleInputFocusIn(...l)),
        onFocusout: e[2] || (e[2] = (...l) => s.handleInputFocusOut && s.handleInputFocusOut(...l))
      }, [
        h("span", {
          ref: "chipsWrapper",
          class: z(["d-recipe-combobox-multi-select__chip-wrapper", s.chipWrapperClass])
        }, [
          (u(!0), b(E, null, D(i.selectedItems, (l) => (u(), f(a, g({
            ref_for: !0,
            ref: "chips",
            key: l,
            "label-class": ["d-chip__label"],
            class: [
              "d-recipe-combobox-multi-select__chip",
              { "d-recipe-combobox-multi-select__chip--truncate": !!i.chipMaxWidth }
            ],
            style: { maxWidth: i.chipMaxWidth },
            size: o.CHIP_SIZES[i.size],
            disabled: i.disabled
          }, K(s.chipListeners), {
            onKeydown: N((S) => s.onChipRemove(l), ["backspace"]),
            onClose: (S) => s.onChipRemove(l)
          }), {
            default: r(() => [
              A(C(l), 1)
            ]),
            _: 2
          }, 1040, ["class", "style", "size", "disabled", "onKeydown", "onClose"]))), 128))
        ], 2),
        y(c, g({
          ref: "input",
          modelValue: o.value,
          "onUpdate:modelValue": e[0] || (e[0] = (l) => o.value = l),
          class: "d-recipe-combobox-multi-select__input",
          "input-class": [
            i.inputClass,
            {
              "d-recipe-combobox-multi-select__input--hidden": o.hideInputText
            }
          ],
          "input-wrapper-class": i.inputWrapperClass,
          disabled: i.disabled,
          "aria-label": i.label,
          label: i.labelVisible ? i.label : "",
          description: i.description,
          placeholder: s.inputPlaceHolder,
          "show-messages": i.showInputMessages,
          messages: i.inputMessages,
          size: i.size
        }, s.inputListeners, { onInput: w }), null, 16, ["modelValue", "input-class", "input-wrapper-class", "disabled", "aria-label", "label", "description", "placeholder", "show-messages", "messages", "size", "onInput"]),
        y(x, {
          "validation-messages": i.maxSelectedMessage,
          "show-messages": o.showValidationMessages
        }, null, 8, ["validation-messages", "show-messages"])
      ], 544)
    ]),
    list: r(() => [
      h("div", {
        ref: "list",
        class: "d-recipe-combobox-multi-select__list",
        onMousedown: e[3] || (e[3] = V(() => {
        }, ["prevent"]))
      }, [
        i.loading ? (u(), b("div", Z, C(i.loadingMessage), 1)) : m(t.$slots, "list", { key: 0 })
      ], 544)
    ]),
    _: 2
  }, [
    o.hasSlotContent(t.$slots.header) ? {
      name: "header",
      fn: r(() => [
        h("div", q, [
          m(t.$slots, "header")
        ], 512)
      ]),
      key: "0"
    } : void 0,
    o.hasSlotContent(t.$slots.footer) ? {
      name: "footer",
      fn: r(() => [
        h("div", G, [
          m(t.$slots, "footer")
        ], 512)
      ]),
      key: "1"
    } : void 0
  ]), 1040, ["label", "show-list", "max-height", "max-width", "popover-offset", "has-suggestion-list", "append-to", "transition", "onSelect", "onHighlight"]);
}
const lt = /* @__PURE__ */ U(j, [["render", J]]);
export {
  lt as default
};
//# sourceMappingURL=combobox-multi-select.js.map
