UNPKG

@txdfe/at

Version:

一个设计体系组件库

455 lines (449 loc) 18.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _icon = _interopRequireDefault(require("../icon")); var _util = require("../util"); var _zhCn = _interopRequireDefault(require("../locale/zh-cn")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } 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 = exports["default"] = /*#__PURE__*/function (_Component) { function Rating(props) { var _this; _classCallCheck(this, Rating); _this = _callSuper(this, Rating, [props]); _this.state = { value: 'value' in props ? props.value : props.defaultValue, hoverValue: 0, iconSpace: 0, iconSize: 0, clicked: false // 标记组件是否被点击过 }; _this.timer = null; bindCtx(_this, ['handleClick', 'handleHover', 'handleLeave', 'onKeyDown']); return _this; } _inherits(Rating, _Component); return _createClass(Rating, [{ key: "componentDidMount", value: function componentDidMount() { this.getRenderResult(); } }, { key: "UNSAFE_componentWillReceiveProps", value: function UNSAFE_componentWillReceiveProps(nextProps) { if ('value' in nextProps) { this.setState({ value: nextProps.value || 0 }); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.clearTimer(); } // 清除延时 }, { key: "clearTimer", value: function clearTimer() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } } }, { key: "getRenderResult", value: function getRenderResult() { var count = this.props.count; var _this$state = this.state, iconSpace = _this$state.iconSpace, iconSize = _this$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 }); } } } }, { key: "getValue", value: function getValue(e) { // 如定位不准,优先纠正定位 this.getRenderResult(); var _this$props = this.props, allowHalf = _this$props.allowHalf, count = _this$props.count, rtl = _this$props.rtl; var _this$state2 = this.state, iconSpace = _this$state2.iconSpace, iconSize = _this$state2.iconSize; var pos = e.pageX - this.underlayNode.getBoundingClientRect().left; var fullNum = Math.floor(pos / (iconSpace + iconSize)); var surplusNum = (pos - fullNum * (iconSpace + iconSize)) / iconSize; var value = Number(fullNum) + Number(surplusNum.toFixed(1)); if (value >= count) { value = count; } else if (allowHalf) { var floorValue = Math.floor(value); value = value - 0.5 >= floorValue ? floorValue + 1 : floorValue + 0.5; } else { value = Math.floor(value) + 1; } return rtl ? count - value + 1 : value; } }, { key: "handleHover", value: function handleHover(e) { var _this2 = this; var value = this.getValue(e); var onHoverChange = this.props.onHoverChange; if (value !== this.state.hoverValue) { this.clearTimer(); this.timer = setTimeout(function () { _this2.setState({ hoverValue: value }, function () { onHoverChange(value); }); }, 0); } } }, { key: "handleLeave", value: function handleLeave() { this.clearTimer(); this.setState({ hoverValue: 0 }); } }, { key: "onKeyDown", value: function onKeyDown(e) { var _this$props2 = this.props, disabled = _this$props2.disabled, onKeyDown = _this$props2.onKeyDown, count = _this$props2.count; if (disabled || supportKeys.indexOf(e.keyCode) < 0) { return !onKeyDown || onKeyDown(e); } var _this$state3 = this.state, hoverValue = _this$state3.hoverValue, value = _this$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); } }, { key: "handleChecked", value: function handleChecked(index) { this.setState({ hoverValue: index }); } }, { key: "handleClick", value: function handleClick(e) { var _this3 = this; var value = this.getValue(e); if (value < 0) { return; } if (!('value' in this.props)) { this.setState({ value: value, clicked: true }); } this.props.onChange(value); setTimeout(function () { _this3.setState({ clicked: false }); }, 100); } }, { key: "getOverlayWidth", value: function getOverlayWidth() { var _this$state4 = this.state, hoverValue = _this$state4.hoverValue, iconSpace = _this$state4.iconSpace, iconSize = _this$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; } }, { key: "getInfoLeft", value: function getInfoLeft() { var _this$state5 = this.state, value = _this$state5.value, hoverValue = _this$state5.hoverValue, iconSpace = _this$state5.iconSpace, iconSize = _this$state5.iconSize; var infoValue = hoverValue || value; var ceilValue = Math.ceil(infoValue); return iconSize * (ceilValue - 1) + ceilValue * iconSpace; } }, { key: "render", value: function render() { var _this4 = this; var _this$props3 = this.props, id = _this$props3.id, prefix = _this$props3.prefix, className = _this$props3.className, showGrade = _this$props3.showGrade, count = _this$props3.count, size = _this$props3.size, iconType = _this$props3.iconType, strokeMode = _this$props3.strokeMode, disabled = _this$props3.disabled, readAs = _this$props3.readAs, rtl = _this$props3.rtl, locale = _this$props3.locale; var others = _util.obj.pickOthers(Rating.propTypes, this.props); var _this$state6 = this.state, hoverValue = _this$state6.hoverValue, clicked = _this$state6.clicked; var underlay = []; var overlay = []; var enableA11y = !!id; // 获得Value var value = Rating.currentValue(0, count, hoverValue, this.state.value); // icon的sizeMap var sizeMap = ICON_SIZE_MAP[size]; for (var i = 0; i < count; i++) { var isCurrent = Math.ceil(value - 1) === i; var iconCls = (0, _classnames["default"])({ hover: hoverValue > 0 && isCurrent, clicked: clicked && isCurrent }); var iconNode = /*#__PURE__*/_react["default"].createElement(_icon["default"], { type: iconType, size: sizeMap, className: iconCls }); underlay.push(/*#__PURE__*/_react["default"].createElement("span", { ref: "rating-icon-".concat(i), key: "underlay-".concat(i), className: "".concat(prefix, "rating-icon") }, iconNode)); if (enableA11y) { overlay.push(/*#__PURE__*/_react["default"].createElement("input", { id: "".concat(id, "-").concat(prefix, "star").concat(i + 1), key: "input-".concat(i), className: "".concat(prefix, "sr-only"), "aria-checked": i + 1 === parseInt(hoverValue), checked: i + 1 === parseInt(hoverValue), onChange: this.handleChecked.bind(this, i + 1), type: "radio", name: "rating" })); } overlay.push(/*#__PURE__*/_react["default"].createElement("label", { key: "overlay-".concat(i), htmlFor: enableA11y ? "".concat(id, "-").concat(prefix, "star").concat(i + 1) : null, className: "".concat(prefix, "rating-icon") }, iconNode, enableA11y ? /*#__PURE__*/_react["default"].createElement("span", { className: "".concat(prefix, "sr-only") }, readAs(i + 1)) : null)); } var ratingCls = (0, _classnames["default"])(["".concat(prefix, "rating"), "".concat(prefix, "rating-").concat(size)], _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, "".concat(prefix, "rating-grade-low"), value <= count * 0.4), "".concat(prefix, "rating-grade-high"), value > count * 0.4), "".concat(prefix, "rating-stroke-mode"), strokeMode), "hover", hoverValue > 0), className); var baseCls = (0, _classnames["default"])("".concat(prefix, "rating-base"), _defineProperty({}, "".concat(prefix, "rating-base-disabled"), disabled)); 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'; } return /*#__PURE__*/_react["default"].createElement("div", _extends({ id: id || null }, others, { className: ratingCls, onKeyDown: this.onKeyDown, tabIndex: "0", role: "group", "aria-label": locale.description }), /*#__PURE__*/_react["default"].createElement("div", _extends({ className: baseCls }, finalProps), /*#__PURE__*/_react["default"].createElement("div", { className: "".concat(prefix, "rating-underlay"), ref: function ref(n) { return _this4.underlayNode = n; }, "aria-hidden": true }, underlay), /*#__PURE__*/_react["default"].createElement("div", { className: "".concat(prefix, "rating-overlay"), style: overlayStyle }, overlay)), showGrade ? /*#__PURE__*/_react["default"].createElement("div", { className: "".concat(prefix, "rating-info"), style: infoStyle }, readAs(value)) : null); } }], [{ key: "currentValue", value: function currentValue(min, max, hoverValue, stateValue) { var value = hoverValue || stateValue; value = value >= max ? max : value; value = value <= min ? min : value; return value || 0; } }]); }(_react.Component); _defineProperty(Rating, "displayName", 'Rating'); _defineProperty(Rating, "propTypes", { prefix: _propTypes["default"].string, /** * 默认值 */ defaultValue: _propTypes["default"].number, /** * 值 */ value: _propTypes["default"].number, /** * 评分的总数 */ count: _propTypes["default"].number, /** * 是否显示 grade */ showGrade: _propTypes["default"].bool, /** * 尺寸 */ size: _propTypes["default"].oneOf(['small', 'medium', 'large']), /** * 是否允许半星评分 */ allowHalf: _propTypes["default"].bool, /** * 用户点击评分时触发的回调 * @param {String} value 评分值 */ onChange: _propTypes["default"].func, /** * 用户hover评分时触发的回调 * @param {String} value 评分值 */ onHoverChange: _propTypes["default"].func, /** * 是否禁用 */ disabled: _propTypes["default"].bool, /** * 评分文案生成方法,传入id支持无障碍时,读屏软件可读 */ readAs: _propTypes["default"].func, // 实验属性: 自定义评分icon iconType: _propTypes["default"].string, // 实验属性: 开启 `-webkit-text-stroke` 显示边框颜色,在IE中无效 strokeMode: _propTypes["default"].bool, className: _propTypes["default"].string, id: _propTypes["default"].string, rtl: _propTypes["default"].bool, /** * 自定义国际化文案对象 */ locale: _propTypes["default"].object }); _defineProperty(Rating, "defaultProps", { prefix: 'next-', size: 'medium', disabled: false, count: 5, showGrade: false, defaultValue: 0, readAs: function readAs(val) { return val; }, allowHalf: false, iconType: 'star-fill', onChange: noop, onHoverChange: noop, locale: _zhCn["default"].Rating });