import { c as MapToComponentField, I as InjectVegaSlimmer, V as VegaSlimmer, L as LogUtility, M as MapToComponentMethod } from './global-slimmer-registry-17c4efd4.js';
import { f as findParent, d as isElementVisible, b as isParent } from './ui-b7600a48.js';
import { I as InternalVegaZIndexManager } from './internal-vega-z-index-manager-7d2b54c3.js';
import { c as createDynamicSlimmer } from './dynamic-slimmer-90b8af32.js';
import { P as PageResizeObserverSlimmer } from './page-resize-observer-slimmer-e24d36c5.js';
import { A as Alignments, P as Placements } from './ui-93922c59.js';
import { G as isTranslocationType, i as isNonNullable, a7 as isEATriggerStrategy } from './type-guard-adc244fd.js';
import { R as ResponsiveFormatFacade } from './responsive-format-facade-456a9f16.js';
import { t as tryGetDocument } from './try-get-document-bef0f526.js';
import { F as FeatureFlag } from './feature-flag-controller-30f7b625.js';
import { C as ChangeManager } from './change-manager-6a7eb88c.js';
import { S as SHADOW_ROOT_ELEMENT_SCROLLING } from './static-subject-title-52f93124.js';
import { O as Observer } from './observer-3959f9dd.js';
import { d as domNodeSubjectFactory, D as DomNodeSubjectObserverFactory } from './dom-node-subject-observer-factory-aca0116e.js';
import { B as VegaInternalNestEAHierarchyTreeChange } from './vega-internal-event-id-db974a0d.js';

var __decorate$b = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is is used to retrieve the body element of document.
 */
class DefaultWrapper {
  /**
   * The canRetrieve function return is always true.
   *
   * @returns {boolean} the boolean type.
   */
  canRetrieve() {
    return true;
  }
  /**
   * The retrieve function get the body element of document.
   *
   * @returns {HTMLElement} the element.
   */
  retrieve() {
    // eslint-disable-next-line no-restricted-globals
    const container = document.body;
    if (this.showConfig.appendableElement.parentElement !== container) {
      container.append(this.showConfig.appendableElement);
    }
    return container;
  }
}
__decorate$b([
  MapToComponentField()
], DefaultWrapper.prototype, "showConfig", void 0);

/**
 * Body positioned wrapper.
 */
class BodyPositionedWrapper {
  /**
   * Valid is a body position used wrapper.
   *
   * @returns {boolean} can retrieve or not.
   */
  canRetrieve() {
    return !this.showConfig.isScreenPosition;
  }
}

var __decorate$a = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is is used to retrieve an HTML element based on a specified selector.
 *
 * @property {HTMLElement} showConfig the show config
 */
class PositionRelativeToWrapper extends BodyPositionedWrapper {
  /**
   * The canRetrieve function just determines whether the showConfig contains the positionRelativeTo object.
   *
   * @returns {boolean} the boolean type.
   */
  canRetrieve() {
    return (super.canRetrieve() &&
      !!this.showConfig.positionRelativeTo &&
      // eslint-disable-next-line no-restricted-globals
      !!document.querySelector(this.showConfig.positionRelativeTo));
  }
  /**
   * The retrieve function query the element of positionRelativeTo in showConfig.
   *
   * @returns {HTMLElement} the element.
   */
  retrieve() {
    // eslint-disable-next-line no-restricted-globals
    const container = document.querySelector(this.showConfig.positionRelativeTo);
    if (this.showConfig.appendableElement.parentElement !== container) {
      container.append(this.showConfig.appendableElement);
    }
    return container;
  }
}
__decorate$a([
  MapToComponentField()
], PositionRelativeToWrapper.prototype, "showConfig", void 0);

var __decorate$9 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is is used to get vega-modal element as a container and store the element appender element to slot.
 *
 * @property {HTMLElement} showConfig the show config
 */
class VegaModalWrapper extends BodyPositionedWrapper {
  /**
   * The canRetrieve function just determines whether the target of showConfig has the `vega-modal` element. If not, search upwards layer by layer.
   *
   * @returns {boolean} the boolean type.
   */
  canRetrieve() {
    return super.canRetrieve() && !!findParent(this.showConfig.target, 'vega-modal');
  }
  /**
   * The retrieve function get the slot position of vega-modal element.
   *
   * @returns {HTMLElement} the element.
   */
  retrieve() {
    return this.getVegaModalShowConfigContainer();
  }
  /**
   * This function `getVegaModalContentWithoutScroll` determines whether vega-modal has a slot whose name is `content` or `modal-content`. If there is a component rendered in the modal, the elementAppender added to the corresponding slot attribute is added. If not, the elementAppender is not directly appended to the root directory of vega-modal.
   *
   * @param {Nullable<HTMLElement>} parentModal The parentModal is vega-modal element.
   * @param {Nullable<HTMLElement>} element The parentModal is vega-modal element.
   */
  setElementSlot(parentModal, element) {
    var _a;
    const slotName = (_a = Array.from(parentModal.children)
      .find((item) => {
      const slotName = item.getAttribute('slot');
      return slotName && ['content', 'modal-content'].includes(slotName);
    })) === null || _a === void 0 ? void 0 : _a.getAttribute('slot');
    if (slotName) {
      element.setAttribute('slot', slotName);
    }
  }
  /**
   * The function "getShowConfigContainer" returns the appended element container. If the modal content can be scrolled, the container is the div element that wraps the append element. Otherwise, the container is the modal dialog itself.
   *
   * @returns {HTMLElement} the `scrollContainer` element.
   */
  getVegaModalShowConfigContainer() {
    const parentModal = findParent(this.showConfig.target, 'vega-modal');
    const modalContentScrollable = parentModal.shadowRoot.querySelector('.vega-modal-content-with-scroll');
    const modalDialog = parentModal.shadowRoot.querySelector('.modal-dialog');
    this.setElementSlot(parentModal, this.showConfig.appendableElement);
    parentModal.append(this.showConfig.appendableElement);
    return modalContentScrollable ? modalContentScrollable : modalDialog;
  }
}
__decorate$9([
  MapToComponentField({ writable: true })
], VegaModalWrapper.prototype, "showConfig", void 0);

var __decorate$8 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is used to get the class `vega-popover` as a container and store the element appender element.
 *
 * @property {HTMLElement} showConfig the show config
 */
class VegaPopoverWrapper extends BodyPositionedWrapper {
  /**
   * The canRetrieve function just determine whether the target of showConfig has the class `vega-popover`. If not, search upwards layer by layer.
   *
   * @returns {boolean} the boolean type.
   */
  canRetrieve() {
    return super.canRetrieve() && !!findParent(this.showConfig.target, '.vega-popover');
  }
  /**
   * The retrieve function get the element that if the target of showConfig does not have the class vega-popover, search upwards layer by layer until this element is found.
   *
   * @returns {HTMLElement} the element.
   */
  retrieve() {
    const container = findParent(this.showConfig.target, '.vega-popover');
    container.append(this.showConfig.appendableElement);
    return container;
  }
}
__decorate$8([
  MapToComponentField()
], VegaPopoverWrapper.prototype, "showConfig", void 0);

var __decorate$7 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Appends the popover content box inside the nearest third-party dialog/modal (e.g. Bootstrap,
 * MUI) so that their focus trap does not block focus on vega-popover content.
 *
 * Detection strategy:
 * 1. Walk up from the target to find `dialog` or `[aria-modal="true"]`.
 * 2. Skip Vega-owned elements (tag starts with `VEGA-`).
 * 3. Locate the focus-trap root via `closest('[tabindex="-1"]')`.
 */
class ThirdPartyDialogWrapper extends BodyPositionedWrapper {
  /**
   * Returns true when the target lives inside a third-party dialog.
   *
   * NOTE: Does NOT call super.canRetrieve() — must activate even when isScreenPosition=true
   * (e.g. image editor popover) so the content box stays inside the focus-trap root.
   *
   * @returns {boolean} Whether the target is inside a third-party dialog.
   */
  canRetrieve() {
    this.focusTrapRoot = this.findFocusTrapRoot(this.showConfig.target);
    return !!this.focusTrapRoot;
  }
  /**
   * Appends the popover content box inside the focus-trap root.
   *
   * @returns {HTMLElement} The focus-trap root element.
   */
  retrieve() {
    const root = this.focusTrapRoot;
    this.focusTrapRoot = null;
    if (this.showConfig.appendableElement.parentElement !== root) {
      root.append(this.showConfig.appendableElement);
    }
    return root;
  }
  /**
   * Finds the focus-trap root of the nearest third-party dialog ancestor.
   * Returns null if not inside a third-party dialog or if the dialog is Vega-owned.
   *
   * @param {Nullable<HTMLElement>} el - The element to start searching from.
   * @returns {Nullable<HTMLElement>} The focus-trap root, or null.
   */
  findFocusTrapRoot(el) {
    var _a;
    const dialog = findParent(el, 'dialog, [aria-modal="true"]');
    if (!dialog || this.isVegaOwned(dialog))
      return null;
    // closest() also matches the element itself — needed when [aria-modal] and [tabindex="-1"]
    // are on the same node (e.g. Bootstrap 5 outer .modal div).
    return (_a = dialog.closest('[tabindex="-1"]')) !== null && _a !== void 0 ? _a : dialog;
  }
  /**
   * Returns true when the element is a Vega custom element (tag starts with `VEGA-`).
   *
   * @param {HTMLElement} el - The element to check.
   * @returns {boolean} True if the element is Vega-owned.
   */
  isVegaOwned(el) {
    return el.tagName.startsWith('VEGA-');
  }
}
__decorate$7([
  MapToComponentField()
], ThirdPartyDialogWrapper.prototype, "showConfig", void 0);

