"use strict";

exports.__esModule = true;
exports.default = exports.TabContext = void 0;

var _babelRuntimeJsxStyleTransform = require("babel-runtime-jsx-style-transform");

var _tslib = require("tslib");

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

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

var _meetReactComponentOne = require("@alifd/meet-react-component-one");

var _icon = _interopRequireDefault(require("../icon"));

var _locale = require("../locale");

var _zhCn = _interopRequireDefault(require("../locale/lang/zh-cn"));

var _picker = _interopRequireDefault(require("../picker"));

var _selectDrawer = require("../select-drawer");

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

var _hooks = require("../utils/hooks");

var _view = _interopRequireDefault(require("../view"));

var _item = _interopRequireDefault(require("./item"));

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || 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); }

var TabContext = /*#__PURE__*/(0, _react.createContext)({
  activeKey: -1,
  fullWidth: true,
  shape: 'normal',
  activeLineType: 'normal',
  change: function change() {}
});
exports.TabContext = TabContext;

var getTabData = function (props) {
  var dataSource = props.dataSource,
      children = props.children;

  if ((0, _utils.isValidArray)(dataSource)) {
    return dataSource.map(function (item) {
      return Object.assign(Object.assign({}, item), {
        label: item.title,
        value: item.key
      });
    });
  } else if (children) {
    return _react.Children.map(children, function (child) {
      var title = child.props.title;
      var key = child.key;
      return {
        label: title,
        value: key
      };
    });
  } else {
    return [];
  }
};

var getInitActiveKey = function (props) {
  if ('activeKey' in props && props.activeKey) {
    return props.activeKey;
  } else if (props.defaultActiveKey || props.defaultActiveKey === 0) {
    return props.defaultActiveKey;
  } else {
    return undefined;
  }
};

var timerMap = {};

