@antmjs/vantui
Version:
一套适用于Taro3及React的vantui组件库
461 lines • 17.6 kB
JavaScript
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
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) { _defineProperty(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 */
import { nextTick } from '@tarojs/taro';
import { useState, isValidElement, cloneElement, useEffect, useRef, useMemo, useCallback } from 'react';
import toArray from 'rc-util/lib/Children/toArray';
import { View, ScrollView } from '@tarojs/components';
import * as utils from '../wxs/utils';
import { isDef } from '../common/validator';
import { Sticky } from '../sticky/index';
import { getRect, getAllRect, requestAnimationFrame } from '../common/utils';
import { Info } from '../info/index';
import { get } from '../default-props';
import * as computed from './wxs';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
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 toArray(children).map(function (node) {
if ( /*#__PURE__*/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;
});
}
export function Tabs(props) {
var _useState = useState(get().Tabs),
_useState2 = _slicedToArray(_useState, 1),
d = _useState2[0];
var ref = useRef({
skipInit: false,
direction: '',
deltaX: 0,
deltaY: 0,
offsetX: 0,
offsetY: 0,
startX: 0,
startY: 0,
swiping: false
});
var indexRef = useRef("".concat(+new Date()).concat(Math.ceil(Math.random() * 10000)));
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
isInited = _useState4[0],
setIsInited = _useState4[1];
var _useState5 = useState('100%'),
_useState6 = _slicedToArray(_useState5, 2),
scrollWidth = _useState6[0],
setScrollWidth = _useState6[1];
var _useState7 = useState({
tabs: [],
scrollLeft: 0,
scrollable: false,
currentIndex: 0,
prevIndex: -1,
scrollWithAnimation: false
}),
_useState8 = _slicedToArray(_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 = _objectWithoutProperties(_d$props, _excluded);
useEffect(function () {
setIsInited(true);
}, []);
var tabs = useMemo(function () {
return parseTabList(children);
}, [children]);
var newChildren = useMemo(function () {
return tabs.map(function (tab, index) {
return /*#__PURE__*/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 (!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 (!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
});
});
requestAnimationFrame(function () {
scrollIntoView(cIndex);
});
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);
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([getAllRect(null, ".tabs-com-index".concat(indexRef.current, " .van-tab")), getRect(null, ".tabs-com-index".concat(indexRef.current, " .van-tabs__nav"))]).then(function (_ref) {
var _ref2 = _slicedToArray(_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) {
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;
};
useEffect(function () {
ref.current.swiping = true;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(function () {
var _ref$current2;
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()]);
useEffect(function () {
if (active !== getCurrentName()) {
setCurrentIndexByName(active);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[active]);
useEffect(function () {
setState(function (pre) {
return _objectSpread(_objectSpread({}, pre), {}, {
scrollable: newChildren.length > swipeThreshold || !ellipsis
});
});
}, [swipeThreshold, newChildren, ellipsis]);
var getScrollWrapWidth = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var othersWidth, res, _res;
return _regeneratorRuntime.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 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 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]);
useEffect(function () {
setTimeout(function () {
getScrollWrapWidth();
}, 66);
}, [getScrollWrapWidth, isInited]);
return /*#__PURE__*/_jsxs(View, _objectSpread(_objectSpread({
className: "tabs-com-index".concat(indexRef.current, " ") + ' ' + utils.bem('tabs', [type] + " ".concat(className || '')),
style: style
}, others), {}, {
children: [/*#__PURE__*/_jsx(Sticky, {
disabled: !sticky,
zIndex: zIndex,
offsetTop: offsetTop,
container: container,
onScroll: onScroll,
children: /*#__PURE__*/_jsxs(View, {
className: utils.bem('tabs__wrap', {
scrollable: scrollable
}) + ' ' + (type === 'line' && border ? 'van-hairline--top-bottom' : ''),
children: [/*#__PURE__*/_jsx(View, {
className: utils.bem('renderNavLeft' + indexRef.current),
children: renderNavLeft
}), /*#__PURE__*/_jsx(ScrollView, {
scrollX: scrollable,
scrollWithAnimation: scrollWithAnimation,
scrollLeft: scrollLeft,
className: utils.bem('tabs__scroll', [type]),
style: {
width: scrollWidth,
borderColor: color
},
children: /*#__PURE__*/_jsx(View, {
className: utils.bem('tabs__nav', [type, {
complete: !ellipsis
}]) + ' nav-class',
style: computed.navStyle(color, type),
children: tabs.map(function (item, index) {
return /*#__PURE__*/_jsxs(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__*/_jsx(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__*/_jsxs(View, {
className: ellipsis ? 'van-ellipsis' : '',
style: item.titleStyle,
children: [item.title, (item.info !== null || item.dot) && /*#__PURE__*/_jsx(Info, {
info: item.info,
dot: item.dot,
className: "van-tab__title__info"
})]
})]
}, index);
})
})
}), /*#__PURE__*/_jsx(View, {
className: utils.bem('renderNavRight' + indexRef.current),
children: renderNavRight
})]
})
}), /*#__PURE__*/_jsx(View, {
className: "van-tabs__content",
onTouchStart: onTouchStart,
onTouchMove: onTouchMove,
onTouchEnd: onTouchEnd,
onTouchCancel: onTouchEnd,
children: /*#__PURE__*/_jsx(View, {
className: utils.bem('tabs__track', [{
animated: animated
}]) + ' van-tabs__track',
style: computed.trackStyle({
duration: duration,
currentIndex: currentIndex,
animated: animated
}),
children: newChildren
})
})]
}));
}
export default Tabs;