var __decorate$6 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is responsible for setting the container element for appending an element based on certain conditions.
 *
 * @property {HTMLElement} container the container
 * @property {HTMLElement} showConfig the show config
 */
class ElementAppenderContainerController extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.positionRelativeToWrapper = new PositionRelativeToWrapper();
    this.vegaPopoverWrapper = new VegaPopoverWrapper();
    this.vegaModalWrapper = new VegaModalWrapper();
    this.thirdPartyDialogWrapper = new ThirdPartyDialogWrapper();
    this.defaultWrapper = new DefaultWrapper();
  }
  /**
   * The function sets the container element by iterating through a list of retrievers, defaulting to the document body.
   */
  setContainer() {
    this.setContainerRetrievers();
    for (const retriever of this.containerRetrievers) {
      if (retriever.canRetrieve()) {
        this.container = retriever.retrieve();
        return;
      }
    }
  }
  /**
   * The function sets up an array of container retrievers based on certain conditions.
   */
  setContainerRetrievers() {
    this.containerRetrievers = [
      this.positionRelativeToWrapper,
      this.vegaPopoverWrapper,
      this.vegaModalWrapper,
      this.thirdPartyDialogWrapper,
      this.defaultWrapper,
    ];
  }
}
__decorate$6([
  MapToComponentField({ writable: true })
], ElementAppenderContainerController.prototype, "container", void 0);
__decorate$6([
  MapToComponentField({ writable: true })
], ElementAppenderContainerController.prototype, "showConfig", void 0);
__decorate$6([
  InjectVegaSlimmer()
], ElementAppenderContainerController.prototype, "positionRelativeToWrapper", void 0);
__decorate$6([
  InjectVegaSlimmer()
], ElementAppenderContainerController.prototype, "vegaPopoverWrapper", void 0);
__decorate$6([
  InjectVegaSlimmer()
], ElementAppenderContainerController.prototype, "vegaModalWrapper", void 0);
__decorate$6([
  InjectVegaSlimmer()
], ElementAppenderContainerController.prototype, "thirdPartyDialogWrapper", void 0);
__decorate$6([
  InjectVegaSlimmer()
], ElementAppenderContainerController.prototype, "defaultWrapper", void 0);

/**
 * calculate position
 */
