"use strict";
const vue = require("vue");
const types = require("./types.js");
const provide = require("./provide.js");
const is = require("../_utils/is.js");
const dom = require("../_utils/dom.js");
const _hoisted_1 = { class: "o-anchor-line" };
const _hoisted_2 = { class: "o-anchor-items" };
const _sfc_main = /* @__PURE__ */ vue.defineComponent({
  __name: "OAnchor",
  props: types.anchorProps,
  emits: ["click", "change"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const ANCHOR_REGX = /#([\S ]+)$/;
    const anchorRef = vue.ref();
    const isScrolling = vue.ref(false);
    const links = vue.ref(/* @__PURE__ */ new Set());
    const activeLink = vue.ref("");
    const indicatorStyle = vue.ref({});
    const scrollContainer = vue.ref();
    const getContainer = (container = window) => {
      if (is.isString(container)) {
        const dom2 = document.querySelector(container);
        return dom2 ? dom2 : window;
      }
      return container;
    };
    const updateIndicatorPosition = () => {
      var _a;
      const el = (_a = anchorRef.value) == null ? void 0 : _a.querySelector(".o-anchor-item-link.is-active");
      if (!el) {
        indicatorStyle.value = {};
      } else {
        const { offsetTop, offsetHeight } = el;
        const depth = el.getAttribute("data-depth");
        indicatorStyle.value.top = `${offsetTop}px`;
        indicatorStyle.value.height = `${offsetHeight}px`;
        indicatorStyle.value.opacity = depth === "0" ? 0 : 1;
      }
    };
    const setActiveLink = async (link) => {
      if (activeLink.value === link) {
        return;
      }
      activeLink.value = link;
      emits("change", activeLink.value);
      await vue.nextTick();
      updateIndicatorPosition();
    };
    const getAnchorTarget = (link) => {
      const anchorMatches = ANCHOR_REGX.exec(link);
      if (!anchorMatches) {
        return;
      }
      const target = document.getElementById(anchorMatches[1]);
      return target;
    };
    const getOffsetTop = (el, container) => {
      const { top } = el.getBoundingClientRect();
      if (is.isWindow(container)) {
        return top - document.documentElement.clientTop;
      }
      return top - container.getBoundingClientRect().top;
    };
    const scrollIntoView = async (link) => {
      if (!is.isCurrentPageLink(link)) {
        return;
      }
      setActiveLink(link);
      const target = getAnchorTarget(link);
      if (!target) {
        return;
      }
      isScrolling.value = true;
      const { scrollTop } = dom.getScroll(scrollContainer.value);
      const offsetTop = getOffsetTop(target, scrollContainer.value);
      const y = scrollTop + offsetTop - props.targetOffset;
      await dom.scrollTo(y, {
        container: scrollContainer.value
      });
      isScrolling.value = false;
    };
    const activeNearest = () => {
      const distances = [];
      const { targetOffset, bounds } = props;
      let active = "";
      links.value.forEach((link) => {
        const target = getAnchorTarget(link);
        if (target) {
          const top = getOffsetTop(target, scrollContainer.value);
          if (top < targetOffset + bounds) {
            distances.push({
              link,
              top
            });
          }
        }
      });
      if (distances.length) {
        const max = distances.reduce((prev, cur) => prev.top > cur.top ? prev : cur);
        active = max.link;
      }
      setActiveLink(active);
    };
    const onScroll = () => {
      if (isScrolling.value) {
        return;
      }
      activeNearest();
    };
    const bindEvent = () => {
      if (is.isUndefined(scrollContainer.value)) {
        return;
      }
      scrollContainer.value.addEventListener("scroll", onScroll, { passive: true });
    };
    const unbindEvent = () => {
      if (is.isUndefined(scrollContainer.value)) {
        return;
      }
      scrollContainer.value.removeEventListener("scroll", onScroll);
    };
    const addLink = (link) => {
      if (!ANCHOR_REGX.test(link) || links.value.has(link)) {
        return;
      }
      links.value.add(link);
    };
    const removeLink = (link) => {
      links.value.add(link);
    };
    const onItemClick = (options) => {
      const { event, link } = options;
      emits("click", event, link);
    };
    vue.provide(provide.anchorInjectKey, {
      addLink,
      removeLink,
      onItemClick,
      activeLink,
      scrollIntoView,
      getChangeHash: () => props.changeHash
    });
    vue.onMounted(() => {
      scrollContainer.value = getContainer(props.container);
      const hash = decodeURIComponent(window.location.hash);
      if (hash) {
        scrollIntoView(hash);
      } else {
        activeNearest();
      }
      vue.nextTick(() => {
        bindEvent();
      });
    });
    vue.onUnmounted(() => {
      unbindEvent();
    });
    return (_ctx, _cache) => {
      return vue.openBlock(), vue.createElementBlock(
        "div",
        {
          ref_key: "anchorRef",
          ref: anchorRef,
          class: vue.normalizeClass(["o-anchor", `o-anchor-${props.size}`])
        },
        [
          vue.createElementVNode("div", _hoisted_1, [
            vue.createElementVNode(
              "div",
              {
                class: "o-anchor-indicator",
                style: vue.normalizeStyle(indicatorStyle.value)
              },
              null,
              4
              /* STYLE */
            )
          ]),
          vue.createElementVNode("div", _hoisted_2, [
            vue.renderSlot(_ctx.$slots, "default")
          ])
        ],
        2
        /* CLASS */
      );
    };
  }
});
module.exports = _sfc_main;
