"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.AnchorProps = void 0;

var _vue = _interopRequireWildcard(require("vue"));

var _vueTypes = _interopRequireDefault(require("../_util/vue-types"));

var _classNames = _interopRequireDefault(require("../_util/classNames"));

var _addEventListener = _interopRequireDefault(require("../vc-util/Dom/addEventListener"));

var _affix = _interopRequireDefault(require("../affix"));

var _scrollTo = _interopRequireDefault(require("../_util/scrollTo"));

var _getScroll = _interopRequireDefault(require("../_util/getScroll"));

var _propsUtil = require("../_util/props-util");

var _BaseMixin = _interopRequireDefault(require("../_util/BaseMixin"));

var _configProvider = require("../config-provider");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getDefaultContainer() {
  return window;
}

function getOffsetTop(element, container) {
  if (!element) {
    return 0;
  }

  if (!element.getClientRects().length) {
    return 0;
  }

  var 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;
} // function easeInOutCubic(t, b, c, d) {
//   const cc = c - b;
//   t /= d / 2;
//   if (t < 1) {
//     return (cc / 2) * t * t * t + b;
//   }
//   return (cc / 2) * ((t -= 2) * t * t + 2) + b;
// }


var sharpMatcherRegx = /#([^#]+)$/; // function scrollTo(href, offsetTop = 0, getContainer, callback = () => {}) {
//   const container = getContainer();
//   const scrollTop = getScroll(container, true);
//   const sharpLinkMatch = sharpMatcherRegx.exec(href);
//   if (!sharpLinkMatch) {
//     return;
//   }
//   const targetElement = document.getElementById(sharpLinkMatch[1]);
//   if (!targetElement) {
//     return;
//   }
//   const eleOffsetTop = getOffsetTop(targetElement, container);
//   const targetScrollTop = scrollTop + eleOffsetTop - offsetTop;
//   const startTime = Date.now();
//   const frameFunc = () => {
//     const timestamp = Date.now();
//     const time = timestamp - startTime;
//     const nextScrollTop = easeInOutCubic(time, scrollTop, targetScrollTop, 450);
//     if (container === window) {
//       window.scrollTo(window.pageXOffset, nextScrollTop);
//     } else {
//       container.scrollTop = nextScrollTop;
//     }
//     if (time < 450) {
//       raf(frameFunc);
//     } else {
//       callback();
//     }
//   };
//   raf(frameFunc);
// }