class BasePositionCalculationStrategy extends VegaSlimmer {
  /**
   * Whether the controller should adjust/recompute position at this time.
   *
   * This hook allows strategies to avoid unnecessary work (for example, on scroll) by deciding
   * whether a re-position is required.
   *
   * @returns {boolean} True when the controller should proceed with width/height/position adjustments.
   */
  shouldAdjustPosition() {
    return true;
  }
  /**
   * Get the position box.
   *
   * @param {PlacementType[]} placement - previous placement.
   * @param {PositionAlignmentType[]} alignment - previous placement.
   * @returns {ElementPositionBox} A function that takes in a container, element, target, placement, and translocation and
   * returns an ElementPositionBox.
   */
  getPositionBox(placement, alignment) {
    const placements = placement && placement.length > 0 ? placement : this.getPlacements();
    const alignments = alignment && alignment.length > 0 ? alignment : this.getAlignments();
    const targetBox = this.getTargetBoundBox();
    const elementBox = this.getElementBoundBox();
    const containerBox = this.getElementScrollDimension();
    const suitablePlacement = this.getSuitablePlacement(containerBox, elementBox, targetBox, placements);
    const activePlacement = suitablePlacement || placements[0];
    const suitableAlignment = this.getSuitableAlignment(containerBox, elementBox, targetBox, activePlacement, alignments);
    const activeAlignment = suitableAlignment || alignments[0];
    const positionBox = this.calculatePosition(elementBox, targetBox, activePlacement, activeAlignment);
    const translocationBox = this.getTranslocationBox(activePlacement);
    positionBox.placement = suitablePlacement;
    positionBox.alignment = suitableAlignment;
    positionBox.left += translocationBox.X;
    positionBox.top += translocationBox.Y;
    if (!this.showConfig.positionRelativeTo && this.showConfig.isScreenPosition) {
      this.adjustPositionForViewport(positionBox, elementBox, targetBox, activePlacement);
    }
    return positionBox;
  }
  /**
   * Whether the alignment space is enough
   *
   * @param {ElementScrollDimension} containerBox - The bounding box of the container element.
   * @param {ElementBoundBox} targetBox - The position of the target element.
   * @param {ElementBoundBox} elementBox - The box of the element that we're trying to position.
   * @param {PlacementType} placement - The placement of the element relative to the target.
   * @param {PlacementType} alignment - The alignment of the element relative to the target.
   * @returns {boolean} return true if it has enough space, otherwise false
   */
  hasEnoughAlignmentSpace(containerBox, targetBox, elementBox, placement, alignment) {
    if (['top', 'bottom'].includes(placement)) {
      switch (alignment) {
        case 'start': {
          return targetBox.left + elementBox.width <= containerBox.width;
        }
        case 'center': {
          return (targetBox.left >= (elementBox.width - targetBox.width) / 2 &&
            targetBox.left + targetBox.width / 2 + elementBox.width / 2 <= containerBox.width);
        }
        case 'end': {
          return targetBox.left + targetBox.width >= elementBox.width;
        }
      }
    }
    if (['right', 'left'].includes(placement)) {
      switch (alignment) {
        case 'start': {
          return targetBox.top + elementBox.height <= containerBox.height;
        }
        case 'center': {
          return (targetBox.top >= (elementBox.height - targetBox.height) / 2 &&
            targetBox.top + targetBox.height / 2 + elementBox.height / 2 <= containerBox.height);
        }
        case 'end': {
          return targetBox.top + targetBox.height >= elementBox.height;
        }
      }
    }
    /* istanbul ignore next */
    return false;
  }
  /**
   * Calculate the left position of the element
   *
   * @param {ElementBoundBox} elementBox - The position box of the element.
   * @param {ElementBoundBox} targetBox - The position box of the target element that is attached to.
   * @param {PlacementType} placement - The placement of the element.
   * @param {PositionAlignmentType} alignment - The alignment of the element
   * @returns {number} The left position of the element.
   */
  calculateLeft(elementBox, targetBox, placement, alignment) {
    switch (placement) {
      case 'top':
      case 'bottom': {
        if (alignment === 'end') {
          return targetBox.left + targetBox.width - elementBox.width;
        }
        else if (alignment === 'center') {
          return targetBox.left - (elementBox.width - targetBox.width) / 2;
        }
        else {
          return targetBox.left;
        }
      }
      case 'left': {
        return targetBox.left - elementBox.width;
      }
      case 'right': {
        return targetBox.left + targetBox.width;
      }
      /* istanbul ignore next */
      default:
        throw new Error(`Unexpected placement: ${placement}. Expected values are top, bottom, left, or right.`);
    }
  }
  /**
   * Calculate the top position of the element
   *
   * @param {ElementBoundBox} elementBox - The position box of the element.
   * @param {ElementBoundBox} targetBox - The position box of the target element that is attached to.
   * @param {PlacementType} placement - The placement of the element.
   * @param {PositionAlignmentType} alignment - The alignment of the element
   * @returns {number} the top position of the element.
   */
  calculateTop(elementBox, targetBox, placement, alignment) {
    switch (placement) {
      case 'left':
      case 'right': {
        if (alignment === 'end') {
          return targetBox.top + targetBox.height - elementBox.height;
        }
        else if (alignment === 'center') {
          return targetBox.top - (elementBox.height - targetBox.height) / 2;
        }
        else {
          return targetBox.top;
        }
      }
      case 'top': {
        return targetBox.top - elementBox.height;
      }
      case 'bottom': {
        return targetBox.top + targetBox.height;
      }
      /* istanbul ignore next */
      default:
        throw new Error(`Unexpected placement: ${placement}. Expected values are top, bottom, left, or right.`);
    }
  }
  /**
   * It returns acceptable alignments.
   *
   * @returns {PositionAlignmentType[]} acceptable alignments
   */
  getAlignments() {
    const alignment = this.showConfig.alignment;
    if (typeof alignment === 'string') {
      const partial = Alignments.filter((item) => item !== alignment);
      return [alignment, ...partial];
    }
    else if (Array.isArray(alignment)) {
      return alignment;
    }
    else {
      return [...Alignments];
    }
  }
  /**
   * It takes a list of placements and returns the first placement that has enough space to place the
   * element
   *
   * @param {ElementScrollDimension} containerBox - The box of the container element.
   * @param {ElementBoundBox} elementBox - The box of the element to be placed.
   * @param {ElementBoundBox} targetBox - The box of the target element.
   * @param {PlacementType[]} placements - The placements that we want to try.
   * @returns {Nullable<PlacementType>} A function that takes in a containerBox, elementBox, targetBox, placements, and element.
   */
  getSuitablePlacement(containerBox, elementBox, targetBox, placements) {
    const defaultPlacement = placements[0];
    const suitablePlacement = placements.find((placement) => this.hasEnoughSpace(containerBox, placement, targetBox, elementBox));
    if (suitablePlacement) {
      return suitablePlacement;
    }
    else {
      LogUtility.warn(`
                No enough space found for placing element and we will keep using the defined placement:
                ${defaultPlacement}
            `);
      return null;
    }
  }
  /**
   * "Get the width, height, and top position of an element."
   *
   * The function takes an element as an argument and returns an object with three properties: width,
   * height, and top.
   *
   * Note: If element is hide, we should temporary change it to `block` to get the bounding client rect of element,
   * After do that, this element will change to origin `hide`, if not, it will be contained in the calculate of `document.documentElement.scrollHeight`
   *
   * @returns {ElementBoundBox} An object with the width, height, and top properties of the element.
   */
  getElementBoundBox() {
    const element = this.showConfig.appendableElement;
    const isElementHide = element.classList.contains('vega-force-hidden');
    if (isElementHide)
      element.classList.remove('vega-force-hidden');
    const elementRect = element.getBoundingClientRect();
    if (isElementHide)
      element.classList.add('vega-force-hidden');
    return {
      width: elementRect.width,
      height: elementRect.height,
      left: elementRect.left,
      top: elementRect.top,
    };
  }
  /**
   * It takes a placement string or array of placements and returns an array of placements
   * if given placement is single, we should completion the placements with the default {@link Placements}
   * and make given placement as default.
   * if given placement is array, we should use it directly, even it partial of {@link Placements}.
   * if not placement give. we should use {@link Placements}.
   *
   * @returns {PlacementType[]} ordered placements.
   */
  getPlacements() {
    const placement = this.showConfig.placement;
    if (typeof placement === 'string') {
      const partial = Placements.filter((direction) => direction !== placement);
      return [placement, ...partial];
    }
    else if (Array.isArray(placement)) {
      return placement;
    }
    else {
      return [...Placements];
    }
  }
  /**
   * It takes a placement, a target box, and a element box, and returns an element box
   *
   * @param {ElementBoundBox} elementBox - The position of the element element.
   * @param {ElementBoundBox} targetBox - The position of the target element.
   * @param {PlacementType} placement - The placement of the element.
   * @param {PositionAlignmentType} alignment - The alignment of the element
   * @returns {ElementPositionBox} An object with top and left properties.
   */
  calculatePosition(elementBox, targetBox, placement, alignment) {
    return {
      top: this.calculateTop(elementBox, targetBox, placement, alignment),
      left: this.calculateLeft(elementBox, targetBox, placement, alignment),
    };
  }
  /**
   * Keeps the vertical position within the visible viewport
   *
   * @param {number} top - The calculated top position.
   * @param {number} elementHeight - The height of the element.
   * @returns {number} The top position constrained to the viewport.
   */
  keepVerticallyInView(top, elementHeight) {
    return Math.max(0, Math.min(top, window.innerHeight - elementHeight));
  }
  /**
   * Keeps the horizontal position within the visible viewport
   *
   * @param {number} left - The calculated left position.
   * @param {number} elementWidth - The width of the element.
   * @returns {number} The left position constrained to the viewport.
   */
  keepHorizontallyInView(left, elementWidth) {
    return Math.max(0, Math.min(left, window.innerWidth - elementWidth));
  }
  /**
   * Checks if the target element is visible in the viewport
   *
   * @param {ElementBoundBox} targetBox - The bounding box of the target element.
   * @returns {boolean} True if target is visible in viewport.
   */
  isTargetInView(targetBox) {
    const innerHeight = window.innerHeight;
    const innerWidth = window.innerWidth;
    const targetBottom = targetBox.top + targetBox.height;
    const targetRight = targetBox.left + targetBox.width;
    return (targetBox.top <= innerHeight &&
      targetBottom >= 0 &&
      targetBox.left <= innerWidth &&
      targetRight >= 0);
  }
  /**
   * Corrects `positionBox` so the element stays within the viewport after translocation.
   * Only runs when the target is visible; skips correction entirely if the target has
   * scrolled out of view so the element simply follows it.
   *
   * @param {ElementPositionBox} positionBox - The final position box to adjust (mutated in place).
   * @param {ElementBoundBox} elementBox - Dimensions of the positioned element.
   * @param {ElementBoundBox} targetBox - Bounding box of the target element.
   * @param {PlacementType} placement - Active placement used to select the correction axis.
   */
  adjustPositionForViewport(positionBox, elementBox, targetBox, placement) {
    if (!this.isTargetInView(targetBox)) {
      return;
    }
    if (placement === 'top' || placement === 'bottom') {
      positionBox.top = this.adjustForVerticalOverflow(positionBox.top, elementBox.height, targetBox.height);
    }
    else if (placement === 'left' || placement === 'right') {
      positionBox.left = this.adjustForHorizontalOverflow(positionBox.left, elementBox.width, targetBox.width);
    }
    positionBox.top = this.keepVerticallyInView(positionBox.top, elementBox.height);
    positionBox.left = this.keepHorizontallyInView(positionBox.left, elementBox.width);
  }
  /**
   * Nudges `top` so the element stays within the viewport vertically.
   * Only corrects when the overflow is less than `targetHeight` to keep the element
   * visually anchored to its target; larger overflows are handled by `keepVerticallyInView`.
   *
   * @param {number} top - The calculated top position.
   * @param {number} elementHeight - Height of the positioned element.
   * @param {number} targetHeight - Height of the target, used as the max correctable overflow.
   * @returns {number} The adjusted top position.
   */
  adjustForVerticalOverflow(top, elementHeight, targetHeight) {
    // Pixels the element bleeds past the bottom of the viewport (positive = overflow).
    const overflowBottom = top + elementHeight - window.innerHeight;
    // Pixels the element bleeds past the top of the viewport (positive = overflow).
    const overflowTop = -top;
    // Only nudge when overflow is smaller than targetHeight; larger overflows are left to
    // keepVerticallyInView to hard-clamp, since nudging that far would detach from the target.
    if (overflowBottom > 0 && overflowBottom < targetHeight) {
      return top - overflowBottom; // shift up until bottom edge is flush with viewport bottom
    }
    if (overflowTop > 0 && overflowTop < targetHeight) {
      return top + overflowTop; // shift down until top edge is flush with viewport top
    }
    return top;
  }
  /**
   * Nudges `left` so the element stays within the viewport horizontally.
   * Only corrects when the overflow is less than `targetWidth` to keep the element
   * visually anchored to its target; larger overflows are handled by `keepHorizontallyInView`.
   *
   * @param {number} left - The calculated left position.
   * @param {number} elementWidth - Width of the positioned element.
   * @param {number} targetWidth - Width of the target, used as the max correctable overflow.
   * @returns {number} The adjusted left position.
   */
  adjustForHorizontalOverflow(left, elementWidth, targetWidth) {
    // Pixels the element bleeds past the right edge of the viewport (positive = overflow).
    const overflowRight = left + elementWidth - window.innerWidth;
    // Pixels the element bleeds past the left edge of the viewport (positive = overflow).
    const overflowLeft = -left;
    // Only nudge when overflow is smaller than targetWidth; larger overflows are left to
    // keepHorizontallyInView to hard-clamp, since nudging that far would detach from the target.
    if (overflowRight > 0 && overflowRight < targetWidth) {
      return left - overflowRight; // shift left until right edge is flush with viewport right
    }
    if (overflowLeft > 0 && overflowLeft < targetWidth) {
      return left + overflowLeft; // shift right until left edge is flush with viewport left
    }
    return left;
  }
  /**
   * It returns the translocation of the element relative to the target element
   *
   * @param {PlacementType} placement - The suitable placement of the element.
   * @returns {TranslocationType} A translocation object with X and Y properties.
   */
  getTranslocationBox(placement) {
    const originPlacement = Array.isArray(this.showConfig.placement)
      ? this.showConfig.placement[0]
      : this.showConfig.placement;
    const translocation = this.getTranslocation();
    const result = { X: 0, Y: 0 };
    if (isTranslocationType(translocation)) {
      let xValue = translocation.X;
      let yValue = translocation.Y;
      // If originPlacement and placement is not in same axis, it should reverse axis.
      if ((originPlacement &&
        ['left', 'right'].includes(originPlacement) &&
        ['top', 'bottom'].includes(placement)) ||
        (originPlacement &&
          ['top', 'bottom'].includes(originPlacement) &&
          ['left', 'right'].includes(placement))) {
        xValue = translocation.Y;
        yValue = translocation.X;
      }
      if (['bottom', 'top'].includes(placement)) {
        result.Y = placement === 'top' ? -yValue : yValue;
        result.X = xValue;
      }
      if (['left', 'right'].includes(placement)) {
        result.X = placement === 'left' ? -xValue : xValue;
        result.Y = yValue;
      }
    }
    return result;
  }
  /**
   * It takes a list of alignments and returns the suitable one that has enough space to fit the element
   *
   * @param {ElementScrollDimension} containerBox - The bounding box of the container element.
   * @param {ElementBoundBox} elementBox - The box of the element that we want to position.
   * @param {ElementBoundBox} targetBox - The box of the element that the element to be positioned is aligned to.
   * @param {PlacementType} placement - The placement of the element relative to the target.
   * @param {PositionAlignmentType[]} alignments - An array of alignments to try.
   * @returns {Nullable<PositionAlignmentType>} the alignment that is suitable for the element.
   */
  getSuitableAlignment(containerBox, elementBox, targetBox, placement, alignments) {
    const defaultAlignment = alignments[0];
    const suitableAlignment = alignments.find((alignment) => this.hasEnoughAlignmentSpace(containerBox, targetBox, elementBox, placement, alignment));
    if (suitableAlignment) {
      return suitableAlignment;
    }
    else {
      LogUtility.warn(`
                No enough space found for placing element and we will keep using the defined alignment:
                ${defaultAlignment}
            `);
      return null;
    }
  }
  /**
   * If the placement is top or left, then the target's top or left position must be greater than or
   * equal to the element's height or width. If the placement is bottom or right, then the container's
   * height or width minus the target's top or left position minus the target's height or width must be
   * greater than or equal to the element's height or width.
   *
   * @param {ElementScrollDimension} containerBox - The bounding box of the container element.
   * @param {PlacementType} placement - The placement of the element.
   * @param {ElementBoundBox} targetBox - The position of the target element.
   * @param {ElementBoundBox} elementBox - The dimensions of the element to be positioned.
   * @returns {boolean} A boolean value.
   */
  hasEnoughSpace(containerBox, placement, targetBox, elementBox) {
    switch (placement) {
      case 'top':
        return targetBox.top >= elementBox.height;
      case 'bottom':
        return containerBox.height - targetBox.top - targetBox.height >= elementBox.height;
      case 'left':
        return targetBox.left >= elementBox.width;
      case 'right':
        return containerBox.width - targetBox.left - targetBox.width >= elementBox.width;
      /* istanbul ignore next */
      default:
        return false;
    }
  }
  /**
   * Retrieves and formats the translocation.
   *
   * @returns {Nullable<TranslocationType>} current translocation.
   */
  getTranslocation() {
    const translocation = this.showConfig.translocation;
    return translocation && ResponsiveFormatFacade.format(translocation, 'translocation');
  }
}

