import { defineComponent as ze, useAttrs as He, useSlots as Pe, ref as c, computed as p, watch as z, nextTick as Z, onMounted as Ne, onUnmounted as Ae, openBlock as i, createBlock as ee, mergeProps as De, unref as B, createSlots as Ue, withCtx as x, createElementVNode as f, toDisplayString as k, createElementBlock as d, Fragment as j, renderList as W, withDirectives as H, withKeys as fe, normalizeClass as P, createCommentVNode as N, renderSlot as A, createTextVNode as D, withModifiers as U, createVNode as S, Teleport as Le, Transition as Ve, normalizeStyle as Ke, vModelText as Ge, vShow as te } from "vue";
import { u as qe, a as je, f as We, o as Xe, c as Ye } from "./floating-ui.vue-B4We5rJr.js";
import Je from "@leaflink/snitch";
import { isPlainObject as Qe, isEqual as he, debounce as le } from "es-toolkit";
import { isEmpty as Ze, uniqueId as et } from "es-toolkit/compat";
import tt from "./useSearch.js";
import { DEBOUNCE as lt, KEY_CODES as C } from "./constants.js";
import st from "./directives/clickoutside.js";
import { D as at } from "./MenusPlugin-Bk6UW6o9.js";
import pe from "./Chip.js";
import { _ as nt } from "./Field.vue_vue_type_script_setup_true_lang-CJUQxQdh.js";
import L from "./Icon.js";
import { _ as ot } from "./_plugin-vue_export-helper-CHgC5LLL.js";
const rt = { class: "flex h-input items-center text-sm" }, it = ["id", "aria-labelledby"], ct = ["id", "aria-errormessage", "aria-invalid", "disabled", "multiple", "name"], ut = ["selected", "value", "disabled"], dt = ["aria-controls", "aria-expanded", "aria-label", "aria-disabled"], ft = ["id"], ht = ["onKeypress", "onMousedown"], pt = {
  key: 0,
  class: "stash-select__total"
}, vt = {
  key: 0,
  class: "flex items-center border-b border-blue-500 pr-1.5"
}, mt = ["data-test", "placeholder"], yt = { class: "stash-select__options options my-1.5 w-full border-white bg-white" }, _t = ["data-test", "onClick", "onMouseenter"], gt = {
  key: 0,
  class: "ml-auto pl-1.5"
}, bt = { class: "m-1.5 cursor-default p-1.5" }, Bt = {
  class: "m-1.5 cursor-default p-1.5",
  "data-test": "stash-select|no-options"
}, kt = /* @__PURE__ */ ze({
  name: "ll-select",
  __name: "Select",
  props: {
    preventEmpty: { type: Boolean, default: !1 },
    allowEmpty: { type: [String, Boolean, null], default: null },
    displayBy: { default: "name" },
    searchBy: { default: () => [] },
    trackBy: { default: "id" },
    placeholder: { default: "Select option" },
    error: { default: "" },
    hint: { default: "" },
    icon: { type: [String, Boolean], default: "caret-down" },
    name: { default: void 0 },
    options: { default: () => [] },
    lazy: { type: Function, default: void 0 },
    modelValue: { default: () => [] },
    value: { default: null },
    hideSearch: { type: Boolean, default: !1 },
    searchable: { type: [String, Boolean, null], default: null },
    preserveSearchTerm: { type: Boolean, default: !1 },
    disableFiltering: { type: Boolean, default: !1 },
    single: { type: Boolean, default: !1 },
    noTruncate: { type: Boolean, default: !1 },
    loading: { type: Boolean, default: !1 },
    searchLoading: { type: Boolean, default: !1 },
    selectItemType: { default: "" },
    hideCheck: { type: Boolean, default: !1 },
    searchPlaceholder: { default: "Search" },
    onSearch: { type: Function, default: void 0 },
    useFuzzySearch: { type: Boolean, default: !1 },
    menuPlacement: { default: "bottom-start" },
    enableTeleport: { type: Boolean, default: !1 },
    teleportTo: { default: `#${at}` },
    addBottomSpace: { type: Boolean },
    errorText: {},
    hintText: {},
    id: {},
    errorId: {},
    isReadOnly: { type: Boolean },
    isRequired: { type: Boolean },
    label: {},
    showOptionalInLabel: { type: Boolean },
    isLabelSrOnly: { type: Boolean },
    fieldset: { type: Boolean },
    isDisabled: { type: Boolean },
    disabled: { type: Boolean }
  },
  emits: ["update:model-value", "clear", "add", "remove", "opened", "closed"],
  setup(ve, { emit: me }) {
    const t = ve, v = me, V = He(), X = Pe(), se = c(null), m = c(null), O = c(null), I = c(null), ae = c(null), R = c(0), M = c(0), a = c([]), ne = c(() => []), y = c(""), h = c(-1), u = c(!1), Y = c({}), oe = c(!1), { floatingStyles: ye, update: _e } = qe(se, O, {
      whileElementsMounted: je,
      placement: t.menuPlacement,
      middleware: [
        We(),
        Xe(({ rects: e, placement: l }) => l.split("-")[0] === "bottom" && R.value > M.value ? R.value - e.reference.height + 6 : 6),
        Ye({
          apply({ availableHeight: e, elements: l, rects: n }) {
            t.enableTeleport && Object.assign(l.floating.style, {
              maxWidth: `${n.reference.width}px`,
              maxHeight: `${Math.min(e, 300)}px`
            });
          }
        })
      ]
    }), F = typeof ResizeObserver < "u" ? new ResizeObserver(() => w()) : null, J = p(() => !t.hideSearch && t.searchable !== "false" && t.searchable !== !1), K = p(() => {
      let e = (oe.value && t.lazy ? t.lazy() : t.options).filter(Boolean);
      return Qe(e[0]) || (e = e.map((l, n) => ({ name: l, id: n }))), e;
    }), ge = p(() => a.value.length ? a.value.map((e) => e[t.displayBy] || e).join(", ") : ""), re = p(() => t.searchLoading || Object.keys(Y.value).length > 0), $ = p(() => t.disableFiltering || !(y.value || "").trim() ? K.value : ne.value(y.value)), be = p(() => R.value <= M.value), Be = p(
      () => !u.value && !t.single && !be.value && a.value.length
    ), ke = p(() => [a.value.length, t.selectItemType, "selected"].filter(Boolean).join(" ")), Se = p(() => t.preventEmpty || t.allowEmpty === "false" || t.allowEmpty === !1);
    z(y, (e, l) => l !== e && q(-1)), z(a, () => w(), { deep: !0 }), z(
      () => t.modelValue,
      (e) => {
        if (Array.isArray(e)) {
          const l = e.filter(Boolean);
          he(l, a.value) || (a.value = l);
          return;
        }
        if (!Ze(e)) {
          he(e, a.value[0]) || (a.value[0] = e);
          return;
        }
        a.value = [];
      },
      { immediate: !0 }
    ), z(
      () => t.options,
      () => {
        const { searchFor: e } = tt({
          items: p(() => K.value),
          fieldNames: t.searchBy.length ? t.searchBy : [t.displayBy],
          trackBy: t.trackBy
        });
        ne.value = (l) => e(l, { fuzzy: t.useFuzzySearch });
      },
      { immediate: !0 }
    ), z(R, () => we());
    const we = le(() => _e(), 50), w = le(() => de(), 50), Q = (e) => e && typeof e == "object" && "disabled" in e && (e == null ? void 0 : e.disabled), Ee = () => {
      a.value = [], v("update:model-value", t.single ? void 0 : a.value), v("clear");
    }, G = (e) => {
      t.disabled || !e || Q(e) || (T(e) ? _(e) : (t.single && (a.value = []), a.value.push(e), v("update:model-value", t.single ? a.value[0] : a.value), v("add", e)), t.single && E());
    }, Te = (e) => {
      if (t.single) {
        const n = K.value.find((o) => {
          var r;
          return ((r = o[t.trackBy]) == null ? void 0 : r.toString()) === e.target.value;
        });
        G(n);
        return;
      }
      const l = [...e.target.selectedOptions];
      for (const n of [...a.value])
        l.find((r) => {
          var g;
          return r.value === ((g = n[t.trackBy]) == null ? void 0 : g.toString());
        }) || _(n);
      for (const n of l) {
        const o = K.value.find(
          (r) => {
            var g;
            return ((g = r[t.trackBy]) == null ? void 0 : g.toString()) === n.value;
          }
        );
        T(o) || G(o);
      }
    }, _ = (e) => {
      if (t.disabled || Se.value && a.value.length === 1)
        return;
      const l = a.value.findIndex((n) => n[t.trackBy] === e[t.trackBy]);
      if (l === -1) {
        Je.warn("ll-select: could not find option to remove", e);
        return;
      }
      a.value.splice(l, 1), v("update:model-value", t.single ? a.value[0] : a.value), v("remove", e, l);
    }, ie = () => {
      u.value || (w(), u.value = !0, v("opened"), J.value && Z(() => {
        var e;
        (e = ae.value) == null || e.focus({ preventScroll: !0 });
      }));
    }, E = () => {
      var e;
      u.value && v("closed", a.value), q(-1), u.value = !1, t.preserveSearchTerm || (y.value = ""), (e = m.value) == null || e.blur();
    }, xe = async (e) => {
      if (await Z(), !m.value)
        return;
      if (![C.ENTER, C.ESCAPE].includes(e.keyCode)) {
        const n = m.value.querySelector(".stash-select__option--highlighted"), o = n == null ? void 0 : n.getBoundingClientRect(), r = m.value.getBoundingClientRect();
        if (!o || !r)
          return;
        (o.bottom >= r.bottom || o.top <= r.top + o.height) && (n == null || n.scrollIntoView({ block: "nearest", inline: "nearest" }));
      }
    }, q = (e) => {
      h.value = e;
    }, Ce = (e) => {
      if (e.keyCode === C.ESCAPE)
        E();
      else if (e.keyCode === C.DOWN && h.value < $.value.length - 1 && u.value)
        h.value++;
      else if (e.keyCode === C.UP && h.value > 0)
        u.value && h.value--, O.value && J.value && h.value === 0 && (O.value.scrollTop -= 100);
      else if (e.keyCode === C.ENTER && h.value !== -1 && u.value)
        G($.value[h.value]);
      else
        return;
      e.preventDefault(), xe(e);
    }, ce = le(function() {
      Oe();
    }, lt.FAST), Oe = async function() {
      if (!t.onSearch)
        return;
      const e = et("search-request-");
      try {
        Y.value[e] = !0, await t.onSearch(y.value);
      } finally {
        delete Y.value[e];
      }
    }, Ie = (e, l) => [
      {
        "stash-select__option": !0,
        "stash-select__option--disabled": Q(e),
        "stash-select__option--highlighted": h.value === l,
        "stash-select__option--selected": T(e)
      },
      // @deprecated
      // backwards compatibility
      {
        "is-selected": h.value === l,
        "bg-ice-200": h.value === l,
        "bg-blue-100 text-ice-700": T(e)
      }
    ], T = (e) => e == null ? !1 : a.value.some((l) => (l == null ? void 0 : l[t.trackBy]) === e[t.trackBy]);
    function ue(e) {
      var o, r;
      if (!e)
        return !1;
      const l = (o = m.value) == null ? void 0 : o.contains(e), n = (r = O.value) == null ? void 0 : r.contains(e);
      return l || n;
    }
    function Re(e) {
      const l = e.relatedTarget;
      !ue(l) && l && E();
    }
    function Me(e) {
      const l = e.target;
      ue(l) || E();
    }
    const Fe = () => {
      q(-1);
    }, de = async () => {
      await Z(), I.value && m.value && (M.value = M.value === 0 ? m.value.clientHeight : M.value, R.value = I.value.clientHeight);
    };
    return Ne(() => {
      if (V.onInput)
        throw new Error("ll-select: use the @update:model-value event instead of @input.");
      F && I.value && F.observe(I.value), window.addEventListener("resize", w), w();
    }), Ae(() => {
      window.removeEventListener("resize", de), F == null || F.disconnect(), w.cancel();
    }), (e, l) => {
      var n;
      return i(), ee(nt, De(t, {
        class: ["input ll-select stash-select relative", B(V).class],
        "data-test": "stash-select",
        "error-text": t.errorText || t.error,
        "hint-text": t.hintText || t.hint
      }), Ue({ _: 2 }, [
        t.isReadOnly ? {
          name: "default",
          fn: x(({ fieldId: o, labelId: r }) => [
            f("div", rt, [
              f("span", {
                id: o,
                "aria-labelledby": r,
                class: "show-empty h-min"
              }, k(ge.value), 9, it)
            ])
          ]),
          key: "0"
        } : {
          name: "default",
          fn: x(({ fieldId: o, fieldErrorId: r, hasError: g }) => [
            f("select", {
              id: o,
              "aria-errormessage": r,
              "aria-invalid": g,
              class: "sr-only",
              disabled: t.disabled,
              multiple: !t.single,
              name: t.name,
              onChange: Te
            }, [
              (i(!0), d(j, null, W($.value, (s, b) => (i(), d("option", {
                key: `srOnlyOption-${b}`,
                selected: T(s),
                value: s[t.trackBy],
                disabled: Q(s)
              }, k(s[t.displayBy] || ""), 9, ut))), 128)),
              l[5] || (l[5] = f("option", { value: "" }, null, -1))
            ], 40, ct),
            H((i(), d("div", {
              ref_key: "selectRef",
              ref: se,
              role: "listbox",
              "aria-hidden": "true",
              class: P(["stash-select__content-wrapper", [
                {
                  "stash-select--disabled": !!t.disabled,
                  "stash-select--error": !!(t.errorText || t.error),
                  "stash-select--active": u.value,
                  "stash-select--single": t.single
                },
                // @deprecated
                // backwards compatibility
                {
                  "is-active": u.value,
                  "is-single": t.single,
                  "is-disabled": t.disabled
                }
              ]]),
              "aria-controls": "listbox-" + o,
              "aria-expanded": u.value,
              "aria-label": t.placeholder,
              "aria-disabled": t.disabled || void 0,
              onKeydown: Ce,
              onKeyup: fe(E, ["esc"])
            }, [
              f("div", {
                id: "listbox-" + o,
                ref_key: "contentRef",
                ref: m,
                class: "input-field stash-select__content",
                tabindex: "0",
                "data-test": "stash-select|dropdown-trigger",
                onFocusin: ie,
                onFocusinOnce: l[4] || (l[4] = (s) => oe.value = !0),
                onFocusout: Re,
                onKeydown: ie,
                onMouseleave: Fe
              }, [
                f("ul", {
                  ref_key: "chipsRef",
                  ref: I,
                  class: "stash-select__chips"
                }, [
                  a.value.length ? N("", !0) : (i(), d("li", {
                    key: 0,
                    class: P(["stash-select__placeholder mr-0 pl-1.5", { truncate: !t.noTruncate }])
                  }, k(t.placeholder), 3)),
                  t.single ? (i(!0), d(j, { key: 1 }, W(a.value, (s) => (i(), d("li", {
                    key: `chip-${s[t.trackBy]}`,
                    class: P(["stash-select__selected mr-0 pl-1.5", { truncate: !t.noTruncate }])
                  }, [
                    A(e.$slots, "selected", {
                      option: s,
                      onRemove: () => _(s),
                      chipSelectedClass: "stash-select__chip"
                    }, () => [
                      D(k(s[t.displayBy] || s) + " ", 1),
                      f("button", {
                        tabindex: "-1",
                        class: "stash-select__remove",
                        onKeypress: fe(U((b) => _(s), ["prevent"]), ["enter"]),
                        onMousedown: U((b) => _(s), ["prevent", "stop"])
                      }, [
                        S(L, {
                          icon: "close",
                          name: "close",
                          size: "small"
                        })
                      ], 40, ht)
                    ])
                  ], 2))), 128)) : (i(!0), d(j, { key: 2 }, W(a.value, (s) => (i(), d("li", {
                    key: `chip-${s[t.trackBy]}`,
                    class: "inline-block"
                  }, [
                    A(e.$slots, "selected", {
                      option: s,
                      onRemove: () => _(s),
                      chipSelectedClass: "stash-select__chip"
                    }, () => [
                      S(pe, {
                        "bg-color": "blue-500",
                        "is-removable": "",
                        "text-color": "white",
                        class: "stash-select__chip",
                        onRemove: (b) => _(s)
                      }, {
                        default: x(() => [
                          D(k(s[t.displayBy] || s), 1)
                        ]),
                        _: 2
                      }, 1032, ["onRemove"])
                    ])
                  ]))), 128))
                ], 512),
                Be.value ? (i(), d("div", pt, [
                  S(pe, {
                    "bg-color": "blue-500",
                    "is-removable": "",
                    "text-color": "white",
                    class: "stash-select__chip",
                    onRemove: Ee
                  }, {
                    default: x(() => [
                      D(k(ke.value), 1)
                    ]),
                    _: 1
                  })
                ])) : N("", !0),
                t.icon ? (i(), ee(L, {
                  key: 1,
                  class: P(["stash-select__icon", { "text-ice-500": t.disabled }]),
                  "data-test": "stash-select|toggle-icon",
                  name: t.icon,
                  onMousedown: l[0] || (l[0] = U((s) => u.value && E(), ["prevent"]))
                }, null, 8, ["name", "class"])) : N("", !0),
                (i(), ee(Le, {
                  to: t.teleportTo,
                  disabled: !t.enableTeleport
                }, [
                  S(Ve, { name: "fade" }, {
                    default: x(() => [
                      H(f("div", {
                        ref_key: "optionsWrapperRef",
                        ref: O,
                        class: "stash-select stash-select__border-selector w-full shadow-2xl",
                        style: Ke(B(ye)),
                        onClick: l[3] || (l[3] = U(() => {
                        }, ["stop"]))
                      }, [
                        J.value ? (i(), d("div", vt, [
                          H(f("input", {
                            ref_key: "searchRef",
                            ref: ae,
                            "onUpdate:modelValue": l[1] || (l[1] = (s) => y.value = s),
                            type: "text",
                            autocomplete: "off",
                            class: "stash-select__search",
                            "data-test": B(V)["data-test"] ? B(V)["data-test"] + "-search" : "stash-select|search",
                            placeholder: t.searchPlaceholder,
                            spellcheck: !1,
                            onInput: l[2] || (l[2] = //@ts-ignore
                            (...s) => B(ce) && B(ce)(...s))
                          }, null, 40, mt), [
                            [Ge, y.value]
                          ]),
                          S(L, {
                            name: "search",
                            class: "text-ice-500"
                          })
                        ])) : N("", !0),
                        f("ul", yt, [
                          (i(!0), d(j, null, W($.value, (s, b) => (i(), d("li", {
                            key: `option-${s[t.trackBy]}`,
                            "data-test": s[t.trackBy],
                            class: P(Ie(s, b)),
                            onClick: ($e) => G(s),
                            onMouseenter: U(($e) => q(b), ["self"])
                          }, [
                            A(e.$slots, "option", { option: s }, () => [
                              D(k(s[t.displayBy] || s), 1)
                            ]),
                            T(s) && !t.hideCheck ? (i(), d("span", gt, [
                              S(L, {
                                class: "text-blue-500",
                                name: "check"
                              })
                            ])) : N("", !0)
                          ], 42, _t))), 128)),
                          H(f("li", bt, [
                            S(L, {
                              "data-test": "stash-select|options-loading",
                              name: "working",
                              class: "animate-spin text-ice-500"
                            })
                          ], 512), [
                            [te, t.loading || re.value]
                          ]),
                          H(f("li", Bt, [
                            A(e.$slots, "no-options", {}, () => [
                              l[6] || (l[6] = D(" No options ", -1))
                            ])
                          ], 512), [
                            [te, !t.loading && !re.value && !$.value.length]
                          ])
                        ])
                      ], 4), [
                        [te, u.value && !t.disabled]
                      ])
                    ]),
                    _: 3
                  })
                ], 8, ["to", "disabled"]))
              ], 40, ft)
            ], 42, dt)), [
              [B(st), Me]
            ])
          ]),
          key: "1"
        },
        (n = X.hint) != null && n.call(X) ? {
          name: "hint",
          fn: x(() => [
            A(e.$slots, "hint")
          ]),
          key: "2"
        } : void 0
      ]), 1040, ["class", "error-text", "hint-text"]);
    };
  }
}), St = {}, wt = {
  $style: St
}, Dt = /* @__PURE__ */ ot(kt, [["__cssModules", wt]]);
export {
  Dt as default
};
//# sourceMappingURL=Select.js.map
