'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
require('../../../../hooks/index.cjs');
var util = require('../util.cjs');
var index = require('../../../../hooks/use-state/index.cjs');

function useTarget(target, open, gap, scrollIntoViewOptions) {
  const [targetElement, setTargetElement] = index.useState(void 0);
  vue.watchEffect(
    () => {
      const nextElement = typeof target.value === "function" ? target.value() : target.value;
      setTargetElement(nextElement || null);
    },
    { flush: "post" }
  );
  const [posInfo, setPosInfo] = index.useState(null);
  const updatePos = () => {
    if (!open.value) {
      setPosInfo(null);
      return;
    }
    if (targetElement.value) {
      if (!util.isInViewPort(targetElement.value) && open.value)
        targetElement.value.scrollIntoView(scrollIntoViewOptions.value);
      const { left, top, width, height } = targetElement.value.getBoundingClientRect();
      const nextPosInfo = { left, top, width, height, radius: 0 };
      if (JSON.stringify(posInfo.value) !== JSON.stringify(nextPosInfo))
        setPosInfo(nextPosInfo);
    } else {
      setPosInfo(null);
    }
  };
  vue.onMounted(() => {
    vue.watch(
      [open, targetElement],
      () => {
        updatePos();
      },
      { flush: "post", immediate: true }
    );
    window.addEventListener("resize", updatePos);
  });
  vue.onBeforeUnmount(() => {
    window.removeEventListener("resize", updatePos);
  });
  const mergedPosInfo = vue.computed(() => {
    var _a, _b;
    if (!posInfo.value)
      return posInfo.value;
    const gapOffset = ((_a = gap.value) == null ? void 0 : _a.offset) || 6;
    const gapRadius = ((_b = gap.value) == null ? void 0 : _b.radius) || 2;
    return {
      left: posInfo.value.left - gapOffset,
      top: posInfo.value.top - gapOffset,
      width: posInfo.value.width + gapOffset * 2,
      height: posInfo.value.height + gapOffset * 2,
      radius: gapRadius
    };
  });
  return [mergedPosInfo, targetElement];
}

exports.default = useTarget;
//# sourceMappingURL=useTarget.cjs.map