var __decorate$5 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * calculate position by body container
 */
class BodyPositionCalculationStrategy extends BasePositionCalculationStrategy {
  /**
   * Get the position of the element in the container according to the target element and the placement
   * If give a translocation, it will apply the translocation to the result.
   * Note: If you use this method to calculate the position, you should make container as relative position at first.
   *
   * @returns {ElementPositionBox} A function that takes in a container, element, target, placement, and translocation and
   * returns an ElementPositionBox.
   */
  getPosition() {
    const containerStyle = window.getComputedStyle(this.container);
    if (containerStyle.position !== 'relative') {
      LogUtility.warn(`Calculate position should make container as 'position: relative', otherwise the result might not be accurate.`);
    }
    return this.getPositionBox();
  }
  /**
   * It returns the position of an element relative to its container and also includes the scroll height of container.
   *
   * @returns {ElementBoundBox} An object with the properties width, height, top, and left.
   */
  getTargetBoundBox() {
    const containerRect = this.container.getBoundingClientRect();
    const targetRect = this.showConfig.target.getBoundingClientRect();
    const targetTop = targetRect.top - containerRect.top + this.container.scrollTop;
    const targetLeft = targetRect.left - containerRect.left + this.container.scrollLeft;
    return {
      width: targetRect.width,
      height: targetRect.height,
      top: targetTop,
      left: targetLeft,
    };
  }
  /**
   * "Get the width and height of an element."
   *
   * The function takes a single parameter, a container element, and returns an object with two
   * properties: width and height
   *
   * @returns {ElementScrollDimension} An object with two properties: width and height.
   */
  getElementScrollDimension() {
    return {
      width: this.container.scrollWidth,
      height: this.container.scrollHeight,
    };
  }
}
__decorate$5([
  MapToComponentField()
], BodyPositionCalculationStrategy.prototype, "container", void 0);
__decorate$5([
  MapToComponentField()
], BodyPositionCalculationStrategy.prototype, "showConfig", void 0);

/**
 * Updates position on scroll When the target rect changes, we recompute placement/alignment.
 */
class ScreenScrollPositionUpdate {
  constructor() {
    this.viewportWidth = window.innerWidth;
    this.viewportHeight = window.innerHeight;
  }
  /**
   * Determines whether the appendable element's position should update on scroll.
   *
   * @param {ScrollPositionUpdateStrategyContext} context - Current/previous rectangles plus viewport size.
   * @returns {ScrollPositionUpdateDecision} Decision that indicates whether to recompute position.
   */
  shouldUpdatePosition(context) {
    const { previousTargetRect, currentTargetRect, appendableRect, viewportWidth, viewportHeight, } = context;
    this.viewportWidth = viewportWidth;
    this.viewportHeight = viewportHeight;
    const targetChanged = !previousTargetRect ||
      currentTargetRect.left !== previousTargetRect.left ||
      currentTargetRect.top !== previousTargetRect.top;
    const isTargetWithinViewport = !this.isRectOutsideViewport(currentTargetRect);
    const isAppendableNotEntirelyInViewport = !this.isRectEntirelyWithinViewport(appendableRect);
    return {
      shouldUpdate: targetChanged && isTargetWithinViewport && isAppendableNotEntirelyInViewport,
    };
  }
  /**
   * Whether the rect is fully within the viewport bounds.
   *
   * @param {DOMRect} rect - The DOMRect to check.
   * @returns {boolean} True when rect is fully within the viewport.
   */
  isRectEntirelyWithinViewport(rect) {
    return (rect.left >= 0 &&
      rect.top >= 0 &&
      rect.right <= this.viewportWidth &&
      rect.bottom <= this.viewportHeight);
  }
  /**
   * Whether the element is fully outside the viewport.
   * If true, the rect has "disappeared" from the viewport.
   *
   * @param {DOMRect} rect - The DOMRect to check.
   * @returns {boolean} True when rect is completely outside viewport bounds.
   */
  isRectOutsideViewport(rect) {
    return (rect.right <= 0 ||
      rect.bottom <= 0 ||
      rect.left >= this.viewportWidth ||
      rect.top >= this.viewportHeight);
  }
}

var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * calculate position by screen container
 */
class ScreenPositionCalculationStrategy extends BasePositionCalculationStrategy {
  constructor() {
    super(...arguments);
    this.scrollFrameRequestId = null;
    this.usePreviousPlacement = false;
    this.scrollPositionUpdateStrategy = new ScreenScrollPositionUpdate();
  }
  /**
   * For screen-positioned appendable we may get a lot of scroll events.
   * This hook throttles the check with requestAnimationFrame and only allows an adjust when
   * the strategy determines we should update.
   *
   * @returns {boolean} True when controller should perform a position adjustment.
   */
  shouldAdjustPosition() {
    if (this.scrollFrameRequestId !== null) {
      return false;
    }
    if (!FeatureFlag.isEnabled('VEGA_ELEMENT_APPENDER.AUTO_PLACEMENT')) {
      this.usePreviousPlacement = true;
      return true;
    }
    if (!this.previousTargetRect) {
      this.previousTargetRect = this.showConfig.target.getBoundingClientRect();
      this.usePreviousPlacement = false;
      return true;
    }
    /**
     * This avoids doing expensive DOM reads on every scroll event, while still
     * updating placement/alignment when the trigger moves and the appendable
     * would be clipped by the viewport (auto placement).
     *
     * The below method is e2e-test covered in @see{module:the-screen-position-scroll-RAFCallback-trigger-as-expected}
     */
    /* istanbul ignore next */
    this.scrollFrameRequestId = requestAnimationFrame(() => {
      var _a;
      this.scrollFrameRequestId = null;
      let viewportWidth = window.innerWidth;
      let viewportHeight = window.innerHeight;
      if (this.showConfig.positionRelativeTo) {
        const containerDom = (_a = tryGetDocument()) === null || _a === void 0 ? void 0 : _a.querySelector(this.showConfig.positionRelativeTo);
        if (containerDom) {
          viewportWidth = containerDom.getBoundingClientRect().width;
          viewportHeight = containerDom.getBoundingClientRect().height;
        }
      }
      const currentTargetRect = this.showConfig.target.getBoundingClientRect();
      const appendableRect = this.showConfig.appendableElement.getBoundingClientRect();
      const { shouldUpdate } = this.scrollPositionUpdateStrategy.shouldUpdatePosition({
        currentTargetRect,
        previousTargetRect: this.previousTargetRect,
        appendableRect,
        viewportWidth,
        viewportHeight,
      });
      this.usePreviousPlacement = !shouldUpdate;
      this.previousTargetRect = currentTargetRect;
    });
    return true;
  }
  /**
   * Clears any pending scroll animation frame callback.
   * Call this when popover is hidden/destroyed to avoid leaks and stale callbacks.
   */
  clearScrollFrame() {
    if (this.scrollFrameRequestId !== null) {
      cancelAnimationFrame(this.scrollFrameRequestId);
      this.scrollFrameRequestId = null;
    }
  }
  /**
   * Get the position of the element in the container according to the target element and the placement
   * If give a translocation, it will apply the translocation to the result.
   *
   * @param {boolean} usePreviousPlacement - Should keep use previous placement and alignment.
   * @returns {ElementPositionBox} A function that takes in a container, element, target, placement, and translocation and
   * returns an ElementPositionBox.
   */
  getPosition(usePreviousPlacement) {
    const stayPlacement = usePreviousPlacement ? this.usePreviousPlacement : false;
    let positionBox;
    if (stayPlacement) {
      positionBox = this.getPositionBox([this.previousPositionBox.placement].filter(isNonNullable), [this.previousPositionBox.alignment].filter(isNonNullable));
      if (!FeatureFlag.isEnabled('VEGA_ELEMENT_APPENDER.AUTO_PLACEMENT')) {
        positionBox.placement = this.previousPositionBox.placement;
        positionBox.alignment = this.previousPositionBox.alignment;
      }
    }
    else {
      positionBox = this.getPositionBox();
    }
    this.previousPositionBox = positionBox;
    return positionBox;
  }
  /**
   * It returns the position of an element relative to its container and also includes the scroll height of container.
   *
   * @returns {ElementBoundBox} An object with the properties width, height, top, and left.
   */
  getTargetBoundBox() {
    const targetRect = this.showConfig.target.getBoundingClientRect();
    return {
      width: targetRect.width,
      height: targetRect.height,
      top: targetRect.top,
      left: targetRect.left,
    };
  }
  /**
   * "Get the width and height of an element."
   *
   * The function takes a single parameter, a container element, and returns an object with two
   * properties: width and height
   *
   * @returns {ElementScrollDimension} An object with two properties: width and height.
   */
  getElementScrollDimension() {
    return {
      width: window.innerWidth,
      height: window.innerHeight,
    };
  }
  /**
   * Whether the alignment space is enough
   *
   * @param {ElementScrollDimension} containerBox - The bounding box of the container element.
   * @param {ElementBoundBox} targetBox - The position of the target element.
   * @param {ElementBoundBox} elementBox - The box of the element that we're trying to position.
   * @param {PlacementType} placement - The placement of the element relative to the target.
   * @param {PlacementType} alignment - The alignment of the element relative to the target.
   * @returns {boolean} return true if it has enough space, otherwise false
   */
  hasEnoughAlignmentSpace(containerBox, targetBox, elementBox, placement, alignment) {
    const left = this.calculateLeft(elementBox, targetBox, placement, alignment);
    const top = this.calculateTop(elementBox, targetBox, placement, alignment);
    return (left >= 0 &&
      top >= 0 &&
      left + elementBox.width <= containerBox.width &&
      top + elementBox.height <= containerBox.height);
  }
  /**
   * Screen-specific suitable placement selection.
   * Tries to find a placement that has enough alignment space within the viewport first,
   * otherwise falls back to the base strategy.
   *
   * @param {ElementScrollDimension} containerBox - The bounding box of the container.
   * @param {ElementBoundBox} elementBox - The box of the element to place.
   * @param {ElementBoundBox} targetBox - The box of the target element.
   * @param {PlacementType[]} placements - Ordered list of placements to try.
   * @returns {Nullable<PlacementType>} The chosen placement.
   */
  getSuitablePlacement(containerBox, elementBox, targetBox, placements) {
    const alignments = this.getAlignments();
    const suitablePlacement = placements.find((placement) => alignments.some((alignment) => this.hasEnoughAlignmentSpace(containerBox, targetBox, elementBox, placement, alignment)));
    if (suitablePlacement) {
      return suitablePlacement;
    }
    return super.getSuitablePlacement(containerBox, elementBox, targetBox, placements);
  }
}
__decorate$4([
  MapToComponentField()
], ScreenPositionCalculationStrategy.prototype, "showConfig", void 0);

