UNPKG

@antmjs/vantui

Version:

一套适用于Taro3及React的vantui组件库

471 lines (470 loc) 19.9 kB
"use strict"; 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 _index2 = require("../sticky/index"); var _utils2 = require("../common/utils"); var _index3 = require("../info/index"); var _defaultProps = require("../default-props"); var computed = _interopRequireWildcard(require("./wxs")); var _jsxRuntime = require("react/jsx-runtime"); var _excluded = ["swipeable", "active", "lazyRender", "type", "sticky", "container", "zIndex", "offsetTop", "border", "color", "ellipsis", "duration", "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; } /* eslint-disable @typescript-eslint/ban-ts-comment */ 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 _useState = (0, _react.useState)((0, _defaultProps.get)().Tabs), _useState2 = (0, _slicedToArray2.default)(_useState, 1), d = _useState2[0]; 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 _useState3 = (0, _react.useState)(false), _useState4 = (0, _slicedToArray2.default)(_useState3, 2), isInited = _useState4[0], setIsInited = _useState4[1]; var _useState5 = (0, _react.useState)('100%'), _useState6 = (0, _slicedToArray2.default)(_useState5, 2), scrollWidth = _useState6[0], setScrollWidth = _useState6[1]; var _useState7 = (0, _react.useState)({ tabs: [], scrollLeft: 0, scrollable: false, currentIndex: 0, prevIndex: -1, scrollWithAnimation: false }), _useState8 = (0, _slicedToArray2.default)(_useState7, 2), state = _useState8[0], setState = _useState8[1]; var scrollLeft = state.scrollLeft, scrollable = state.scrollable, currentIndex = state.currentIndex, prevIndex = state.prevIndex, scrollWithAnimation = state.scrollWithAnimation; var _d$props = _objectSpread(_objectSpread({}, d), props), swipeable = _d$props.swipeable, _d$props$active = _d$props.active, active = _d$props$active === void 0 ? 0 : _d$props$active, _d$props$lazyRender = _d$props.lazyRender, lazyRender = _d$props$lazyRender === void 0 ? true : _d$props$lazyRender, _d$props$type = _d$props.type, type = _d$props$type === void 0 ? 'line' : _d$props$type, sticky = _d$props.sticky, container = _d$props.container, zIndex = _d$props.zIndex, _d$props$offsetTop = _d$props.offsetTop, offsetTop = _d$props$offsetTop === void 0 ? 0 : _d$props$offsetTop, border = _d$props.border, color = _d$props.color, _d$props$ellipsis = _d$props.ellipsis, ellipsis = _d$props$ellipsis === void 0 ? true : _d$props$ellipsis, _d$props$duration = _d$props.duration, duration = _d$props$duration === void 0 ? 0.3 : _d$props$duration, titleActiveColor = _d$props.titleActiveColor, titleInactiveColor = _d$props.titleInactiveColor, _d$props$swipeThresho = _d$props.swipeThreshold, swipeThreshold = _d$props$swipeThresho === void 0 ? 5 : _d$props$swipeThresho, animated = _d$props.animated, renderNavLeft = _d$props.renderNavLeft, renderNavRight = _d$props.renderNavRight, onScroll = _d$props.onScroll, onClick = _d$props.onClick, onChange = _d$props.onChange, onDisabled = _d$props.onDisabled, style = _d$props.style, className = _d$props.className, children = _d$props.children, others = (0, _objectWithoutProperties2.default)(_d$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, prevIndex: pre.currentIndex }); }); (0, _utils2.requestAnimationFrame)(function () { 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 onTap = function onTap(index_) { var 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 _index; index = (_index = index) !== null && _index !== void 0 ? _index : currentIndex; if (!scrollable || index === undefined) { return; } 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 (_ref) { var _ref2 = (0, _slicedToArray2.default)(_ref, 2), tabRects = _ref2[0], navRect = _ref2[1]; if (tabRects && tabRects.length && 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) { event.preventDefault(); event.stopPropagation(); 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 () { var _ref$current2; (0, _taro.nextTick)(function () { setTimeout(function () { scrollIntoView(); }, 33); }); 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 () { 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]); 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(); }, 66); }, [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)(_index2.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.jsx)(_components.View, { className: utils.bem('tabs__nav', [type, { complete: !ellipsis }]) + ' nav-class', style: computed.navStyle(color, type), children: tabs.map(function (item, index) { return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_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: function onClick() { return onTap(index); }, children: [type === 'line' && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, { className: "van-tab--active-line ".concat(index === currentIndex ? 'van-tab--active-line-show' : '', " ").concat(index === prevIndex && index !== currentIndex ? 'van-tab--active-line-hidden' : '') }), /*#__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)(_index3.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;