@antmjs/vantui
Version:
一套适用于Taro3及React的vantui组件库
443 lines (435 loc) • 19.1 kB
JavaScript
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.Swiper_ = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _taro = require("@tarojs/taro");
var _components = require("@tarojs/components");
var _defaultProps = require("../default-props");
var _utils = require("./utils");
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["children", "direction", "className", "pageContent", "onChange", "initPage", "paginationColor", "paginationVisible", "touchable", "isPreventDefault", "isStopPropagation", "autoPlay", "isCenter", "style", "height", "width", "loop", "duration", "containerSize"];
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/no-unused-vars */
var defaultProps = {
width: 0,
height: 0,
duration: 500,
initPage: 0,
autoPlay: 0,
direction: 'horizontal',
paginationColor: '#fff',
paginationVisible: false,
loop: true,
touchable: true,
isPreventDefault: true,
isStopPropagation: true,
isCenter: false,
className: ''
// infinite: true,
};
var getValidNumber = function getValidNumber(num) {
if (typeof num === 'number') {
return num;
} else if (typeof num === 'string') {
return isNaN(Number(num.replace('px', ''))) ? 0 : Number(num.replace('px', ''));
} else return 0;
};
var Swiper = function Swiper(props, ref) {
var _classNames, _classNames2;
var _useState = (0, _react.useState)((0, _defaultProps.get)().Swiper),
_useState2 = (0, _slicedToArray2.default)(_useState, 1),
d = _useState2[0];
var propSwiper = _objectSpread(_objectSpread(_objectSpread({}, defaultProps), d), props);
var children = propSwiper.children,
direction = propSwiper.direction,
className = propSwiper.className,
pageContent = propSwiper.pageContent,
onChange = propSwiper.onChange,
_propSwiper$initPage = propSwiper.initPage,
initPage = _propSwiper$initPage === void 0 ? 0 : _propSwiper$initPage,
paginationColor = propSwiper.paginationColor,
paginationVisible = propSwiper.paginationVisible,
touchable = propSwiper.touchable,
isPreventDefault = propSwiper.isPreventDefault,
isStopPropagation = propSwiper.isStopPropagation,
autoPlay = propSwiper.autoPlay,
isCenter = propSwiper.isCenter,
style = propSwiper.style,
height = propSwiper.height,
width = propSwiper.width,
loop = propSwiper.loop,
duration = propSwiper.duration,
containerSize = propSwiper.containerSize,
rest = (0, _objectWithoutProperties2.default)(propSwiper, _excluded);
var isVertical = direction === 'vertical';
var timer = (0, _react.useRef)(null);
var containerRef = (0, _react.useRef)(null);
var innerRef = (0, _react.useRef)(null);
var _useState3 = (0, _react.useState)(Math.random().toString(36).slice(-8)),
_useState4 = (0, _slicedToArray2.default)(_useState3, 1),
refRandomId = _useState4[0];
var _useState5 = (0, _react.useState)(false),
_useState6 = (0, _slicedToArray2.default)(_useState5, 2),
moving = _useState6[0],
setmoving = _useState6[1];
// eslint-disable-next-line prefer-const
var _useState7 = (0, _react.useState)(typeof initPage === 'number' ? initPage : 0),
_useState8 = (0, _slicedToArray2.default)(_useState7, 2),
active = _useState8[0],
setActive_ = _useState8[1];
var setActive = function setActive(a) {
active = a;
setActive_(a);
};
var _useState9 = (0, _react.useState)(getValidNumber(width)),
_useState10 = (0, _slicedToArray2.default)(_useState9, 2),
W = _useState10[0],
setW = _useState10[1];
var _useState11 = (0, _react.useState)(getValidNumber(height)),
_useState12 = (0, _slicedToArray2.default)(_useState11, 2),
H = _useState12[0],
setH = _useState12[1];
var _useState13 = (0, _react.useState)(false),
_useState14 = (0, _slicedToArray2.default)(_useState13, 2),
showToDo = _useState14[0],
setShowToDo = _useState14[1];
var _useState15 = (0, _react.useState)({
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
offsetX: 0,
offsetY: 0,
stateDirection: '',
delta: 0
}),
_useState16 = (0, _slicedToArray2.default)(_useState15, 1),
touch = _useState16[0];
var size = (0, _react.useMemo)(function () {
return isVertical ? H : W;
}, [H, W, isVertical]);
var _useMemo = (0, _react.useMemo)(function () {
var childCount = 0;
var childFirst = children === null || children === void 0 ? void 0 : children[0];
var childs = _react.Children.map(children, function (child) {
if (! /*#__PURE__*/(0, _react.isValidElement)(child)) return null;
childCount++;
return child;
}) || [];
var resetChilds = (0, _toConsumableArray2.default)(childs);
var childLast = children === null || children === void 0 ? void 0 : children[childCount - 1];
var pageCount = childCount === 2 ? 2 : childCount;
if (childCount === 2) {
if (childFirst) {
resetChilds.push(childFirst);
}
childCount += 1;
if (childLast) {
resetChilds.unshift(childLast);
}
childCount += 1;
}
return {
childs: childs,
childCount: childCount,
pageCount: pageCount,
resetChilds: resetChilds
};
}, [children]),
childs = _useMemo.childs,
childCount = _useMemo.childCount,
pageCount = _useMemo.pageCount,
resetChilds = _useMemo.resetChilds;
// 重置 全部位移信息
var touchReset = (0, _react.useCallback)(function () {
touch.startX = 0;
touch.startY = 0;
touch.deltaX = 0;
touch.deltaY = 0;
touch.offsetX = 0;
touch.offsetY = 0;
touch.delta = 0;
touch.stateDirection = '';
}, [touch]);
// 取值 方法
var range = (0, _react.useCallback)(function (num, min, max) {
return Math.min(Math.max(num, min), max);
}, []);
var getMinOffset = (0, _react.useCallback)(function () {
return size - Number(size) * childCount;
}, [childCount, size]);
// 计算位移
var getOffset = (0, _react.useCallback)(function (active) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var minOffset = getMinOffset();
var currentPosition = active * Number(size);
if (!loop) {
currentPosition = Math.min(currentPosition, -minOffset);
}
var targetOffset = offset - currentPosition;
if (!loop) {
targetOffset = range(targetOffset, minOffset, 0);
}
return targetOffset;
}, [getMinOffset, loop, range, size]);
var wrapperStyle = (0, _react.useMemo)(function () {
var style = {};
if (isVertical) {
style.height = size * childCount ? "".concat(size * childCount, "px") : '100%';
} else {
style.width = size * childCount ? "".concat(size * childCount, "px") : '100%';
}
return style;
}, [childCount, isVertical, size]);
var contentClass = (0, _classnames.default)((_classNames = {}, (0, _defineProperty2.default)(_classNames, 'van-swiper__inner', true), (0, _defineProperty2.default)(_classNames, 'van-swiper__vertical', isVertical), _classNames));
var touchStart = (0, _react.useCallback)(function (e) {
var _e$touches$, _e$touches$2;
if (!touchable) return;
if (moving) return;
touchReset();
touch.startX = (e === null || e === void 0 ? void 0 : (_e$touches$ = e.touches[0]) === null || _e$touches$ === void 0 ? void 0 : _e$touches$.clientX) || 0;
touch.startY = (e === null || e === void 0 ? void 0 : (_e$touches$2 = e.touches[0]) === null || _e$touches$2 === void 0 ? void 0 : _e$touches$2.clientY) || 0;
}, [moving, touch, touchReset, touchable]);
// 触摸事件移动
var touchMove = (0, _react.useCallback)(function (e) {
var _e$touches$3, _e$touches$4;
if (!touchable) return;
if (timer.current) {
clearInterval(timer.current);
timer.current = null;
}
if (moving) return;
touch.deltaX = ((e === null || e === void 0 ? void 0 : (_e$touches$3 = e.touches[0]) === null || _e$touches$3 === void 0 ? void 0 : _e$touches$3.clientX) || 0) - touch.startX;
touch.deltaY = ((e === null || e === void 0 ? void 0 : (_e$touches$4 = e.touches[0]) === null || _e$touches$4 === void 0 ? void 0 : _e$touches$4.clientY) || 0) - touch.startY;
touch.offsetX = Math.abs(touch.deltaX);
touch.offsetY = Math.abs(touch.deltaY);
touch.delta = isVertical ? touch.deltaY : touch.deltaX;
if (!touch.stateDirection) {
touch.stateDirection = (0, _utils.getDirection)(touch.offsetX, touch.offsetY);
}
var offset = getOffset(active) + touch.delta;
innerRef.current.style.transitionDuration = "0ms";
if (isVertical) {
innerRef.current.style.transform = "translate3d(0, ".concat(offset, "px, 0)");
} else {
innerRef.current.style.transform = "translate3d(".concat(offset, "px, 0, 0)");
}
}, [moving, touch, isVertical, getOffset, active, touchable]);
// eslint-disable-next-line react-hooks/exhaustive-deps
var setInnertStyle = function setInnertStyle(active, _duration) {
var delta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var offset = delta || getOffset(active);
innerRef.current.style.transitionDuration = "".concat(_duration, "ms");
if (isVertical) {
innerRef.current.style.transform = "translate3d(0, ".concat(offset, "px, 0)");
} else {
innerRef.current.style.transform = "translate3d(".concat(offset, "px, 0, 0)");
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
var moveTo = function moveTo(activeNew, touchEnd, callback) {
setmoving(true);
if (activeNew === active && !touchEnd) return;
// 手动滑动的变更
if (touchEnd) {
var step = Math.ceil(Math.abs(touch.delta / size));
if (touch.delta > 0) {
activeNew = active - step;
activeNew = activeNew < 0 ? childCount - 1 : activeNew;
} else if (touch.delta < 0) {
activeNew = active + step;
activeNew = activeNew > childCount - 1 ? 0 : activeNew;
}
}
var _duration = duration;
var timeout = 0;
// 第一张和最后一样的特殊情况
if (active === 0 && activeNew === childCount - 1) {
_duration = 0;
timeout = duration || 0 + 16.66;
setInnertStyle(active, duration, size);
} else if (active === childCount - 1 && activeNew === 0) {
_duration = 0;
timeout = duration || 0 + 16.66;
setInnertStyle(active, duration, -childCount * size);
}
setTimeout(function () {
setmoving(false);
setActive(activeNew);
setInnertStyle(activeNew, _duration);
callback === null || callback === void 0 ? void 0 : callback();
}, timeout);
};
var startPlay = (0, _react.useCallback)(function () {
if (autoPlay && autoPlay !== '0') {
timer.current = setInterval(function () {
moveTo(active + 1 > childCount - 1 ? 0 : active + 1);
}, Number(autoPlay));
}
}, [active, autoPlay, childCount, moveTo]);
var onTouchEnd = (0, _react.useCallback)(function () {
if (!touchable) return;
if (touch.stateDirection === direction) {
moveTo(active, true, function () {
startPlay();
});
}
}, [touchable, touch.stateDirection, direction, moveTo, active, startPlay]);
var itemStyle = (0, _react.useCallback)(function (index) {
if (childCount === 1) {
return {
transform: "translate3d(0, 0, 0)",
transitionDuration: "0ms"
};
}
if (index === 0 && active === childCount - 1) {
if (isVertical) {
return {
transform: "translate3d(0, ".concat(size * childCount, "px, 0)"),
transitionDuration: "0ms"
};
} else {
return {
transform: "translate3d(".concat(size * childCount, "px, 0, 0)"),
transitionDuration: "0ms"
};
}
} else if (index === childCount - 1 && active === 0) {
if (isVertical) {
return {
transform: "translate3d(0, ".concat(-size * childCount, "px, 0)"),
transitionDuration: "0ms"
};
} else {
return {
transform: "translate3d(".concat(-size * childCount, "px, 0, 0)"),
transitionDuration: "0ms"
};
}
}
return {};
}, [active, childCount, isVertical, size]);
(0, _react.useImperativeHandle)(ref, function () {
return {
to: function to(n) {
return moveTo(n);
},
prev: function prev() {
return moveTo(active - 1 < 0 ? childCount - 1 : active - 1);
},
next: function next() {
return moveTo(active + 1 > childCount - 1 ? 0 : active + 1);
}
};
});
(0, _react.useEffect)(function () {
onChange === null || onChange === void 0 ? void 0 : onChange((active + pageCount) % pageCount);
}, [active, pageCount, onChange]);
(0, _taro.useDidShow)(function () {
setShowToDo(true);
startPlay();
});
(0, _react.useEffect)(function () {
setShowToDo(true);
return function () {
setShowToDo(false);
clearInterval(timer.current);
};
}, []);
(0, _taro.useDidHide)(function () {
setShowToDo(false);
clearInterval(timer.current);
});
(0, _react.useEffect)(function () {
if (showToDo) {
(0, _taro.nextTick)(function () {
// h5环境容器宽度100%渲染延迟
setTimeout(function () {
(0, _taro.createSelectorQuery)().select('#container-' + refRandomId).boundingClientRect().exec(function (ret) {
if (ret && ret[0]) {
if (!W) setW(ret[0].width);
if (!H) setH(ret[0].height);
}
});
}, 100);
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showToDo]);
(0, _react.useEffect)(function () {
if (size) {
if (active) {
setInnertStyle(active, 0);
}
clearInterval(timer.current);
if (childCount > 1) startPlay();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [size, childCount]);
var containerStyle = (0, _react.useMemo)(function () {
var _style = _objectSpread({
width: W || '100%',
height: H || '100%'
}, style);
if (containerSize) {
_style[isVertical ? 'height' : 'width'] = containerSize;
}
return _style;
}, [H, W, containerSize, isVertical, style]);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.View, _objectSpread(_objectSpread({
className: "van-swiper ".concat(className),
ref: containerRef
}, rest), {}, {
id: 'container-' + refRandomId,
onTouchStart: touchStart,
onTouchMove: touchMove,
onTouchEnd: onTouchEnd
// @ts-ignore
,
catchMove: isVertical,
style: containerStyle,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: contentClass,
style: wrapperStyle,
ref: innerRef,
children: _react.Children.map(resetChilds, function (child, index) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: 'van-swiper-item-wrapper',
style: _objectSpread({
width: W || '100%',
height: H || '100%'
}, itemStyle(index)),
children: child
}, index);
})
}), paginationVisible && !('pageContent' in propSwiper) ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
className: (0, _classnames.default)((_classNames2 = {}, (0, _defineProperty2.default)(_classNames2, 'van-swiper__pagination', true), (0, _defineProperty2.default)(_classNames2, 'van-swiper__pagination-vertical', isVertical), _classNames2)),
children: _react.Children.map(childs, function (_, index) {
var _classNames3;
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Text, {
style: (active + pageCount) % pageCount === index ? {
backgroundColor: paginationColor
} : undefined,
className: (0, _classnames.default)((_classNames3 = {}, (0, _defineProperty2.default)(_classNames3, 'van-swiper__pagination-item', true), (0, _defineProperty2.default)(_classNames3, "active", (active + pageCount) % pageCount === index), _classNames3))
}, index);
})
}) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.View, {
children: pageContent
})]
}));
};
var Swiper_ = /*#__PURE__*/(0, _react.forwardRef)(Swiper);
exports.Swiper_ = Swiper_;
var _default = Swiper_;
exports.default = _default;
;