var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Calculation and adjustment of positions for appendable elements based on target element positions.
 */
class PositionCalculationController extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.bodyPositionStrategy = new BodyPositionCalculationStrategy();
    this.screenPositionStrategy = new ScreenPositionCalculationStrategy();
  }
  /**
   * Clears any pending screen-position scroll animation frame callback.
   * Call this when the appendable is hidden/destroyed.
   */
  clearScreenPositionScrollFrame() {
    this.screenPositionStrategy.clearScrollFrame();
  }
  /**
   * Sets the calculate postion strategy.
   */
  setCalculationStrategy() {
    this.positionStrategy = this.showConfig.isScreenPosition
      ? this.screenPositionStrategy
      : this.bodyPositionStrategy;
  }
  /**
   * Calculates the position and applies it to the appendable element.
   *
   * @param {boolean} [usePreviousPlacement] - Should keep use previous placement and alignment.
   */
  adjustPosition(usePreviousPlacement) {
    if (!this.positionStrategy.shouldAdjustPosition())
      return;
    this.adjustWidth();
    this.adjustHeight();
    this.applyPosition(this.positionStrategy.getPosition(usePreviousPlacement));
  }
  /**
   * Apply the position to the appendable element.
   *
   * @param {ElementPositionBox} positionBox - position box
   */
  applyPosition(positionBox) {
    const appendableElement = this.showConfig.appendableElement;
    // TODO: should control position style in element appender but in component level
    // https://gethired.atlassian.net/browse/VD-7883
    if (this.showConfig.isScreenPosition) {
      appendableElement.style.position = 'fixed';
    }
    else {
      if (appendableElement.classList.contains('date-picker-content-box')) {
        appendableElement.style.position = 'absolute';
      }
    }
    appendableElement.style.left = `${positionBox.left}px`;
    appendableElement.style.top = `${positionBox.top}px`;
    appendableElement.classList.remove('vega-placement-left', 'vega-placement-right', 'vega-placement-top', 'vega-placement-bottom', 'vega-no-suitable-placement');
    appendableElement.classList.remove('vega-alignment-start', 'vega-alignment-center', 'vega-alignment-end', 'vega-no-suitable-alignment');
    if (positionBox.placement) {
      appendableElement.classList.add(`vega-placement-${positionBox.placement}`);
    }
    else {
      appendableElement.classList.add(`vega-no-suitable-placement`);
    }
    if (positionBox.alignment) {
      appendableElement.classList.add(`vega-alignment-${positionBox.alignment}`);
    }
    else {
      appendableElement.classList.add(`vega-no-suitable-alignment`);
    }
  }
  /**
   * It sets the width of the appendable element to the width of the target element if the
   * matchTargetWidth property is true, otherwise it sets the width of the appendable element to the
   * size property
   *
   * @returns {void}
   */
  adjustWidth() {
    if (this.showConfig.matchTargetWidth) {
      const { width: hostWidth } = this.showConfig.target.getBoundingClientRect();
      this.setRelatedWidth('width', hostWidth);
    }
    else {
      this.setRelatedWidth('width', this.showConfig.size);
      this.setRelatedWidth('minWidth', this.showConfig.minWidth);
      this.setRelatedWidth('maxWidth', this.showConfig.maxWidth);
    }
  }
  /**
   * It takes a name and a value, formats the value, and then sets the style of the element
   *
   * @param {'width' | 'maxWidth' | 'minWidth'} name - 'width' | 'maxWidth' | 'minWidth'
   * @param {ResponsiveType<SizeType>} value - ResponsiveType<SizeType>
   * @returns {void}
   */
  setRelatedWidth(name, value) {
    if (!value)
      return;
    const formattedValue = ResponsiveFormatFacade.format(value, 'size');
    if (formattedValue) {
      this.showConfig.appendableElement.style[name] =
        typeof formattedValue === 'number' ? `${formattedValue}px` : formattedValue;
    }
  }
  /**
   * > If the `matchContainerHeight` property is set to `true`, then the maximum height of the dropdown
   * is set to the height of the container minus the height of the target minus the top offset of the
   * target
   *
   * @returns {void}
   */
  adjustHeight() {
    if (this.showConfig.matchContainerHeight && !this.showConfig.isScreenPosition) {
      const { height: targetHeight } = this.showConfig.target.getBoundingClientRect();
      let maxHeight = this.container.scrollHeight - this.showConfig.target.offsetTop - targetHeight;
      if (this.showConfig.maxHeight) {
        maxHeight = Math.min(maxHeight, this.showConfig.maxHeight);
      }
      this.showConfig.appendableElement.style.maxHeight = `${maxHeight}px`;
    }
    else if (this.showConfig.maxHeight) {
      this.showConfig.appendableElement.style.maxHeight = `${this.showConfig.maxHeight}px`;
    }
  }
}
__decorate$3([
  MapToComponentField()
], PositionCalculationController.prototype, "container", void 0);
__decorate$3([
  MapToComponentField()
], PositionCalculationController.prototype, "showConfig", void 0);
__decorate$3([
  InjectVegaSlimmer()
], PositionCalculationController.prototype, "bodyPositionStrategy", void 0);
__decorate$3([
  InjectVegaSlimmer()
], PositionCalculationController.prototype, "screenPositionStrategy", void 0);

var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * This class is responsible for attaching the appendable element to the host element and adjusting its position
 *
 * @property {HTMLElement} showConfigCallback This is the callback function that will be
 * called when the user clicks on the "Configure" button.
 * @property {HTMLElement} showConfigCallbackTarget he component that will be used as the
 * target for the showConfigCallback.
 * @property {HTMLElement} showConfig the show config
 */
