UNPKG

@txdfe/at

Version:

一个设计体系组件库

609 lines (604 loc) 24.8 kB
"use strict"; 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(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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } 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 _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 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 = exports["default"] = /*#__PURE__*/function (_React$Component) { function Base(_props2) { var _this; _classCallCheck(this, Base); _this = _callSuper(this, Base, [_props2]); /** * Calculate and set width of popup menu * @protected */ _defineProperty(_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(_this, "handleResize", function () { clearTimeout(_this.resizeTimeout); if (_this.state.visible) { _this.resizeTimeout = setTimeout(function () { _this.syncWidth(); }, 200); } }); /** * Get structured dataSource, for cache * @protected * @param {Object} [props=this.props] * @return {Array} */ _defineProperty(_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 []; }); /** * Set popup visible * @protected * @param {boolean} visible * @param {string} type trigger type */ _defineProperty(_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(_this, "setFirstHightLightKeyForMenu", function () { // 设置高亮 item key if (_this.dataStore.getMenuDS().length && _this.dataStore.getEnableDS().length) { _this.setState({ highlightKey: "".concat(_this.dataStore.getEnableDS()[0].value) }); } }); _defineProperty(_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)); }); /** * Handle Menu body click * @param {Event} e click event */ _defineProperty(_this, "handleMenuBodyClick", function (e) { _this.focusInput(e); }); /** * Toggle highlight MenuItem * @private * @param {number} dir -1: up, 1: down */ _defineProperty(_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; }); // scroll into focus item _defineProperty(_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... } }); }); /** * render popup menu header * @abstract */ _defineProperty(_this, "renderMenuHeader", function () { return null; }); /** * render popup menu footer */ _defineProperty(_this, "renderMenuFooter", function () { var _this$props2 = _this.props, useVirtual = _this$props2.useVirtual, footer = _this$props2.footer; return !useVirtual ? footer : null; }); _defineProperty(_this, "handleSelect", function () {}); /** * render popup children * @protected * @param {object} props */ _defineProperty(_this, "renderMenu", function () { 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"])(_defineProperty(_defineProperty({}, "".concat(prefix, "select-menu"), true), "".concat(prefix, "select-menu-empty"), !children || !children.length)); 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)); }); /** * render menu item * @protected * @param {Array} dataSource */ _defineProperty(_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(_this, "saveSelectRef", function (ref) { _this.selectDOM = (0, _reactDom.findDOMNode)(ref); }); _defineProperty(_this, "saveInputRef", function (ref) { if (ref && ref.getInstance()) { _this.inputRef = ref.getInstance(); } }); /** * 点击 arrow 或 label 的时候焦点切到 input 中 * @override */ _defineProperty(_this, "focusInput", function () { _this.inputRef && _this.inputRef.focus(); }); _defineProperty(_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(_this, "beforeClose", function () {}); _defineProperty(_this, "afterClose", function () {}); _defineProperty(_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; } _inherits(Base, _React$Component); return _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); } }, { key: "render", value: function render() { 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"])(_defineProperty(_defineProperty({}, "".concat(prefix, "select-auto-complete-menu"), !popupContent && this.isAutoComplete), "".concat(prefix, "select-").concat(mode, "-menu"), !popupContent && !!mode), 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())); } }]); }(_react["default"].Component); _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 });