"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 = void 0;

var _react = _interopRequireWildcard(require("react"));

var _one = require("remax/one");

var _classnames = _interopRequireDefault(require("classnames"));

var _one2 = require("../one");

var _utils = require("../_utils");

var _common = require("../common");

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _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 _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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var prefixCls = (0, _common.getPrefixCls)('tabs');
var heightUnit = 48; // const prevTabs: any[] = [];

var getTabContents = function getTabContents(children, activeKey, animated) {
  var tabContents = [];
  var tabs = [];

  _react.default.Children.forEach(children, function (node, index) {
    var newNode = node;

    if ( /*#__PURE__*/_react.default.isValidElement(node)) {
      return tabs.push({
        key: newNode.key,
        tab: newNode.props.tab
      }) && tabContents.push( /*#__PURE__*/_react.default.createElement(TabContent, Object.assign({
        key: newNode.key
      }, newNode.props, {
        active: activeKey === undefined ? index === 0 && newNode.key : String(activeKey) === newNode.key,
        animated: animated
      })));
    }
  });

  return [tabs, tabContents];
};

var getTabIndex = function getTabIndex(tabs, activeKey) {
  var tIndex = 0;
  tabs.forEach(function (i, index) {
    if (i.key === activeKey) {
      tIndex = index;
    }
  });
  return tIndex;
};

