import { C as R, n as l } from "./lib-cortex-element.CVMmyPMC.js";
import { c as N } from "./component.styles.CRO4Odto.js";
import { c as G } from "./custom-element.L4WJXn1j.js";
import { L as M } from "./i18n.BABe9hN4.js";
import { c as K } from "./math.DqTA6ya4.js";
import { w as b } from "./watch.BCJD77bD.js";
import { i as Z, x as g, E as L } from "./lit-element.jLBm65_O.js";
import { r as y } from "./state.CSDxrqLd.js";
import { e as f } from "./query.BBf1UFkC.js";
import { s as z, a as U, b as $ } from "./animate.El-MpOws.js";
import { e as C } from "./class-map.BiVq-cVR.js";
import { o as _ } from "./if-defined.BRoBj_Rp.js";
import { l as W } from "./live.SCz6M8Gs.js";
import { n as E } from "./when.Dr1es41R.js";
import { g as P, s as H } from "./animation-registry.HmpwNuGH.js";
import Y from "../components/checkbox.js";
import J from "../components/icon.js";
import Q from "../components/spinner.js";
import { i as ee } from "./browser.BHOCIF_A.js";
import { S as te } from "./sortable.esm.oSzf6C5Q.js";
function ie(e, t, i) {
  let n;
  return function(...r) {
    const a = this, d = function() {
      n = null, e.apply(a, r);
    };
    n && clearTimeout(n), n = window.setTimeout(d, t);
  };
}
const p = [];
for (let e = 0; e < 256; ++e)
  p.push((e + 256).toString(16).slice(1));
