'use strict';

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

var vue = require('vue');
var scrollIntoView = require('scroll-into-view-if-needed');
require('../../../utils/index.cjs');
var index$1 = require('../../affix/index.cjs');
var useConfigInject = require('../../config-provider/src/hooks/useConfigInject.cjs');
var index = require('../style/index.cjs');
var AnchorLink = require('./AnchorLink.cjs');
var context = require('./context.cjs');
var props = require('./props.cjs');
var log = require('../../../utils/log.cjs');
var getScroll = require('../../../utils/scroll/getScroll.cjs');
var scrollTo = require('../../../utils/scroll/scrollTo.cjs');
var addEventListener = require('../../../utils/event/addEventListener.cjs');
var _class = require('../../../utils/dom/class.cjs');

function getDefaultContainer() {
  return window;
}
function getOffsetTop(element, container) {
  if (!element.getClientRects().length)
    return 0;
  const rect = element.getBoundingClientRect();
  if (rect.width || rect.height) {
    if (container === window) {
      container = element.ownerDocument.documentElement;
      return rect.top - container.clientTop;
    }
    return rect.top - container.getBoundingClientRect().top;
  }
  return rect.top;
}
const sharpMatcherRegx = /#([\S ]+)$/;
var AAnchor = /* @__PURE__ */ vue.defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "AAnchor",
  inheritAttrs: false,
  props: props.anchorProps(),
  setup(props, {
    emit,
    attrs,
    slots,
    expose
  }) {
    var _a;
    const {
      prefixCls,
      getTargetContainer,
      direction
    } = useConfigInject.default("anchor", props);
    const anchorDirection = vue.computed(() => {
      var _a2;
      return (_a2 = props.direction) != null ? _a2 : "vertical";
    });
    if (process.env.NODE_ENV !== "production") {
      log.devWarning(props.items && typeof slots.default !== "function", "Anchor", "`Anchor children` is deprecated. Please use `items` instead.");
    }
    if (process.env.NODE_ENV !== "production") {
      log.devWarning(!(anchorDirection.value === "horizontal" && ((_a = props.items) == null ? void 0 : _a.some((n) => "children" in n))), "Anchor", "`Anchor items#children` is not supported when `Anchor` direction is horizontal.");
    }
    const spanLinkNode = vue.ref(null);
    const anchorRef = vue.ref();
    const state = vue.reactive({
      links: [],
      scrollContainer: null,
      scrollEvent: null,
      animating: false
    });
    const activeLink = vue.ref(null);
    const getContainer = vue.computed(() => {
      return props.getContainer || (getTargetContainer == null ? void 0 : getTargetContainer.value) || getDefaultContainer;
    });
    const getCurrentAnchor = (offsetTop = 0, bounds = 5) => {
      const linkSections = [];
      const container = getContainer.value();
      state.links.forEach((link) => {
        const sharpLinkMatch = sharpMatcherRegx.exec(link.toString());
        if (!sharpLinkMatch)
          return;
        const target = document.getElementById(sharpLinkMatch[1]);
        if (target) {
          const top = getOffsetTop(target, container);
          if (top < offsetTop + bounds) {
            linkSections.push({
              link,
              top
            });
          }
        }
      });
      if (linkSections.length) {
        const maxSection = linkSections.reduce((prev, curr) => curr.top > prev.top ? curr : prev);
        return maxSection.link;
      }
      return "";
    };
    const setCurrentActiveLink = (link) => {
      if (activeLink.value === link)
        return;
      activeLink.value = typeof props.getCurrentAnchor === "function" ? props.getCurrentAnchor(link) : link;
      emit("change", link);
    };
    const handleScrollTo = (link) => {
      const {
        offsetTop,
        targetOffset
      } = props;
      setCurrentActiveLink(link);
      const sharpLinkMatch = sharpMatcherRegx.exec(link);
      if (!sharpLinkMatch)
        return;
      const targetElement = document.getElementById(sharpLinkMatch[1]);
      if (!targetElement)
        return;
      const container = getContainer.value();
      const scrollTop = getScroll.getScroll(container, true);
      const eleOffsetTop = getOffsetTop(targetElement, container);
      let y = scrollTop + eleOffsetTop;
      y -= targetOffset !== void 0 ? targetOffset : offsetTop || 0;
      state.animating = true;
      scrollTo.scrollTo(y, {
        callback: () => {
          state.animating = false;
        },
        getContainer: getContainer.value
      });
    };
    expose({
      scrollTo: handleScrollTo
    });
    const handleScroll = () => {
      if (state.animating)
        return;
      const {
        offsetTop,
        bounds,
        targetOffset
      } = props;
      const currentActiveLink = getCurrentAnchor(targetOffset !== void 0 ? targetOffset : offsetTop || 0, bounds);
      setCurrentActiveLink(currentActiveLink);
    };
    const updateInk = () => {
      const linkNode = anchorRef.value.querySelector(`.${prefixCls.value}-link-title-active`);
      if (linkNode && spanLinkNode.value) {
        const horizontalAnchor = anchorDirection.value === "horizontal";
        spanLinkNode.value.style.top = horizontalAnchor ? "" : `${linkNode.offsetTop + linkNode.clientHeight / 2}px`;
        spanLinkNode.value.style.height = horizontalAnchor ? "" : `${linkNode.clientHeight}px`;
        spanLinkNode.value.style.left = horizontalAnchor ? `${linkNode.offsetLeft}px` : "";
        spanLinkNode.value.style.width = horizontalAnchor ? `${linkNode.clientWidth}px` : "";
        if (horizontalAnchor) {
          scrollIntoView(linkNode, {
            scrollMode: "if-needed",
            block: "nearest"
          });
        }
      }
    };
    context.useProvideAnchor({
      registerLink: (link) => {
        if (!state.links.includes(link))
          state.links.push(link);
      },
      unregisterLink: (link) => {
        const index = state.links.indexOf(link);
        if (index !== -1)
          state.links.splice(index, 1);
      },
      activeLink,
      scrollTo: handleScrollTo,
      handleClick: (e, info) => {
        emit("click", e, info);
      },
      direction: anchorDirection
    });
    vue.onMounted(() => {
      vue.nextTick(() => {
        const container = getContainer.value();
        state.scrollContainer = container;
        state.scrollEvent = addEventListener.addEventListenerWrap(state.scrollContainer, "scroll", handleScroll);
        handleScroll();
      });
    });
    vue.onBeforeUnmount(() => {
      if (state.scrollEvent)
        state.scrollEvent.remove();
    });
    vue.onUpdated(() => {
      if (state.scrollEvent) {
        const currentContainer = getContainer.value();
        if (state.scrollContainer !== currentContainer) {
          state.scrollContainer = currentContainer;
          state.scrollEvent.remove();
          state.scrollEvent = addEventListener.addEventListenerWrap(state.scrollContainer, "scroll", handleScroll);
          handleScroll();
        }
      }
      updateInk();
    });
    const createNestedLink = (options) => Array.isArray(options) ? options.map((option) => {
      const {
        children,
        key,
        href,
        target,
        class: cls,
        style,
        title
      } = option;
      return vue.createVNode(AnchorLink.default, {
        "key": key,
        "href": href,
        "target": target,
        "class": cls,
        "style": style,
        "title": title,
        "customTitleProps": option
      }, {
        default: () => [anchorDirection.value === "vertical" ? createNestedLink(children) : null],
        customTitle: slots.customTitle
      });
    }) : null;
    const [wrapSSR, hashId] = index.default(prefixCls);
    return () => {
      var _a2;
      const {
        offsetTop,
        affix,
        showInkInFixed
      } = props;
      const pre = prefixCls.value;
      const inkClass = _class.classNames(`${pre}-ink`, {
        [`${pre}-ink-visible`]: activeLink.value
      });
      const wrapperClass = _class.classNames(hashId.value, props.wrapperClass, `${pre}-wrapper`, {
        [`${pre}-wrapper-horizontal`]: anchorDirection.value === "horizontal",
        [`${pre}-rtl`]: direction.value === "rtl"
      });
      const anchorClass = _class.classNames(pre, {
        [`${pre}-fixed`]: !affix && !showInkInFixed
      });
      const wrapperStyle = {
        maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : "100vh",
        ...props.wrapperStyle
      };
      const anchorContent = vue.createVNode("div", {
        "class": wrapperClass,
        "style": wrapperStyle,
        "ref": anchorRef
      }, [vue.createVNode("div", {
        "class": anchorClass
      }, [vue.createVNode("span", {
        "class": inkClass,
        "ref": spanLinkNode
      }, null), Array.isArray(props.items) ? createNestedLink(props.items) : (_a2 = slots.default) == null ? void 0 : _a2.call(slots)])]);
      return wrapSSR(!affix ? anchorContent : vue.createVNode(index$1.Affix, {
        ...attrs,
        "offsetTop": offsetTop,
        "target": getContainer.value
      }, {
        default: () => [anchorContent]
      }));
    };
  }
});

exports.default = AAnchor;
//# sourceMappingURL=Anchor.cjs.map
