vantui-edit
Version:
一套适用于Taro3及React的vantui组件库
611 lines (523 loc) • 21.9 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Tabs = Tabs;
exports.default = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _taro = require("@tarojs/taro");
var _react = require("react");
var _toArray = _interopRequireDefault(require("rc-util/lib/Children/toArray"));
var _components = require("@tarojs/components");
var utils = _interopRequireWildcard(require("../wxs/utils"));
var _validator = require("../common/validator");
var _index3 = require("../sticky/index");
var _utils2 = require("../common/utils");
var _index4 = require("../info/index");
var computed = _interopRequireWildcard(require("./wxs"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["swipeable", "active", "lazyRender", "type", "sticky", "container", "zIndex", "offsetTop", "border", "color", "ellipsis", "lineHeight", "duration", "lineWidth", "titleActiveColor", "titleInactiveColor", "swipeThreshold", "animated", "renderNavLeft", "renderNavRight", "onScroll", "onClick", "onChange", "onDisabled", "style", "className", "children"];
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var MIN_DISTANCE = 10;
function getDirection(x, y) {
if (x > y && x > MIN_DISTANCE) {
return 'horizontal';
}
if (y > x && y > MIN_DISTANCE) {
return 'vertical';
}
return '';
}
function parseTabList(children) {
return (0, _toArray.default)(children).map(function (node) {
if ( /*#__PURE__*/(0, _react.isValidElement)(node)) {
var key = node.key !== undefined ? String(node.key) : undefined;
return _objectSpread(_objectSpread({
key: key
}, node.props), {}, {
node: node
});
}
return null;
}).filter(function (tab) {
return tab;
});
}
function Tabs(props) {
var ref = (0, _react.useRef)({
skipInit: false,
direction: '',
deltaX: 0,
deltaY: 0,
offsetX: 0,
offsetY: 0,
startX: 0,
startY: 0,
swiping: false
});
var indexRef = (0, _react.useRef)("".concat(+new Date()).concat(Math.ceil(Math.random() * 10000)));
var _useState = (0, _react.useState)(false),
_useState2 = (0, _slicedToArray2.default)(_useState, 2),
isInited = _useState2[0],
setIsInited = _useState2[1];
var _useState3 = (0, _react.useState)('100%'),
_useState4 = (0, _slicedToArray2.default)(_useState3, 2),
scrollWidth = _useState4[0],
setScrollWidth = _useState4[1];
var _useState5 = (0, _react.useState)({
tabs: [],
scrollLeft: 0,
scrollable: false,
currentIndex: 0,
skipTransition: true,
scrollWithAnimation: false,
lineOffsetLeft: 0
}),
_useState6 = (0, _slicedToArray2.default)(_useState5, 2),
state = _useState6[0],
setState = _useState6[1];
var scrollLeft = state.scrollLeft,
scrollable = state.scrollable,
currentIndex = state.currentIndex,
skipTransition = state.skipTransition,
scrollWithAnimation = state.scrollWithAnimation,
lineOffsetLeft = state.lineOffsetLeft;
var swipeable = props.swipeable,
_props$active = props.active,
active = _props$active === void 0 ? 0 : _props$active,
_props$lazyRender = props.lazyRender,
lazyRender = _props$lazyRender === void 0 ? true : _props$lazyRender,
_props$type = props.type,
type = _props$type === void 0 ? 'line' : _props$type,
sticky = props.sticky,
container = props.container,
zIndex = props.zIndex,
_props$offsetTop = props.offsetTop,
offsetTop = _props$offsetTop === void 0 ? 0 : _props$offsetTop,
border = props.border,
color = props.color,
_props$ellipsis = props.ellipsis,
ellipsis = _props$ellipsis === void 0 ? true : _props$ellipsis,
_props$lineHeight = props.lineHeight,
lineHeight = _props$lineHeight === void 0 ? -1 : _props$lineHeight,
_props$duration = props.duration,
duration = _props$duration === void 0 ? 0.3 : _props$duration,
_props$lineWidth = props.lineWidth,
lineWidth = _props$lineWidth === void 0 ? 40 : _props$lineWidth,
titleActiveColor = props.titleActiveColor,
titleInactiveColor = props.titleInactiveColor,
_props$swipeThreshold = props.swipeThreshold,
swipeThreshold = _props$swipeThreshold === void 0 ? 5 : _props$swipeThreshold,
animated = props.animated,
renderNavLeft = props.renderNavLeft,
renderNavRight = props.renderNavRight,
onScroll = props.onScroll,
onClick = props.onClick,
onChange = props.onChange,
onDisabled = props.onDisabled,
style = props.style,
className = props.className,
children = props.children,
others = (0, _objectWithoutProperties2.default)(props, _excluded);
(0, _react.useEffect)(function () {
setIsInited(true);
}, []);
var tabs = (0, _react.useMemo)(function () {
return parseTabList(children);
}, [children]);
var newChildren = (0, _react.useMemo)(function () {
return tabs.map(function (tab, index) {
return /*#__PURE__*/(0, _react.cloneElement)(tab.node, {
key: index,
active: currentIndex === index,
lazyRender: lazyRender,
animated: animated,
index: index
});
});
}, [animated, currentIndex, lazyRender, tabs]);
var trigger = function trigger(eventName, child) {
var _func$eventName;
var currentChild = child || newChildren[currentIndex];
if (!(0, _validator.isDef)(currentChild)) {
return;
}
var func = {
onClick: onClick,
onChange: onChange,
onDisabled: onDisabled
};
(_func$eventName = func[eventName]) === null || _func$eventName === void 0 ? void 0 : _func$eventName.call(func, {
detail: {
index: currentChild.props.index,
name: currentChild.props.name || currentChild.props.index,
title: currentChild.props.title
}
});
};
var getCurrentName = function getCurrentName() {
var activeTab = newChildren[currentIndex];
if (activeTab) {
return activeTab.props.name || activeTab.props.index;
}
};
var setCurrentIndex = function setCurrentIndex(cIndex) {
if (!(0, _validator.isDef)(cIndex) || cIndex >= newChildren.length || cIndex < 0) {
return;
}
if (cIndex === currentIndex) {
return;
}
var shouldEmitChange = currentIndex !== null;
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
currentIndex: cIndex
});
});
(0, _utils2.requestAnimationFrame)(function () {
resize(cIndex);
scrollIntoView(cIndex);
});
(0, _taro.nextTick)(function () {
if (shouldEmitChange) {
trigger('onChange', newChildren[cIndex]);
}
});
};
var setCurrentIndexByName = function setCurrentIndexByName(name) {
var matched = newChildren.filter(function (child) {
return (child.props.name || child.props.index) === name;
});
if (matched.length) {
setCurrentIndex(matched[0].props.index);
}
};
var resize = function resize(index) {
var _index;
if (type !== 'line') {
return;
}
index = (_index = index) !== null && _index !== void 0 ? _index : currentIndex;
(0, _taro.nextTick)(function () {
Promise.all([(0, _utils2.getAllRect)(null, ".tabs-com-index".concat(indexRef.current, " .van-tab")), (0, _utils2.getRect)(null, ".tabs-com-index".concat(indexRef.current, " .van-tabs__line"))]).then(function (_ref) {
var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
_ref2$ = _ref2[0],
rects = _ref2$ === void 0 ? [] : _ref2$,
lineRect = _ref2[1];
if (rects && lineRect) {
var rect = rects[index];
if (rect == null) {
return;
}
var _lineOffsetLeft = rects.slice(0, index).reduce(function (prev, curr) {
return prev + curr.width;
}, 0);
_lineOffsetLeft += (rect.width - lineRect.width) / 2 + (ellipsis ? 0 : 8);
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
lineOffsetLeft: _lineOffsetLeft
});
});
ref.current.swiping = true;
if (skipTransition) {
(0, _taro.nextTick)(function () {
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
skipTransition: false
});
});
});
}
}
});
});
};
var onTap = function onTap(event) {
var index = event.currentTarget.dataset.index;
index = parseInt(index);
var child = newChildren[index];
if (child.props.disabled) {
trigger('onDisabled', child);
} else {
setCurrentIndex(index);
(0, _taro.nextTick)(function () {
trigger('onClick', child);
});
}
};
var scrollIntoView = function scrollIntoView(index) {
var _index2;
if (!scrollable) {
return;
}
index = (_index2 = index) !== null && _index2 !== void 0 ? _index2 : currentIndex;
Promise.all([(0, _utils2.getAllRect)(null, ".tabs-com-index".concat(indexRef.current, " .van-tab")), (0, _utils2.getRect)(null, ".tabs-com-index".concat(indexRef.current, " .van-tabs__nav"))]).then(function (_ref3) {
var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
tabRects = _ref4[0],
navRect = _ref4[1];
if (tabRects && navRect) {
var tabRect = tabRects[index];
var offsetLeft = tabRects.slice(0, index).reduce(function (prev, curr) {
return prev + curr.width;
}, 0);
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
scrollLeft: offsetLeft - (navRect.width - tabRect.width) / 2
});
});
if (!scrollWithAnimation) {
(0, _taro.nextTick)(function () {
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
scrollWithAnimation: true
});
});
});
}
}
});
};
var resetTouchStatus = function resetTouchStatus() {
ref.current.direction = '';
ref.current.deltaX = 0;
ref.current.deltaY = 0;
ref.current.offsetX = 0;
ref.current.offsetY = 0;
};
var touchStart = function touchStart(event) {
resetTouchStatus();
var touch = event.touches[0];
ref.current.startX = touch.clientX;
ref.current.startY = touch.clientY;
};
var touchMove = function touchMove(event) {
var touch = event.touches[0];
ref.current.deltaX = touch.clientX - ref.current.startX;
ref.current.deltaY = touch.clientY - ref.current.startY;
ref.current.offsetX = Math.abs(ref.current.deltaX);
ref.current.offsetY = Math.abs(ref.current.deltaY);
ref.current.direction = ref.current.direction || getDirection(ref.current.offsetX, ref.current.offsetY);
};
var getAvaiableTab = function getAvaiableTab(direction) {
var step = direction > 0 ? -1 : 1;
for (var i = step; currentIndex + i < tabs.length && currentIndex + i >= 0; i += step) {
var index = currentIndex + i;
if (index >= 0 && index < tabs.length && tabs[index] && !tabs[index].disabled) {
return index;
}
}
return -1;
};
var onTouchStart = function onTouchStart(event) {
if (!swipeable) return;
ref.current.swiping = true;
touchStart(event);
};
var onTouchMove = function onTouchMove(event) {
if (!swipeable || !ref.current.swiping) return;
touchMove(event);
};
var onTouchEnd = function onTouchEnd() {
if (!swipeable || !ref.current.swiping) return;
var _ref$current = ref.current,
direction = _ref$current.direction,
deltaX = _ref$current.deltaX,
offsetX = _ref$current.offsetX;
var minSwipeDistance = 50;
if (direction === 'horizontal' && offsetX >= minSwipeDistance) {
var index = getAvaiableTab(deltaX);
if (index !== -1) {
setCurrentIndex(index);
}
}
ref.current.swiping = false;
};
(0, _react.useEffect)(function () {
ref.current.swiping = true; // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0, _react.useEffect)(function () {
(0, _taro.nextTick)(function () {
var _ref$current2;
resize();
scrollIntoView();
if (active !== getCurrentName() && !((_ref$current2 = ref.current) !== null && _ref$current2 !== void 0 && _ref$current2.swiping) && !swipeable) {
setCurrentIndexByName(active);
}
});
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[getCurrentName()]);
(0, _react.useEffect)(function () {
resize();
scrollIntoView();
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[lineWidth]);
(0, _react.useEffect)(function () {
if (active !== getCurrentName()) {
setCurrentIndexByName(active);
}
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[active]);
(0, _react.useEffect)(function () {
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
scrollable: newChildren.length > swipeThreshold || !ellipsis
});
});
}, [swipeThreshold, newChildren, ellipsis]); // 解决异步加载的时候默认的下划线不出现的问题
(0, _react.useEffect)(function () {
(0, _taro.nextTick)(function () {
resize();
});
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[newChildren]);
var getScrollWrapWidth = (0, _react.useCallback)( /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
var othersWidth, res, _res;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
othersWidth = 0;
if (!(renderNavLeft && isInited)) {
_context.next = 6;
break;
}
_context.next = 4;
return (0, _utils2.getAllRect)(null, // @ts-ignore
'.' + utils.bem('renderNavLeft' + indexRef.current));
case 4:
res = _context.sent;
if (res.length) othersWidth += res[0].width;
case 6:
if (!(renderNavRight && isInited)) {
_context.next = 11;
break;
}
_context.next = 9;
return (0, _utils2.getAllRect)(null, // @ts-ignore
'.' + utils.bem('renderNavRight' + indexRef.current));
case 9:
_res = _context.sent;
if (_res.length) othersWidth += _res[0].width;
case 11:
if (othersWidth) setScrollWidth("calc(100% - ".concat(othersWidth, "px)"));
case 12:
case "end":
return _context.stop();
}
}
}, _callee);
})), [renderNavLeft, isInited, renderNavRight]);
(0, _react.useEffect)(function () {
setTimeout(function () {
getScrollWrapWidth();
});
}, [getScrollWrapWidth, isInited]);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.View, _objectSpread(_objectSpread({
className: "tabs-com-index".concat(indexRef.current, " ") + ' ' + utils.bem('tabs', [type] + " ".concat(className || '')),
style: style
}, others), {}, {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_index3.Sticky, {
disabled: !sticky,
zIndex: zIndex,
offsetTop: offsetTop,
container: container,
onScroll: onScroll,
children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.View, {
className: utils.bem('tabs__wrap', {
scrollable: scrollable
}) + ' ' + (type === 'line' && border ? 'van-hairline--top-bottom' : ''),
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: utils.bem('renderNavLeft' + indexRef.current),
children: renderNavLeft
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.ScrollView, {
scrollX: scrollable,
scrollWithAnimation: scrollWithAnimation,
scrollLeft: scrollLeft,
className: utils.bem('tabs__scroll', [type]),
style: {
width: scrollWidth,
borderColor: color
},
children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.View, {
className: utils.bem('tabs__nav', [type, {
complete: !ellipsis
}]) + ' nav-class',
style: computed.navStyle(color, type),
children: [type === 'line' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: "van-tabs__line",
style: computed.lineStyle({
color: color,
lineOffsetLeft: lineOffsetLeft,
lineHeight: lineHeight,
skipTransition: skipTransition,
duration: duration,
lineWidth: lineWidth
})
}), tabs.map(function (item, index) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
"data-index": index,
className: computed.tabClass(index === currentIndex, ellipsis) + ' ' + utils.bem('tab', {
active: index === currentIndex,
disabled: item.disabled,
complete: !ellipsis
}),
style: computed.tabStyle({
active: index === currentIndex,
ellipsis: ellipsis,
color: color,
type: type,
disabled: item.disabled,
titleActiveColor: titleActiveColor,
titleInactiveColor: titleInactiveColor,
swipeThreshold: swipeThreshold,
scrollable: scrollable
}),
onClick: onTap,
children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.View, {
className: ellipsis ? 'van-ellipsis' : '',
style: item.titleStyle,
children: [item.title, (item.info !== null || item.dot) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_index4.Info, {
info: item.info,
dot: item.dot,
className: "van-tab__title__info"
})]
})
}, index);
})]
})
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: utils.bem('renderNavRight' + indexRef.current),
children: renderNavRight
})]
})
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: "van-tabs__content",
onTouchStart: onTouchStart,
onTouchMove: onTouchMove,
onTouchEnd: onTouchEnd,
onTouchCancel: onTouchEnd,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: utils.bem('tabs__track', [{
animated: animated
}]) + ' van-tabs__track',
style: computed.trackStyle({
duration: duration,
currentIndex: currentIndex,
animated: animated
}),
children: newChildren
})
})]
}));
}
var _default = Tabs;
exports.default = _default;