function ne(e, t = 0) {
  return (p[e[t + 0]] + p[e[t + 1]] + p[e[t + 2]] + p[e[t + 3]] + "-" + p[e[t + 4]] + p[e[t + 5]] + "-" + p[e[t + 6]] + p[e[t + 7]] + "-" + p[e[t + 8]] + p[e[t + 9]] + "-" + p[e[t + 10]] + p[e[t + 11]] + p[e[t + 12]] + p[e[t + 13]] + p[e[t + 14]] + p[e[t + 15]]).toLowerCase();
}
let I;
const ae = new Uint8Array(16);
function oe() {
  if (!I) {
    if (typeof crypto > "u" || !crypto.getRandomValues)
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    I = crypto.getRandomValues.bind(crypto);
  }
  return I(ae);
}
const re = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), F = { randomUUID: re };
function se(e, t, i) {
  if (F.randomUUID && !e)
    return F.randomUUID();
  e = e || {};
  const n = e.random ?? e.rng?.() ?? oe();
  if (n.length < 16)
    throw new Error("Random bytes length must be >= 16");
  return n[6] = n[6] & 15 | 64, n[8] = n[8] & 63 | 128, ne(n);
}
const le = Z`:host{--selected-color:var(--cx-color-primary-600);--selected-background-color:var(--cx-color-primary-50);--hover-background-color:var(--cx-menu-item-background-color-hover);--active-background-color:var(--cx-color-neutral-200);--item-padding:var(--cx-spacing-2x-small) var(--cx-spacing-x-small);outline:0;display:block}:host(:focus-visible) .tree-item{outline:var(--cx-focus-ring);outline-offset:calc(-1 * var(--cx-focus-ring-width))}[hidden]{display:none!important}slot:not([name])::slotted(cx-icon){margin-inline-end:var(--cx-spacing-x-small)}.tree-item{color:var(--cx-color-neutral);cursor:pointer;-webkit-user-select:none;user-select:none;flex-direction:column;align-items:stretch;display:flex;position:relative}.tree-item__checkbox{margin-inline-end:var(--cx-spacing-x-small)}.tree-item__expand-button,.tree-item__checkbox,.tree-item__label{font-family:var(--cx-font-sans);font-size:var(--cx-tree-item-font-size,var(--cx-font-size-small));font-weight:var(--cx-tree-item-font-weight,var(--cx-font-weight-medium));line-height:var(--cx-tree-item-line-height,var(--cx-line-height-large));letter-spacing:var(--cx-tree-item-letter-spacing,var(--cx-letter-spacing-normal))}.tree-item__checkbox::part(base){align-items:center;display:flex}.tree-item__checkbox::part(label){margin-inline-start:0}.tree-item__indentation{flex-shrink:0;width:1em;display:block}.tree-item__expand-spinner{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.tree-item__expand-button{box-sizing:content-box;color:var(--cx-color-neutral-500);cursor:pointer;min-width:max(1em,1rem);min-height:max(1em,1rem);transition:var(--cx-transition-medium) rotate ease;flex-shrink:0;justify-content:center;align-items:center;display:flex;position:relative}.tree-item--expanded .tree-item__expand-button{rotate:90deg}.tree-item--expanded.tree-item--rtl .tree-item__expand-button{rotate:-90deg}.tree-item--expanded slot[name=expand-icon],.tree-item:not(.tree-item--expanded) slot[name=collapse-icon]{display:none}:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__item .tree-item__expand-icon-slot{color:var(--selected-color)}.tree-item:not(.tree-item--has-expand-button) .tree-item__expand-icon-slot{visibility:hidden;opacity:0;pointer-events:none}.tree-item__expand-button--visible{cursor:pointer}.tree-item__item{border-radius:var(--cx-border-radius-large);padding:var(--item-padding,var(--cx-spacing-x-small) var(--cx-spacing-small));transition:var(--cx-transition-x-fast) background-color ease;align-items:center;display:flex}.tree-item__item:hover{background-color:var(--hover-background-color)}.tree-item__item:active{background-color:var(--active-background-color)}.tree-item--disabled .tree-item__item{opacity:.5;cursor:default;outline:none}:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__item{background-color:var(--selected-background-color);color:var(--selected-color)}:host(:not([aria-disabled=true])) .tree-item__expand-button{color:var(--cx-color-neutral)}:host(:not([aria-disabled=true])) .tree-item--selected,:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__expand-button,:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__actions::slotted(cx-icon-button){color:var(--cx-color-neutral-0)}:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__actions::slotted(cx-icon-button){--hover-background-color:var(--cx-color-neutral-0)}.tree-item__label{align-items:center;display:flex}.tree-item__actions{font-size:var(--cx-font-size-medium);align-items:center;width:fit-content;margin-inline-start:auto;display:flex}.tree-item__actions::slotted(*){visibility:hidden;opacity:0;transition:var(--cx-transition-x-fast) visibility, var(--cx-transition-x-fast) opacity ease}.tree-item__item:hover .tree-item__actions::slotted(*){visibility:visible;opacity:1}@supports not (overlay:auto){.tree-item__actions::slotted(cx-dropdown[open]){visibility:visible;opacity:1}}.tree-item__children{font-size:calc(1em + var(--indent-size,var(--cx-spacing-medium)));gap:var(--children-gap,0);flex-direction:column;display:flex}@media (forced-colors:active){:host(:not([aria-disabled=true])) .tree-item--selected .tree-item__item{outline:1px dashed selecteditem}}::slotted(cx-tree-item){--hover-background-color:inherit;--active-background-color:inherit;--selected-background-color:inherit;--selected-color:inherit}:host([data-dragging]){position:relative}:host([data-dragging=inside]){background-color:var(--cx-color-primary-400)}:host([data-dragging=before]):before{content:"";border-top:var(--cx-spacing-2x-small) solid var(--cx-color-primary-400);width:100%;position:absolute;top:0;left:0}:host([data-dragging=after]):before{content:"";border-bottom:var(--cx-spacing-2x-small) solid var(--cx-color-primary-400);width:100%;position:absolute;bottom:0;left:0}`, k = "tree-sortable", w = 0.2, O = (e) => e == null;
function de() {
  function e() {
  }
  let t = null;
  return e.prototype = {
    dragOver({
      cancel: i,
      target: n
    }) {
      if (t && (t.el.removeAttribute("data-dragging"), t = null), !["CX-TREE-ITEM", "CX-TREE"].includes(n.tagName) || n.hasAttribute("no-drag")) {
        i();
        return;
      }
    },
    dragOverValid({
      activeSortable: i,
      cancel: n,
      changed: r,
      completed: a,
      dragEl: d,
      originalEvent: m,
      putSortable: x,
      target: u
    }) {
      if (t = null, !i || !i.options[k] || !i.options.getDropZone || O(i.options.insertBeforeZonePercentage) || O(i.options.insertAfterZonePercentage) || !["CX-TREE-ITEM", "CX-TREE"].includes(u.tagName) || u.hasAttribute("no-drag")) {
        n();
        return;
      }
      const B = i.options.getDropZone(u);
      if (!B) {
        n();
        return;
      }
      const T = B.getBoundingClientRect(), D = (m.clientY - T.top) / T.height, v = x || this.sortable;
      v.captureAnimationState(), v !== i && i.captureAnimationState();
      const V = u.parentNode;
      if (d && V)
        if (D < i.options.insertBeforeZonePercentage)
          t = {
            dragEl: d,
            el: u,
            position: -1
          }, u.setAttribute("data-dragging", "before");
        else if (D > i.options.insertAfterZonePercentage)
          t = {
            dragEl: d,
            el: u,
            position: 1
          }, u.setAttribute("data-dragging", "after");
        else {
          if (u.hasAttribute("no-drag-inside")) {
            r(), a(!0), n();
            return;
          }
          t = {
            dragEl: d,
            el: u,
            position: 0
          }, u.setAttribute("data-dragging", "inside");
        }
      if (v.animateAll(), v !== i && i.animateAll(), t)
        r(), a(!0), n();
      else
        return !0;
    },
    dragStart({
      cancel: i,
      dragEl: n
    }) {
      if (n && !o.isTreeItem(n)) {
        i();
        return;
      }
    },
    drop() {
      if (t) {
        const i = t.el.parentNode;
        i && (i.tagName === "CX-TREE" ? t.dragEl.removeAttribute("slot") : i.tagName === "CX-TREE-ITEM" && t.dragEl.setAttribute("slot", "children"), t.position === -1 ? i.insertBefore(t.dragEl, t.el) : t.position === 1 ? i.insertBefore(t.dragEl, t.el.nextSibling) : (t.dragEl.setAttribute("slot", "children"), t.el.appendChild(t.dragEl))), t.el.removeAttribute("data-dragging"), t = null;
      }
    }
  }, Object.assign(e, {
    pluginName: k
  });
}
class S extends te {
  constructor(t, i) {
    super(t, i);
  }
  static create(t, i = {}) {
    return new S(t, i);
  }
}
S.mount(new de());
const j = (e) => ({
  ...e,
  animation: 100,
  draggable: "cx-tree-item:not([no-drag])",
  emptyInsertThreshold: 0,
  fallbackOnBody: !0,
  forceFallback: ee(),
  getDropZone: (t) => t?.shadowRoot?.querySelector(".tree-item__item"),
  insertAfterZonePercentage: 1 - w,
  insertBeforeZonePercentage: w,
  invertSwap: !0,
  onStart(t) {
    if (e.onStart?.(t), t.item.tagName === "CX-TREE-ITEM") {
      const i = t.item;
      i.expanded = !1;
    }
  },
  [k]: !0,
  swapThreshold: w
});
var ce = Object.defineProperty, he = Object.getOwnPropertyDescriptor, s = (e, t, i, n) => {
  for (var r = n > 1 ? void 0 : n ? he(t, i) : t, a = e.length - 1, d; a >= 0; a--)
    (d = e[a]) && (r = (n ? d(t, i, r) : d(r)) || r);
  return n && r && ce(t, i, r), r;
};
let o = class extends R {
  constructor() {
    super(), this.localize = new M(this), this.expanded = !1, this.selected = !1, this.disabled = !1, this.readonly = !1, this.lazy = !1, this.href = "", this.rel = "noreferrer noopener", this.itemId = "", this.sortable = !1, this.noDrag = !1, this.noSelect = !1, this.noDragInside = !1, this.sortableGroup = void 0, this.expandButtonPlacement = "start", this.noForwardExpandButtonPlacement = !1, this.disabledSyncCheckboxes = !1, this.partialSyncCheckboxes = !1, this.previouslySelected = !1, this.focusable = !1, this.indeterminate = !1, this.isLeaf = !1, this.loading = !1, this.selectable = !1, this.sortableInstance = null, this.onDragStart = (e) => {
      if (e.dataTransfer) {
        const t = this.cloneNode(!0);
        t.style.backgroundColor = "red", t.style.display = "none", this.ownerDocument.body.appendChild(t), e.dataTransfer.setDragImage(t, 0, 0);
      }
    }, this.onDragStart = this.onDragStart.bind(this), this.renderExpandButton = this.renderExpandButton.bind(this), this.handleSortableUpdate = this.handleSortableUpdate.bind(this), this.handleSortableEnd = this.handleSortableEnd.bind(this), this.handleSortableStart = this.handleSortableStart.bind(this);
  }
  static isTreeItem(e) {
    return e instanceof Element && e.getAttribute("role") === "treeitem";
  }
  get showExpandButton() {
    return !this.loading && (!this.isLeaf || this.lazy);
  }
  runFirstUpdated() {
    this.hasAttribute("role") || this.setAttribute("role", "treeitem"), this.setAttribute("tabindex", this.focusable ? "0" : "-1"), this.isNestedItem() && (this.slot = "children"), this.childrenContainer.hidden = !this.expanded, this.childrenContainer.style.height = this.expanded ? "auto" : "0", this.noForwardExpandButtonPlacement || this.getChildrenItems().forEach(
      (e) => e.expandButtonPlacement = this.expandButtonPlacement
    ), this.isLeaf = !this.lazy && this.getChildrenItems().length === 0, this.handleExpandedChange();
  }
  async animateCollapse() {
    this.emit("cx-collapse"), await z(this.childrenContainer);
    const { keyframes: e, options: t } = P(this, "tree-item.collapse", {
      dir: this.localize.dir()
    });
    await U(
      this.childrenContainer,
      $(e, this.childrenContainer.scrollHeight),
      t
    ), this.childrenContainer.hidden = !0, this.emit("cx-after-collapse");
  }
  // Checks whether the item is nested into an item
  isNestedItem() {
    const e = this.parentElement;
    return !!e && o.isTreeItem(e);
  }
  /**
   * Wait for this item to be fully updated before processing the slot change.
   * Since children items may not be fully updated yet.
   */
  async handleChildrenSlotChange() {
    await this.updateComplete, this.loading = !1, this.noForwardExpandButtonPlacement || this.getChildrenItems().forEach(
      (e) => e.expandButtonPlacement = this.expandButtonPlacement
    ), this.isLeaf = !this.lazy && this.getChildrenItems().length === 0;
  }
  willUpdate(e) {
    e.has("selected") && !e.has("indeterminate") && (this.indeterminate = !1);
  }
  async animateExpand() {
    this.emit("cx-expand"), await z(this.childrenContainer), this.childrenContainer.hidden = !1;
    const { keyframes: e, options: t } = P(this, "tree-item.expand", {
      dir: this.localize.dir()
    });
    await U(
      this.childrenContainer,
      $(e, this.childrenContainer.scrollHeight),
      t
    ), this.childrenContainer.style.height = "auto", this.emit("cx-after-expand");
  }
  handleLoadingChange() {
    this.setAttribute("aria-busy", this.loading ? "true" : "false"), this.loading || this.animateExpand();
  }
  handleDisabledChange() {
    this.setAttribute("aria-disabled", this.disabled ? "true" : "false");
  }
  handleSelectedChange() {
    this.setAttribute("aria-selected", this.selected ? "true" : "false"), this.hasUpdated && this.emit("cx-selected-change", {
      detail: {
        selected: this.selected
      }
    });
  }
  handleExpandedChange() {
    this.isLeaf ? this.removeAttribute("aria-expanded") : this.setAttribute("aria-expanded", this.expanded ? "true" : "false");
  }
  handleExpandAnimation() {
    this.expanded ? this.lazy ? (this.loading = !0, this.emit("cx-lazy-load")) : this.animateExpand() : this.animateCollapse();
  }
  async handleLazyChange() {
    !this.lazy && this.loading && (this.loading = !1, this.handleChildrenSlotChange()), this.selected && (await this.updateComplete, A(this)), this.emit("cx-lazy-change");
  }
  /** Gets all the nested tree items in this node. */
  getChildrenItems({
    includeDisabled: e = !0
  } = {}) {
    return this.childrenSlot ? [...this.childrenSlot.assignedElements({ flatten: !0 })].filter(
      (t) => o.isTreeItem(t) && (e || !t.disabled)
    ) : [];
  }
  renderExpandButton() {
    const e = this.localize.dir() === "rtl", t = this.showExpandButton;
    return g`<div part="expand-button" class=${C({
      "tree-item__expand-button": !0,
      "tree-item__expand-button--visible": t
    })} aria-hidden="true">${E(
      this.loading,
      () => g`<cx-spinner part="spinner" class="tree-item__expand-spinner" exportparts="base:spinner__base"></cx-spinner>`
    )}<slot class="tree-item__expand-icon-slot" name="expand-icon"><cx-icon name=${e ? "chevron_left" : "chevron_right"}></cx-icon></slot><slot class="tree-item__expand-icon-slot" name="collapse-icon"><cx-icon name=${e ? "chevron_left" : "chevron_right"}></cx-icon></slot></div>`;
  }
  handleSortableUpdate(e) {
    const t = this.getChildrenItems({ includeDisabled: !0 });
    this.emit("cx-reorder", {
      detail: {
        from: e.from,
        item: e.item,
        items: t,
        newIndex: e.newIndex,
        oldIndex: e.oldIndex,
        to: e.to,
        type: e.type
      }
    });
  }
  handleSortableStart() {
    this.emit("cx-drag-start");
  }
  handleSortableEnd() {
    this.emit("cx-drag-end");
  }
  destroySortable() {
    this.removeEventListener("dragstart", this.onDragStart), this.sortableInstance && (this.sortableInstance.destroy(), this.sortableInstance = null);
  }
  initSortable() {
    this.addEventListener("dragstart", this.onDragStart), this.focusable || this.setAttribute("tabindex", "-1"), this.sortableInstance = S.create(this, {
      ...j({
        group: this.sortableGroup,
        onAdd: this.handleSortableUpdate,
        onEnd: this.handleSortableEnd,
        onRemove: this.handleSortableUpdate,
        onStart: this.handleSortableStart,
        onUpdate: this.handleSortableUpdate
      })
    });
  }
  updated(e) {
    super.updated(e), (e.has("sortable") || e.has("sortableGroup")) && (this.destroySortable(), this.sortable && this.initSortable());
  }
  renderBase(e) {
    const t = this.showExpandButton;
    return this.href ? g`<a id="anchor" part="base" class=${C({
      "tree-item": !0,
      "tree-item--disabled": this.disabled,
      "tree-item--expanded": this.expanded,
      "tree-item--has-expand-button": t,
      "tree-item--leaf": this.isLeaf,
      "tree-item--rtl": this.localize.dir() === "rtl",
      "tree-item--selected": this.selected
    })} href=${_(this.href)} target=${_(this.target)} download=${_(this.download)} rel=${_(this.rel)} ?inert=${this.disabled}>${e}</a>` : g`<div part="base" class=${C({
      "tree-item": !0,
      "tree-item--disabled": this.disabled,
      "tree-item--expanded": this.expanded,
      "tree-item--has-expand-button": t,
      "tree-item--leaf": this.isLeaf,
      "tree-item--rtl": this.localize.dir() === "rtl",
      "tree-item--selected": this.selected
    })}>${e}</div>`;
  }
  render() {
    return this.renderBase(g`<div class="tree-item__item" part="
            item
            ${this.disabled ? "item--disabled" : ""}
            ${this.expanded ? "item--expanded" : ""}
            ${this.indeterminate ? "item--indeterminate" : ""}
            ${this.selected ? "item--selected" : ""}
          "><div class="tree-item__indentation" part="indentation"></div>${E(
      this.expandButtonPlacement === "start",
      this.renderExpandButton,
      () => L
    )}
        ${E(
      this.selectable,
      () => g`<cx-checkbox part="checkbox" aria-label=${this.localize.term("checkbox")} exportparts="
                base:checkbox__base,
                control:checkbox__control,
                control--checked:checkbox__control--checked,
                control--indeterminate:checkbox__control--indeterminate,
                checked-icon:checkbox__checked-icon,
                indeterminate-icon:checkbox__indeterminate-icon,
                label:checkbox__label
              " class="tree-item__checkbox" ?disabled=${this.disabled} ?checked=${W(this.selected)} ?indeterminate=${this.indeterminate} tabindex="-1"></cx-checkbox>`
    )}<slot class="tree-item__label" part="label"></slot><slot class="tree-item__actions" part="actions" name="actions"></slot>${E(
      this.expandButtonPlacement === "end",
      this.renderExpandButton,
      () => L
    )}</div><div class="tree-item__children" part="children" role="group"><slot name="children" @slotchange=${this.handleChildrenSlotChange}></slot></div>`);
  }
};
o.styles = [N, le];
o.dependencies = {
  "cx-checkbox": Y,
  "cx-icon": J,
  "cx-spinner": Q
};
s([
  f("slot:not([name])")
], o.prototype, "defaultSlot", 2);
s([
  f("slot[name=children]")
], o.prototype, "childrenSlot", 2);
s([
  f(".tree-item__item")
], o.prototype, "itemElement", 2);
s([
  f(".tree-item__children")
], o.prototype, "childrenContainer", 2);
s([
  f(".tree-item__expand-button slot")
], o.prototype, "expandButtonSlot", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "expanded", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "selected", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "disabled", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "readonly", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "lazy", 2);
s([
  l()
], o.prototype, "href", 2);
s([
  l()
], o.prototype, "target", 2);
s([
  l()
], o.prototype, "rel", 2);
s([
  l()
], o.prototype, "download", 2);
s([
  l({ attribute: "itemid", reflect: !0, type: String })
], o.prototype, "itemId", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "sortable", 2);
s([
  l({ attribute: "no-drag", reflect: !0, type: Boolean })
], o.prototype, "noDrag", 2);
s([
  l({ attribute: "no-select", reflect: !0, type: Boolean })
], o.prototype, "noSelect", 2);
s([
  l({ attribute: "no-drag-inside", reflect: !0, type: Boolean })
], o.prototype, "noDragInside", 2);
s([
  l({ attribute: "sortable-group", type: String })
], o.prototype, "sortableGroup", 2);
s([
  l({
    attribute: "expand-button-placement",
    reflect: !0,
    type: String
  })
], o.prototype, "expandButtonPlacement", 2);
s([
  l({ attribute: "no-forward-expand-button-placement", type: Boolean })
], o.prototype, "noForwardExpandButtonPlacement", 2);
s([
  l({
    attribute: "disabled-sync-checkboxes",
    reflect: !0,
    type: Boolean
  })
], o.prototype, "disabledSyncCheckboxes", 2);
s([
  l({
    attribute: "partial-sync-checkboxes",
    reflect: !0,
    type: Boolean
  })
], o.prototype, "partialSyncCheckboxes", 2);
s([
  l({ attribute: "previously-selected", reflect: !0, type: Boolean })
], o.prototype, "previouslySelected", 2);
s([
  l({ reflect: !0, type: Boolean })
], o.prototype, "focusable", 2);
s([
  y()
], o.prototype, "indeterminate", 2);
s([
  y()
], o.prototype, "isLeaf", 2);
s([
  y()
], o.prototype, "loading", 2);
s([
  y()
], o.prototype, "selectable", 2);
s([
  y()
], o.prototype, "sortableInstance", 2);
s([
  b("loading", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleLoadingChange", 1);
s([
  b("disabled")
], o.prototype, "handleDisabledChange", 1);
s([
  b("selected")
], o.prototype, "handleSelectedChange", 1);
s([
  b("expanded", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleExpandedChange", 1);
s([
  b("expanded", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleExpandAnimation", 1);
s([
  b("lazy", { waitUntilFirstUpdate: !0 })
], o.prototype, "handleLazyChange", 1);
o = s([
  G("cx-tree-item")
], o);
H("tree-item.expand", {
  keyframes: [
    { height: "0", opacity: "0", overflow: "hidden" },
    { height: "auto", opacity: "1", overflow: "hidden" }
  ],
  options: { duration: 250, easing: "cubic-bezier(0.4, 0.0, 0.2, 1)" }
});
H("tree-item.collapse", {
  keyframes: [
    { height: "auto", opacity: "1", overflow: "hidden" },
    { height: "0", opacity: "0", overflow: "hidden" }
  ],
  options: { duration: 200, easing: "cubic-bezier(0.4, 0.0, 0.2, 1)" }
});
const pe = Z`:host{--indent-guide-color:var(--cx-color-neutral-200);--indent-guide-offset:0;--indent-guide-style:solid;--indent-guide-width:0;--indent-size:var(--cx-spacing-large);font-size:0;display:block}:host::part(children){gap:var(--children-gap,0);flex-direction:column;display:flex}:host([dragging]) ::slotted(cx-tree-item){--hover-background-color:transparent!important;--active-background-color:transparent!important;--selected-background-color:transparent!important}`;
var ue = Object.defineProperty, me = Object.getOwnPropertyDescriptor, h = (e, t, i, n) => {
  for (var r = n > 1 ? void 0 : n ? me(t, i) : t, a = e.length - 1, d; a >= 0; a--)
    (d = e[a]) && (r = (n ? d(t, i, r) : d(r)) || r);
  return n && r && ue(t, i, r), r;
};
function q(e) {
  const t = e.getChildrenItems({ includeDisabled: !1 });
  if (t.length) {
    const i = t.every((d) => d.selected), n = t.every(
      (d) => !d.selected && !d.indeterminate
    );
    let r = !1, a = !1;
    (!i && !n || e.partialSyncCheckboxes && (i || n && e.previouslySelected)) && (r = !0), e.partialSyncCheckboxes ? a = i && !r : a = i, e.indeterminate = r, e.selected = a;
  }
}
function X(e, t = "single") {
  const i = e.parentElement;
  o.isTreeItem(i) && !i.disabledSyncCheckboxes && t === "multiple" && (q(i), X(i, t));
}
function A(e, t = !1, i = "single") {
  function n(r) {
    if (!(!(r instanceof o) && r.getAttribute("role") !== "treeitem")) {
      for (const a of r.getChildrenItems())
        a.selected = t ? r.selected || a.selected : !a.disabled && !a.readonly && r.selected, n(a);
      t && q(r);
    }
  }
  !e.disabledSyncCheckboxes && i === "multiple" && (e.partialSyncCheckboxes && (e.selected ? e.previouslySelected = !0 : e.previouslySelected = !1), n(e)), X(e, i);
}
let c = class extends R {
  constructor() {
    super(), this.sortable = !1, this.sortableGroup = null, this.disabledSortableGroup = !1, this.selection = "single", this.disabledAutoExpand = !1, this.autoExpandToSelected = !1, this.expandButtonPlacement = "start", this.noForwardExpandButtonPlacement = !1, this.forceOnChange = !1, this.labelSelectSingle = !1, this.noDragInside = !1, this.focusable = !1, this.clickTarget = null, this.localize = new M(this), this.sortableInstance = null, this.handleSortableUpdate = this.handleSortableUpdate.bind(this), this.handleSortableStart = this.handleSortableStart.bind(this), this.handleSortableEnd = this.handleSortableEnd.bind(this), this.handleFocusIn = this.handleFocusIn.bind(this), this.handleFocusOut = this.handleFocusOut.bind(this), this.handleSlotChange = this.handleSlotChange.bind(this), this.handleTreeChanged = this.handleTreeChanged.bind(this), this.initTreeItem = this.initTreeItem.bind(this);
  }
  runConnectedCallback() {
    if (this.addEventListener("focusin", this.handleFocusIn), this.addEventListener("focusout", this.handleFocusOut), this.addEventListener("cx-lazy-change", this.handleSlotChange), this.setAttribute("role", "tree"), this.setAttribute("tabindex", "0"), this.mutationObserver = new MutationObserver(this.handleTreeChanged), this.mutationObserver.observe(this, { childList: !0, subtree: !0 }), this.autoExpandToSelected) {
      const e = ie(() => {
        customElements.whenDefined("cx-tree-item").then(() => {
          this.selectedItems.forEach((t) => {
            this.expandToItem(t);
          });
        });
      }, 500);
      this.autoExpandObserver = new MutationObserver(e), this.autoExpandObserver.observe(this, {
        attributeFilter: ["selected"],
        attributes: !0,
        childList: !0,
        subtree: !0
      });
    }
    this.hasUpdated && this.sortable && this.initSortable();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.removeEventListener("focusin", this.handleFocusIn), this.removeEventListener("focusout", this.handleFocusOut), this.removeEventListener("cx-lazy-change", this.handleSlotChange), this.mutationObserver?.disconnect(), this.autoExpandObserver?.disconnect(), this.destroySortable();
  }
  /**
   * Generates a clone of the expand icon element to use for each tree item
   */
  getExpandButtonIcon(e) {
    const i = (e === "expand" ? this.expandedIconSlot : this.collapsedIconSlot)?.assignedElements({ flatten: !0 })[0];
    if (i) {
      const n = i.cloneNode(!0);
      return [n, ...n.querySelectorAll("[id]")].forEach(
        (r) => r.removeAttribute("id")
      ), n.setAttribute("data-default", ""), n.slot = `${e}-icon`, n;
    }
    return null;
  }
  /**
   * Initializes new items by setting the `selectable` property and the expanded/collapsed icons if any
   */
  initTreeItem(e) {
    this.noForwardExpandButtonPlacement || (e.expandButtonPlacement = this.expandButtonPlacement), e.selectable = this.selection === "multiple", e.focusable = this.focusable, ["expand", "collapse"].filter((t) => !!this.querySelector(`[slot="${t}-icon"]`)).forEach((t) => {
      const i = e.querySelector(`[slot="${t}-icon"]`), n = this.getExpandButtonIcon(t);
      n && (i === null ? e.append(n) : i.hasAttribute("data-default") && i.replaceWith(n));
    }), this.sortable ? (e.sortable = !0, e.sortableGroup = this.getSortableGroup(), this.noDragInside && (e.noDragInside = !0)) : e.sortable = !1;
  }
  initTreeItems() {
    this.getAllTreeItems().forEach(this.initTreeItem);
  }
  handleTreeChanged(e) {
    for (const t of e) {
      const i = [...t.addedNodes].filter(
        o.isTreeItem
      ), n = [...t.removedNodes].filter(
        o.isTreeItem
      );
      i.forEach(this.initTreeItem), this.lastFocusedItem && n.includes(this.lastFocusedItem) && (this.lastFocusedItem = null);
    }
  }
  /**
   * Handles the selection of a tree item based on the current selection mode.
   *
   * @param selectedItem - The tree item that is being selected or toggled.
   * @param isSingleSelect - Optional flag to force the item to be selected and unselect all other items.
   */
  async selectItem(e, t = !1) {
    const i = [...this.selectedItems], n = this.getAllTreeItems();
    if (this.selection === "multiple")
      t && await Promise.all(
        n.map(async (a) => {
          a.selected = !1, a.indeterminate = !1, a.previouslySelected = !1, await a.updateComplete;
        })
      ), e.selected = t || !e.selected, e.lazy && !this.disabledAutoExpand && (e.expanded = !0), A(e, !1, this.selection);
    else if ((this.selection === "single" || e.isLeaf) && !e.noSelect)
      for (const a of n)
        a.selected = a === e;
    else (this.selection === "leaf" || e.noSelect) && (e.expanded = !e.expanded);
    if (e.noSelect)
      return;
    const r = this.selectedItems;
    (i.length !== r.length || r.some((a) => !i.includes(a)) || this.forceOnChange || t) && Promise.all(r.map((a) => a.updateComplete)).then(() => {
      this.emit("cx-selection-change", {
        /**
         * Use this.selectedItems instead of nextSelection because
         * this.selectedItems may have changed since the last updateComplete
         */
        detail: { selection: this.selectedItems }
      });
    });
  }
  getAllTreeItems() {
    return [...this.querySelectorAll("cx-tree-item")];
  }
  getAllDirectTreeItems() {
    return [...this.querySelectorAll(":scope > cx-tree-item")];
  }
  focusItem(e) {
    e?.focus();
  }
  handleKeyDown(e) {
    if (![
      "ArrowDown",
      "ArrowUp",
      "ArrowRight",
      "ArrowLeft",
      "Home",
      "End",
      "Enter",
      " "
    ].includes(e.key) || e.composedPath().some(
      (r) => ["input", "textarea"].includes(
        r?.tagName?.toLowerCase()
      )
    ))
      return;
    const t = this.getFocusableItems(), i = this.localize.dir() === "ltr", n = this.localize.dir() === "rtl";
    if (t.length > 0) {
      e.preventDefault();
      const r = t.findIndex((x) => x.matches(":focus")), a = t[r], d = (x) => {
        const u = t[K(x, 0, t.length - 1)];
        this.focusItem(u);
      }, m = (x) => {
        a.expanded = x;
      };
      e.key === "ArrowDown" ? d(r + 1) : e.key === "ArrowUp" ? d(r - 1) : i && e.key === "ArrowRight" || n && e.key === "ArrowLeft" ? !a || a.disabled || a.readonly || a.expanded || a.isLeaf && !a.lazy ? d(r + 1) : m(!0) : i && e.key === "ArrowLeft" || n && e.key === "ArrowRight" ? !a || a.disabled || a.readonly || a.isLeaf || !a.expanded ? d(r - 1) : m(!1) : e.key === "Home" ? d(0) : e.key === "End" ? d(t.length - 1) : (e.key === "Enter" || e.key === " ") && !a.disabled && !a.readonly && this.selectItem(a);
    }
  }
  handleClick(e) {
    const t = e.composedPath(), i = e.target, n = i.closest("cx-tree-item"), r = e.composedPath().some(
      (m) => m?.classList?.contains("tree-item__expand-button")
    ), a = e.composedPath().some(
      (m) => m?.classList?.contains("tree-item__actions")
    );
    if (!n || n.disabled || n.readonly || i !== this.clickTarget)
      return;
    const d = !t.find(
      (m) => m.tagName?.toLowerCase() === "cx-checkbox"
    );
    r && n.showExpandButton ? n.expanded = !n.expanded : a || this.selectItem(
      n,
      d && this.labelSelectSingle && this.selection === "multiple"
    );
  }
  handleMouseDown(e) {
    this.clickTarget = e.target;
  }
  handleFocusOut(e) {
    const t = e.relatedTarget;
    (!t || !this.contains(t)) && (this.tabIndex = 0);
  }
  handleFocusIn(e) {
    const t = e.target;
    e.target === this && this.focusItem(this.lastFocusedItem || this.getAllTreeItems()[0]), o.isTreeItem(t) && !t.disabled && !t.readonly && (this.lastFocusedItem && !this.focusable && (this.lastFocusedItem.tabIndex = -1), this.lastFocusedItem = t, this.tabIndex = -1, t.tabIndex = 0);
  }
  expandToItem(e) {
    const t = e.parentElement?.closest("cx-tree-item");
    t && !t.expanded && !t.lazy && (t.expanded = !0, this.expandToItem(t));
  }
  handleSlotChange() {
    this.initTreeItems();
  }
  handleSortableUpdate(e) {
    const t = this.getAllDirectTreeItems();
    this.emit("cx-reorder", {
      detail: {
        from: e.from,
        item: e.item,
        items: t,
        newIndex: e.newIndex,
        oldIndex: e.oldIndex,
        to: e.to,
        type: e.type
      }
    });
  }
  destroySortable() {
    this.removeEventListener("cx-drag-start", this.handleSortableStart), this.removeEventListener("cx-drag-end", this.handleSortableEnd), this.sortableInstance && (this.sortableInstance.destroy(), this.sortableInstance = null);
  }
  getSortableGroup() {
    if (!this.disabledSortableGroup)
      return this.sortableGroup || (this.sortableGroup = se()), this.sortableGroup;
  }
  handleSortableStart() {
    this.setAttribute("dragging", "");
  }
  handleSortableEnd() {
    this.removeAttribute("dragging");
  }
  initSortable() {
    this.addEventListener("cx-drag-start", this.handleSortableStart), this.addEventListener("cx-drag-end", this.handleSortableEnd), this.sortableInstance = S.create(this, {
      ...j({
        group: this.getSortableGroup(),
        onAdd: this.handleSortableUpdate,
        onEnd: this.handleSortableEnd,
        onRemove: this.handleSortableUpdate,
        onStart: this.handleSortableStart,
        onUpdate: this.handleSortableUpdate
      })
    });
  }
  async handleSelectionChange() {
    const e = this.selection === "multiple", t = this.getAllTreeItems();
    this.setAttribute(
      "aria-multiselectable",
      e ? "true" : "false"
    );
    for (const i of t)
      i.selectable = e;
    e ? (await this.updateComplete, [...this.querySelectorAll(":scope > cx-tree-item")].forEach(
      (i) => A(i, !0, this.selection)
    )) : this.autoExpandToSelected || t.forEach((i) => {
      i.selected = !1, i.indeterminate = !1;
    });
  }
  updated(e) {
    super.updated(e), e.has("sortable") && (this.destroySortable(), this.sortable && this.initSortable());
  }
  /**
   * Returns the list of tree items that are selected in the tree.
   *
   * @internal
   */
  get selectedItems() {
    const e = this.getAllTreeItems(), t = (i) => i.partialSyncCheckboxes ? i.selected || i.indeterminate && i.previouslySelected : i.selected;
    return e.filter(t);
  }
  /**
   * Gets focusable tree items in the tree.
   *
   * @internal
   */
  getFocusableItems() {
    const e = this.getAllTreeItems(), t = /* @__PURE__ */ new Set();
    return e.filter((i) => {
      if (i.disabled || i.readonly)
        return !1;
      const n = i.parentElement?.closest("[role=treeitem]");
      return n instanceof o ? (n && (!n.expanded || n.loading || t.has(n)) && t.add(i), !t.has(i)) : !0;
    });
  }
  render() {
    return g`<div part="base" class="tree" @click=${this.handleClick} @keydown=${this.handleKeyDown} @mousedown=${this.handleMouseDown}><slot part="children" @slotchange=${this.handleSlotChange}></slot><span hidden aria-hidden="true"><slot name="expand-icon"></slot></span><span hidden aria-hidden="true"><slot name="collapse-icon"></slot></span></div>`;
  }
};
c.styles = [N, pe];
h([
  f("slot:not([name])")
], c.prototype, "defaultSlot", 2);
h([
  f("slot[name=expand-icon]")
], c.prototype, "expandedIconSlot", 2);
h([
  f("slot[name=collapse-icon]")
], c.prototype, "collapsedIconSlot", 2);
h([
  l({ reflect: !0, type: Boolean })
], c.prototype, "sortable", 2);
h([
  l({ attribute: "sortable-group", type: String })
], c.prototype, "sortableGroup", 2);
h([
  l({ attribute: "disabled-sortable-group", type: Boolean })
], c.prototype, "disabledSortableGroup", 2);
h([
  l()
], c.prototype, "selection", 2);
h([
  l({ attribute: "disabled-auto-expand", type: Boolean })
], c.prototype, "disabledAutoExpand", 2);
h([
  l({ attribute: "auto-expand-to-selected", type: Boolean })
], c.prototype, "autoExpandToSelected", 2);
h([
  l({
    attribute: "expand-button-placement",
    reflect: !0,
    type: String
  })
], c.prototype, "expandButtonPlacement", 2);
h([
  l({ attribute: "no-forward-expand-button-placement", type: Boolean })
], c.prototype, "noForwardExpandButtonPlacement", 2);
h([
  l({ attribute: "force-on-change", type: Boolean })
], c.prototype, "forceOnChange", 2);
h([
  l({ attribute: "label-select-single", reflect: !0, type: Boolean })
], c.prototype, "labelSelectSingle", 2);
h([
  l({ attribute: "no-drag-inside", reflect: !0, type: Boolean })
], c.prototype, "noDragInside", 2);
h([
  l({ reflect: !0, type: Boolean })
], c.prototype, "focusable", 2);
h([
  y()
], c.prototype, "sortableInstance", 2);
h([
  b("sortable")
], c.prototype, "initTreeItems", 1);
h([
  b("selection")
], c.prototype, "handleSelectionChange", 1);
c = h([
  G("cx-tree")
], c);
export {
  o as C,
  c as a,
  X as b,
  q as c,
  ie as d,
  A as s,
  se as v
};