var Tabs = function Tabs(props) {
  var type = props.type,
      _props$direction = props.direction,
      direction = _props$direction === void 0 ? 'horizontal' : _props$direction,
      activeKey = props.activeKey,
      animated = props.animated,
      fixed = props.fixed,
      onTabClick = props.onTabClick,
      headerContent = props.headerContent,
      children = props.children,
      headerStyle = props.headerStyle,
      extra = props.extra,
      titleWidth = props.titleWidth,
      titleSquare = props.titleSquare,
      titleAlign = props.titleAlign,
      titleStyle = props.titleStyle; // 针对同一个页面出现两个Tabs，给每个Tabs一个 UniqueID

  var TABS_TITLE_ID = (0, _react.useMemo)(_utils.guid, []);

  var _useMemo = (0, _react.useMemo)(function () {
    return getTabContents(children, activeKey, animated);
  }, [children]),
      _useMemo2 = _slicedToArray(_useMemo, 2),
      tabs = _useMemo2[0],
      tabContents = _useMemo2[1]; // 将 activeKey 实时转化成当前 selected 的Tab，后面都将以 selected 作为当前选择的 Tab 的标志符


  var selected = (0, _react.useMemo)(function () {
    return getTabIndex(tabs, activeKey);
  }, [activeKey, tabs]);

  var _useState = (0, _react.useState)(0),
      _useState2 = _slicedToArray(_useState, 2),
      titleWrapperLeft = _useState2[0],
      setTitleWrapperLeft = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      titleNodes = _useState4[0],
      setTitleNodes = _useState4[1];

  (0, _react.useEffect)(function () {
    var _a, _b;

    if (type === 'plain') {
      var query = (0, _one2.createSelectorQuery)();
      (_b = (_a = query.select(".".concat(prefixCls, "-plain-").concat(TABS_TITLE_ID))).scrollOffset) === null || _b === void 0 ? void 0 : _b.call(_a).exec(function (ret) {
        var r = Array.isArray(ret) ? ret[0] : ret;
        setTitleWrapperLeft(-((r === null || r === void 0 ? void 0 : r.scrollLeft) || 0));
      });
    }
  }, [activeKey]);
  (0, _react.useEffect)(function () {
    if (type === 'plain') {
      var query = (0, _one2.createSelectorQuery)(); // 不加setTimeout的话只能获取部分的nodes(可能是部分 .anna-tabs-plain-title 节点还没来得及渲染出来)

      setTimeout(function () {
        query.selectAll(".".concat(prefixCls, "-plain-").concat(TABS_TITLE_ID, " .").concat(prefixCls, "-plain-title")).boundingClientRect().exec(function (ret) {
          var r = Array.isArray(ret) ? ret[0] : [ret];
          var nodes = (r === null || r === void 0 ? void 0 : r.map(function (i) {
            return {
              offsetLeft: i.left,
              offsetWidth: i.width
            };
          })) || []; // 解决切换tabbar导致页面渲染找不到相关节点(因为此时已经在跳转后一个页面，所以找不到)，从而使nodes这个数组为空，继而导致Tabs下标left重置为0。

          nodes.length > 0 && setTitleNodes(nodes);
        });
      }, 200);
    }
  }, [tabs.length]);

  var handleTabClick = function handleTabClick(item) {
    onTabClick === null || onTabClick === void 0 ? void 0 : onTabClick(item);
  };

  var activeKeyStr = String(activeKey);

  var renderTabs = function renderTabs() {
    var _classNames4;

    if (type === 'plain') {
      var _classNames;

      var titleNode = (titleNodes === null || titleNodes === void 0 ? void 0 : titleNodes[selected]) || {
        offsetLeft: 0,
        offsetWidth: 0
      }; // 注；此处left的位置是相对于 .anna-tabs-plain 的，不是相对于手机视窗左侧的。所以如果 .anna-tabs-plain 不能
      // 占据视窗width的100%，Tabs的下标位置就会偏右。

      var left = titleNode.offsetLeft + titleNode.offsetWidth / 2; // 解决小程序下无法获取到元素的 offsetLeft 的问题，使用 scrollOffset 来获取 scrollLeft。

      if (titleWrapperLeft < 0) {// left += Math.abs(titleWrapperLeft); //不需要这一步，因为offsetLeft是相对于父元素的，而不是相对于视窗的
      }

      return /*#__PURE__*/_react.default.createElement(_one.View, {
        className: (0, _classnames.default)((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-plain"), true), _defineProperty(_classNames, "".concat(prefixCls, "-plain-center"), titleAlign === 'center'), _defineProperty(_classNames, "".concat(prefixCls, "-plain-").concat(TABS_TITLE_ID), true), _classNames))
      }, tabs.map(function (item) {
        var _classNames2;

        return /*#__PURE__*/_react.default.createElement(_one.View, {
          key: item.key,
          className: (0, _classnames.default)((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefixCls, "-plain-title"), true), _defineProperty(_classNames2, "".concat(prefixCls, "-plain-center-title"), titleAlign === 'center'), _classNames2)),
          style: titleStyle,
          onTap: function onTap() {
            return handleTabClick(item);
          }
        }, item.tab);
      }), /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-plain-active"),
        style: {
          transform: "translateX(".concat(left, "PX) translateX(-50%)")
        }
      }));
    }

    if (type === 'card') {
      return /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-card")
      }, tabs.map(function (item) {
        var _classNames3;

        return /*#__PURE__*/_react.default.createElement(_one.View, {
          key: item.key,
          className: (0, _classnames.default)((_classNames3 = {}, _defineProperty(_classNames3, "".concat(prefixCls, "-card-title"), true), _defineProperty(_classNames3, "".concat(prefixCls, "-card-active"), activeKeyStr === item.key), _classNames3)),
          style: titleStyle,
          onTap: function onTap() {
            return handleTabClick(item);
          }
        }, item.tab);
      }));
    }

    return /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-slider")
    }, /*#__PURE__*/_react.default.createElement(_one.View, {
      className: (0, _classnames.default)((_classNames4 = {}, _defineProperty(_classNames4, "".concat(prefixCls, "-slider-bg"), true), _defineProperty(_classNames4, "".concat(prefixCls, "-slider-bg-square"), titleSquare), _classNames4))
    }, /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-slider-container")
    }, tabs.map(function (item) {
      return /*#__PURE__*/_react.default.createElement(_one.View, {
        key: item.key,
        className: "".concat(prefixCls, "-slider-title"),
        style: Object.assign(Object.assign({}, titleStyle), {
          fontWeight: activeKeyStr === item.key ? 500 : 400,
          width: titleWidth ? "".concat(titleWidth, "px") : null
        }),
        onTap: function onTap() {
          handleTabClick(item);
        }
      }, item.tab);
    }), /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-slider-active"),
      style: {
        width: "".concat(100 / tabs.length, "%"),
        transform: "translateX(".concat(selected * 100, "%)")
      }
    }))), extra);
  };

  if (direction === 'vertical') {
    return /*#__PURE__*/_react.default.createElement(_one.View, {
      className: prefixCls
    }, /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-vertical")
    }, /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-vertical-sidebar")
    }, tabs === null || tabs === void 0 ? void 0 : tabs.map(function (item, index) {
      return /*#__PURE__*/_react.default.createElement(_one.View, {
        key: item.key,
        className: "".concat(prefixCls, "-vertical-sidebar-item"),
        style: Object.assign(Object.assign({}, titleStyle), {
          fontWeight: selected === index ? 500 : 400,
          backgroundColor: selected === index ? '#FDFFFD' : '#FAFAFA'
        }),
        onTap: function onTap() {
          return handleTabClick(item);
        }
      }, item.tab, selected === index && /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-vertical-sidebar-top")
      }, /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-vertical-sidebar-top-circle")
      })), selected === index && /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-vertical-sidebar-bottom")
      }, /*#__PURE__*/_react.default.createElement(_one.View, {
        className: "".concat(prefixCls, "-vertical-sidebar-bottom-circle")
      })));
    }), /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-vertical-sidebar-active"),
      style: {
        transform: "translate3d(0, ".concat(selected * heightUnit, "PX, 0)")
      }
    })), /*#__PURE__*/_react.default.createElement(_one.View, {
      className: "".concat(prefixCls, "-vertical-content")
    }, tabContents)));
  }

  return /*#__PURE__*/_react.default.createElement(_one.View, {
    className: prefixCls
  }, /*#__PURE__*/_react.default.createElement(_one.View, {
    className: (0, _classnames.default)("".concat(prefixCls, "-header"), _defineProperty({}, "".concat(prefixCls, "-header-fixed"), fixed)),
    style: Object.assign({}, headerStyle)
  }, renderTabs(), /*#__PURE__*/_react.default.createElement(_one.View, {
    className: "".concat(prefixCls, "-header-content")
  }, headerContent)), /*#__PURE__*/_react.default.createElement(_one.View, {
    className: "".concat(prefixCls, "-content")
  }, /*#__PURE__*/_react.default.createElement(_one.View, {
    className: "".concat(prefixCls, "-content-wrapper"),
    style: animated ? {
      transition: "all 0.3s ease",
      transform: "translate3d(".concat(-selected * 100, "%, 0, 0)")
    } : {}
  }, tabContents)));
};

var TabContent = function TabContent(props) {
  var active = props.active,
      style = props.style,
      animated = props.animated,
      children = props.children;

  if (!active) {
    var _classNames6;

    return /*#__PURE__*/_react.default.createElement(_one.View, {
      className: (0, _classnames.default)("".concat(prefixCls, "-content-tab"), (_classNames6 = {}, _defineProperty(_classNames6, "".concat(prefixCls, "-content-tab-inactive"), !animated), _defineProperty(_classNames6, "".concat(prefixCls, "-content-tab-inactive-animated"), animated), _classNames6)),
      style: style
    }, children);
  }

  return /*#__PURE__*/_react.default.createElement(_one.View, {
    className: "".concat(prefixCls, "-content-tab"),
    style: style
  }, children);
};

Tabs.TabContent = TabContent;
var _default = Tabs;
exports.default = _default;