import '../../../utils/index.mjs';
import { addEventListenerWrap } from '../../../utils/event/addEventListener.mjs';
import { supportsPassive } from '../../../utils/event/supportsPassive.mjs';

function getTargetRect(target) {
  return target !== window ? target.getBoundingClientRect() : { top: 0, bottom: window.innerHeight };
}
function getFixedTop(placeholderRect, targetRect, offsetTop) {
  if (offsetTop !== void 0 && targetRect.top > placeholderRect.top - offsetTop)
    return `${offsetTop + targetRect.top}px`;
  return void 0;
}
function getFixedBottom(placeholderRect, targetRect, offsetBottom) {
  if (offsetBottom !== void 0 && targetRect.bottom < placeholderRect.bottom + offsetBottom) {
    const targetBottomOffset = window.innerHeight - targetRect.bottom;
    return `${offsetBottom + targetBottomOffset}px`;
  }
  return void 0;
}
const TRIGGER_EVENTS = [
  "resize",
  "scroll",
  "touchstart",
  "touchmove",
  "touchend",
  "pageshow",
  "load"
];
let observerEntities = [];
function getObserverEntities() {
  return observerEntities;
}
function addObserveTarget(target, affix) {
  if (!target)
    return;
  let entity = observerEntities.find((item) => item.target === target);
  if (entity) {
    entity.affixList.push(affix);
  } else {
    entity = {
      target,
      affixList: [affix],
      eventHandlers: {}
    };
    observerEntities.push(entity);
    TRIGGER_EVENTS.forEach((eventName) => {
      entity.eventHandlers[eventName] = addEventListenerWrap(target, eventName, () => {
        entity.affixList.forEach(
          (targetAffix) => {
            const { lazyUpdatePosition } = targetAffix.exposed;
            lazyUpdatePosition();
          },
          (eventName === "touchstart" || eventName === "touchmove") && supportsPassive ? { passive: true } : false
        );
      });
    });
  }
}
function removeObserveTarget(affix) {
  const observerEntity = observerEntities.find((oriObserverEntity) => {
    const hasAffix = oriObserverEntity.affixList.includes(affix);
    if (hasAffix)
      oriObserverEntity.affixList = oriObserverEntity.affixList.filter((item) => item !== affix);
    return hasAffix;
  });
  if (observerEntity && observerEntity.affixList.length === 0) {
    observerEntities = observerEntities.filter((item) => item !== observerEntity);
    TRIGGER_EVENTS.forEach((eventName) => {
      const handler = observerEntity.eventHandlers[eventName];
      if (handler && handler.remove)
        handler.remove();
    });
  }
}

export { addObserveTarget, getFixedBottom, getFixedTop, getObserverEntities, getTargetRect, removeObserveTarget };
//# sourceMappingURL=utils.mjs.map