var Tab = function (props, ref) {
  var _classNames, _classNames2, _classNames3;

  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      activeKey = props.activeKey,
      _props$defaultActiveK = props.defaultActiveKey,
      defaultActiveKey = _props$defaultActiveK === void 0 ? -1 : _props$defaultActiveK,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$activeLineType = props.activeLineType,
      activeLineType = _props$activeLineType === void 0 ? 'normal' : _props$activeLineType,
      _props$shape = props.shape,
      shape = _props$shape === void 0 ? 'normal' : _props$shape,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? true : _props$fullWidth,
      renderTool = props.renderTool,
      _props$onChange = props.onChange,
      onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
      _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
      className = props.className,
      contentClassName = props.contentClassName,
      contentStyle = props.contentStyle,
      renderTab = props.renderTab,
      children = props.children,
      others = (0, _tslib.__rest)(props, ["prefix", "activeKey", "defaultActiveKey", "size", "activeLineType", "shape", "fullWidth", "renderTool", "onChange", "dataSource", "className", "contentClassName", "contentStyle", "renderTab", "children"]);
  var locale = (0, _locale.useLocale)('Tab', others, _zhCn.default.Tab);

  var _useState = (0, _react.useState)(getInitActiveKey(props)),
      curActiveKey = _useState[0],
      setActiveKey = _useState[1];

  var _useState2 = (0, _react.useState)(false),
      drawerVisible = _useState2[0],
      setDrawerVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(getInitActiveKey(props)),
      internalTabKey = _useState3[0],
      setInternalActiveKey = _useState3[1];

  var curTabScrollId = (0, _hooks.useGuid)('tab-scroll-');
  var curScrollContainerId = (0, _hooks.useGuid)('tab-ctn-');
  var scrollRef = (0, _react.useRef)();
  var activeTabRef = (0, _react.useRef)();
  var isControlled = ('activeKey' in props);

  var _useState4 = (0, _react.useState)(false),
      isOverflow = _useState4[0],
      setOverflow = _useState4[1];

  var isExcessMode = !fullWidth && isOverflow;
  var clsPrefix = prefix + "tab";
  var clses = {
    tab: (0, _classnames.default)([clsPrefix, clsPrefix + "--" + shape, className]),
    divider: (0, _classnames.default)((_classNames = {}, _classNames[clsPrefix + "-divider"] = shape !== 'capsule', _classNames)),
    container: (0, _classnames.default)(clsPrefix + "-container", (_classNames2 = {}, _classNames2[clsPrefix + "-container--wechat"] = _utils.isStrictWechatMiniProgram, _classNames2)),
    scrollContainer: (0, _classnames.default)(clsPrefix + "-scroll-container", (_classNames3 = {}, _classNames3[clsPrefix + "-scroll-container--fullwidth"] = fullWidth, _classNames3[clsPrefix + "-scroll-container--wechat"] = _utils.isStrictWechatMiniProgram, _classNames3)),
    tool: (0, _classnames.default)(clsPrefix + "-tool", clsPrefix + "-tool--" + size),
    toolIcon: (0, _classnames.default)(clsPrefix + "-tool-icon", clsPrefix + "-tool-icon--" + size),
    drawer: (0, _classnames.default)(clsPrefix + "-drawer"),
    content: (0, _classnames.default)(clsPrefix + "-content", contentClassName)
  };

  var scrollTo = function (offset) {
    if (!timerMap[curTabScrollId]) {
      timerMap[curTabScrollId] = setTimeout(function () {
        if (scrollRef && scrollRef.current && scrollRef.current.scrollTo) {
          scrollRef.current.scrollTo(Object.assign(Object.assign({}, offset), {
            duration: 150
          }));
          timerMap[curTabScrollId] = null;
        }
      }, 200);
    }
  };

  (0, _react.useEffect)(function () {
    if (isControlled && curActiveKey && !props.activeKey) {
      setActiveKey(getInitActiveKey(props));
      return;
    }

    if (isControlled) {
      setActiveKey(props.activeKey);
    }
  });
  (0, _react.useEffect)(function () {
    setTimeout(function () {
      (function () {
        return (0, _tslib.__awaiter)(void 0, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var activeTabId, containerWidth, containerOffsetLeft, scrollLeft, activeTabWidth, activeTabOffsetLeft, totalWidth, centerMarkerPos, distance;
          return regeneratorRuntime.wrap(function (_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  activeTabId = activeTabRef.current && activeTabRef.current.id;
                  _context.next = 3;
                  return (0, _utils.getWidth)(curTabScrollId);

                case 3:
                  containerWidth = _context.sent;
                  _context.next = 6;
                  return (0, _utils.getLeft)(curTabScrollId);

                case 6:
                  containerOffsetLeft = _context.sent;
                  _context.next = 9;
                  return (0, _utils.getScrollLeft)(curTabScrollId);

                case 9:
                  scrollLeft = _context.sent;
                  _context.next = 12;
                  return (0, _utils.getWidth)(activeTabId);

                case 12:
                  activeTabWidth = _context.sent;
                  _context.next = 15;
                  return (0, _utils.getLeft)(activeTabId);

                case 15:
                  _context.t0 = _context.sent;
                  _context.t1 = containerOffsetLeft;
                  activeTabOffsetLeft = _context.t0 - _context.t1;
                  _context.next = 20;
                  return (0, _utils.getWidth)(curScrollContainerId);

                case 20:
                  totalWidth = _context.sent;
                  centerMarkerPos = containerWidth / 2;

                  if (!fullWidth) {
                    setOverflow(totalWidth > containerWidth);
                  }

                  if (scrollRef.current && activeTabRef.current) {
                    distance = Math.floor(Math.max(activeTabOffsetLeft - centerMarkerPos + scrollLeft + activeTabWidth / 2, 0));

                    if (scrollLeft !== distance) {
                      scrollTo({
                        x: distance / _utils.screenPixelRatio,
                        y: 0
                      });
                    }
                  }

                case 24:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
      })();
    }, 50);
  });
  var content;

  if (dataSource && dataSource.length > 0) {
    content = dataSource.map(function (item, index) {
      return /*#__PURE__*/(0, _react.createElement)(_item.default, _extends({
        key: item.key || index,
        itemKey: item.key,
        renderContent: renderTab,
        ref: item.key === curActiveKey ? activeTabRef : null,
        prefix: prefix,
        size: size
      }, item));
    });
  } else {
    content = _react.Children.map(children, function (child, index) {
      return (0, _react.cloneElement)(child, {
        key: "mt_tab_" + index,
        itemKey: child.key || index,
        ref: "" + child.key === "" + curActiveKey ? activeTabRef : null,
        renderContent: child.renderContent || renderTab,
        prefix: prefix,
        size: size
      });
    });
  }

  var handleChange = function (v) {
    if (!isControlled) {
      setActiveKey(v);
    }

    onChange(v);
  };

  return /*#__PURE__*/(0, _react.createElement)(TabContext.Provider, {
    value: {
      activeKey: curActiveKey,
      change: handleChange,
      shape: shape,
      fullWidth: fullWidth,
      activeLineType: activeLineType
    }
  }, /*#__PURE__*/(0, _react.createElement)(_view.default, null, /*#__PURE__*/(0, _react.createElement)(_view.default, _extends({}, others, {
    className: clses.tab,
    ref: ref
  }), /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.ScrollView, {
    ref: scrollRef,
    id: curTabScrollId,
    className: clses.container,
    contentContainerStyle: {
      flex: props.renderTool ? null : 1
    },
    horizontal: true,
    showsHorizontalScrollIndicator: false
  }, /*#__PURE__*/(0, _react.createElement)(_view.default, {
    id: curScrollContainerId,
    className: clses.scrollContainer
  }, content)), shape !== 'capsule' && /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: clses.divider
  }), function getTool() {
    if (!isExcessMode) {
      return null;
    }

    var _children = /*#__PURE__*/(0, _react.createElement)(_react.Fragment, null, /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Text, null, locale.more), /*#__PURE__*/(0, _react.createElement)(_icon.default, {
      className: clses.toolIcon,
      name: "arrow-down",
      size: "xxs"
    }));

    if ((0, _utils.isFunction)(renderTool)) {
      var renderedToolEl = renderTool();

      if (renderedToolEl) {
        _children = renderedToolEl;
      } else {
        _children = null;
      }
    }

    return _children ? /*#__PURE__*/(0, _react.createElement)(_view.default, {
      className: clses.tool,
      onClick: function onClick() {
        setDrawerVisible(true);
        setInternalActiveKey(curActiveKey);
      }
    }, _children) : null;
  }()), /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: clses.content,
    style: (0, _babelRuntimeJsxStyleTransform.rpx2vw4style)(contentStyle)
  }, function getChildren(activeTabKey) {
    var ret = null;

    _react.Children.forEach(children, function (child) {
      if (ret) {
        return;
      }

      var _key = child.key;

      if ("" + _key === "" + activeTabKey) {
        ret = child.props.children;
      }
    });

    return ret;
  }(curActiveKey))), isExcessMode ? /*#__PURE__*/(0, _react.createElement)(_selectDrawer.BaseSelectDrawer, {
    visible: drawerVisible,
    onOk: function handleDrawerOk() {
      setDrawerVisible(false);
      handleChange(internalTabKey);
    },
    onCancel: function handleDrawerCancel() {
      setDrawerVisible(false);
      setInternalActiveKey(curActiveKey);
    }
  }, /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.ScrollView, {
    className: clses.drawer
  }, /*#__PURE__*/(0, _react.createElement)(_picker.default, {
    cascade: true,
    data: getTabData(props),
    value: [internalTabKey],
    onChange: function (v) {
      if ((0, _utils.isValidArray)(v)) {
        setInternalActiveKey(v[0]);
      }
    }
  }))) : null);
};

Tab.displayName = 'Tab';

var _default = /*#__PURE__*/(0, _react.forwardRef)(Tab);

exports.default = _default;