/**
 * ldesign v0.4.2
 * (c) 2023 ldesign
 * @license MIT
 */

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import { defineComponent, ref, reactive, onMounted, nextTick, onUnmounted, watchEffect, provide, createVNode, mergeProps, isVNode } from 'vue';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { off, isServer, getScrollContainer, on, getScroll, scrollTo } from '../utils/dom.js';
import { useTNodeJSX } from '../hooks/tnode.js';
import { Affix } from '../affix/index.js';
import { usePrefixClass, useCommonClassName } from '../hooks/useConfig.js';
import { getOffsetTop, ANCHOR_SHARP_REGEXP } from './utils.js';
import props from './props.js';
import { AnchorInjectionKey } from './constants.js';
import '../_chunks/dep-c9c789a8.js';
import 'lodash/isString';
import 'lodash/isFunction';
import 'lodash/isArray';
import '../utils/easing.js';
import 'lodash/camelCase';
import 'lodash/kebabCase';
import '../utils/render-tnode.js';
import 'lodash/isEmpty';
import 'lodash/isObject';
import '../utils/withInstall.js';
import '../affix/affix.js';
import 'lodash/isUndefined';
import '../affix/props.js';
import '../config-provider/useConfig.js';
import 'lodash/cloneDeep';
import '../config-provider/context.js';
import 'lodash/mergeWith';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '@babel/runtime/helpers/typeof';
import 'dayjs';

