@alifd/next
Version:
A configurable component library for web built on React.
602 lines (497 loc) • 18.7 kB
JavaScript
'use strict';
exports.__esModule = true;
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _class, _temp;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _reactLifecyclesCompat = require('react-lifecycles-compat');
var _icon = require('../icon');
var _icon2 = _interopRequireDefault(_icon);
var _util = require('../util');
var _zhCn = require('../locale/zh-cn');
var _zhCn2 = _interopRequireDefault(_zhCn);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var noop = _util.func.noop,
bindCtx = _util.func.bindCtx;
var ENTER = _util.KEYCODE.ENTER,
LEFT = _util.KEYCODE.LEFT,
UP = _util.KEYCODE.UP,
RIGHT = _util.KEYCODE.RIGHT,
DOWN = _util.KEYCODE.DOWN;
var supportKeys = [ENTER, LEFT, UP, RIGHT, DOWN];
// 评分组件的大小与icon的大小映射关系
var ICON_SIZE_MAP = {
small: 'xs',
medium: 'small',
large: 'medium'
};
/** Rating */
var Rating = (_temp = _class = function (_Component) {
(0, _inherits3.default)(Rating, _Component);
Rating.currentValue = function currentValue(min, max, hoverValue, stateValue) {
var value = hoverValue ? hoverValue : stateValue;
value = value >= max ? max : value;
value = value <= min ? min : value;
return value || 0;
};
function Rating(props) {
(0, _classCallCheck3.default)(this, Rating);
var _this = (0, _possibleConstructorReturn3.default)(this, _Component.call(this, props));
_this.saveRef = function (ref, i) {
_this['refs-rating-icon-' + i] = ref;
};
_this.state = {
value: 'value' in props ? props.value : props.defaultValue,
hoverValue: 0,
cleanedValue: null,
iconSpace: 0,
iconSize: 0,
clicked: false // 标记组件是否被点击过
};
_this.timer = null;
bindCtx(_this, ['handleClick', 'handleHover', 'handleLeave', 'onKeyDown']);
return _this;
}
Rating.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var state = {};
if ('value' in nextProps) {
state.value = nextProps.value || 0;
}
if ('disabled' in nextProps || 'readOnly' in nextProps || 'isPreview' in nextProps || 'renderPreview' in nextProps) {
state.disabled = nextProps.disabled || nextProps.readOnly || nextProps.isPreview && !('renderPreview' in nextProps);
}
return state;
};
Rating.prototype.componentDidMount = function componentDidMount() {
this.getRenderResult();
};
Rating.prototype.componentWillUnmount = function componentWillUnmount() {
this.clearTimer();
};
// 清除延时
Rating.prototype.clearTimer = function clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
};
Rating.prototype.getRenderResult = function getRenderResult() {
var count = this.props.count;
var _state = this.state,
iconSpace = _state.iconSpace,
iconSize = _state.iconSize;
var icon = this['refs-rating-icon-0'];
if (icon && this.underlayNode) {
var newIconSize = icon.offsetWidth;
var newIconSpace = (this.underlayNode.offsetWidth - count * newIconSize) / (count + 1);
if (newIconSize !== iconSize || newIconSpace !== iconSpace) {
this.setState({
iconSpace: newIconSpace,
iconSize: newIconSize
});
}
}
};
Rating.prototype.getValue = function getValue(e) {
// 如定位不准,优先纠正定位
this.getRenderResult();
var _props = this.props,
allowHalf = _props.allowHalf,
count = _props.count,
rtl = _props.rtl;
var _state2 = this.state,
iconSpace = _state2.iconSpace,
iconSize = _state2.iconSize;
var pos = e.pageX - this.underlayNode.getBoundingClientRect().left;
var fullNum = Math.floor(pos / (iconSpace + iconSize));
var surplusNum = (pos - fullNum * (iconSpace + iconSize) - iconSpace) / iconSize;
var value = Number(fullNum) + Number(surplusNum.toFixed(1));
if (value >= count) {
value = count;
} else if (allowHalf) {
var floorValue = Math.floor(value);
if (rtl) {
value = value - 0.5 >= floorValue ? floorValue + 1.5 : floorValue + 1;
} else {
value = value - 0.5 >= floorValue ? floorValue + 1 : floorValue + 0.5;
}
} else {
value = Math.floor(value) + 1;
}
return rtl ? count - value + 1 : value;
};
Rating.prototype.handleHover = function handleHover(e) {
var _this2 = this;
if (this.state.disabled) {
return;
}
var value = this.getValue(e);
var onHoverChange = this.props.onHoverChange;
var cleanedValue = this.state.cleanedValue;
if (cleanedValue !== value) {
this.clearTimer();
this.timer = setTimeout(function () {
_this2.setState({ hoverValue: value, cleanedValue: null }, function () {
onHoverChange(value);
});
}, 0);
}
};
Rating.prototype.handleLeave = function handleLeave() {
var onHoverChange = this.props.onHoverChange;
if (this.state.disabled) {
return;
}
this.clearTimer();
this.setState({
hoverValue: 0,
cleanedValue: null
});
onHoverChange(undefined);
};
Rating.prototype.onKeyDown = function onKeyDown(e) {
if (this.state.disabled) {
return;
}
var _props2 = this.props,
onKeyDown = _props2.onKeyDown,
count = _props2.count;
var disabled = this.state.disabled;
if (disabled || supportKeys.indexOf(e.keyCode) < 0) {
return !onKeyDown || onKeyDown(e);
}
var _state3 = this.state,
hoverValue = _state3.hoverValue,
value = _state3.value;
var changingValue = hoverValue;
if (changingValue === 0) {
changingValue = value;
}
switch (e.keyCode) {
case DOWN:
case RIGHT:
if (changingValue < count) {
changingValue += 1;
} else {
changingValue = 1;
}
this.handleChecked(changingValue);
break;
case UP:
case LEFT:
if (changingValue > 1) {
changingValue -= 1;
} else {
changingValue = count;
}
this.handleChecked(changingValue);
break;
case ENTER:
this.props.onChange(changingValue);
this.setState({
value: changingValue,
hoverValue: changingValue
});
break;
}
return !onKeyDown || onKeyDown(e);
};
Rating.prototype.handleChecked = function handleChecked(index) {
if (this.state.disabled) {
return;
}
this.setState({ hoverValue: index });
};
Rating.prototype.handleClick = function handleClick(e) {
var _this3 = this;
if (this.state.disabled) {
return;
}
var allowClear = this.props.allowClear;
var value = this.state.value;
var newValue = this.getValue(e);
var isReset = false;
if (allowClear) {
isReset = newValue === value;
}
this.handleLeave();
if (newValue < 0) {
return;
}
if (!('value' in this.props)) {
this.setState({ value: isReset ? 0 : newValue, clicked: true });
}
this.props.onChange(isReset ? 0 : newValue);
setTimeout(function () {
_this3.setState({ clicked: false });
}, 100);
this.setState({
cleanedValue: isReset ? newValue : null
});
};
Rating.prototype.getOverlayWidth = function getOverlayWidth() {
var _state4 = this.state,
hoverValue = _state4.hoverValue,
iconSpace = _state4.iconSpace,
iconSize = _state4.iconSize;
if (!iconSpace || !iconSize) {
return 'auto';
}
var value = Rating.currentValue(0, this.props.count, hoverValue, this.state.value);
var floorValue = Math.floor(value);
return iconSize * value + (floorValue + 1) * iconSpace;
};
Rating.prototype.getInfoLeft = function getInfoLeft() {
var _state5 = this.state,
value = _state5.value,
hoverValue = _state5.hoverValue,
iconSpace = _state5.iconSpace,
iconSize = _state5.iconSize;
var infoValue = hoverValue || value;
var ceilValue = Math.ceil(infoValue);
return iconSize * (ceilValue - 1) + ceilValue * iconSpace;
};
Rating.prototype.render = function render() {
var _classNames,
_classNames2,
_classNames3,
_this4 = this;
var _props3 = this.props,
id = _props3.id,
prefix = _props3.prefix,
className = _props3.className,
showGrade = _props3.showGrade,
count = _props3.count,
size = _props3.size,
iconType = _props3.iconType,
strokeMode = _props3.strokeMode,
readAs = _props3.readAs,
rtl = _props3.rtl,
isPreview = _props3.isPreview,
renderPreview = _props3.renderPreview,
locale = _props3.locale;
var disabled = this.state.disabled;
var others = _util.obj.pickOthers(Rating.propTypes, this.props);
var _state6 = this.state,
hoverValue = _state6.hoverValue,
clicked = _state6.clicked;
var underlay = [],
overlay = [];
var enableA11y = !!id;
// 获得Value
var value = Rating.currentValue(0, count, hoverValue, this.state.value);
// icon的sizeMap
var sizeMap = ICON_SIZE_MAP[size];
var _loop = function _loop(i) {
var _classNames4;
var isCurrent = Math.ceil(value - 1) === i;
var iconCls = (0, _classnames2.default)((_classNames4 = {
hover: hoverValue > 0 && isCurrent,
clicked: clicked && isCurrent
}, _classNames4[prefix + 'rating-symbol-icon'] = !iconType, _classNames4));
var iconNode = iconType ? _react2.default.createElement(_icon2.default, { type: iconType, size: sizeMap, className: iconCls }) : _react2.default.createElement(_icon2.default, { type: 'favorites-filling', size: sizeMap, className: iconCls });
var saveRefs = function saveRefs(ref) {
_this4.saveRef(ref, i);
};
underlay.push(_react2.default.createElement(
'span',
{ ref: saveRefs, key: 'underlay-' + i, className: prefix + 'rating-icon' },
iconNode
));
if (enableA11y) {
overlay.push(_react2.default.createElement('input', {
id: id + '-' + prefix + 'star' + (i + 1),
key: 'input-' + i,
className: prefix + 'sr-only',
'aria-checked': i + 1 === parseInt(hoverValue),
checked: i + 1 === parseInt(hoverValue),
onChange: _this4.handleChecked.bind(_this4, i + 1),
type: 'radio',
name: 'rating'
}));
}
overlay.push(_react2.default.createElement(
'label',
{
key: 'overlay-' + i,
htmlFor: enableA11y ? id + '-' + prefix + 'star' + (i + 1) : null,
className: prefix + 'rating-icon'
},
iconNode,
enableA11y ? _react2.default.createElement(
'span',
{ className: prefix + 'sr-only' },
readAs(i + 1)
) : null
));
};
for (var i = 0; i < count; i++) {
_loop(i);
}
var ratingCls = (0, _classnames2.default)([prefix + 'rating', prefix + 'rating-' + size], (_classNames = {}, _classNames[prefix + 'rating-grade-low'] = value <= count * 0.4, _classNames[prefix + 'rating-grade-high'] = value > count * 0.4, _classNames[prefix + 'rating-stroke-mode'] = strokeMode, _classNames.hover = hoverValue > 0, _classNames), className);
var baseCls = (0, _classnames2.default)(prefix + 'rating-base', (_classNames2 = {}, _classNames2[prefix + 'rating-base-disabled'] = disabled, _classNames2));
var previewCls = (0, _classnames2.default)((_classNames3 = {}, _classNames3[prefix + 'form-preview'] = true, _classNames3[className] = !!className, _classNames3));
var overlayStyle = {
width: this.getOverlayWidth()
};
var infoStyle = {
left: this.getInfoLeft(),
display: hoverValue ? 'block' : 'none'
};
var finalProps = disabled ? {} : {
onClick: this.handleClick,
onMouseOver: this.handleHover,
onMouseMove: this.handleHover,
onMouseLeave: this.handleLeave
};
if (rtl) {
others.dir = 'rtl';
}
if (isPreview && 'renderPreview' in this.props) {
return _react2.default.createElement(
'div',
(0, _extends3.default)({ id: id }, others, { className: previewCls }),
renderPreview(value, this.props)
);
}
return _react2.default.createElement(
'div',
(0, _extends3.default)({
id: id
}, others, {
className: ratingCls,
onKeyDown: this.onKeyDown,
tabIndex: '0',
role: 'group',
'aria-label': locale.description
}),
_react2.default.createElement(
'div',
(0, _extends3.default)({ className: baseCls }, finalProps),
_react2.default.createElement(
'div',
{ className: prefix + 'rating-underlay', ref: function ref(n) {
return _this4.underlayNode = n;
}, 'aria-hidden': true },
underlay
),
_react2.default.createElement(
'div',
{ className: prefix + 'rating-overlay', style: overlayStyle, onClick: function onClick(e) {
return e.preventDefault();
} },
overlay
)
),
showGrade ? _react2.default.createElement(
'div',
{ className: prefix + 'rating-info', style: infoStyle },
readAs(value)
) : null
);
};
return Rating;
}(_react.Component), _class.propTypes = {
prefix: _propTypes2.default.string,
/**
* 默认值
*/
defaultValue: _propTypes2.default.number,
/**
* 值
*/
value: _propTypes2.default.number,
/**
* 评分的总数
*/
count: _propTypes2.default.number,
/**
* 是否显示 grade
*/
showGrade: _propTypes2.default.bool,
/**
* 尺寸
*/
size: _propTypes2.default.oneOf(['small', 'medium', 'large']),
/**
* 是否允许半星评分
*/
allowHalf: _propTypes2.default.bool,
/**
* 是否允许再次点击后清除
*/
allowClear: _propTypes2.default.bool,
/**
* 用户点击评分时触发的回调
* @param {Number} value 评分值
*/
onChange: _propTypes2.default.func,
/**
* 用户hover评分时触发的回调
* @param {Number} value 评分值
*/
onHoverChange: _propTypes2.default.func,
/**
* 是否禁用
*/
disabled: _propTypes2.default.bool,
/**
* 评分文案生成方法,传入id支持无障碍时,读屏软件可读
*/
readAs: _propTypes2.default.func,
// 实验属性: 自定义评分icon
iconType: _propTypes2.default.string,
// 实验属性: 开启 `-webkit-text-stroke` 显示边框颜色,在IE中无效
strokeMode: _propTypes2.default.bool,
className: _propTypes2.default.string,
id: _propTypes2.default.string,
rtl: _propTypes2.default.bool,
/**
* 自定义国际化文案对象
*/
locale: _propTypes2.default.object,
/**
* 是否为预览态
*/
isPreview: _propTypes2.default.bool,
/**
* 预览态模式下渲染的内容
* @param {number} value 评分值
*/
renderPreview: _propTypes2.default.func,
/**
* 是否为只读态,效果上同 disabeld
*/
readOnly: _propTypes2.default.bool
}, _class.defaultProps = {
prefix: 'next-',
size: 'medium',
disabled: false,
readOnly: false,
isPreview: false,
count: 5,
showGrade: false,
defaultValue: 0,
readAs: function readAs(val) {
return val;
},
allowHalf: false,
allowClear: false,
onChange: noop,
onHoverChange: noop,
locale: _zhCn2.default.Rating
}, _temp);
Rating.displayName = 'Rating';
exports.default = (0, _reactLifecyclesCompat.polyfill)(Rating);
module.exports = exports['default'];