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

'use strict';

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

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var vue = require('vue');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var utils_dom = require('../utils/dom.js');
var hooks_tnode = require('../hooks/tnode.js');
var affix_index = require('../affix/index.js');
var hooks_useConfig = require('../hooks/useConfig.js');
var anchor_utils = require('./utils.js');
var anchor_props = require('./props.js');
var anchor_constants = require('./constants.js');
require('../_chunks/dep-7f0559c3.js');
require('lodash/isString');
require('lodash/isFunction');
require('lodash/isArray');
require('../utils/easing.js');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../utils/render-tnode.js');
require('lodash/isEmpty');
require('lodash/isObject');
require('../utils/withInstall.js');
require('../affix/affix.js');
require('lodash/isUndefined');
require('../affix/props.js');
require('../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('@babel/runtime/helpers/typeof');
require('dayjs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);

function _isSlot(s) {
  return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !vue.isVNode(s);
}
var _Anchor = vue.defineComponent({
  name: "TAnchor",
  inheritAttrs: false,
  props: anchor_props["default"],
  setup: function setup(props2, _ref) {
    var attrs = _ref.attrs;
    var anchorRef = vue.ref(null);
    var links = vue.ref([]);
    var active = vue.ref("");
    var scrollContainer = vue.ref(null);
    var handleScrollLock = vue.ref(false);
    var activeLineStyle = vue.reactive({});
    var COMPONENT_NAME = hooks_useConfig.usePrefixClass("anchor");
    var ANCHOR_LINE_CLASSNAME = hooks_useConfig.usePrefixClass("anchor__line");
    var ANCHOR_LINE_CURSOR_CLASSNAME = hooks_useConfig.usePrefixClass("anchor__line-cursor");
    var _useCommonClassName = hooks_useConfig.useCommonClassName(),
      STATUS = _useCommonClassName.STATUS,
      SIZE = _useCommonClassName.SIZE;
    var renderTNodeJSX = hooks_tnode.useTNodeJSX();
    var getScrollContainer = function getScrollContainer() {
      if (utils_dom.isServer) return;
      var container = props2.container;
      scrollContainer.value = utils_dom.getScrollContainer(container);
      utils_dom.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 = anchor_utils.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_utils.ANCHOR_SHARP_REGEXP);
      if (!matcher) return;
      var anchor = document.getElementById(matcher[1]);
      if (!anchor) return;
      return anchor;
    };
    var registerLink = function registerLink(link) {
      if (!anchor_utils.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__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(link) {
        var _props2$onChange;
        return _regeneratorRuntime__default["default"].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 vue.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__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(link) {
        var anchor, targetOffset, scrollTop, offsetTop, top;
        return _regeneratorRuntime__default["default"].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 = utils_dom.getScroll(scrollContainer.value);
              offsetTop = anchor_utils.getOffsetTop(anchor, scrollContainer.value);
              top = scrollTop + offsetTop - targetOffset;
              _context2.next = 11;
              return utils_dom.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 || vue.createVNode("div", {
        "class": ANCHOR_LINE_CURSOR_CLASSNAME.value
      }, null);
    };
    vue.onMounted( /*#__PURE__*/_asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3() {
      return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            getScrollContainer();
            if (!active.value) {
              _context3.next = 5;
              break;
            }
            _context3.next = 4;
            return vue.nextTick();
          case 4:
            handleScrollTo(active.value);
          case 5:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    vue.onUnmounted(function () {
      if (!scrollContainer.value) return;
      utils_dom.off(scrollContainer.value, "scroll", handleScroll);
    });
    vue.watchEffect(function () {
      if (scrollContainer.value) utils_dom.off(scrollContainer.value, "scroll", handleScroll);
      getScrollContainer();
    });
    vue.provide(anchor_constants.AnchorInjectionKey, vue.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 = vue.createVNode("div", vue.mergeProps({
        "ref": anchorRef,
        "class": className
      }, attrs), [vue.createVNode("div", {
        "class": ANCHOR_LINE_CLASSNAME.value
      }, [vue.createVNode("div", {
        "class": "".concat(ANCHOR_LINE_CURSOR_CLASSNAME.value, "-wrapper"),
        "style": activeLineStyle
      }, [renderCursor()])]), renderTNodeJSX("default")]);
      if (affixProps) return vue.createVNode(affix_index.Affix, affixProps, _isSlot(content) ? content : {
        "default": function _default() {
          return [content];
        }
      });
      return content;
    };
  }
});

exports["default"] = _Anchor;
//# sourceMappingURL=anchor.js.map
