var _excluded = ["anchors", "onTouchAnchor", "scrollerDOM", "children"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { Fragment, forwardRef, useRef, useImperativeHandle, useEffect, useState } from 'react';
import getAnchorsByScroller from "./getAnchorsByScroller";
import getAnchorByPoint from "./getAnchorByPoint";
import getAnchorByViewport from "./getAnchorByViewport";
import activeButton from "./activeButton";
import scrollToAnchor from "./scrollToAnchor";

// 内库使用-start
import DOMUtil from "./../../../utils/DOMUtil";
// 内库使用-end

/* 测试使用-start
import { DOMUtil } from 'seedsui-react'
测试使用-end */

var IndexBar = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var externalAnchors = _ref.anchors,
    onTouchAnchor = _ref.onTouchAnchor,
    scrollerDOM = _ref.scrollerDOM,
    children = _ref.children,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    anchors = _useState2[0],
    setAnchors = _useState2[1];

  // Nodes
  var scrollerRef = useRef(null);
  var sidebarRef = useRef(null);
  var tooltipRef = useRef(null);

  // Touches
  var touchesRef = useRef({
    startX: 0
  });
  useImperativeHandle(ref, function () {
    return {
      rootDOM: sidebarRef.current,
      tooltipDOM: tooltipRef.current,
      getRootDOM: function getRootDOM() {
        return sidebarRef.current;
      },
      getTooltipDOM: function getTooltipDOM() {
        return sidebarRef.current;
      },
      activeAnchor: function activeAnchor(currentAnchor) {
        activeButton({
          anchor: currentAnchor,
          sidebarDOM: sidebarRef.current,
          tooltipDOM: tooltipRef.current
        });
      },
      update: updateAnchors,
      scrollToAnchor: goAnchor
    };
  });
  useEffect(function () {
    var _sidebarRef$current;
    // 获取滚动容器
    scrollerRef.current = scrollerDOM || ((_sidebarRef$current = sidebarRef.current) === null || _sidebarRef$current === void 0 ? void 0 : _sidebarRef$current.previousElementSibling);
    if (!scrollerRef.current) return;

    // 滚动事件
    scrollerRef.current.addEventListener('scroll', handleScroll, false);

    // 更新锚记
    updateAnchors();
    return function () {
      scrollerRef.current && scrollerRef.current.removeEventListener('scroll', handleScroll, false);
    };
    // eslint-disable-next-line
  }, []);
  useEffect(function () {
    // 更新锚记
    updateAnchors();
    // eslint-disable-next-line
  }, [children]);
  useEffect(function () {
    // 更新锚记
    if (Array.isArray(externalAnchors) && externalAnchors.length) {
      setAnchors(externalAnchors);
    } else {
      setAnchors([]);
    }
    // eslint-disable-next-line
  }, [externalAnchors]);

  // 获取所有锚点
  function updateAnchors() {
    // 自定义anchors
    if (Array.isArray(externalAnchors) && externalAnchors.length) {
      setAnchors(externalAnchors);
      return;
    }
    if (!scrollerRef.current) return;
    anchors = getAnchorsByScroller(scrollerRef.current);
    setAnchors(anchors);

    // 锚记渲染完成后更新右侧选中效果
    setTimeout(function () {
      handleScroll();
    }, 0);
  }

  // Scroller scroll to position sidebar
  function handleScroll() {
    var currentAnchor = getAnchorByViewport(scrollerRef.current);
    currentAnchor && activeButton({
      anchor: currentAnchor,
      sidebarDOM: sidebarRef.current,
      tooltipDOM: tooltipRef.current
    });
  }

  // 触摸时滚动至anchor
  function goAnchor(currentAnchor) {
    if (!currentAnchor) return;
    scrollToAnchor({
      scrollerDOM: scrollerRef.current,
      anchor: currentAnchor
    });
    activeButton({
      anchor: currentAnchor,
      sidebarDOM: sidebarRef.current,
      tooltipDOM: tooltipRef.current
    });

    // 触发回调
    onTouchAnchor && onTouchAnchor(currentAnchor);
  }

  // Sidebar touch move to position Anchor
  function handleTouchStart(e) {
    e.stopPropagation();
    // 解决拖动时影响document弹性
    e.currentTarget.addEventListener('touchmove', DOMUtil.preventDefault, false);

    // 激活indexbar
    sidebarRef.current.classList.add('active');

    // 滚动到指定位置
    touchesRef.current.startX = e.touches[0].clientX;
    var currentAnchor = getAnchorByPoint({
      x: touchesRef.current.startX,
      y: e.touches[0].clientY
    });
    goAnchor(currentAnchor);
  }
  function handleTouchMove(e) {
    e.stopPropagation();

    // 滚动到指定位置
    var currentAnchor = getAnchorByPoint({
      x: touchesRef.current.startX,
      y: e.touches[0].clientY
    });
    goAnchor(currentAnchor);
  }
  function handleTouchEnd(e) {
    e.stopPropagation();
    // 解除对move时的弹性对当前div的锁定
    e.currentTarget.removeEventListener('touchmove', DOMUtil.preventDefault, false);
    sidebarRef.current.classList.remove('active');
  }
  var DOM = /*#__PURE__*/React.createElement(Fragment, null, children, /*#__PURE__*/React.createElement("div", _extends({}, props, {
    className: "indexbar".concat(props.className ? ' ' + props.className : ''),
    ref: sidebarRef,
    onTouchStart: handleTouchStart,
    onTouchMove: handleTouchMove,
    onTouchEnd: handleTouchEnd
  }), (anchors || []).map(function (anchor, i) {
    return /*#__PURE__*/React.createElement("div", {
      className: "indexbar-button",
      "data-indexbar-anchor-button": anchor,
      key: "btn".concat(i)
    }, /*#__PURE__*/React.createElement("div", {
      className: "indexbar-button-name"
    }, anchor));
  })), /*#__PURE__*/React.createElement("div", {
    ref: tooltipRef,
    className: "indexbar-tooltip"
  }));
  return DOM;
});
export default IndexBar;