function _isSlot(s) {
  return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !isVNode(s);
}
var _Anchor = defineComponent({
  name: "TAnchor",
  inheritAttrs: false,
  props: props,
  setup: function setup(props2, _ref) {
    var attrs = _ref.attrs;
    var anchorRef = ref(null);
    var links = ref([]);
    var active = ref("");
    var scrollContainer = ref(null);
    var handleScrollLock = ref(false);
    var activeLineStyle = reactive({});
    var COMPONENT_NAME = usePrefixClass("anchor");
    var ANCHOR_LINE_CLASSNAME = usePrefixClass("anchor__line");
    var ANCHOR_LINE_CURSOR_CLASSNAME = usePrefixClass("anchor__line-cursor");
    var _useCommonClassName = useCommonClassName(),
      STATUS = _useCommonClassName.STATUS,
      SIZE = _useCommonClassName.SIZE;
    var renderTNodeJSX = useTNodeJSX();
    var getScrollContainer$1 = function getScrollContainer$1() {
      if (isServer) return;
      var container = props2.container;
      scrollContainer.value = getScrollContainer(container);
      on(scrollContainer.value, "scroll", handleScroll);
      handleScroll();
    };
    var handleScroll = function handleScroll() {
      if (handleScrollLock.value) return;
      var bounds = props2.bounds,
        targetOffset = props2.targetOffset;
      var filters = [];
      var active2 = "";
      links.value.forEach(function (link) {
        var anchor = getAnchorTarget(link);
        if (!anchor) return;
        var top = getOffsetTop(anchor, scrollContainer.value);
        if (top < bounds + targetOffset) {
          filters.push({
            link: link,
            top: top
          });
        }
      });
      if (filters.length) {
        var latest = filters.reduce(function (prev, cur) {
          return prev.top > cur.top ? prev : cur;
        });
        active2 = latest.link;
      }
      setCurrentActiveLink(active2);
    };
    var getAnchorTarget = function getAnchorTarget(link) {
      var matcher = link.match(ANCHOR_SHARP_REGEXP);
      if (!matcher) return;
      var anchor = document.getElementById(matcher[1]);
      if (!anchor) return;
      return anchor;
    };
    var registerLink = function registerLink(link) {
      if (!ANCHOR_SHARP_REGEXP.test(link) || links.value.includes(link)) return;
      links.value.push(link);
    };
    var unregisterLink = function unregisterLink(link) {
      links.value = links.value.filter(function (each) {
        return each !== link;
      });
    };
    var setCurrentActiveLink = /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(link) {
        var _props2$onChange;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!(active.value === link)) {
                _context.next = 2;
                break;
              }
              return _context.abrupt("return");
            case 2:
              active.value = link;
              (_props2$onChange = props2.onChange) === null || _props2$onChange === void 0 ? void 0 : _props2$onChange.call(props2, link, active.value);
              _context.next = 6;
              return nextTick();
            case 6:
              updateActiveLine();
            case 7:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function setCurrentActiveLink(_x) {
        return _ref2.apply(this, arguments);
      };
    }();
    var updateActiveLine = function updateActiveLine() {
      var _anchorRef$value;
      var ele = (_anchorRef$value = anchorRef.value) === null || _anchorRef$value === void 0 ? void 0 : _anchorRef$value.querySelector(".".concat(STATUS.value.active, ">a"));
      if (!ele) {
        Object.assign(activeLineStyle, {});
        return;
      }
      var top = ele.offsetTop,
        height = ele.offsetHeight;
      Object.assign(activeLineStyle, {
        top: "".concat(top, "px"),
        height: "".concat(height, "px"),
        opacity: 1
      });
    };
    var handleLinkClick = function handleLinkClick(link) {
      var _props2$onClick;
      (_props2$onClick = props2.onClick) === null || _props2$onClick === void 0 ? void 0 : _props2$onClick.call(props2, link);
    };
    var handleScrollTo = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(link) {
        var anchor, targetOffset, scrollTop, offsetTop, top;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              anchor = getAnchorTarget(link);
              setCurrentActiveLink(link);
              if (anchor) {
                _context2.next = 4;
                break;
              }
              return _context2.abrupt("return");
            case 4:
              handleScrollLock.value = true;
              targetOffset = props2.targetOffset;
              scrollTop = getScroll(scrollContainer.value);
              offsetTop = getOffsetTop(anchor, scrollContainer.value);
              top = scrollTop + offsetTop - targetOffset;
              _context2.next = 11;
              return scrollTo(top, {
                container: scrollContainer.value
              });
            case 11:
              handleScrollLock.value = false;
            case 12:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function handleScrollTo(_x2) {
        return _ref3.apply(this, arguments);
      };
    }();
    var renderCursor = function renderCursor() {
      var titleContent = renderTNodeJSX("cursor");
      return titleContent || createVNode("div", {
        "class": ANCHOR_LINE_CURSOR_CLASSNAME.value
      }, null);
    };
    onMounted( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            getScrollContainer$1();
            if (!active.value) {
              _context3.next = 5;
              break;
            }
            _context3.next = 4;
            return nextTick();
          case 4:
            handleScrollTo(active.value);
          case 5:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    onUnmounted(function () {
      if (!scrollContainer.value) return;
      off(scrollContainer.value, "scroll", handleScroll);
    });
    watchEffect(function () {
      if (scrollContainer.value) off(scrollContainer.value, "scroll", handleScroll);
      getScrollContainer$1();
    });
    provide(AnchorInjectionKey, reactive({
      registerLink: registerLink,
      unregisterLink: unregisterLink,
      handleScrollTo: handleScrollTo,
      handleLinkClick: handleLinkClick,
      active: active
    }));
    return function () {
      var size = props2.size,
        affixProps = props2.affixProps;
      var className = [COMPONENT_NAME.value, SIZE.value[size]];
      var content = createVNode("div", mergeProps({
        "ref": anchorRef,
        "class": className
      }, attrs), [createVNode("div", {
        "class": ANCHOR_LINE_CLASSNAME.value
      }, [createVNode("div", {
        "class": "".concat(ANCHOR_LINE_CURSOR_CLASSNAME.value, "-wrapper"),
        "style": activeLineStyle
      }, [renderCursor()])]), renderTNodeJSX("default")]);
      if (affixProps) return createVNode(Affix, affixProps, _isSlot(content) ? content : {
        "default": function _default() {
          return [content];
        }
      });
      return content;
    };
  }
});

export { _Anchor as default };
//# sourceMappingURL=anchor.js.map