var AnchorProps = {
  prefixCls: _vueTypes.default.string,
  offsetTop: _vueTypes.default.number,
  bounds: _vueTypes.default.number,
  affix: _vueTypes.default.bool,
  showInkInFixed: _vueTypes.default.bool,
  getContainer: _vueTypes.default.func,
  wrapperClass: _vueTypes.default.string,
  wrapperStyle: _vueTypes.default.object,
  getCurrentAnchor: _vueTypes.default.func,
  targetOffset: _vueTypes.default.number,
  onChange: _vueTypes.default.func,
  onClick: _vueTypes.default.func
};
exports.AnchorProps = AnchorProps;
var _default2 = {
  name: 'AAnchor',
  mixins: [_BaseMixin.default],
  inheritAttrs: false,
  props: (0, _propsUtil.initDefaultProps)(AnchorProps, {
    affix: true,
    showInkInFixed: false,
    getContainer: getDefaultContainer
  }),
  data: function data() {
    this.links = [];
    this._sPrefixCls = '';
    return {
      activeLink: null
    };
  },
  created: function created() {
    var _this = this;

    (0, _vue.provide)('antAnchor', {
      registerLink: function registerLink(link) {
        if (!_this.links.includes(link)) {
          _this.links.push(link);
        }
      },
      unregisterLink: function unregisterLink(link) {
        var index = _this.links.indexOf(link);

        if (index !== -1) {
          _this.links.splice(index, 1);
        }
      },
      $data: this.$data,
      scrollTo: this.handleScrollTo
    });
    (0, _vue.provide)('antAnchorContext', this);
  },
  setup: function setup() {
    return {
      configProvider: (0, _vue.inject)('configProvider', _configProvider.ConfigConsumerProps)
    };
  },
  mounted: function mounted() {
    var _this2 = this;

    this.$nextTick(function () {
      var getContainer = _this2.getContainer;
      _this2.scrollContainer = getContainer();
      _this2.scrollEvent = (0, _addEventListener.default)(_this2.scrollContainer, 'scroll', _this2.handleScroll);

      _this2.handleScroll();
    });
  },
  updated: function updated() {
    var _this3 = this;

    this.$nextTick(function () {
      if (_this3.scrollEvent) {
        var getContainer = _this3.getContainer;
        var currentContainer = getContainer();

        if (_this3.scrollContainer !== currentContainer) {
          _this3.scrollContainer = currentContainer;

          _this3.scrollEvent.remove();

          _this3.scrollEvent = (0, _addEventListener.default)(_this3.scrollContainer, 'scroll', _this3.handleScroll);

          _this3.handleScroll();
        }
      }

      _this3.updateInk();
    });
  },
  beforeUnmount: function beforeUnmount() {
    if (this.scrollEvent) {
      this.scrollEvent.remove();
    }
  },
  methods: {
    getCurrentActiveLink: function getCurrentActiveLink() {
      var offsetTop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
      var bounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5;
      var getCurrentAnchor = this.getCurrentAnchor;

      if (typeof getCurrentAnchor === 'function') {
        return getCurrentAnchor();
      }

      var activeLink = '';

      if (typeof document === 'undefined') {
        return activeLink;
      }

      var linkSections = [];
      var getContainer = this.getContainer;
      var container = getContainer();
      this.links.forEach(function (link) {
        var sharpLinkMatch = sharpMatcherRegx.exec(link.toString());

        if (!sharpLinkMatch) {
          return;
        }

        var target = document.getElementById(sharpLinkMatch[1]);

        if (target) {
          var top = getOffsetTop(target, container);

          if (top < offsetTop + bounds) {
            linkSections.push({
              link: link,
              top: top
            });
          }
        }
      });

      if (linkSections.length) {
        var maxSection = linkSections.reduce(function (prev, curr) {
          return curr.top > prev.top ? curr : prev;
        });
        return maxSection.link;
      }

      return '';
    },
    handleScrollTo: function handleScrollTo(link) {
      var _this4 = this;

      var offsetTop = this.offsetTop,
          getContainer = this.getContainer,
          targetOffset = this.targetOffset;
      this.setCurrentActiveLink(link);
      var container = getContainer();
      var scrollTop = (0, _getScroll.default)(container, true);
      var sharpLinkMatch = sharpMatcherRegx.exec(link);

      if (!sharpLinkMatch) {
        return;
      }

      var targetElement = document.getElementById(sharpLinkMatch[1]);

      if (!targetElement) {
        return;
      }

      var eleOffsetTop = getOffsetTop(targetElement, container);
      var y = scrollTop + eleOffsetTop;
      y -= targetOffset !== undefined ? targetOffset : offsetTop || 0;
      this.animating = true;
      (0, _scrollTo.default)(y, {
        callback: function callback() {
          _this4.animating = false;
        },
        getContainer: getContainer
      });
    },
    setCurrentActiveLink: function setCurrentActiveLink(link) {
      var activeLink = this.activeLink;

      if (activeLink !== link) {
        this.setState({
          activeLink: link
        });
        this.$emit('change', link);
      }
    },
    handleScroll: function handleScroll() {
      if (this.animating) {
        return;
      }

      var offsetTop = this.offsetTop,
          bounds = this.bounds,
          targetOffset = this.targetOffset;
      var currentActiveLink = this.getCurrentActiveLink(targetOffset !== undefined ? targetOffset : offsetTop || 0, bounds);
      this.setCurrentActiveLink(currentActiveLink);
    },
    updateInk: function updateInk() {
      if (typeof document === 'undefined') {
        return;
      }

      var _sPrefixCls = this._sPrefixCls;
      var linkNode = (0, _propsUtil.findDOMNode)(this).getElementsByClassName("".concat(_sPrefixCls, "-link-title-active"))[0];

      if (linkNode) {
        this.$refs.inkNode.style.top = "".concat(linkNode.offsetTop + linkNode.clientHeight / 2 - 4.5, "px");
      }
    }
  },
  render: function render() {
    var customizePrefixCls = this.prefixCls,
        offsetTop = this.offsetTop,
        affix = this.affix,
        showInkInFixed = this.showInkInFixed,
        activeLink = this.activeLink,
        $slots = this.$slots,
        getContainer = this.getContainer;
    var getPrefixCls = this.configProvider.getPrefixCls;
    var prefixCls = getPrefixCls('anchor', customizePrefixCls);
    this._sPrefixCls = prefixCls;
    var inkClass = (0, _classNames.default)("".concat(prefixCls, "-ink-ball"), {
      visible: activeLink
    });
    var wrapperClass = (0, _classNames.default)(this.wrapperClass, "".concat(prefixCls, "-wrapper"));
    var anchorClass = (0, _classNames.default)(prefixCls, {
      fixed: !affix && !showInkInFixed
    });

    var wrapperStyle = _objectSpread({
      maxHeight: offsetTop ? "calc(100vh - ".concat(offsetTop, "px)") : '100vh'
    }, this.wrapperStyle);

    var anchorContent = _vue.createVNode("div", {
      "class": wrapperClass,
      "style": wrapperStyle
    }, [_vue.createVNode("div", {
      "class": anchorClass
    }, [_vue.createVNode("div", {
      "class": "".concat(prefixCls, "-ink")
    }, [_vue.createVNode("span", {
      "class": inkClass,
      "ref": "inkNode"
    }, null)]), $slots.default && $slots.default()])]);

    return !affix ? anchorContent : _vue.createVNode(_affix.default, _vue.mergeProps(this.$attrs, {
      "offsetTop": offsetTop,
      "target": getContainer
    }), {
      default: function _default() {
        return [anchorContent];
      }
    });
  }
};
exports.default = _default2;