acud
Version:
acg react 组件库
555 lines (552 loc) • 23.8 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _isNativeReflectConstruct2 = _interopRequireDefault(require("@babel/runtime/helpers/isNativeReflectConstruct"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
var _filter = _interopRequireDefault(require("lodash/filter"));
var _findIndex = _interopRequireDefault(require("lodash/findIndex"));
var _sortBy = _interopRequireDefault(require("lodash/sortBy"));
var _rcTrigger = _interopRequireDefault(require("rc-trigger"));
var _KeyCode = _interopRequireDefault(require("rc-util/lib/KeyCode"));
var _arrayTreeFilter = _interopRequireDefault(require("array-tree-filter"));
var _utils = require("./utils");
var _Menus = _interopRequireDefault(require("./Menus"));
var _placements = _interopRequireDefault(require("./placements"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, (0, _isNativeReflectConstruct2["default"])() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
var __rest = void 0 && (void 0).__rest || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
// eslint-disable-next-line no-duplicate-imports
var getFieldNames = function getFieldNames(_ref) {
var fieldNames = _ref.fieldNames;
return fieldNames;
};
var getFilledFieldNames = function getFilledFieldNames(props) {
var fieldNames = getFieldNames(props) || {};
var names = {
children: fieldNames.children || 'children',
label: fieldNames.label || 'label',
value: fieldNames.value || 'value'
};
return names;
};
var _flattenTree = function flattenTree(options, props) {
var ancestor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var names = getFilledFieldNames(props);
var flattenOptions = [];
var childrenName = names.children;
options.forEach(function (option) {
var path = ancestor.concat(option);
if (props.changeOnSelect || !option[childrenName] || !option[childrenName].length) {
flattenOptions.push(path);
}
if (option[childrenName]) {
flattenOptions = flattenOptions.concat(_flattenTree(option[childrenName], props, path));
}
});
return flattenOptions;
};
var _getEnableOptions = function getEnableOptions(options) {
var enabledOptions = [];
if (options && options.length) {
options.forEach(function (option) {
var disabled = option.disabled,
children = option.children;
if (disabled) {
return;
}
if (children && children.length) {
var enabledChilren = _getEnableOptions(children);
if (!(0, _isEmpty["default"])(enabledChilren)) {
enabledOptions.push((0, _extends2["default"])((0, _extends2["default"])({}, option), {
children: enabledChilren
}));
}
return;
}
enabledOptions.push(option);
});
}
return enabledOptions;
};
var Cascader = /*#__PURE__*/function (_React$Component) {
function Cascader(props) {
var _this;
(0, _classCallCheck2["default"])(this, Cascader);
_this = _callSuper(this, Cascader, [props]);
_this.setPopupVisible = function (popupVisible) {
var value = _this.props.value;
if (!('popupVisible' in _this.props)) {
_this.setState({
popupVisible: popupVisible
});
}
// sync activeValue with value when panel open
if (popupVisible && !_this.state.popupVisible && !(0, _isEmpty["default"])(value)) {
if (_this.props.mode !== 'multiple') {
_this.setState({
activeValue: value
});
} else {
// 展开后才能获取到options值
window.setTimeout(function () {
var totalValues = _this.getTotalValues();
var sortedValue = (0, _sortBy["default"])(value, function (valueItem) {
return (0, _findIndex["default"])(totalValues, function (totalValueItem) {
return (0, _utils.isEqualArrays)(totalValueItem, valueItem);
});
});
_this.setState({
activeValue: sortedValue === null || sortedValue === void 0 ? void 0 : sortedValue[0]
});
}, 0);
}
}
_this.setState({
hoveredValue: []
});
_this.props.onPopupVisibleChange(popupVisible);
};
_this.handleChange = function (options, _ref2, e) {
var visible = _ref2.visible;
if (e.type !== 'keydown' || e.keyCode === _KeyCode["default"].ENTER) {
_this.props.onChange(options.map(function (o) {
return o[_this.getFieldName('value')];
}), options);
_this.setPopupVisible(visible);
}
};
_this.handlePopupVisibleChange = function (popupVisible) {
_this.setPopupVisible(popupVisible);
};
_this.handleMenuSelect = function (targetOption, menuIndex, e) {
// Keep focused state for keyboard support
var triggerNode = _this.trigger.getRootDomNode();
if (triggerNode && triggerNode.focus && e.type === 'click') {
triggerNode.focus();
}
var _this$props = _this.props,
changeOnSelect = _this$props.changeOnSelect,
loadData = _this$props.loadData,
expandTrigger = _this$props.expandTrigger;
if (!targetOption || targetOption.disabled) {
return;
}
var activeValue = _this.state.activeValue;
activeValue = activeValue.slice(0, menuIndex + 1);
activeValue[menuIndex] = targetOption[_this.getFieldName('value')];
var activeOptions = _this.getActiveOptions(activeValue);
if (targetOption.isLeaf === false && !targetOption[_this.getFieldName('children')] && loadData) {
if (changeOnSelect && (e.type === 'click' || e.type === 'keydown')) {
_this.handleChange(activeOptions, {
visible: true
}, e);
}
loadData(activeOptions);
_this.setState({
activeValue: activeValue
});
return;
}
var newState = {};
if (!targetOption[_this.getFieldName('children')] || !targetOption[_this.getFieldName('children')].length) {
if (_this.props.mode !== 'multiple' && e.type === 'click') {
_this.handleChange(activeOptions, {
visible: false
}, e);
// add e.type judgement to prevent `onChange` being triggered by mouseEnter
}
} else if (changeOnSelect && (e.type === 'click' || e.type === 'keydown')) {
if (expandTrigger === 'hover') {
_this.handleChange(activeOptions, {
visible: false
}, e);
} else {
_this.handleChange(activeOptions, {
visible: true
}, e);
}
}
newState.activeValue = activeValue;
newState.hoveredValue = activeValue;
_this.setState(newState);
};
_this.handleMenuMultiSelect = function (targetOption, _menuIndex, optionKey, e) {
var checked = e.target.checked;
var targetOptionChildren = targetOption[_this.getFieldName('children')];
var _this$props2 = _this.props,
keyword = _this$props2.keyword,
_this$props2$value = _this$props2.value,
value = _this$props2$value === void 0 ? [] : _this$props2$value;
var newValue = [];
// 1、当前有子级:将除disabled外的所有子级全部push进value
if (targetOptionChildren && targetOptionChildren.length) {
var enableChildren = _getEnableOptions(targetOptionChildren);
var flattenOptions = _flattenTree(enableChildren, _this.props);
var childrenValue = flattenOptions.map(function (option) {
return [].concat((0, _toConsumableArray2["default"])(optionKey), (0, _toConsumableArray2["default"])(option.map(function (o) {
return o[_this.getFieldName('value')];
})));
});
newValue = checked ? [].concat((0, _toConsumableArray2["default"])(value), (0, _toConsumableArray2["default"])(childrenValue.filter(function (valueItem) {
return !(0, _utils.isIncludeArray)(value, valueItem);
}))) : value.filter(function (valueItem) {
return !(0, _utils.isIncludeArray)(childrenValue, valueItem);
});
}
// 2、当前是最后一级:直接push进value
else {
if (checked) {
newValue = keyword ? [].concat((0, _toConsumableArray2["default"])(value), (0, _toConsumableArray2["default"])(optionKey)) : [].concat((0, _toConsumableArray2["default"])(value), [optionKey]);
} else {
newValue = value.filter(function (valueItem) {
return !(0, _utils.isEqualArrays)(valueItem, keyword ? optionKey[0] : optionKey);
});
}
}
// 3、对newValue进行排序
// const totalValues = this.getTotalValues();
// let newSortedValue = [];
// totalValues.forEach(value => {
// if (isIncludeArray(newValue, value)) {
// newSortedValue.push(value);
// }
// });
// 先取消排序
var newSortedValue = newValue;
var newSortedSelectOptions = newSortedValue.map(function (valueItem) {
return _this.getActiveOptions(valueItem, _this.props.originOptions);
});
_this.props.onChange(newSortedValue, newSortedSelectOptions);
};
_this.handleMenuMultiSelectAll = function (e) {
var checked = e.target.checked;
var value = _this.props.value;
var disabledValues = _this.getDisabledValues();
if (checked) {
var enableValues = _this.getEnableValues();
var disabledInValue = (0, _filter["default"])(value, function (valueItem) {
return (0, _utils.isIncludeArray)(disabledValues, valueItem);
});
var newValue = [].concat((0, _toConsumableArray2["default"])(enableValues), (0, _toConsumableArray2["default"])(disabledInValue));
var newSelectOptions = newValue.map(function (valueItem) {
return (0, _arrayTreeFilter["default"])(_this.props.options || [], function (o, level) {
return o[_this.getFieldName('value')] === valueItem[level];
}, {
childrenKeyName: _this.getFieldName('children')
});
});
_this.props.onChange(newValue, newSelectOptions);
_this.setState({
activeValue: []
});
_this.setPopupVisible(false);
} else {
var _newValue = value.filter(function (valueItem) {
return (0, _utils.isIncludeArray)(disabledValues, valueItem);
});
var _newSelectOptions = _newValue.map(function (valueItem) {
return _this.getActiveOptions(valueItem);
});
_this.props.onChange(_newValue, _newSelectOptions);
_this.setState({
activeValue: []
});
}
};
_this.handleActiveValueSet = function (activeValue) {
_this.setState(function (prevState) {
return (0, _extends2["default"])((0, _extends2["default"])({}, prevState), {
activeValue: activeValue
});
});
};
_this.handleItemDoubleClick = function () {
var changeOnSelect = _this.props.changeOnSelect;
if (changeOnSelect) {
_this.setPopupVisible(false);
}
};
_this.handleKeyDown = function (e) {
var children = _this.props.children;
// Don't bind keyboard support when children specify the onKeyDown
if (children && children.props.onKeyDown) {
children.props.onKeyDown(e);
return;
}
var activeValue = (0, _toConsumableArray2["default"])(_this.state.activeValue);
var currentLevel = activeValue.length - 1 < 0 ? 0 : activeValue.length - 1;
var currentOptions = _this.getCurrentLevelOptions();
var currentIndex = currentOptions.map(function (o) {
return o[_this.getFieldName('value')];
}).indexOf(activeValue[currentLevel]);
if (e.keyCode !== _KeyCode["default"].DOWN && e.keyCode !== _KeyCode["default"].UP && e.keyCode !== _KeyCode["default"].LEFT && e.keyCode !== _KeyCode["default"].RIGHT && e.keyCode !== _KeyCode["default"].ENTER && e.keyCode !== _KeyCode["default"].SPACE && e.keyCode !== _KeyCode["default"].BACKSPACE && e.keyCode !== _KeyCode["default"].ESC && e.keyCode !== _KeyCode["default"].TAB) {
return;
}
// Press any keys above to reopen menu
if (!_this.state.popupVisible && e.keyCode !== _KeyCode["default"].BACKSPACE && e.keyCode !== _KeyCode["default"].LEFT && e.keyCode !== _KeyCode["default"].RIGHT && e.keyCode !== _KeyCode["default"].ESC && e.keyCode !== _KeyCode["default"].TAB) {
_this.setPopupVisible(true);
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
return;
}
if (e.keyCode === _KeyCode["default"].DOWN || e.keyCode === _KeyCode["default"].UP) {
e.preventDefault();
var nextIndex = currentIndex;
if (nextIndex !== -1) {
if (e.keyCode === _KeyCode["default"].DOWN) {
nextIndex += 1;
nextIndex = nextIndex >= currentOptions.length ? 0 : nextIndex;
} else {
nextIndex -= 1;
nextIndex = nextIndex < 0 ? currentOptions.length - 1 : nextIndex;
}
} else {
nextIndex = 0;
}
activeValue[currentLevel] = currentOptions[nextIndex][_this.getFieldName('value')];
} else if (e.keyCode === _KeyCode["default"].LEFT || e.keyCode === _KeyCode["default"].BACKSPACE) {
e.preventDefault();
activeValue.splice(activeValue.length - 1, 1);
} else if (e.keyCode === _KeyCode["default"].RIGHT) {
e.preventDefault();
if (currentOptions[currentIndex] && currentOptions[currentIndex][_this.getFieldName('children')]) {
activeValue.push(currentOptions[currentIndex][_this.getFieldName('children')][0][_this.getFieldName('value')]);
}
} else if (e.keyCode === _KeyCode["default"].ESC || e.keyCode === _KeyCode["default"].TAB) {
_this.setPopupVisible(false);
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
return;
}
if (!activeValue || activeValue.length === 0) {
_this.setPopupVisible(false);
}
var activeOptions = _this.getActiveOptions(activeValue);
var targetOption = activeOptions[activeOptions.length - 1];
_this.handleMenuSelect(targetOption, activeOptions.length - 1, e);
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
};
_this.saveTrigger = function (node) {
_this.trigger = node;
};
var initialValue = [];
if ('value' in props) {
initialValue = props.value || [];
} else if ('defaultValue' in props) {
initialValue = props.defaultValue || [];
}
_this.state = {
popupVisible: props.popupVisible,
activeValue: props.initialActiveValue || initialValue,
hoveredValue: [],
prevProps: props
};
_this.defaultFieldNames = {
label: 'label',
value: 'value',
children: 'children'
};
return _this;
}
(0, _inherits2["default"])(Cascader, _React$Component);
return (0, _createClass2["default"])(Cascader, [{
key: "getPopupDOMNode",
value: function getPopupDOMNode() {
return this.trigger.getPopupDomNode();
}
}, {
key: "getFieldName",
value: function getFieldName(name) {
return this.props.fieldNames[name] || this.defaultFieldNames[name];
}
}, {
key: "getFieldNames",
value: function getFieldNames() {
return this.props.fieldNames;
}
}, {
key: "getActiveOptions",
value: function getActiveOptions(activeValue, options) {
var _this2 = this;
return (0, _arrayTreeFilter["default"])(options || this.props.options || [], function (o, level) {
return o[_this2.getFieldName('value')] === activeValue[level];
}, {
childrenKeyName: this.getFieldName('children')
});
}
}, {
key: "getCurrentLevelOptions",
value: function getCurrentLevelOptions() {
var _this$props$options = this.props.options,
options = _this$props$options === void 0 ? [] : _this$props$options;
var _this$state$activeVal = this.state.activeValue,
activeValue = _this$state$activeVal === void 0 ? [] : _this$state$activeVal;
var result = this.getActiveOptions(activeValue);
if (result[result.length - 2]) {
return result[result.length - 2][this.getFieldName('children')];
}
return (0, _toConsumableArray2["default"])(options).filter(function (o) {
return !o.disabled;
});
}
}, {
key: "getTotalValues",
value: function getTotalValues(options) {
var _this3 = this;
var flattenOptions = _flattenTree(options || this.props.options, this.props);
return flattenOptions.map(function (option) {
return option.map(function (o) {
var value = o[_this3.getFieldName('value')];
return _this3.props.keyword ? value[0] : value;
});
});
}
}, {
key: "getEnableValues",
value: function getEnableValues(options) {
var _this4 = this;
var enableOptions = _getEnableOptions(options || this.props.options);
var flattenOptions = _flattenTree(enableOptions, this.props);
return flattenOptions.map(function (option) {
return option.map(function (o) {
return o[_this4.getFieldName('value')];
});
});
}
}, {
key: "getDisabledValues",
value: function getDisabledValues() {
var _this5 = this;
var flattenOptions = _flattenTree(this.props.options, this.props);
var disabledOptions = flattenOptions.filter(function (options) {
return options.some(function (option) {
return option.disabled;
});
});
return disabledOptions.map(function (options) {
return options.map(function (o) {
return o[_this5.getFieldName('value')];
});
});
}
}, {
key: "render",
value: function render() {
var _a = this.props,
prefixCls = _a.prefixCls,
transitionName = _a.transitionName,
popupClassName = _a.popupClassName,
_a$options = _a.options,
options = _a$options === void 0 ? [] : _a$options,
disabled = _a.disabled,
builtinPlacements = _a.builtinPlacements,
popupPlacement = _a.popupPlacement,
children = _a.children,
dropdownRender = _a.dropdownRender,
restProps = __rest(_a, ["prefixCls", "transitionName", "popupClassName", "options", "disabled", "builtinPlacements", "popupPlacement", "children", "dropdownRender"]);
// Did not show popup when there is no options
var menus = /*#__PURE__*/React.createElement("div", null);
var emptyMenuClassName = '';
if (options && options.length > 0) {
menus = /*#__PURE__*/React.createElement(_Menus["default"], (0, _extends2["default"])({}, this.props, {
fieldNames: this.getFieldNames(),
defaultFieldNames: this.defaultFieldNames,
visible: this.state.popupVisible,
activeValue: this.state.activeValue,
hoveredValue: this.state.hoveredValue,
enableValues: this.getEnableValues(),
getEnableValues: this.getEnableValues,
totalValues: this.getTotalValues(),
getTotalValues: this.getTotalValues,
onActiveValueSet: this.handleActiveValueSet,
onSelect: this.handleMenuSelect,
onMultiSelect: this.handleMenuMultiSelect,
onMultiSelectAll: this.handleMenuMultiSelectAll,
onItemDoubleClick: this.handleItemDoubleClick
}));
} else {
emptyMenuClassName = " ".concat(prefixCls, "-menus-empty");
}
var popupNode = menus;
if (dropdownRender) {
popupNode = dropdownRender(menus);
}
return /*#__PURE__*/React.createElement(_rcTrigger["default"], (0, _extends2["default"])({
ref: this.saveTrigger
}, restProps, {
popupPlacement: popupPlacement,
builtinPlacements: builtinPlacements,
popupTransitionName: transitionName,
action: disabled ? [] : ['click'],
popupVisible: disabled ? false : this.state.popupVisible,
onPopupVisibleChange: this.handlePopupVisibleChange,
prefixCls: "".concat(prefixCls, "-menus"),
popupClassName: popupClassName + emptyMenuClassName,
popup: popupNode
}), /*#__PURE__*/React.cloneElement(children, {
onKeyDown: this.handleKeyDown,
tabIndex: disabled ? undefined : 0
}));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
var _prevState$prevProps = prevState.prevProps,
prevProps = _prevState$prevProps === void 0 ? {} : _prevState$prevProps;
var newState = {
prevProps: nextProps
};
if ('value' in nextProps && !(0, _utils.isEqualArrays)(prevProps.value, nextProps.value)) {
// allow activeValue diff from value
if (!('loadData' in nextProps) && nextProps.mode !== 'multiple') {
newState.activeValue = nextProps.value || [];
}
}
if ('popupVisible' in nextProps) {
newState.popupVisible = nextProps.popupVisible;
}
return newState;
}
}]);
}(React.Component);
Cascader.defaultProps = {
onChange: function onChange() {},
onPopupVisibleChange: function onPopupVisibleChange() {},
disabled: false,
transitionName: '',
prefixCls: 'rc-cascader',
popupClassName: '',
popupPlacement: 'bottomLeft',
builtinPlacements: _placements["default"],
expandTrigger: 'hover',
fieldNames: {
label: 'label',
value: 'value',
children: 'children'
},
expandIcon: '>'
};
var _default = exports["default"] = Cascader;