class ElementAppender {
  /**
   * The `constructor` function is used to initialize the `showConfigCallback` and
   * `showConfigCallbackTarget` properties of the class.
   *
   * @param {ShowConfigCallbackType} showConfigCallback - This is the callback function that will be
   * called when the user clicks on the "Configure" button.
   * @param {ComponentInterface} [showConfigCallbackTarget] - The component that will be used as the
   * target for the showConfigCallback.
   */
  constructor(showConfigCallback, showConfigCallbackTarget) {
    var _a;
    this.resizeObserverSlimmer = createDynamicSlimmer(ElementAppender, PageResizeObserverSlimmer, [], [
      { mapFrom: 'connectResizeObserver', mapTo: 'connectResizeObserver' },
      { mapFrom: 'disconnectResizeObserver', mapTo: 'disconnectResizeObserver' },
    ], [
      {
        /**
         * The above code is defining a callback function. Inside the function,
         * it checks if both the `target` and `appendableElement` are visible using the `isElementVisible` function.
         * If both elements are visible, it calls three other functions: `adjustWidth`, `adjustHeight`, and `adjustPosition`.
         * These functions are responsible for adjusting the width, height, and position of the elements respectively.
         * The below method is e2e-test covered in @see{module:element-appender-helper-resize-callback-e2e }
         */
        callback: /* istanbul ignore next */ () => {
          // while target and appendableElement are both visible, we can adjust position.
          // https://gethired.atlassian.net/browse/VD-1087
          if (isElementVisible(this.showConfig.target) &&
            isElementVisible(this.showConfig.appendableElement)) {
            this.adjustPosition();
          }
        },
        // eslint-disable-next-line jsdoc/require-jsdoc, no-restricted-globals
        target: () => [document.body, this.showConfig.appendableElement, this.showConfig.target],
      },
    ]);
    this.elementAppenderContainerController = new ElementAppenderContainerController();
    this.positionCalculationController = new PositionCalculationController();
    this.showConfigCallback = showConfigCallback;
    this.showConfigCallbackTarget = showConfigCallbackTarget;
    const config = this.getShowConfig();
    this.hideElementAppender(config.appendableElement);
    (_a = config.appendableElement) === null || _a === void 0 ? void 0 : _a.classList.add('vega-element-appender-appendable');
  }
  /**
   * It takes an element and appends it to the DOM, then adjusts its position and size to match the
   * target element
   *
   * @returns {void} Nothing is being returned.
   */
  show() {
    this.positionCalculationController.clearScreenPositionScrollFrame();
    this.setShowConfig();
    if (!this.showConfig.target) {
      LogUtility.error(`No target element found, please add it at new elementAppender.`);
      return;
    }
    if (!this.showConfig.appendableElement) {
      LogUtility.error(`No appendable element found, please add it at new elementAppender.`);
      return;
    }
    /* A function that takes no parameters and returns nothing. It sets the position of the appendable
    element. */
    this.prepareShow();
    this.adjustPosition();
    this.setZIndex();
    this.toggleShow(true);
    this.connectResizeObserver();
  }
  /**
   * > If the appendable element exists, hide it
   */
  hide() {
    if (!this.showConfig)
      return;
    this.positionCalculationController.clearScreenPositionScrollFrame();
    this.toggleShow(false);
    this.resetContainerPosition();
    InternalVegaZIndexManager.removeZIndex(this.showConfig.appendableElement, 'base');
  }
  /**
   * Update position while window scroll.
   */
  onScroll() {
    if (this.showConfig.isScreenPosition) {
      this.adjustPosition(true);
    }
  }
  /* istanbul ignore next */
  /**
   * It removes the z-index from the appendable element, removes the appendable element from the DOM, and
   * disconnects the resize observer
   */
  destroy() {
    if (!this.showConfig)
      return;
    this.positionCalculationController.clearScreenPositionScrollFrame();
    this.removeVisibleAppendElement(this.showConfig.appendableElement);
    this.resetContainerPosition();
    InternalVegaZIndexManager.removeZIndex(this.showConfig.appendableElement, 'base');
    this.showConfig.appendableElement.remove();
    this.disconnectResizeObserver();
  }
  /**
   * The function "connectResizeObserver" is used to connect a resize observer.
   */
  connectResizeObserver() {
  }
  /**
   * The function disconnects a resize observer.
   */
  disconnectResizeObserver() {
  }
  /**
   * Toggle appendableElement show or hide
   *
   * @param {boolean} show remove hidden style if true, otherwise add it
   */
  toggleShow(show) {
    if (show) {
      this.showElementAppender(this.showConfig.appendableElement);
      this.saveVisibleAppendElement(this.showConfig.appendableElement);
    }
    else {
      this.hideElementAppender(this.showConfig.appendableElement);
      this.removeVisibleAppendElement(this.showConfig.appendableElement);
    }
  }
  /**
   * Show the appendable element by removing hidden styles
   * TODO: should directly control display style. https://gethired.atlassian.net/browse/VD-7884
   *
   * @param {HTMLElement} appendableElement - Appendable element controlled by ElementAppender
   */
  showElementAppender(appendableElement) {
    if (appendableElement.classList.contains('date-picker-content-box')) {
      appendableElement.style.display = 'block';
    }
    else {
      appendableElement.classList.remove('vega-force-hidden');
    }
  }
  /**
   * Hide the appendable element by adding hidden styles.
   * TODO: should directly control display style. https://gethired.atlassian.net/browse/VD-7884
   *
   * @param {HTMLElement} appendableElement - Appendable element controlled by ElementAppender
   */
  hideElementAppender(appendableElement) {
    if (!appendableElement)
      return;
    if (appendableElement.classList.contains('date-picker-content-box')) {
      appendableElement.style.display = 'none';
    }
    else {
      appendableElement.classList.add('vega-force-hidden');
    }
  }
  /**
   * Save visible AppendableElement from the container state
   *
   * @param {HTMLElement} appendableElement - Appendable element controlled by ElementAppender
   */
  saveVisibleAppendElement(appendableElement) {
    const containerState = ElementAppender.containerMap.get(this.container);
    if (containerState) {
      containerState.visibleAppendElements.add(appendableElement);
    }
  }
  /**
   * Remove the AppendableElement from the container state.
   * If the container not includes visible element, will remove the container Map.
   *
   * @param {HTMLElement} appendableElement - Appendable element controlled by ElementAppender
   */
  removeVisibleAppendElement(appendableElement) {
    const containerState = ElementAppender.containerMap.get(this.container);
    if (containerState) {
      containerState.visibleAppendElements.delete(appendableElement);
    }
  }
  /**
   * The below method is e2e-test covered in @see {module:should-not-reset-dropdown-append-container-position-style-to-origin-when-there-is-another-dropdown-need-to-show}
   */
  resetContainerPosition() {
    const containerState = ElementAppender.containerMap.get(this.container);
    if (containerState) {
      const { visibleAppendElements, originPosition = 'static' } = containerState;
      if (visibleAppendElements.size === 0) {
        this.container.style.position = originPosition;
        ElementAppender.containerMap.delete(this.container);
      }
    }
  }
  /**
   * If the showConfigCallback is a function, then call it and set the showConfig to the result.
   * Otherwise, set the showConfig to the showConfigCallback
   */
  setShowConfig() {
    this.showConfig = this.getShowConfig();
    this.showConfig = Object.assign({
      matchTargetWidth: false,
      matchContainerHeight: false,
    }, this.showConfig);
    if (this.showConfig.target && this.showConfig.appendableElement) {
      this.elementAppenderContainerController.setContainer();
    }
  }
  /**
   * It makes sure that the container element is positioned relatively, and that the appendable element
   * has box-sizing set to border-box
   *
   * @returns {void}
   */
  prepareShow() {
    // Add relative position to the container while the container is static,
    // https://developer.mozilla.org/en-US/docs/Web/CSS/position#types_of_positioning
    if (!this.showConfig.isScreenPosition) {
      this.initVisibleAppendElement();
    }
    this.showConfig.appendableElement.style.boxSizing = 'border-box';
    this.positionCalculationController.setCalculationStrategy();
  }
  /**
   * init visible append element.
   */
  initVisibleAppendElement() {
    const containerStyle = window.getComputedStyle(this.container);
    const originContainerPosition = containerStyle.position;
    if (!ElementAppender.containerMap.has(this.container)) {
      ElementAppender.containerMap.set(this.container, {
        visibleAppendElements: new Set(),
        originPosition: originContainerPosition,
      });
    }
    if (originContainerPosition === 'static') {
      this.container.style.position = 'relative';
    }
  }
  /**
   * A function that takes no parameters and returns nothing. It sets the position of the appendable element.
   *
   * @param {boolean} usePreviousPlacement - Should keep use previous placement and alignment.
   * @returns {void}
   */
  adjustPosition(usePreviousPlacement) {
    this.positionCalculationController.adjustPosition(usePreviousPlacement);
  }
  /**
   * Sets the z-index of the appendable element to 11000.
   *
   * @returns {void}
   */
  setZIndex() {
    InternalVegaZIndexManager.setZIndex(this.showConfig.appendableElement, 'base');
  }
  /**
   * If the showConfigCallback is a function, call it and return the result, otherwise return the
   * showConfigCallback
   *
   * @returns {ElementAppenderShowConfig} The showConfigCallback is being returned.
   */
  getShowConfig() {
    if (this.showConfigCallback instanceof Function) {
      return this.showConfigCallback(this.showConfigCallbackTarget);
    }
    else {
      return this.showConfigCallback;
    }
  }
}
/**
 * To maintain the state between container and the visible dropdown within it.
 * Key is containerElement
 */
ElementAppender.containerMap = new Map();
__decorate$2([
  InjectVegaSlimmer()
], ElementAppender.prototype, "resizeObserverSlimmer", void 0);
__decorate$2([
  InjectVegaSlimmer()
], ElementAppender.prototype, "elementAppenderContainerController", void 0);
__decorate$2([
  InjectVegaSlimmer()
], ElementAppender.prototype, "positionCalculationController", void 0);

