UNPKG

@txdfe/at

Version:

一个设计体系组件库

698 lines (555 loc) 25.6 kB
"use strict"; 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 = _interopRequireWildcard(require("react")); var _reactDom = require("react-dom"); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _util = require("../util"); var _menu = _interopRequireDefault(require("../menu")); var _overlay = _interopRequireDefault(require("../overlay")); var _loading = _interopRequireDefault(require("../loading")); var _zhCn = _interopRequireDefault(require("../locale/zh-cn")); var _dataStore = _interopRequireDefault(require("./data-store")); var _virtualList = _interopRequireDefault(require("../virtual-list")); var _util2 = require("./util"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 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 _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); Object.defineProperty(Constructor, "prototype", { writable: false }); 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 } }); 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 Popup = _overlay["default"].Popup; var MenuItem = _menu["default"].Item, MenuGroup = _menu["default"].Group; var noop = _util.func.noop, makeChain = _util.func.makeChain; function preventDefault(e) { e.preventDefault(); } var Base = /*#__PURE__*/function (_React$Component) { _inherits(Base, _React$Component); var _super = _createSuper(Base); function Base(_props2) { var _this; _classCallCheck(this, Base); _this = _super.call(this, _props2); _defineProperty(_assertThisInitialized(_this), "syncWidth", function () { var width = _util.dom.getStyle(_this.selectDOM, 'width'); if (width && _this.width !== width) { _this.width = width; if (_this.popupRef && _this.props.autoWidth) { // overy 的 node 节点可能没有挂载完成,所以这里需要异步 setTimeout(function () { if (_this.popupRef && _this.popupRef.getInstance().overlay) { _util.dom.setStyle(_this.popupRef.getInstance().overlay.getInstance().getContentNode(), 'width', _this.width); // 更新下Menu的宽度 _this.forceUpdate(); } }, 0); } } }); _defineProperty(_assertThisInitialized(_this), "handleResize", function () { clearTimeout(_this.resizeTimeout); if (_this.state.visible) { _this.resizeTimeout = setTimeout(function () { _this.syncWidth(); }, 200); } }); _defineProperty(_assertThisInitialized(_this), "setDataSource", function (props) { var dataSource = props.dataSource, children = props.children; // children is higher priority then dataSource if (_react.Children.count(children)) { return _this.dataStore.updateByDS(children, true); } else if (Array.isArray(dataSource)) { return _this.dataStore.updateByDS(dataSource, false); } return []; }); _defineProperty(_assertThisInitialized(_this), "setVisible", function (visible, type) { if (_this.props.disabled || _this.state.visible === visible) { return; } if (!('visible' in _this.props)) { _this.setState({ visible: visible }); } _this.props.onVisibleChange(visible, type); }); _defineProperty(_assertThisInitialized(_this), "setFirstHightLightKeyForMenu", function () { // 设置高亮 item key if (_this.dataStore.getMenuDS().length && _this.dataStore.getEnableDS().length) { _this.setState({ highlightKey: "".concat(_this.dataStore.getEnableDS()[0].value) }); } }); _defineProperty(_assertThisInitialized(_this), "handleChange", function (value) { var _this$props; // 非受控模式清空内部数据 if (!('value' in _this.props)) { _this.setState({ value: value }); } for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } (_this$props = _this.props).onChange.apply(_this$props, [value].concat(args)); }); _defineProperty(_assertThisInitialized(_this), "handleMenuBodyClick", function (e) { _this.focusInput(e); }); _defineProperty(_assertThisInitialized(_this), "toggleHighlightItem", function (dir) { if (!_this.state.visible) { _this.setVisible(true, 'enter'); return; } var maxCount = _this.dataStore.getEnableDS().length; // When there is no enabled item if (!maxCount) { return false; } var highlightKey = _this.state.highlightKey; var highlightIndex = -1; // find previous highlight index highlightKey !== null && _this.dataStore.getEnableDS().some(function (item, index) { if ("".concat(item.value) === highlightKey) { highlightIndex = index; } return highlightIndex > -1; }); // toggle highlight index highlightIndex += dir; if (highlightIndex < 0) { highlightIndex = maxCount - 1; } if (highlightIndex >= maxCount) { highlightIndex = 0; } // get highlight key var highlightItem = _this.dataStore.getEnableDS()[highlightIndex]; highlightKey = highlightItem ? "".concat(highlightItem.value) : null; _this.setState({ highlightKey: highlightKey, srReader: highlightItem.label }); _this.scrollMenuIntoView(); return highlightItem; }); _defineProperty(_assertThisInitialized(_this), "scrollMenuIntoView", function () { var prefix = _this.props.prefix; clearTimeout(_this.highlightTimer); _this.highlightTimer = setTimeout(function () { try { var menuNode = (0, _reactDom.findDOMNode)(_this.menuRef); var itemNode = menuNode.querySelector(".".concat(prefix, "select-menu-item.").concat(prefix, "focused")); itemNode && itemNode.scrollIntoViewIfNeeded(); } catch (ex) {// I don't care... } }); }); _defineProperty(_assertThisInitialized(_this), "renderMenuHeader", function () { return null; }); _defineProperty(_assertThisInitialized(_this), "renderMenuFooter", function () { var _this$props2 = _this.props, useVirtual = _this$props2.useVirtual, footer = _this$props2.footer; return !useVirtual ? footer : null; }); _defineProperty(_assertThisInitialized(_this), "handleSelect", function () {}); _defineProperty(_assertThisInitialized(_this), "renderMenu", function () { var _classNames; var _this$props3 = _this.props, prefix = _this$props3.prefix, mode = _this$props3.mode, autoWidth = _this$props3.autoWidth, locale = _this$props3.locale, notFoundContent = _this$props3.notFoundContent, useVirtual = _this$props3.useVirtual, onPopupScroll = _this$props3.onPopupScroll; var _this$state = _this.state, dataSource = _this$state.dataSource, highlightKey = _this$state.highlightKey; var value = _this.state.value; var selectedKeys; if ((0, _util2.isNull)(value) || value.length === 0) { selectedKeys = []; } else if ((0, _util2.isSingle)(mode)) { selectedKeys = [(0, _util2.valueToSelectKey)(value)]; } else { selectedKeys = [].concat(value).map(function (n) { return (0, _util2.valueToSelectKey)(n); }); } var children = _this.renderMenuItem(dataSource); var menuClassName = (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "select-menu"), true), _defineProperty(_classNames, "".concat(prefix, "select-menu-empty"), !children || !children.length), _classNames)); if (!children || !children.length) { children = /*#__PURE__*/_react["default"].createElement("span", { className: "".concat(prefix, "select-menu-empty-content") }, notFoundContent || locale.notFoundContent); } var menuProps = { children: children, role: 'listbox', style: autoWidth ? { width: _this.width } : { minWidth: _this.width }, selectedKeys: selectedKeys, focusedKey: highlightKey, focusable: false, selectMode: (0, _util2.isSingle)(mode) ? 'single' : 'multiple', onSelect: _this.handleMenuSelect, onItemClick: _this.handleItemClick, header: _this.renderMenuHeader(), footer: _this.renderMenuFooter(), onClick: _this.handleMenuBodyClick, onMouseDown: preventDefault, className: menuClassName, onScroll: onPopupScroll }; return useVirtual && children.length ? /*#__PURE__*/_react["default"].createElement("div", { className: "".concat(prefix, "select-menu-wrapper"), style: { position: 'relative' } }, /*#__PURE__*/_react["default"].createElement(_virtualList["default"], { itemsRenderer: function itemsRenderer(items, _ref) { return /*#__PURE__*/_react["default"].createElement(_menu["default"], _extends({ ref: function ref(c) { _ref(c); _this.menuRef = c; } }, menuProps), items); } }, children)) : /*#__PURE__*/_react["default"].createElement(_menu["default"], _extends({ ref: function ref(c) { _this.menuRef = c; } }, menuProps)); }); _defineProperty(_assertThisInitialized(_this), "renderMenuItem", function (dataSource) { var _this$props4 = _this.props, prefix = _this$props4.prefix, itemRender = _this$props4.itemRender; // If it has. var searchKey; if (_this.isAutoComplete) { // In AutoComplete, value is the searchKey searchKey = _this.state.value; } else { searchKey = _this.state.searchValue; } return dataSource.map(function (item, index) { if (!item) { return null; } if (Array.isArray(item.children)) { return /*#__PURE__*/_react["default"].createElement(MenuGroup, { key: index, label: item.label }, _this.renderMenuItem(item.children)); } else { var itemProps = { role: 'option', key: item.value, className: "".concat(prefix, "select-menu-item"), disabled: item.disabled }; if (item.title) { itemProps.title = item.title; } return /*#__PURE__*/_react["default"].createElement(MenuItem, itemProps, itemRender(item, searchKey)); } }); }); _defineProperty(_assertThisInitialized(_this), "saveSelectRef", function (ref) { _this.selectDOM = (0, _reactDom.findDOMNode)(ref); }); _defineProperty(_assertThisInitialized(_this), "saveInputRef", function (ref) { if (ref && ref.getInstance()) { _this.inputRef = ref.getInstance(); } }); _defineProperty(_assertThisInitialized(_this), "focusInput", function () { _this.inputRef && _this.inputRef.focus(); }); _defineProperty(_assertThisInitialized(_this), "beforeOpen", function () { var _this$state2 = _this.state, value = _this$state2.value, highlightKey = _this$state2.highlightKey; if (_this.props.mode === 'single' && !value && !highlightKey) { _this.setFirstHightLightKeyForMenu(); } _this.syncWidth(); }); _defineProperty(_assertThisInitialized(_this), "beforeClose", function () {}); _defineProperty(_assertThisInitialized(_this), "afterClose", function () {}); _defineProperty(_assertThisInitialized(_this), "savePopupRef", function (ref) { _this.popupRef = ref; if (_this.props.popupProps && typeof _this.props.popupProps.ref === 'function') { _this.props.popupProps.ref(ref); } }); _this.dataStore = new _dataStore["default"]({ filter: _props2.filter, filterLocal: _props2.filterLocal }); _this.state = { value: 'value' in _props2 ? _props2.value : _props2.defaultValue, visible: 'visible' in _props2 ? _props2.visible : _props2.defaultVisible, dataSource: [], width: 100, // current highlight key highlightKey: null, srReader: '' }; return _this; } _createClass(Base, [{ key: "UNSAFE_componentWillMount", value: function UNSAFE_componentWillMount() { this.setState({ dataSource: this.setDataSource(this.props) }); } }, { key: "componentDidMount", value: function componentDidMount() { var _this2 = this; // overlay 还没有完成 mount,所以需要滞后同步宽度 setTimeout(function () { return _this2.syncWidth(); }, 0); _util.events.on(window, 'resize', this.handleResize); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (prevProps.label !== this.props.label || prevState.value !== this.state.value) { this.syncWidth(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { _util.events.off(window, 'resize', this.handleResize); clearTimeout(this.resizeTimeout); } /** * Calculate and set width of popup menu * @protected */ }, { key: "render", value: function render() { var _classNames2; var _this$props5 = this.props, prefix = _this$props5.prefix, mode = _this$props5.mode, state = _this$props5.state, popupProps = _this$props5.popupProps, popupContainer = _this$props5.popupContainer, popupClassName = _this$props5.popupClassName, popupStyle = _this$props5.popupStyle, popupContent = _this$props5.popupContent, autoWidth = _this$props5.autoWidth, canCloseByTrigger = _this$props5.canCloseByTrigger, followTrigger = _this$props5.followTrigger, cache = _this$props5.cache, showEmpty = _this$props5.showEmpty; var cls = (0, _classnames["default"])((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefix, "select-auto-complete-menu"), !popupContent && this.isAutoComplete), _defineProperty(_classNames2, "".concat(prefix, "select-").concat(mode, "-menu"), !popupContent && !!mode), _classNames2), popupClassName || popupProps.className); var _props = _objectSpread(_objectSpread({ offset: [0, 4], animation: { "in": 'fadeInDown', out: 'fadeOutUp' }, triggerType: 'click', autoFocus: false, cache: cache }, popupProps), {}, { // beforeOpen node not mount, afterOpen too slow. // from display:none to block, we may need to recompute width beforeOpen: makeChain(this.beforeOpen, popupProps.beforeOpen), beforeClose: makeChain(this.beforeClose, popupProps.beforeClose), afterClose: makeChain(this.afterClose, popupProps.afterClose), canCloseByTrigger: canCloseByTrigger, followTrigger: followTrigger, visible: this.state.visible, onVisibleChange: this.handleVisibleChange, shouldUpdatePosition: true, container: popupContainer || popupProps.container, className: cls, style: popupStyle || popupProps.style }); // 用于 Search 不显示弹出层 if (!showEmpty) { return this.renderSelect(); } return /*#__PURE__*/_react["default"].createElement(Popup, _extends({}, _props, { trigger: this.renderSelect(), ref: this.savePopupRef }), /*#__PURE__*/_react["default"].createElement(_loading["default"], { className: "".concat(prefix, "select-loading"), visible: state === 'loading' }, popupContent ? /*#__PURE__*/_react["default"].createElement("div", { className: "".concat(prefix, "select-popup-wrap"), style: autoWidth ? { width: this.width } : {} }, popupContent) : this.renderMenu())); } }]); return Base; }(_react["default"].Component); exports["default"] = Base; _defineProperty(Base, "propTypes", { prefix: _propTypes["default"].string, /** * 选择器尺寸 */ size: _propTypes["default"].oneOf(['xs', 'small', 'medium']), // 当前值,用于受控模式 value: _propTypes["default"].any, // to be override // 初始化的默认值 defaultValue: _propTypes["default"].any, // to be override /** * 没有值的时候的占位符 */ placeholder: _propTypes["default"].string, /** * 下拉菜单是否与选择器对齐 */ autoWidth: _propTypes["default"].bool, /** * 自定义内联 label */ label: _propTypes["default"].node, /** * 是否有清除按钮(单选模式有效) */ hasClear: _propTypes["default"].bool, /** * 校验状态 */ state: _propTypes["default"].oneOf(['error', 'loading']), /** * 是否只读,只读模式下可以展开弹层但不能选 */ readOnly: _propTypes["default"].bool, /** * 是否禁用选择器 */ disabled: _propTypes["default"].bool, /** * 当前弹层是否显示 */ visible: _propTypes["default"].bool, /** * 弹层初始化是否显示 */ defaultVisible: _propTypes["default"].bool, /** * 弹层显示或隐藏时触发的回调 * @param {Boolean} visible 弹层是否显示 * @param {String} type 触发弹层显示或隐藏的来源 fromContent 表示由Dropdown内容触发; fromTrigger 表示由trigger的点击触发; docClick 表示由document的点击触发 */ onVisibleChange: _propTypes["default"].func, /** * value变化时回调 */ onChange: _propTypes["default"].func, /** * 弹层挂载的容器节点 */ popupContainer: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]), /** * 弹层的 className */ popupClassName: _propTypes["default"].any, /** * 弹层的内联样式 */ popupStyle: _propTypes["default"].object, /** * 添加到弹层上的属性 */ popupProps: _propTypes["default"].object, /** * 是否跟随滚动 */ followTrigger: _propTypes["default"].bool, /** * 自定义弹层的内容 */ popupContent: _propTypes["default"].node, /** * 是否使用本地过滤,在数据源为远程的时候需要关闭此项 */ filterLocal: _propTypes["default"].bool, /** * 本地过滤方法,返回一个 Boolean 值确定是否保留 */ filter: _propTypes["default"].func, /** * 键盘上下键切换菜单高亮选项的回调 */ onToggleHighlightItem: _propTypes["default"].func, /** * 是否开启虚拟滚动模式 */ useVirtual: _propTypes["default"].bool, // 自定义类名 className: _propTypes["default"].any, children: _propTypes["default"].any, dataSource: _propTypes["default"].array, itemRender: _propTypes["default"].func, /** * 弹层菜单footer */ footer: _propTypes["default"].node, mode: _propTypes["default"].string, notFoundContent: _propTypes["default"].node, /** * 内容为空是否显示弹层 */ showEmpty: _propTypes["default"].bool, locale: _propTypes["default"].object, rtl: _propTypes["default"].bool, /** * 监听滚动事件 */ onPopupScroll: _propTypes["default"].func }); _defineProperty(Base, "defaultProps", { prefix: 'next-', size: 'medium', autoWidth: true, onChange: noop, onVisibleChange: noop, onToggleHighlightItem: noop, popupProps: {}, filterLocal: true, filter: _util2.filter, itemRender: function itemRender(item) { return item.label || item.value; }, locale: _zhCn["default"].Select, showEmpty: true });