@fesjs/fes-design
Version:
fes-design for PC
103 lines (100 loc) • 2.94 kB
JavaScript
import { isArray } from 'lodash-es';
const getCurrentValueByKeys = function (nodeList) {
let keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let props = arguments.length > 2 ? arguments[2] : undefined;
const value = props.multiple || props.emitPath ? [] : null;
if (!keys.length) {
return value;
}
if (props.multiple) {
const nodeValues = Object.keys(nodeList);
// 兼容异步加载,未匹配到节点的情况
const notMatchedKeys = keys.filter(key => !nodeValues.includes(key));
// 保持层级顺序不变
return [].concat(notMatchedKeys, nodeValues.filter(key => keys.includes(key)).map(key => props.emitPath ? [...nodeList[key].indexPath] : key));
} else {
return props.emitPath ? [...nodeList[keys[0]].indexPath] : keys[0];
}
};
const getKeysByCurrentValue = (currentValue, props) => {
const keys = [];
if (currentValue === null) {
return keys;
}
if (props.multiple) {
return currentValue.map(value => {
if (props.emitPath && isArray(value)) {
return value[value.length - 1];
} else {
return value;
}
});
} else {
if (props.emitPath && isArray(currentValue)) {
return currentValue.slice(currentValue.length - 1);
} else {
return [currentValue];
}
}
};
const getNotMatchedPathByKey = (currentValue, props, key) => {
let path = [];
if (currentValue === null) {
return path;
}
if (props.multiple) {
const keyIndex = currentValue.findIndex(value => {
if (props.emitPath && isArray(value)) {
return value.includes(key);
} else {
return value === key;
}
});
if (keyIndex > -1) {
const keyValue = currentValue[keyIndex];
if (props.emitPath && isArray(keyValue)) {
path = keyValue.map(value => {
return {
value,
label: value
};
});
} else {
path = [{
value: keyValue,
label: keyValue
}];
}
}
} else {
if (props.emitPath && isArray(currentValue)) {
if (currentValue.includes(key)) {
path = currentValue.map(value => {
return {
value,
label: value
};
});
}
} else {
if (key === currentValue) {
path = [{
value: currentValue,
label: currentValue
}];
}
}
}
return path;
};
const getExpandedKeysBySelectedKeys = function (nodeList) {
let selectedKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
const selectedNode = selectedKeys[0] && nodeList[selectedKeys[0]] || null;
if (selectedNode) {
// 叶子节点也包含在内,以便操作反馈
return [...selectedNode.indexPath];
} else {
return [];
}
};
export { getCurrentValueByKeys, getExpandedKeysBySelectedKeys, getKeysByCurrentValue, getNotMatchedPathByKey };