var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var NestEANotifyType;
(function (NestEANotifyType) {
  NestEANotifyType["SHOW"] = "show";
  NestEANotifyType["HIDE"] = "hide";
})(NestEANotifyType || (NestEANotifyType = {}));
/**
 * Dynamically add parents and children of nest element appender while it show or hide.
 */
class ElementAppenderHierarchyTreeManager extends VegaSlimmer {
  constructor(currentEA) {
    super();
    this.childrenEA = [];
    this.currentEA = currentEA;
  }
  /**
   * Listen current element appender did load.
   */
  componentDidLoad() {
    this.register();
  }
  /**
   * Listen current element appender show.
   */
  onShow() {
    this.notify(NestEANotifyType.SHOW);
  }
  /**
   * Listen current element appender hide.
   */
  onHide() {
    this.notify(NestEANotifyType.HIDE);
  }
  /**
   * Get current parent of element appender.
   *
   * @returns {Nullable<ElementAppenderSlimmer>} - parent.
   */
  getParent() {
    return this.parentEA;
  }
  /**
   * Get current children of element appender.
   *
   * @returns {ElementAppenderSlimmer[]} - children.
   */
  getChildren() {
    return this.childrenEA;
  }
  /**
   * While current element appender show or hide we should notify nest element appender to add or remove chain.
   *
   * @param {NestEANotifyType} type - Notify type.
   */
  notify(type) {
    const parent = findParent(this.showConfig.target, '.vega-element-appender-appendable');
    if (parent) {
      ChangeManager.notify(domNodeSubjectFactory.getSubject(parent, VegaInternalNestEAHierarchyTreeChange), {
        type: type,
        child: this.currentEA,
        callback: 
        /* eslint-disable jsdoc/require-jsdoc */
        (parentEASlimmer) => {
          this.parentEA = parentEASlimmer;
        },
      });
    }
  }
  /**
   * Add a change manager to observer the nest element appender show or hide.
   */
  register() {
    if (this.showConfig) {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(this.showConfig.appendableElement, VegaInternalNestEAHierarchyTreeChange, (payload) => {
        if (payload.type === NestEANotifyType.SHOW) {
          this.childrenEA.push(payload.child);
        }
        else if (payload.type === NestEANotifyType.HIDE) {
          this.childrenEA = this.childrenEA.filter((child) => child !== payload.child);
        }
        payload.callback(this.currentEA);
      });
    }
  }
}
__decorate$1([
  MapToComponentField()
], ElementAppenderHierarchyTreeManager.prototype, "showConfig", void 0);
__decorate$1([
  MapToComponentMethod('componentDidLoad')
], ElementAppenderHierarchyTreeManager.prototype, "componentDidLoad", null);
__decorate$1([
  MapToComponentMethod('show')
], ElementAppenderHierarchyTreeManager.prototype, "onShow", null);
__decorate$1([
  MapToComponentMethod('hide')
], ElementAppenderHierarchyTreeManager.prototype, "onHide", null);

/**
 * ClickTriggerStrategy handles 'targetClick' and 'globalMouseDown' events to toggle or hide the appendable element.
 */
class ClickTriggerStrategy {
  /**
   * Determines if the strategy can evaluate the given event type.
   *
   * @param {VegaEAEventType} type - The type of the event.
   * @returns {boolean} True if the event type is 'targetClick' or 'globalMouseDown', otherwise false.
   */
  canEvaluate(type) {
    return type === 'target-click' || type === 'click-outside';
  }
  /**
   * Evaluates the trigger context and determines whether to show, hide, or toggle the appendable element.
   *
   * @param {VegaEATriggerContext} context - The context of the trigger event.
   * @returns {VegaEATriggerResult} An object indicating whether to show, hide, or toggle the appendable element.
   */
  evaluate(context) {
    if (context.eventType === 'target-click') {
      return {
        nextAction: context.currentState.isVisible ? 'hide' : 'show',
      };
    }
    if (context.eventType === 'click-outside' && context.currentState.isVisible) {
      return {
        nextAction: 'hide',
      };
    }
    return {};
  }
}

/**
 * HoverTriggerStrategy handles mouse enter and leave events on the target and appendable elements,
 * as well as global mouse down events to show or hide the appendable element.
 */
class HoverTriggerStrategy {
  /**
   * Determines if the strategy can evaluate the given event type.
   *
   * @param {VegaEAEventType} type - The type of the event.
   * @returns {boolean} True if the event type is related to hover actions or global mouse down, otherwise false.
   */
  canEvaluate(type) {
    return [
      'target-mouseenter',
      'target-mouseleave',
      'element-mouseenter',
      'element-mouseleave',
    ].includes(type);
  }
  /**
   * Evaluates the trigger context and determines whether to show, hide, or toggle the appendable element.
   *
   * @param {VegaEATriggerContext} context - The context of the trigger event.
   * @returns {VegaEATriggerResult} An object indicating whether to show, hide, or toggle the appendable element.
   */
  evaluate(context) {
    if (['target-mouseenter', 'element-mouseenter'].includes(context.eventType)) {
      return !context.currentState.isVisible
        ? {
          nextAction: 'show',
        }
        : {};
    }
    if (['target-mouseleave', 'element-mouseleave'].includes(context.eventType)) {
      return {
        nextAction: 'hide',
      };
    }
    /* istanbul ignore next */
    return {};
  }
}

/**
 * NoneTriggerStrategy does not respond to any events and always indicates no action.
 */
