function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import throttle from 'lodash.throttle';
import React from 'react';
export var AnchorNavigationContext = /*#__PURE__*/React.createContext({
  offset: 0,
  sections: [],
  active: '',
  registerSection: function registerSection() {},
  unregisterSection: function unregisterSection() {},
  setActive: function setActive() {}
});
export var useAnchorNavigationContext = function useAnchorNavigationContext() {
  return React.useContext(AnchorNavigationContext);
};
function findScrollContainer(element) {
  var parent = element.parentElement;
  while (parent) {
    var _window$getComputedSt = window.getComputedStyle(parent),
      overflow = _window$getComputedSt.overflow;
    if (overflow.split(' ').every(function (o) {
      return o === 'auto' || o === 'scroll';
    })) {
      return parent;
    }
    parent = parent.parentElement;
  }
  return document.documentElement;
}
function getElementScrollPosition(element, scroller) {
  var y = 0;
  var el = element;
  do {
    y += el.offsetTop;
    el = el.offsetParent;
  } while (el && el !== scroller);
  return y;
}
export function AnchorNavigationProvider(_ref) {
  var children = _ref.children,
    _ref$offset = _ref.offset,
    offset = _ref$offset === void 0 ? 0 : _ref$offset;
  var _React$useState = React.useState(''),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    active = _React$useState2[0],
    setActive = _React$useState2[1];
  var ref = React.useRef({
    sections: [],
    blockScrollTimestamp: 0,
    scroller: null
  });
  var changeActive = function changeActive(id) {
    var _sections$find;
    var _ref$current = ref.current,
      sections = _ref$current.sections,
      scroller = _ref$current.scroller;
    setActive(id);
    var element = (_sections$find = sections.find(function (section) {
      return section.id === id;
    })) === null || _sections$find === void 0 ? void 0 : _sections$find.element;
    if (element) {
      ;
      (scroller || window).scrollTo({
        top: getElementScrollPosition(element, scroller) - offset,
        behavior: 'smooth'
      });

      // Disable scroll listener to avoid changing active element
      ref.current.blockScrollTimestamp = new Date().getTime();
    }
  };
  React.useEffect(function () {
    var onScroll = function onScroll(event) {
      var _ref$current2 = ref.current,
        blockScrollTimestamp = _ref$current2.blockScrollTimestamp,
        sections = _ref$current2.sections,
        scroller = _ref$current2.scroller;
      var now = new Date().getTime();
      if (!sections.length) return;

      // Disable scroll event when auto scrolling by clicking on the anchor
      if (now - blockScrollTimestamp < 200) {
        ref.current.blockScrollTimestamp = now;
        return;
      }
      var y = (scroller ? scroller.scrollTop : window.scrollY || document.documentElement.scrollTop) + offset;

      // Before the first element
      if (getElementScrollPosition(sections[0].element, scroller) > y) {
        if (event) {
          var _sections$;
          setActive((_sections$ = sections[0]) === null || _sections$ === void 0 ? void 0 : _sections$.id);
        }
        return;
      }

      // Get first element overflowing top, get the previous one
      var selectedIndex = sections.findIndex(function (item) {
        return getElementScrollPosition(item.element, scroller) > y;
      });
      var selectedElement = selectedIndex === -1 ? sections[sections.length - 1] : sections[Math.max(selectedIndex - 1, 0)];
      if (selectedElement) {
        setActive(selectedElement.id);
      }
    };
    var throttleScrollEvent = throttle(onScroll, 100);
    addEventListener('scroll', throttleScrollEvent, {
      capture: false,
      passive: true
    });
    onScroll();
    return function () {
      removeEventListener('scroll', throttleScrollEvent, {
        capture: false
      });
      throttleScrollEvent.cancel();
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  var registerSection = function registerSection(id, label, element) {
    if (!ref.current.scroller) {
      ref.current.scroller = findScrollContainer(element);
    }
    var _ref$current3 = ref.current,
      sections = _ref$current3.sections,
      scroller = _ref$current3.scroller;
    if (sections.find(function (section) {
      return section.id === id;
    })) {
      return;
    }
    var y = getElementScrollPosition(element, scroller);
    var index = sections.findIndex(function (section) {
      return getElementScrollPosition(section.element, scroller) > y;
    });
    if (index === -1) {
      sections.push({
        id: id,
        label: label,
        element: element
      });
    } else {
      sections.splice(index, 0, {
        id: id,
        label: label,
        element: element
      });
    }
    if (sections.length === 1) {
      setActive(id);
    }
  };
  var unregisterSection = function unregisterSection(id) {
    var sections = ref.current.sections;
    var index = sections.findIndex(function (section) {
      return section.id === id;
    });
    if (index !== -1) {
      sections.splice(index, 1);
    }
  };
  return /*#__PURE__*/React.createElement(AnchorNavigationContext.Provider, {
    value: {
      offset: offset,
      active: active,
      sections: ref.current.sections,
      setActive: changeActive,
      registerSection: registerSection,
      unregisterSection: unregisterSection
    }
  }, children);
}
//# sourceMappingURL=AnchorNavigationProvider.js.map