acud
Version:
acg react 组件库
544 lines • 21.5 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _isNativeReflectConstruct from "@babel/runtime/helpers/esm/isNativeReflectConstruct";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _extends from "@babel/runtime/helpers/esm/extends";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
var __rest = this && this.__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;
};
import * as React from 'react';
import isEmpty from 'lodash/isEmpty';
import filter from 'lodash/filter';
import findIndex from 'lodash/findIndex';
import sortBy from 'lodash/sortBy';
// eslint-disable-next-line no-duplicate-imports
import Trigger from 'rc-trigger';
import KeyCode from "rc-util/es/KeyCode";
import arrayTreeFilter from 'array-tree-filter';
import { isEqualArrays, isIncludeArray } from './utils';
import Menus from './Menus';
import BUILT_IN_PLACEMENTS from './placements';
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 (!isEmpty(enabledChilren)) {
enabledOptions.push(_extends(_extends({}, option), {
children: enabledChilren
}));
}
return;
}
enabledOptions.push(option);
});
}
return enabledOptions;
};
var Cascader = /*#__PURE__*/function (_React$Component) {
function Cascader(props) {
var _this;
_classCallCheck(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 && !isEmpty(value)) {
if (_this.props.mode !== 'multiple') {
_this.setState({
activeValue: value
});
} else {
// 展开后才能获取到options值
window.setTimeout(function () {
var totalValues = _this.getTotalValues();
var sortedValue = sortBy(value, function (valueItem) {
return findIndex(totalValues, function (totalValueItem) {
return 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.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(_toConsumableArray(optionKey), _toConsumableArray(option.map(function (o) {
return o[_this.getFieldName('value')];
})));
});
newValue = checked ? [].concat(_toConsumableArray(value), _toConsumableArray(childrenValue.filter(function (valueItem) {
return !isIncludeArray(value, valueItem);
}))) : value.filter(function (valueItem) {
return !isIncludeArray(childrenValue, valueItem);
});
}
// 2、当前是最后一级:直接push进value
else {
if (checked) {
newValue = keyword ? [].concat(_toConsumableArray(value), _toConsumableArray(optionKey)) : [].concat(_toConsumableArray(value), [optionKey]);
} else {
newValue = value.filter(function (valueItem) {
return !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 = filter(value, function (valueItem) {
return isIncludeArray(disabledValues, valueItem);
});
var newValue = [].concat(_toConsumableArray(enableValues), _toConsumableArray(disabledInValue));
var newSelectOptions = newValue.map(function (valueItem) {
return arrayTreeFilter(_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 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 _extends(_extends({}, 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 = _toConsumableArray(_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.DOWN && e.keyCode !== KeyCode.UP && e.keyCode !== KeyCode.LEFT && e.keyCode !== KeyCode.RIGHT && e.keyCode !== KeyCode.ENTER && e.keyCode !== KeyCode.SPACE && e.keyCode !== KeyCode.BACKSPACE && e.keyCode !== KeyCode.ESC && e.keyCode !== KeyCode.TAB) {
return;
}
// Press any keys above to reopen menu
if (!_this.state.popupVisible && e.keyCode !== KeyCode.BACKSPACE && e.keyCode !== KeyCode.LEFT && e.keyCode !== KeyCode.RIGHT && e.keyCode !== KeyCode.ESC && e.keyCode !== KeyCode.TAB) {
_this.setPopupVisible(true);
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
return;
}
if (e.keyCode === KeyCode.DOWN || e.keyCode === KeyCode.UP) {
e.preventDefault();
var nextIndex = currentIndex;
if (nextIndex !== -1) {
if (e.keyCode === KeyCode.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.LEFT || e.keyCode === KeyCode.BACKSPACE) {
e.preventDefault();
activeValue.splice(activeValue.length - 1, 1);
} else if (e.keyCode === KeyCode.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.ESC || e.keyCode === KeyCode.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;
}
_inherits(Cascader, _React$Component);
return _createClass(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 arrayTreeFilter(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 _toConsumableArray(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, _extends({}, 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(Trigger, _extends({
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 && !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: BUILT_IN_PLACEMENTS,
expandTrigger: 'hover',
fieldNames: {
label: 'label',
value: 'value',
children: 'children'
},
expandIcon: '>'
};
export default Cascader;