class NoneTriggerStrategy {
  /**
   * Determines if the strategy can evaluate the given event type.
   *
   * @returns {boolean} Always false as this strategy does not respond to any events.
   */
  canEvaluate() {
    return false;
  }
  /* istanbul ignore next */
  /**
   * Evaluates the trigger context and always indicates no action.
   *
   * @returns {VegaEATriggerResult} An object indicating no action (no show, hide, or toggle).
   */
  evaluate() {
    return {};
  }
}

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
class ElementAppenderSlimmer extends VegaSlimmer {
  constructor(showConfigFactory, getTrigger, isDropdownShowName = 'isDropdownShow', disableInteractiveGetter = () => false) {
    super();
    this.hierarchyTreeManager = new ElementAppenderHierarchyTreeManager(this);
    /**
     * It adds event listeners to the target and the appendable element
     */
    this.registerElementAppenderListener = () => {
      var _a, _b, _c, _d, _e, _f;
      this.unRegisterElementAppenderListener();
      if (this.showConfig) {
        (_a = this.showConfig.target) === null || _a === void 0 ? void 0 : _a.addEventListener('click', this.targetClickHandler);
        (_b = this.showConfig.target) === null || _b === void 0 ? void 0 : _b.addEventListener('mouseenter', this.targetMouseEnterHandler);
        (_c = this.showConfig.target) === null || _c === void 0 ? void 0 : _c.addEventListener('mouseleave', this.targetMouseLeaveHandler);
        (_d = this.showConfig.target) === null || _d === void 0 ? void 0 : _d.addEventListener('focusout', this.targetFocusoutHandler);
        (_e = this.showConfig.appendableElement) === null || _e === void 0 ? void 0 : _e.addEventListener('mouseenter', this.elementMouseEnterHandler);
        (_f = this.showConfig.appendableElement) === null || _f === void 0 ? void 0 : _f.addEventListener('mouseleave', this.elementMouseLeaveHandler);
      }
      window.addEventListener('mousedown', this.globalMouseDownHandler);
      // eslint-disable-next-line no-restricted-globals
      document.addEventListener('scroll', this.globalScrollHandler, { capture: true });
      this.listenShadowRootElementScrolling();
    };
    /* It's a function that listens to the click event on the dropdown. It checks if the trigger
    property is equal to 'click'. If it is, then it toggles the dropdown. */
    this.targetClickHandler = (event) => {
      const triggerStrategy = this.getTriggerStrategy();
      if (triggerStrategy.canEvaluate('target-click')) {
        this.executeTriggerStrategy(triggerStrategy, event, 'target-click');
      }
    };
    /* It's a function that listens to the mouseenter event on the dropdown. It checks if the trigger
    property is equal to 'hover'. If it is, then it clears the timer. */
    this.targetMouseEnterHandler = (event) => {
      const triggerStrategy = this.getTriggerStrategy();
      if (triggerStrategy.canEvaluate('target-mouseenter')) {
        this.executeTriggerStrategy(triggerStrategy, event, 'target-mouseenter');
        this.clearDelayHideTimer();
      }
    };
    /* It's a function that listens to the mouseleave event on the dropdown. It checks if the trigger
    property is equal to 'hover'. If it is, then it creates a timer that will hide the dropdown after a
    certain amount of time. */
    this.targetMouseLeaveHandler = (event) => {
      const triggerStrategy = this.getTriggerStrategy();
      if (triggerStrategy.canEvaluate('target-mouseleave')) {
        this.createDelayHideTimer(event, 'target-mouseleave');
      }
    };
    /* istanbul ignore next */
    /* While focused element is in appendable element, like search input or vega-dropdown-item, we should not hide dropdown */
    this.targetFocusoutHandler = (e) => {
      var _a;
      if (!isParent(e.relatedTarget, (_a = this.showConfig) === null || _a === void 0 ? void 0 : _a.appendableElement)) {
        this.targetMouseLeaveHandler(e);
      }
    };
    /* It's a function that listens to the mouseenter event on the dropdown. It checks if the trigger
    property is equal to 'hover'. If it is, then it clears the timer. */
    this.elementMouseEnterHandler = () => {
      var _a;
      (_a = this.hierarchyTreeManager.getParent()) === null || _a === void 0 ? void 0 : _a.elementMouseEnterHandler();
      const triggerStrategy = this.getTriggerStrategy();
      if (triggerStrategy.canEvaluate('element-mouseenter') && !this.disableInteractiveGetter()) {
        this.clearDelayHideTimer();
      }
    };
    /* It's a function that listens to the mouseleave event on the dropdown. It checks if the trigger
    property is equal to 'hover'. If it is, then it creates a timer that will hide the dropdown after a
    certain amount of time. */
    this.elementMouseLeaveHandler = (event) => {
      var _a;
      (_a = this.hierarchyTreeManager.getParent()) === null || _a === void 0 ? void 0 : _a.elementMouseLeaveHandler(event);
      const triggerStrategy = this.getTriggerStrategy();
      if (triggerStrategy.canEvaluate('element-mouseleave') && !this.disableInteractiveGetter()) {
        this.createDelayHideTimer(event, 'element-mouseleave');
      }
    };
    /* It's a function that listens to the global mousedown event. It checks if the dropdown is showing,
    and if the target of the event is not a child of the dropdown or the trigger. If it is, then it
    hides the dropdown. */
    this.globalMouseDownHandler = (e) => {
      const currentTarget = e.composedPath()[0];
      const hasChildShowing = this.hierarchyTreeManager
        .getChildren()
        .some((child) => child.isShowing());
      const triggerStrategy = this.getTriggerStrategy();
      if (!hasChildShowing &&
        triggerStrategy.canEvaluate('click-outside') &&
        this.showConfig &&
        !isParent(currentTarget, this.showConfig.appendableElement) &&
        !isParent(currentTarget, this.showConfig.target) &&
        (this.showConfig.isScreenPosition ||
          findParent(currentTarget, 'vega-modal') === findParent(this.showConfig.target, 'vega-modal'))) {
        this.executeTriggerStrategy(triggerStrategy, e, 'click-outside');
      }
    };
    /* istanbul ignore next */
    /* Listen global scroll event */
    this.globalScrollHandler = () => {
      var _a;
      if (this.showConfig && this.showConfig.isScreenPosition && this.isShowing()) {
        (_a = this.elementAppender) === null || _a === void 0 ? void 0 : _a.onScroll();
      }
    };
    /* A timer that will hide the dropdown after a certain amount of time. */
    this.createDelayHideTimer = (event, eventType) => {
      const triggerStrategy = this.getTriggerStrategy();
      this.delayHideTimer = setTimeout(() => {
        this.executeTriggerStrategy(triggerStrategy, event, eventType);
        clearTimeout(this.delayHideTimer);
      }, ElementAppenderSlimmer.DELAY_HIDE_TIME);
    };
    /* A function that clears the timer. */
    this.clearDelayHideTimer = () => {
      this.delayHideTimer && clearTimeout(this.delayHideTimer);
    };
    this.executeTriggerStrategy = (triggerStrategy, event, eventType) => {
      if (this.showConfig) {
        const result = triggerStrategy.evaluate({
          target: this.showConfig.target,
          appendableElement: this.showConfig.appendableElement,
          htmlEvent: event,
          eventType: eventType,
          currentState: {
            isVisible: this.isShowing(),
          },
        });
        if (result) {
          result.nextAction === 'hide' && this.hide();
          result.nextAction === 'show' && this.show();
        }
      }
    };
    this.showConfigFactory = showConfigFactory;
    this.getTrigger = getTrigger;
    this.isDropdownShowName = isDropdownShowName;
    this.disableInteractiveGetter = disableInteractiveGetter;
  }
  connectedCallback() {
    if (this.elementAppender === null) {
      this.setElementAppender();
      this.registerElementAppenderListener();
    }
  }
  disconnectedCallback() {
    this.unRegisterElementAppenderListener();
    this.destroyElementAppender();
  }
  componentDidLoad() {
    this.initElementAppender();
  }
  getElementAppender() {
    return this.elementAppender;
  }
  show() {
    this.elementAppender && this.elementAppender.show();
    this[this.isDropdownShowName] = true;
    this.setAriaOwns();
  }
  hide() {
    this.elementAppender && this.elementAppender.hide();
    this[this.isDropdownShowName] = false;
    this.hierarchyTreeManager.getChildren().map((child) => {
      child.hide();
    });
  }
  destroy() {
    this.removeAriaOwns();
    this.destroyElementAppender();
    this[this.isDropdownShowName] = false;
  }
  updateShowConfigFactory(showConfigFactory) {
    this.showConfigFactory = showConfigFactory;
    this.initElementAppender();
  }
  destroyElementAppender() {
    if (this.elementAppender) {
      this.elementAppender.destroy();
      this.elementAppender = null;
    }
  }
  initElementAppender() {
    this.setShowConfig();
    this.setElementAppender();
    this.registerElementAppenderListener();
  }
  setElementAppender() {
    this.elementAppender = new ElementAppender(this.showConfigFactory, this);
  }
  isShowing() {
    return this[this.isDropdownShowName];
  }
  setShowConfig() {
    this.showConfig = this.showConfigFactory();
  }
  /**
   * It removes all event listeners that were added in the `register()` function
   */
  unRegisterElementAppenderListener() {
    var _a, _b, _c, _d, _e, _f;
    if (this.showConfig) {
      (_a = this.showConfig.target) === null || _a === void 0 ? void 0 : _a.removeEventListener('click', this.targetClickHandler);
      (_b = this.showConfig.target) === null || _b === void 0 ? void 0 : _b.removeEventListener('mouseenter', this.targetMouseEnterHandler);
      (_c = this.showConfig.target) === null || _c === void 0 ? void 0 : _c.removeEventListener('mouseleave', this.targetMouseLeaveHandler);
      (_d = this.showConfig.target) === null || _d === void 0 ? void 0 : _d.removeEventListener('focusout', this.targetMouseLeaveHandler);
      (_e = this.showConfig.appendableElement) === null || _e === void 0 ? void 0 : _e.removeEventListener('mouseenter', this.elementMouseEnterHandler);
      (_f = this.showConfig.appendableElement) === null || _f === void 0 ? void 0 : _f.removeEventListener('mouseleave', this.elementMouseLeaveHandler);
    }
    window.removeEventListener('mousedown', this.globalMouseDownHandler);
    // eslint-disable-next-line no-restricted-globals
    document.removeEventListener('scroll', this.globalScrollHandler);
    this.removeShadowRootElementScrolling();
  }
  /**
   * Sets up an observer to handle scroll events in a shadow root element.
   */
  listenShadowRootElementScrolling() {
    this.shadowRootElementScrollingObserver = new Observer(this.canAcceptShadowRootScrollEvent.bind(this), this.globalScrollHandler.bind(this));
    ChangeManager.register(SHADOW_ROOT_ELEMENT_SCROLLING, this.shadowRootElementScrollingObserver);
  }
  /**
   * Checks if the host element is a parent of the target element.
   *
   * @param {ShadowRootElementScrollingPayload} payload - payload.
   * @returns {boolean} - Can accept.
   */
  canAcceptShadowRootScrollEvent(payload) {
    return Boolean(this.showConfig && isParent(this.showConfig.target, payload.host));
  }
  /**
   * Remove observer for scrolling in a shadow root element.
   */
  removeShadowRootElementScrolling() {
    ChangeManager.unregister(SHADOW_ROOT_ELEMENT_SCROLLING, this.shadowRootElementScrollingObserver);
  }
  getTriggerStrategy() {
    const trigger = this.getTrigger();
    if (trigger === 'click') {
      return new ClickTriggerStrategy();
    }
    else if (trigger === 'hover') {
      return new HoverTriggerStrategy();
    }
    else if (isEATriggerStrategy(trigger)) {
      return trigger;
    }
    else {
      return new NoneTriggerStrategy();
    }
  }
  /**
   * Sets `ariaOwnsElements` on the target element to reference the appendable element directly.
   * Uses the Element Reflection API which works across shadow DOM boundaries by using
   * direct element references instead of IDREF strings.
   * This ensures screen readers (e.g. VoiceOver) can navigate to the portal-appended
   * content immediately after the trigger, rather than at the end of the document.
   */
  setAriaOwns() {
    if (this.showConfig) {
      const target = this.showConfig.target;
      const appendableElement = this.showConfig.appendableElement;
      if (target && appendableElement) {
        target.ariaOwnsElements = [appendableElement];
      }
    }
  }
  /**
   * Removes `ariaOwnsElements` from the target element when the popup is hidden or destroyed.
   */
  removeAriaOwns() {
    var _a;
    if ((_a = this.showConfig) === null || _a === void 0 ? void 0 : _a.target) {
      this.showConfig.target.ariaOwnsElements = [];
    }
  }
}
ElementAppenderSlimmer.DELAY_HIDE_TIME = 100;
__decorate([
  InjectVegaSlimmer()
], ElementAppenderSlimmer.prototype, "hierarchyTreeManager", void 0);
__decorate([
  MapToComponentMethod('connectedCallback')
], ElementAppenderSlimmer.prototype, "connectedCallback", null);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], ElementAppenderSlimmer.prototype, "disconnectedCallback", null);
__decorate([
  MapToComponentMethod('componentDidLoad')
], ElementAppenderSlimmer.prototype, "componentDidLoad", null);

export { ElementAppenderSlimmer as E };
