@txdfe/at
Version:
一个设计体系组件库
476 lines (369 loc) • 19.4 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _util = require("../util");
var _input = _interopRequireDefault(require("../input"));
var _base = _interopRequireDefault(require("./base"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": 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 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) { _defineProperty(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; }
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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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 { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], 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 noop = _util.func.noop;
/**
* Select.AutoComplete
*/
var AutoComplete = /*#__PURE__*/function (_Base) {
_inherits(AutoComplete, _Base);
var _super = _createSuper(AutoComplete);
function AutoComplete(_props) {
var _this;
_classCallCheck(this, AutoComplete);
_this = _super.call(this, _props);
_defineProperty(_assertThisInitialized(_this), "shouldControlPopup", function () {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props;
var type = arguments.length > 1 ? arguments[1] : undefined;
var hasPopup = props.popupContent || _this.dataStore.getMenuDS().length;
if (hasPopup) {
_this.setVisible(true, type);
} else {
_this.setVisible(false, type);
}
});
_defineProperty(_assertThisInitialized(_this), "handleMenuSelect", function (keys) {
var key = keys[0];
if (_this.state.value === keys[0]) {
return _this.setVisible(false, 'itemClick');
}
var mapDS = _this.dataStore.getMapDS();
if (key in mapDS) {
var item = mapDS[key];
_this.handleSelectEvent(key, item, 'itemClick');
}
});
_defineProperty(_assertThisInitialized(_this), "handleItemClick", function () {
_this.setVisible(false, 'itemClick');
});
_defineProperty(_assertThisInitialized(_this), "handleSelectEvent", function (key, item, triggerType) {
var value = item && item[_this.props.fillProps] || key;
if (triggerType === 'itemClick' || triggerType === 'enter') {
// 点击 item 的时候不会触发关闭,需要手动关闭,其它类型比如 keyDown 等都会有其它事件句柄处理
_this.setVisible(false, triggerType);
}
_this.handleChange(value, triggerType, item);
});
_defineProperty(_assertThisInitialized(_this), "handleChange", function (value, proxy, item) {
var _this$props = _this.props,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly,
filterLocal = _this$props.filterLocal;
if (disabled || readOnly) {
return false;
}
var actionType = typeof proxy === 'string' ? proxy : 'change';
_this.isInputing = actionType === 'change';
if (filterLocal) {
_this.setState({
dataSource: _this.dataStore.updateByKey(value)
});
_this.shouldControlPopup(_this.props, actionType);
_this.setFirstHightLightKeyForMenu();
} // 非受控模式清空内部数据
if (!('value' in _this.props)) {
_this.setState({
value: value
});
}
_this.props.onChange(value, actionType, item);
if (actionType === 'itemClick' || actionType === 'enter') {
// 点击 item 的时候不会触发关闭,需要手动关闭,其它类型比如 keyDown 等都会有其它事件句柄处理
_this.setVisible(false, actionType);
}
});
_defineProperty(_assertThisInitialized(_this), "handleVisibleChange", function (visible, type) {
// 去掉这段逻辑,统一由base.jsx中的setVisible进行处理
// if (
// !('visible' in this.props) &&
// visible &&
// !this.props.popupContent &&
// !this.dataStore.getMenuDS().length
// ) {
// return;
// }
_this.setVisible(visible, type);
});
_defineProperty(_assertThisInitialized(_this), "beforeClose", function () {
_this.isInputing = false; // 清空选项的获焦状态
_this.setState({
highlightKey: ''
});
});
_defineProperty(_assertThisInitialized(_this), "handleTriggerKeyDown", function (e) {
var _this$props2 = _this.props,
popupContent = _this$props2.popupContent,
onToggleHighlightItem = _this$props2.onToggleHighlightItem,
onKeyDown = _this$props2.onKeyDown;
if (popupContent) {
// stopPropagation can make use onChange triggerd while typing space('') in Input
e.stopPropagation();
return onKeyDown(e);
}
switch (e.keyCode) {
case _util.KEYCODE.UP:
e.preventDefault();
onToggleHighlightItem(_this.toggleHighlightItem(-1, e), 'up');
break;
case _util.KEYCODE.DOWN:
e.preventDefault();
onToggleHighlightItem(_this.toggleHighlightItem(1, e), 'down');
break;
case _util.KEYCODE.ENTER:
e.preventDefault();
_this.chooseHighlightItem(e);
break;
case _util.KEYCODE.SPACE:
// stopPropagation can make use onChange triggerd while typing space('') in Input
e.stopPropagation();
break;
case _util.KEYCODE.ESC:
e.preventDefault();
_this.state.visible && _this.setVisible(false, 'esc');
break;
default:
break;
}
onKeyDown(e);
});
_defineProperty(_assertThisInitialized(_this), "chooseHighlightItem", function () {
if (!_this.state.visible) {
return false;
}
var highlightKey = _this.state.highlightKey;
var highlightItem = _this.dataStore.getEnableDS().find(function (item) {
return highlightKey === "".concat(item.value);
});
if (highlightItem) {
_this.handleSelectEvent(highlightKey, highlightItem, 'enter');
}
});
_defineProperty(_assertThisInitialized(_this), "hasClear", function () {
var _this$props3 = _this.props,
hasClear = _this$props3.hasClear,
readOnly = _this$props3.readOnly,
disabled = _this$props3.disabled;
var value = _this.state.value;
return value && hasClear && !readOnly && !disabled;
});
_defineProperty(_assertThisInitialized(_this), "renderSelect", function () {
var _classNames;
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props;
var placeholder = props.placeholder,
size = props.size,
prefix = props.prefix,
className = props.className,
style = props.style,
label = props.label,
readOnly = props.readOnly,
disabled = props.disabled,
highlightHolder = props.highlightHolder,
locale = props.locale,
hasClear = props.hasClear,
state = props.state,
rtl = props.rtl;
var others = _util.obj.pickOthers(AutoComplete.propTypes, props);
var othersData = _util.obj.pickAttrsWith(others, 'data-');
var value = _this.state.value;
var visible = _this.state.visible; // // 下拉箭头
// const arrowNode = this.renderArrowNode(props, () => {
// this.focusInput();
// this.setVisible(!this.state.visible);
// });
// trigger className
var triggerClazz = (0, _classnames["default"])(["".concat(prefix, "select"), "".concat(prefix, "select-auto-complete"), "".concat(prefix, "size-").concat(size), className], (_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "active"), visible), _defineProperty(_classNames, "".concat(prefix, "disabled"), disabled), _classNames)); // highlightKey into placeholder
// compatible with selectPlaceHolder. TODO: removed in 2.0 version
var _placeholder = placeholder || locale.autoCompletePlaceholder || locale.autoCompletePlaceHolder;
if (highlightHolder && visible) {
_placeholder = _this.state.highlightKey || _placeholder;
} // Input props
// state 为loading时效果转到弹层面板中
var _inputProps = _objectSpread(_objectSpread({}, _util.obj.pickOthers(othersData, others)), {}, {
state: state === 'loading' ? undefined : state,
ref: _this.saveInputRef,
hasClear: hasClear,
value: value,
size: size,
disabled: disabled,
readOnly: readOnly,
placeholder: _placeholder,
label: label,
// extra: arrowNode,
onChange: _this.handleChange,
onKeyDown: _this.handleTriggerKeyDown
});
return /*#__PURE__*/_react["default"].createElement("span", _extends({}, othersData, {
className: triggerClazz,
style: style,
dir: rtl ? 'rtl' : undefined,
ref: _this.saveSelectRef,
onClick: _this.focusInput
}), /*#__PURE__*/_react["default"].createElement(_input["default"], _extends({
role: "combobox",
"aria-autocomplete": "list",
"aria-disabled": disabled,
"aria-expanded": _this.state.visible
}, _inputProps)), /*#__PURE__*/_react["default"].createElement("span", {
className: "".concat(prefix, "sr-only"),
"aria-live": "polite"
}, _this.state.srReader));
});
_this.isAutoComplete = true;
_this.isInputing = false;
return _this;
}
_createClass(AutoComplete, [{
key: "UNSAFE_componentWillMount",
value: function UNSAFE_componentWillMount() {
this.dataStore.setOptions({
key: this.state.value
});
if (_get(_getPrototypeOf(AutoComplete.prototype), "UNSAFE_componentWillMount", this)) {
_get(_getPrototypeOf(AutoComplete.prototype), "UNSAFE_componentWillMount", this).call(this);
}
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.dataStore.setOptions({
key: nextProps.value
});
this.setState({
value: nextProps.value
});
}
if ('visible' in nextProps) {
this.setState({
visible: nextProps.visible
});
}
this.dataStore.setOptions({
filter: nextProps.filter,
filterLocal: nextProps.filterLocal
});
if (nextProps.children !== this.props.children || nextProps.dataSource !== this.props.dataSource) {
var dataSource = this.setDataSource(nextProps);
this.setState({
dataSource: dataSource
});
} // remote dataSource and focused
// 因为autoComplete没有下拉数据不展示,搜索并且有数据了需要自动展示下拉
if (!nextProps.filterLocal && this.isInputing) {
this.shouldControlPopup(nextProps, 'update');
}
if (!nextProps.filterLocal && !nextProps.popupContent) {
this.setFirstHightLightKeyForMenu();
}
if (!this.props.visible && nextProps.visible) {
// 当面板由收起到展开时,面板显示完整的数据(无过滤效果)
this.setState({
dataSource: this.dataStore.getOriginDS()
}); // 更新菜单数据
this.dataStore.updateByKey('');
}
}
}, {
key: "UNSAFE_componentWillUpdate",
value: function UNSAFE_componentWillUpdate() {
if (this.hasClear()) {
var inputNode = _reactDom["default"].findDOMNode(this.inputRef);
if (inputNode) {
this.clearNode = inputNode.querySelector(".".concat(this.props.prefix, "input-control"));
}
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
if (this.hasClear()) {
// clear 按钮点击后,会在 dom 结构中被删除掉,需要将其额外设置为安全节点,防止触发弹层的显示或隐藏
var safeNode = this.props.popupProps.safeNode || [];
var safeNodes = Array.isArray(safeNode) ? safeNode : [safeNode];
safeNodes.push(function () {
return _this2.clearNode;
});
this.props.popupProps.safeNode = safeNodes;
}
return _get(_getPrototypeOf(AutoComplete.prototype), "render", this).call(this, _extends({}, this.props, {
canCloseByTrigger: false
}));
}
}]);
return AutoComplete;
}(_base["default"]);
_defineProperty(AutoComplete, "propTypes", _objectSpread(_objectSpread({}, _base["default"].propTypes), {}, {
/**
* 当前值,用于受控模式
*/
value: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
/**
* 初始化的默认值
*/
defaultValue: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
/**
* Select发生改变时触发的回调
* @param {*} value 选中的值
* @param {String} actionType 触发的方式, 'itemClick', 'enter', 'change'
* @param {*} item 选中的值的对象数据
*/
onChange: _propTypes["default"].func,
/**
* 传入的数据源,可以动态渲染子项
*/
dataSource: _propTypes["default"].arrayOf(_propTypes["default"].oneOfType([_propTypes["default"].shape({
value: _propTypes["default"].string,
label: _propTypes["default"].any,
disabled: _propTypes["default"].bool,
children: _propTypes["default"].array
}), _propTypes["default"].string])),
/**
* 填充到选择框里的值的 key,默认是 value
*/
fillProps: _propTypes["default"].string,
/**
* 渲染 MenuItem 内容的方法
* @param {Object} item 渲染节点的 item
* @return {ReactNode} item node
*/
itemRender: _propTypes["default"].func,
// input keydown
onKeyDown: _propTypes["default"].func,
// 是否将当前高亮的选项作为 placeholder
highlightHolder: _propTypes["default"].bool,
style: _propTypes["default"].object
}));
_defineProperty(AutoComplete, "defaultProps", _objectSpread(_objectSpread({}, _base["default"].defaultProps), {}, {
onKeyDown: noop,
fillProps: 'value'
}));
var _default = AutoComplete;
exports["default"] = _default;