@fruits-chain/react-native-xiaoshu
Version:
🌈 React Native UI library
130 lines (110 loc) • 3.44 kB
JavaScript
import isArray from 'lodash/isArray';
/**
* 获取当前选项是什么数据
* @description cascade 联级选择,multiple 多列选择,single 单列选择
*/
export const getDataType = columns => {
const firstColumn = columns[0];
if (firstColumn) {
if ('children' in firstColumn) {
return 'cascade';
}
if ('options' in firstColumn || isArray(firstColumn)) {
return 'multiple';
}
}
return 'single';
};
export const findDefaultValue = (value, options) => {
// value 是否在 options 内
const valueIndex = options.findIndex(item => item.value === value);
if (valueIndex < 0 || options[valueIndex].disabled) {
// 重新找一个
const index = options.findIndex(item => !item.disabled);
if (index < 0) {
return null;
}
return options[index].value;
}
return value;
};
/** 把联级选择的所有子级找到 */
export const findNextAllColumns = columns => {
const options = [];
const values = [];
const findNext = c => {
if (c.length) {
options.push(c);
values.push(c[0].value);
const cc = c[0].children || [];
findNext(cc);
}
};
findNext(columns);
return {
options,
values
};
};
/** 通过已有值找到联级选择的所有子级找到 */
export const findAllColumnsByValues = (columns, values) => {
const options = []; // TODO 补全候选项还是不需要管
let currentColumn = columns;
values.forEach(value => {
var _currentColumn$nextIn;
options.push(currentColumn);
const nextIndex = currentColumn.findIndex(item => item.value === value);
currentColumn = ((_currentColumn$nextIn = currentColumn[nextIndex]) === null || _currentColumn$nextIn === void 0 ? void 0 : _currentColumn$nextIn.children) || [];
});
return options;
};
/** 构建选项 */
export const buildOptions = (dataType, columns, values) => {
switch (dataType) {
case 'cascade':
{
if (!(values !== null && values !== void 0 && values.length)) {
const data = findNextAllColumns(columns);
return [data.options, [], data.values];
}
return [findAllColumnsByValues(columns, values), [], values];
}
case 'multiple':
{
const mixOptions = [];
const defaultValues = [];
columns.forEach(item => {
const isOption = isArray(item); // 默认值需要检验它是否合法
if (isOption) {
const option = item;
mixOptions.push(option);
defaultValues.push(findDefaultValue(option[0].value, option));
} else {
const {
options: _options,
defaultValue: _defaultValue
} = item;
mixOptions.push(_options);
defaultValues.push(findDefaultValue(_defaultValue, _options));
}
});
return [mixOptions, defaultValues, []];
}
default:
{
const options = [columns];
const [firstColumn] = options[0];
const defaultValues = [firstColumn.value];
return [options, defaultValues, []];
}
}
};
/** 构建选中的值 */
export const buildSelectedValue = (values, options) => {
const selectedColumns = values.map((v, index) => {
const vIndex = options[index].findIndex(o => o.value === v);
return options[index][vIndex];
});
return [values, selectedColumns];
};
//# sourceMappingURL=picker.js.map