import { n as s, C as w } from "../chunks/lib-cortex-element.CVMmyPMC.js";
import { c as b } from "../chunks/component.styles.CRO4Odto.js";
import { s as c, a as u } from "../chunks/animate.El-MpOws.js";
import { c as x } from "../chunks/custom-element.L4WJXn1j.js";
import { w as m } from "../chunks/event.mFzZi4sr.js";
import { L as v } from "../chunks/i18n.BABe9hN4.js";
import { H as k } from "../chunks/slot.j5oheLJC.js";
import { g as f } from "../chunks/tabbable.CcMz3mIL.js";
import { w as E } from "../chunks/watch.BCJD77bD.js";
import { i as C, x as D } from "../chunks/lit-element.jLBm65_O.js";
import { e as h } from "../chunks/query.BBf1UFkC.js";
import { e as T } from "../chunks/class-map.BiVq-cVR.js";
import { o as O } from "../chunks/if-defined.BRoBj_Rp.js";
import { s as y, g } from "../chunks/animation-registry.HmpwNuGH.js";
import _ from "./input.js";
import d from "./menu.js";
import L from "./popup.js";
import A from "./textarea.js";
const S = C`:host{--panel-padding:0px;--panel-overflow:auto;display:inline-block}.dropdown::part(popup){z-index:var(--cx-z-index-dropdown)}.dropdown[data-current-placement^=top]::part(popup){transform-origin:bottom}.dropdown[data-current-placement^=bottom]::part(popup){transform-origin:top}.dropdown[data-current-placement^=left]::part(popup){transform-origin:100%}.dropdown[data-current-placement^=right]::part(popup){transform-origin:0}.dropdown__trigger{display:var(--trigger-display,block)}.dropdown__panel{padding:var(--panel-padding);background-color:var(--cx-panel-background-color);border:var(--cx-panel-border-width) solid var(--cx-panel-border-color);font-family:var(--cx-font-sans);font-size:var(--cx-font-size-medium);font-weight:var(--cx-font-weight-regular);box-shadow:var(--cx-shadow-large);border-radius:var(--cx-border-radius-large);pointer-events:none;max-height:min(var(--auto-size-available-height), var(--max-height,var(--auto-size-available-height)));overflow:var(--panel-overflow,auto);display:block}.dropdown--open .dropdown__panel{pointer-events:all}::slotted(cx-menu){border:none;max-width:min(100%, var(--auto-size-available-width))!important}.dropdown__trigger::slotted(cx-tooltip){display:inline-block}`;
var K = Object.defineProperty, P = Object.getOwnPropertyDescriptor, n = (e, t, i, a) => {
  for (var r = a > 1 ? void 0 : a ? P(t, i) : t, p = e.length - 1, l; p >= 0; p--)
    (l = e[p]) && (r = (a ? l(t, i, r) : l(r)) || r);
  return a && r && K(t, i, r), r;
};
let o = class extends w {
  constructor() {
    super(), this.localize = new v(this), this.hasSlotController = new k(this, "[default]"), this.open = !1, this.placement = "bottom-start", this.disabled = !1, this.stayOpenOnSelect = !1, this.distance = 0, this.skidding = 0, this.hoist = !1, this.sync = void 0, this.autoWidthFactor = 1, this.ignoredKeys = [], this.noFlip = !1, this.flipPadding = 10, this.handleKeyDown = this.handleKeyDown.bind(this), this.handleDocumentKeyDown = this.handleDocumentKeyDown.bind(this), this.handleDocumentMouseDown = this.handleDocumentMouseDown.bind(this), this.handlePanelSelect = this.handlePanelSelect.bind(this);
  }
  connectedUpdatedCallback() {
    this.containingElement ??= this, this.panel.hidden = !this.open || !this.hasSlotController.test("[default]"), this.open && (this.addOpenListeners(), this.popup.active = !0);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.removeOpenListeners(), this.hide();
  }
  focusOnTrigger() {
    const e = this.trigger.assignedElements({ flatten: !0 })[0];
    typeof e?.focus == "function" && e.focus();
  }
  getMenu() {
    return this.panel.assignedElements({ flatten: !0 }).find((e) => e.tagName.toLowerCase() === "cx-menu");
  }
  handleKeyDown(e) {
    this.open && e.key === "Escape" && (e.stopPropagation(), this.hide(), this.focusOnTrigger());
  }
  handleDocumentKeyDown(e) {
    e.key === "Escape" && this.open && (e.stopPropagation(), this.focusOnTrigger(), this.hide());
  }
  handleDocumentMouseDown(e) {
    const t = e.composedPath();
    this.containingElement && !t.includes(this.containingElement) && this.hide();
  }
  handlePanelSelect(e) {
    const t = e.target;
    !this.stayOpenOnSelect && t.tagName.toLowerCase() === "cx-menu" && (this.hide(), this.focusOnTrigger());
  }
  async handleTriggerClick() {
    this.open ? (this.hide(), this.panel.assignedElements().forEach(async (e) => {
      e instanceof d && e.variant === "multiple" && e.resetActiveMenu();
    })) : (this.show(), this.focusOnTrigger());
  }
  async handleTriggerKeyDown(e) {
    if (this.ignoredKeys.includes(e.key) || [" ", "Enter"].includes(e.key) && e.key === " " && (e.target instanceof _ || e.target instanceof A || e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement))
      return;
    const t = this.getMenu();
    if (t) {
      const i = t.getAllItems(), a = i[0], r = i.at(-1);
      ["ArrowDown", "ArrowUp", "Home", "End", "Enter", " "].includes(
        e.key
      ) && (e.preventDefault(), this.open || (this.show(), await this.updateComplete), i.length > 0 && (typeof t.checkVisibility == "function" && !t?.checkVisibility() && await new Promise((p) => {
        this.popup.addEventListener("cx-opened", p);
      }), this.updateComplete.then(() => {
        (e.key === "ArrowDown" || e.key === "Home" || e.key === "Enter" || e.key === " ") && (t.setCurrentItem(a), a.focus()), r && (e.key === "ArrowUp" || e.key === "End") && (t.setCurrentItem(r), r.focus());
      })));
    }
  }
  handleTriggerKeyUp(e) {
    e.key === " " && e.preventDefault();
  }
  handleTriggerSlotChange() {
    this.updateAccessibleTrigger();
  }
  //
  // Slotted triggers can be arbitrary content, but we need to link them to the dropdown panel with `aria-haspopup` and
  // `aria-expanded`. These must be applied to the "accessible trigger" (the tabbable portion of the trigger element
  // that gets slotted in) so screen readers will understand them. The accessible trigger could be the slotted element,
  // a child of the slotted element, or an element in the slotted element's shadow root.
  //
  // For example, the accessible trigger of an <cx-button> is a <button> located inside its shadow root.
  //
  // To determine this, we assume the first tabbable element in the trigger slot is the "accessible trigger."
  //
  updateAccessibleTrigger() {
    const t = this.trigger.assignedElements({
      flatten: !0
    }).find(
      (a) => f(a).start
    );
    let i;
    if (t) {
      switch (t.tagName.toLowerCase()) {
        // Shoelace buttons have to update the internal button so it's announced correctly by screen readers
        case "cx-button":
        case "cx-icon-button":
          i = t.button;
          break;
        default:
          i = t;
      }
      i.setAttribute("aria-haspopup", "true"), i.setAttribute("aria-expanded", this.open ? "true" : "false");
    }
  }
  blurTrigger() {
    const t = this.trigger.assignedElements({
      flatten: !0
    }).find(
      (a) => f(a).start
    );
    let i;
    if (t) {
      switch (t.tagName.toLowerCase()) {
        // Shoelace buttons have to update the internal button so it's announced correctly by screen readers
        case "cx-button":
        case "cx-icon-button":
          i = t.button;
          break;
        default:
          i = t;
      }
      i.blur();
    }
  }
  /** Shows the dropdown panel. */
  async show() {
    if (!this.open)
      return this.open = !0, await this.updateComplete, m(this, "cx-after-show");
  }
  /** Hides the dropdown panel */
  async hide() {
    if (this.open)
      return this.open = !1, m(this, "cx-after-hide");
  }
  /**
   * Instructs the dropdown menu to reposition. Useful when the position or size of the trigger changes when the menu
   * is activated.
   */
  reposition() {
    this.popup.reposition();
  }
  addOpenListeners() {
    this.panel.addEventListener("cx-select", this.handlePanelSelect), "CloseWatcher" in globalThis ? (this.closeWatcher?.destroy(), this.closeWatcher = new CloseWatcher(), this.closeWatcher.onclose = () => {
      this.hide(), this.focusOnTrigger();
    }) : this.panel.addEventListener("keydown", this.handleKeyDown), document.addEventListener("keydown", this.handleDocumentKeyDown), document.addEventListener("mousedown", this.handleDocumentMouseDown);
  }
  removeOpenListeners() {
    this.panel && (this.panel.removeEventListener("cx-select", this.handlePanelSelect), this.panel.removeEventListener("keydown", this.handleKeyDown)), document.removeEventListener("keydown", this.handleDocumentKeyDown), document.removeEventListener("mousedown", this.handleDocumentMouseDown), this.closeWatcher?.destroy();
  }
  async handleOpenChange() {
    if (this.disabled) {
      this.open = !1;
      return;
    }
    if (this.updateAccessibleTrigger(), this.open && this.hasSlotController.test("[default]")) {
      this.emit("cx-show"), this.addOpenListeners(), await c(this), this.panel.hidden = !1, this.popup.active = !0;
      const { keyframes: e, options: t } = g(this, "dropdown.show", {
        dir: this.localize.dir()
      });
      await u(this.popup.popup, e, t), this.emit("cx-after-show"), this.panel.assignedElements().forEach(async (i) => {
        i instanceof d && i.variant === "multiple" && (await i.updateComplete, i.adjustMenuSize(0));
      });
    } else {
      this.emit("cx-hide"), this.removeOpenListeners(), await c(this);
      const { keyframes: e, options: t } = g(this, "dropdown.hide", {
        dir: this.localize.dir()
      });
      await u(this.popup.popup, e, t), this.panel.hidden = !0, this.popup.active = !1, this.emit("cx-after-hide"), this.panel.assignedElements().forEach(async (i) => {
        i instanceof d && i.variant === "multiple" && i.resetActiveMenu();
      });
    }
  }
  render() {
    return D`<cx-popup part="base" exportparts="popup:base__popup" id="dropdown" placement=${this.placement} distance=${this.distance} skidding=${this.skidding} strategy=${this.hoist ? "overlay" : "absolute"} ?flip=${!this.noFlip} shift auto-size="both" auto-size-padding="10" flip-padding=${this.flipPadding} sync=${O(this.sync ? this.sync : void 0)} class=${T({
      dropdown: !0,
      "dropdown--open": this.open
    })} auto-width-factor=${this.autoWidthFactor}><slot name="trigger" slot="anchor" part="trigger" class="dropdown__trigger" @click=${this.handleTriggerClick} @keydown=${this.handleTriggerKeyDown} @keyup=${this.handleTriggerKeyUp} @slotchange=${this.handleTriggerSlotChange}></slot><div aria-hidden=${this.open && this.hasSlotController.test("[default]") ? "false" : "true"} aria-labelledby="dropdown"><slot part="panel" class="dropdown__panel"></slot></div></cx-popup>`;
  }
};
o.styles = [b, S];
o.dependencies = { "cx-popup": L };
n([
  h(".dropdown")
], o.prototype, "popup", 2);
n([
  h(".dropdown__trigger")
], o.prototype, "trigger", 2);
n([
  h(".dropdown__panel")
], o.prototype, "panel", 2);
n([
  s({ reflect: !0, type: Boolean })
], o.prototype, "open", 2);
n([
  s({ reflect: !0 })
], o.prototype, "placement", 2);
n([
  s({ reflect: !0, type: Boolean })
], o.prototype, "disabled", 2);
n([
  s({ attribute: "stay-open-on-select", reflect: !0, type: Boolean })
], o.prototype, "stayOpenOnSelect", 2);
n([
  s({ attribute: "containing-element" })
], o.prototype, "containingElement", 2);
n([
  s({ type: Number })
], o.prototype, "distance", 2);
n([
  s({ type: Number })
], o.prototype, "skidding", 2);
n([
  s({ type: Boolean })
], o.prototype, "hoist", 2);
n([
  s({ reflect: !0 })
], o.prototype, "sync", 2);
n([
  s({ attribute: "auto-width-factor" })
], o.prototype, "autoWidthFactor", 2);
n([
  s({
    attribute: "ignored-keys",
    converter: {
      fromAttribute: (e) => e?.split(" ") ?? [],
      toAttribute: (e) => e.join(" ")
    },
    type: String
  })
], o.prototype, "ignoredKeys", 2);
n([
  s({ attribute: "no-flip", reflect: !0, type: Boolean })
], o.prototype, "noFlip", 2);
n([
  s({ attribute: "flip-padding", type: Number })
], o.prototype, "flipPadding", 2);
n([
  E("open", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleOpenChange", 1);
o = n([
  x("cx-dropdown")
], o);
y("dropdown.show", {
  keyframes: [
    { opacity: 0, scale: 0.9 },
    { opacity: 1, scale: 1 }
  ],
  options: { duration: 100, easing: "ease" }
});
y("dropdown.hide", {
  keyframes: [
    { opacity: 1, scale: 1 },
    { opacity: 0, scale: 0.9 }
  ],
  options: { duration: 100, easing: "ease" }
});
export {
  o as default
};
