react-responsive-carousel
Version:
React Responsive Carousel
385 lines (303 loc) • 16.2 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _cssClasses = _interopRequireDefault(require("../cssClasses"));
var _dimensions = require("../dimensions");
var _CSSTranslate = _interopRequireDefault(require("../CSSTranslate"));
var _reactEasySwipe = _interopRequireDefault(require("react-easy-swipe"));
var _window = _interopRequireDefault(require("../shims/window"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(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); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var isKeyboardEvent = function isKeyboardEvent(e) {
return e.hasOwnProperty('key');
};
var Thumbs = /*#__PURE__*/function (_Component) {
_inherits(Thumbs, _Component);
var _super = _createSuper(Thumbs);
function Thumbs(_props) {
var _this;
_classCallCheck(this, Thumbs);
_this = _super.call(this, _props);
_defineProperty(_assertThisInitialized(_this), "itemsWrapperRef", void 0);
_defineProperty(_assertThisInitialized(_this), "itemsListRef", void 0);
_defineProperty(_assertThisInitialized(_this), "thumbsRef", void 0);
_defineProperty(_assertThisInitialized(_this), "setItemsWrapperRef", function (node) {
_this.itemsWrapperRef = node;
});
_defineProperty(_assertThisInitialized(_this), "setItemsListRef", function (node) {
_this.itemsListRef = node;
});
_defineProperty(_assertThisInitialized(_this), "setThumbsRef", function (node, index) {
if (!_this.thumbsRef) {
_this.thumbsRef = [];
}
_this.thumbsRef[index] = node;
});
_defineProperty(_assertThisInitialized(_this), "updateSizes", function () {
if (!_this.props.children || !_this.itemsWrapperRef || !_this.thumbsRef) {
return;
}
var total = _react.Children.count(_this.props.children);
var wrapperSize = _this.itemsWrapperRef.clientWidth;
var itemSize = _this.props.thumbWidth ? _this.props.thumbWidth : (0, _dimensions.outerWidth)(_this.thumbsRef[0]);
var visibleItems = Math.floor(wrapperSize / itemSize);
var showArrows = visibleItems < total;
var lastPosition = showArrows ? total - visibleItems : 0;
_this.setState(function (_state, props) {
return {
itemSize: itemSize,
visibleItems: visibleItems,
firstItem: showArrows ? _this.getFirstItem(props.selectedItem) : 0,
lastPosition: lastPosition,
showArrows: showArrows
};
});
});
_defineProperty(_assertThisInitialized(_this), "handleClickItem", function (index, item, e) {
if (!isKeyboardEvent(e) || e.key === 'Enter') {
var handler = _this.props.onSelectItem;
if (typeof handler === 'function') {
handler(index, item);
}
}
});
_defineProperty(_assertThisInitialized(_this), "onSwipeStart", function () {
_this.setState({
swiping: true
});
});
_defineProperty(_assertThisInitialized(_this), "onSwipeEnd", function () {
_this.setState({
swiping: false
});
});
_defineProperty(_assertThisInitialized(_this), "onSwipeMove", function (delta) {
var deltaX = delta.x;
if (!_this.state.itemSize || !_this.itemsWrapperRef || !_this.state.visibleItems) {
return false;
}
var leftBoundary = 0;
var childrenLength = _react.Children.count(_this.props.children);
var currentPosition = -(_this.state.firstItem * 100) / _this.state.visibleItems;
var lastLeftItem = Math.max(childrenLength - _this.state.visibleItems, 0);
var lastLeftBoundary = -lastLeftItem * 100 / _this.state.visibleItems; // prevent user from swiping left out of boundaries
if (currentPosition === leftBoundary && deltaX > 0) {
deltaX = 0;
} // prevent user from swiping right out of boundaries
if (currentPosition === lastLeftBoundary && deltaX < 0) {
deltaX = 0;
}
var wrapperSize = _this.itemsWrapperRef.clientWidth;
var position = currentPosition + 100 / (wrapperSize / deltaX); // if 3d isn't available we will use left to move
if (_this.itemsListRef) {
['WebkitTransform', 'MozTransform', 'MsTransform', 'OTransform', 'transform', 'msTransform'].forEach(function (prop) {
_this.itemsListRef.style[prop] = (0, _CSSTranslate.default)(position, '%', _this.props.axis);
});
}
return true;
});
_defineProperty(_assertThisInitialized(_this), "slideRight", function (positions) {
_this.moveTo(_this.state.firstItem - (typeof positions === 'number' ? positions : 1));
});
_defineProperty(_assertThisInitialized(_this), "slideLeft", function (positions) {
_this.moveTo(_this.state.firstItem + (typeof positions === 'number' ? positions : 1));
});
_defineProperty(_assertThisInitialized(_this), "moveTo", function (position) {
// position can't be lower than 0
position = position < 0 ? 0 : position; // position can't be higher than last postion
position = position >= _this.state.lastPosition ? _this.state.lastPosition : position;
_this.setState({
firstItem: position
});
});
_this.state = {
selectedItem: _props.selectedItem,
swiping: false,
showArrows: false,
firstItem: 0,
visibleItems: 0,
lastPosition: 0
};
return _this;
}
_createClass(Thumbs, [{
key: "componentDidMount",
value: function componentDidMount() {
this.setupThumbs();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.props.selectedItem !== this.state.selectedItem) {
this.setState({
selectedItem: this.props.selectedItem,
firstItem: this.getFirstItem(this.props.selectedItem)
});
}
if (this.props.children === prevProps.children) {
return;
} // This will capture any size changes for arrow adjustments etc.
// usually in the same render cycle so we don't see any flickers
this.updateSizes();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.destroyThumbs();
}
}, {
key: "setupThumbs",
value: function setupThumbs() {
// as the widths are calculated, we need to resize
// the carousel when the window is resized
(0, _window.default)().addEventListener('resize', this.updateSizes); // issue #2 - image loading smaller
(0, _window.default)().addEventListener('DOMContentLoaded', this.updateSizes); // when the component is rendered we need to calculate
// the container size to adjust the responsive behaviour
this.updateSizes();
}
}, {
key: "destroyThumbs",
value: function destroyThumbs() {
// removing listeners
(0, _window.default)().removeEventListener('resize', this.updateSizes);
(0, _window.default)().removeEventListener('DOMContentLoaded', this.updateSizes);
}
}, {
key: "getFirstItem",
value: function getFirstItem(selectedItem) {
var firstItem = selectedItem;
if (selectedItem >= this.state.lastPosition) {
firstItem = this.state.lastPosition;
}
if (selectedItem < this.state.firstItem + this.state.visibleItems) {
firstItem = this.state.firstItem;
}
if (selectedItem < this.state.firstItem) {
firstItem = selectedItem;
}
return firstItem;
}
}, {
key: "renderItems",
value: function renderItems() {
var _this2 = this;
return this.props.children.map(function (img, index) {
var itemClass = _cssClasses.default.ITEM(false, index === _this2.state.selectedItem);
var thumbProps = {
key: index,
ref: function ref(e) {
return _this2.setThumbsRef(e, index);
},
className: itemClass,
onClick: _this2.handleClickItem.bind(_this2, index, _this2.props.children[index]),
onKeyDown: _this2.handleClickItem.bind(_this2, index, _this2.props.children[index]),
'aria-label': "".concat(_this2.props.labels.item, " ").concat(index + 1),
style: {
width: _this2.props.thumbWidth
}
};
return /*#__PURE__*/_react.default.createElement("li", _extends({}, thumbProps, {
role: "button",
tabIndex: 0
}), img);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
if (!this.props.children) {
return null;
}
var isSwipeable = _react.Children.count(this.props.children) > 1; // show left arrow?
var hasPrev = this.state.showArrows && this.state.firstItem > 0; // show right arrow
var hasNext = this.state.showArrows && this.state.firstItem < this.state.lastPosition; // obj to hold the transformations and styles
var itemListStyles = {};
var currentPosition = -this.state.firstItem * (this.state.itemSize || 0);
var transformProp = (0, _CSSTranslate.default)(currentPosition, 'px', this.props.axis);
var transitionTime = this.props.transitionTime + 'ms';
itemListStyles = {
WebkitTransform: transformProp,
MozTransform: transformProp,
MsTransform: transformProp,
OTransform: transformProp,
transform: transformProp,
msTransform: transformProp,
WebkitTransitionDuration: transitionTime,
MozTransitionDuration: transitionTime,
MsTransitionDuration: transitionTime,
OTransitionDuration: transitionTime,
transitionDuration: transitionTime,
msTransitionDuration: transitionTime
};
return /*#__PURE__*/_react.default.createElement("div", {
className: _cssClasses.default.CAROUSEL(false)
}, /*#__PURE__*/_react.default.createElement("div", {
className: _cssClasses.default.WRAPPER(false),
ref: this.setItemsWrapperRef
}, /*#__PURE__*/_react.default.createElement("button", {
type: "button",
className: _cssClasses.default.ARROW_PREV(!hasPrev),
onClick: function onClick() {
return _this3.slideRight();
},
"aria-label": this.props.labels.leftArrow
}), isSwipeable ? /*#__PURE__*/_react.default.createElement(_reactEasySwipe.default, {
tagName: "ul",
className: _cssClasses.default.SLIDER(false, this.state.swiping),
onSwipeLeft: this.slideLeft,
onSwipeRight: this.slideRight,
onSwipeMove: this.onSwipeMove,
onSwipeStart: this.onSwipeStart,
onSwipeEnd: this.onSwipeEnd,
style: itemListStyles,
innerRef: this.setItemsListRef,
allowMouseEvents: this.props.emulateTouch
}, this.renderItems()) : /*#__PURE__*/_react.default.createElement("ul", {
className: _cssClasses.default.SLIDER(false, this.state.swiping),
ref: function ref(node) {
return _this3.setItemsListRef(node);
},
style: itemListStyles
}, this.renderItems()), /*#__PURE__*/_react.default.createElement("button", {
type: "button",
className: _cssClasses.default.ARROW_NEXT(!hasNext),
onClick: function onClick() {
return _this3.slideLeft();
},
"aria-label": this.props.labels.rightArrow
})));
}
}]);
return Thumbs;
}(_react.Component);
exports.default = Thumbs;
_defineProperty(Thumbs, "displayName", 'Thumbs');
_defineProperty(Thumbs, "defaultProps", {
axis: 'horizontal',
labels: {
leftArrow: 'previous slide / item',
rightArrow: 'next slide / item',
item: 'slide item'
},
selectedItem: 0,
thumbWidth: 80,
transitionTime: 350
});