zarm-web
Version:
基于 React 的桌面端UI库
476 lines (393 loc) • 19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames3 = _interopRequireDefault(require("classnames"));
var _dom = _interopRequireDefault(require("../utils/dom"));
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; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { 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) { 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 _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; }
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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
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); }
var noop = function noop() {};
var Slider =
/*#__PURE__*/
function (_Component) {
_inherits(Slider, _Component);
function Slider(props) {
var _this;
_classCallCheck(this, Slider);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Slider).call(this, props));
_this.draggingPayload = void 0;
_this.offsetLeft = void 0;
_this.isTouchSuported = void 0;
_this.sliderBody = void 0;
_this.removeTransition = void 0;
var handleAmount = _this.props.handleAmount;
var states = {};
var i = 0;
while (i < handleAmount) {
states["currentValue".concat(i)] = 0;
i += 1;
}
_this.state = states;
_this.onHandleDown = _this.onHandleDown.bind(_assertThisInitialized(_this));
_this.onHandleMove = _this.onHandleMove.bind(_assertThisInitialized(_this));
_this.onHandleUp = _this.onHandleUp.bind(_assertThisInitialized(_this));
_this.clickhandler = _this.clickhandler.bind(_assertThisInitialized(_this));
_this.draggingPayload = {
isDragging: false,
prevX: 0,
isThreshhold: false,
// 是否到达阈值
handleMove: undefined,
// 记录匿名函数的指针
handleUp: undefined // 记录匿名函数的指针
};
return _this;
}
_createClass(Slider, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
setTimeout(function () {
var _this2$props = _this2.props,
min = _this2$props.min,
max = _this2$props.max,
handleAmount = _this2$props.handleAmount,
defaultValue = _this2$props.defaultValue;
var states = {};
var i = 0;
var dv = _this2.isArray(defaultValue) ? defaultValue : [defaultValue];
while (i < handleAmount) {
if (dv[i] === undefined) {
dv[i] = min;
}
states["currentValue".concat(i)] = _this2.validateDefault(dv[i], min, max);
i += 1;
}
_this2.setState(states);
}, 0);
this.offsetLeft = _dom.default.getLeft(this.sliderBody);
this.isTouchSuported = _dom.default.probTouch();
}
}, {
key: "componentWillReceiveProps",
value: function componentWillReceiveProps(nextProps) {
var _this3 = this;
setTimeout(function () {
var min = nextProps.min,
max = nextProps.max,
handleAmount = nextProps.handleAmount,
defaultValue = nextProps.defaultValue;
var states = {};
var i = 0;
var dv = _this3.isArray(defaultValue) ? defaultValue : [defaultValue];
while (i < handleAmount) {
if (dv[i] === undefined) {
dv[i] = min;
}
states["currentValue".concat(i)] = _this3.validateDefault(dv[i], min, max);
i += 1;
}
_this3.setState(states);
}, 0);
}
}, {
key: "onHandleDown",
value: function onHandleDown(i) {
var _this4 = this;
return function (e) {
e.stopPropagation();
e.preventDefault();
var addBodyListener = document.body.addEventListener.bind(document.body);
_this4.draggingPayload.handleMove = _this4.onHandleMove(i);
_this4.draggingPayload.handleUp = _this4.onHandleUp();
if (!_this4.isTouchSuported) {
addBodyListener('mousemove', _this4.draggingPayload.handleMove, false);
addBodyListener('mouseup', _this4.draggingPayload.handleUp, false);
} else {
addBodyListener('touchmove', _this4.draggingPayload.handleMove, false);
addBodyListener('touchend', _this4.draggingPayload.handleUp, false);
} // 移除初始化时的transition效果,否则会影响slider的推动
_this4.removeTransition = true;
_this4.draggingPayload.isDragging = true;
_this4.draggingPayload.prevX = _this4.isTouchSuported ? e.touches[0].clientX : e.clientX;
};
}
}, {
key: "onHandleMove",
value: function onHandleMove(i) {
var _this5 = this;
return function (e) {
e.stopPropagation();
e.preventDefault();
if (_this5.draggingPayload.isDragging) {
var _this5$props = _this5.props,
min = _this5$props.min,
max = _this5$props.max,
step = _this5$props.step,
styleWidth = _this5$props.styleWidth,
getValue = _this5$props.getValue,
isPass = _this5$props.isPass;
var mouseMovedDist = (_this5.isTouchSuported && e.touches && e.touches[0] ? e.touches[0].clientX : e.clientX) - _this5.draggingPayload.prevX;
var percent = mouseMovedDist / (styleWidth || 200);
var value = percent * (max - min);
if (Math.abs(value) >= step) {
// 寻找最接近value的step倍数
var closestStepToValue = Math.round(value / step) * step; // eslint-disable-next-line react/destructuring-assignment
var newValue = _this5.state["currentValue".concat(i)] + closestStepToValue;
if (!isPass && _this5.isHandleMeet(i, newValue)) {
return;
}
_this5.draggingPayload.prevX = _this5.isTouchSuported && e.touches && e.touches[0] ? e.touches[0].clientX : e.clientX;
if (newValue <= max && newValue >= min) {
if (getValue) {
getValue(newValue, i);
}
_this5.draggingPayload.isThreshhold = false;
_this5.setState(_defineProperty({}, "currentValue".concat(i), newValue));
} else if (newValue > max && !_this5.draggingPayload.isThreshhold) {
if (getValue) {
getValue(max, i);
}
_this5.draggingPayload.isThreshhold = true;
_this5.setState(_defineProperty({}, "currentValue".concat(i), max));
} else if (newValue < min && !_this5.draggingPayload.isThreshhold) {
if (getValue) {
getValue(min, i);
}
_this5.draggingPayload.isThreshhold = true;
_this5.setState(_defineProperty({}, "currentValue".concat(i), min));
}
}
}
};
}
}, {
key: "onHandleUp",
value: function onHandleUp() {
var _this6 = this;
return function (e) {
e.stopPropagation();
e.preventDefault();
var removeBodyListener = document.body.removeEventListener.bind(document.body);
if (!_this6.isTouchSuported) {
removeBodyListener('mousemove', _this6.draggingPayload.handleMove, false);
removeBodyListener('mouseup', _this6.draggingPayload.handleUp, false);
} else {
removeBodyListener('touchmove', _this6.draggingPayload.handleMove, false);
removeBodyListener('touchend', _this6.draggingPayload.handleUp, false);
} // fix ‘click event triggered after mouseup’ bug
setTimeout(function () {
_this6.draggingPayload.isDragging = false;
}, 0);
};
}
}, {
key: "clickhandler",
value: function clickhandler(e) {
e.stopPropagation();
e.preventDefault();
if (this.draggingPayload.isDragging) {
return;
}
this.removeTransition = false;
var _this$props = this.props,
min = _this$props.min,
max = _this$props.max,
step = _this$props.step,
styleWidth = _this$props.styleWidth,
getValue = _this$props.getValue; // 此处用pageX,兼容有x轴滚动条的情况
var mouseLeft = e.pageX - this.offsetLeft;
if (mouseLeft < 0 || mouseLeft > (styleWidth || 200)) {
return;
}
var percent = mouseLeft / (styleWidth || 200);
var value = Math.floor(percent * (max - min)) + min; // 寻找最接近的handle的value值
var closestHandleValue = this.findClosestHandle(value);
var handleIndex = this.findHandleIndex(this.state, closestHandleValue);
var delta = value - closestHandleValue;
if (Math.abs(delta) >= step) {
var closestStepToDelta = Math.round(delta / step) * step;
if (getValue) {
getValue( // eslint-disable-next-line react/destructuring-assignment
this.state["currentValue".concat(handleIndex)] + closestStepToDelta, handleIndex);
}
this.setState(_defineProperty({}, "currentValue".concat(handleIndex), // eslint-disable-next-line react/destructuring-assignment,react/no-access-state-in-setstate
this.state["currentValue".concat(handleIndex)] + closestStepToDelta));
}
} // eslint-disable-next-line
}, {
key: "validateDefault",
value: function validateDefault(defaultValue, min, max) {
// eslint-disable-next-line
return defaultValue < min ? min : defaultValue > max ? max : defaultValue;
} // eslint-disable-next-line
}, {
key: "isArray",
value: function isArray(ele) {
return Object.prototype.toString.call(ele) === '[object Array]';
}
}, {
key: "findClosestHandle",
value: function findClosestHandle(value) {
var _this7 = this;
var stateKeys = Object.keys(this.state); // eslint-disable-next-line react/destructuring-assignment
var states = stateKeys.map(function (v) {
return _this7.state[v];
});
/* eslint-disable */
return states.reduce(function (pre, cur) {
return value > Math.max(pre, cur) ? Math.max(pre, cur) : value < Math.min(pre, cur) ? Math.min(pre, cur) : Math.abs(value - pre) < Math.abs(value - cur) ? pre : cur;
}, this.state["currentValue".concat(0)]);
/* eslint-enable */
}
}, {
key: "findHandleIndex",
value: function findHandleIndex(state, v) {
var _this8 = this;
var states = Object.keys(state); // eslint-disable-next-line react/destructuring-assignment
states = states.map(function (value) {
return _this8.state[value];
});
return states.indexOf(v);
} // 判断handle是否互相接触
}, {
key: "isHandleMeet",
value: function isHandleMeet(index, value) {
var _this9 = this;
var _this$props2 = this.props,
max = _this$props2.max,
min = _this$props2.min;
var stateKeys = Object.keys(this.state); // eslint-disable-next-line react/destructuring-assignment
var states = stateKeys.map(function (v) {
return _this9.state[v];
});
states.sort(function (a, b) {
return a - b;
}); // eslint-disable-next-line react/destructuring-assignment
var v = this.state["currentValue".concat(index)];
var vIndex = states.indexOf(v);
var vMax = states[vIndex + 1] ? states[vIndex + 1] : max;
var vMin = states[vIndex - 1] ? states[vIndex - 1] : min;
return !(value > vMin && value < vMax);
}
}, {
key: "render",
value: function render() {
var _classnames,
_classnames2,
_this10 = this;
var _this$props3 = this.props,
prefixCls = _this$props3.prefixCls,
min = _this$props3.min,
max = _this$props3.max,
styleWidth = _this$props3.styleWidth,
isRound = _this$props3.isRound,
isSolid = _this$props3.isSolid,
showTip = _this$props3.showTip,
tipAlwayShow = _this$props3.tipAlwayShow,
customCls = _this$props3.customCls,
theme = _this$props3.theme,
handleAmount = _this$props3.handleAmount,
isRange = _this$props3.isRange,
rangeColors = _this$props3.rangeColors;
var styleWidthObj = {
width: "".concat(styleWidth || 200, "px")
};
var tipClass = (0, _classnames3.default)((_classnames = {}, _defineProperty(_classnames, "".concat(prefixCls, "-tip"), true), _defineProperty(_classnames, "".concat(prefixCls, "-tip-show"), tipAlwayShow), _classnames));
var customClass = (0, _classnames3.default)((_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefixCls, "-wraper"), true), _defineProperty(_classnames2, customCls, !!customCls), _defineProperty(_classnames2, "round", 'round' in this.props || isRound), _defineProperty(_classnames2, "solid", 'solid' in this.props || isSolid), _defineProperty(_classnames2, "theme-".concat(theme), !!theme), _classnames2));
var transitionArray = ['WebkitTransition', 'MozTransition', 'msTransition', 'OTransition', 'Transition']; // eslint-disable-next-line
var rangeColorArray = rangeColors ? this.isArray(rangeColors) ? rangeColors : [rangeColors] : ['#fff', '#eee'];
var handles = [];
var i = 0;
var styleObjArr;
while (i < handleAmount) {
// eslint-disable-next-line
var percent = (this.state["currentValue".concat(i)] - min) / (max - min) * 100;
styleObjArr = {
handle: {
left: "".concat(percent, "%")
},
back: {
width: "".concat(percent, "%"),
backgroundColor: isRange && rangeColorArray[i],
zIndex: 10 - i
}
};
if (!this.removeTransition) {
// eslint-disable-next-line
transitionArray.forEach(function (transition) {
styleObjArr.handle[transition] = 'left 0.6s ease-out';
styleObjArr.back[transition] = 'width 0.6s ease-out';
});
}
handles.push(_react.default.createElement("div", {
key: "handleBack".concat(i)
}, _react.default.createElement("div", {
key: "Back".concat(i),
className: "".concat(prefixCls, "-back"),
style: styleObjArr.back
}), _react.default.createElement("span", {
key: "handle".concat(i),
className: "".concat(prefixCls, "-handle"),
style: styleObjArr.handle,
onMouseDown: !this.isTouchSuported ? this.onHandleDown(i) : noop,
onMouseMove: !this.isTouchSuported ? this.onHandleMove(i) : noop,
onMouseUp: !this.isTouchSuported ? this.onHandleUp() : noop,
onClick: function onClick(e) {
return e.stopPropagation();
},
onTouchStart: this.isTouchSuported ? this.onHandleDown(i) : noop,
onTouchMove: this.isTouchSuported ? this.onHandleMove(i) : noop,
onTouchEnd: this.isTouchSuported ? this.onHandleMove(i) : noop
}, showTip && _react.default.createElement("em", {
className: tipClass
}, this.state["currentValue".concat(i)]))));
i += 1;
}
return _react.default.createElement("div", {
className: customClass
}, _react.default.createElement("div", {
className: "".concat(prefixCls, "-horizontal"),
style: styleWidthObj,
ref: function ref(sliderBody) {
_this10.sliderBody = sliderBody;
},
onClick: this.clickhandler
}, handles));
}
}]);
return Slider;
}(_react.Component);
Slider.defaultProps = {
prefixCls: 'ui-slider',
min: 0,
step: 1,
defaultValue: 0,
showTip: true,
tipAlwayShow: false,
handleAmount: 1,
isRound: false,
isSolid: false,
isRange: false,
isPass: true,
theme: 'default',
styleWidth: 200,
rangeColor: '',
customCls: '',
getValue: function getValue() {}
};
var _default = Slider;
exports.default = _default;