valueCompare 传入 valueField

This commit is contained in:
2betop 2019-12-23 20:06:09 +08:00
parent 67d4146d0c
commit 575a537a9d
4 changed files with 309 additions and 290 deletions

View File

@ -4,14 +4,14 @@
* @author fex
*/
import React from 'react';
import uncontrollable = require('uncontrollable');
import Checkbox from './Checkbox';
import find = require('lodash/find');
import chunk = require('lodash/chunk');
import {flattenTree, isObject} from '../utils/helper';
import {ClassNamesFn, themeable} from '../theme';
import {optionValueCompare} from './Select';
import React from "react";
import uncontrollable = require("uncontrollable");
import Checkbox from "./Checkbox";
import find = require("lodash/find");
import chunk = require("lodash/chunk");
import { flattenTree, isObject } from "../utils/helper";
import { ClassNamesFn, themeable } from "../theme";
import { optionValueCompare } from "./Select";
// import isPlainObject = require('lodash/isPlainObject');
export interface Option {
@ -43,8 +43,8 @@ export function value2array(
props: Partial<OptionProps>
): Array<Option> {
if (props.multi || props.multiple) {
if (typeof value === 'string') {
value = value.split(props.delimiter || ',');
if (typeof value === "string") {
value = value.split(props.delimiter || ",");
}
if (!Array.isArray(value)) {
@ -60,8 +60,8 @@ export function value2array(
expandValue(
!props.joinValues &&
value &&
value.hasOwnProperty(props.valueField || 'value')
? (value as any)[props.valueField || 'value']
value.hasOwnProperty(props.valueField || "value")
? (value as any)[props.valueField || "value"]
: value,
props
)
@ -80,29 +80,32 @@ export function expandValue(
const valueType = typeof value;
if (
valueType !== 'string' &&
valueType !== 'number' &&
valueType !== 'boolean' &&
valueType !== 'object'
valueType !== "string" &&
valueType !== "number" &&
valueType !== "boolean" &&
valueType !== "object"
) {
return null;
}
let {options, valueField} = props;
let { options, valueField } = props;
if (!options) {
return null;
}
if (
valueType === 'object' &&
valueType === "object" &&
value &&
value.hasOwnProperty(props.valueField || 'value')
value.hasOwnProperty(valueField || "value")
) {
value = (value as Option)[valueField || 'value'] || '';
value = (value as Option)[valueField || "value"] || "";
}
return find(flattenTree(options), optionValueCompare(value)) as Option;
return find(
flattenTree(options),
optionValueCompare(value, valueField || "value")
) as Option;
}
/**
@ -138,7 +141,7 @@ export class Checkboxes extends React.PureComponent<CheckboxesProps, any> {
joinValues: true,
extractValue: false,
inline: false,
delimiter: ',',
delimiter: ",",
columnsCount: 1 // 一行显示一个
};
@ -163,7 +166,7 @@ export class Checkboxes extends React.PureComponent<CheckboxesProps, any> {
if (!~idx) {
option =
value2array(option[valueField || 'value'], {
value2array(option[valueField || "value"], {
multiple: true,
valueField,
delimiter,
@ -182,10 +185,10 @@ export class Checkboxes extends React.PureComponent<CheckboxesProps, any> {
if (joinValues) {
newValue = newValue
.map(item => item[valueField || 'value'])
.map(item => item[valueField || "value"])
.join(delimiter);
} else if (extractValue) {
newValue = newValue.map(item => item[valueField || 'value']);
newValue = newValue.map(item => item[valueField || "value"]);
}
onChange && onChange(newValue);
@ -231,8 +234,8 @@ export class Checkboxes extends React.PureComponent<CheckboxesProps, any> {
if (!inline && (columnsCount as number) > 1) {
let cellClassName = `col-sm-${(12 / (columnsCount as number))
.toFixed(1)
.replace(/\.0$/, '')
.replace(/\./, '-')}`;
.replace(/\.0$/, "")
.replace(/\./, "-")}`;
body = chunk(body, columnsCount).map((group, groupIndex) => (
<div className="row" key={groupIndex}>
{group.map((item, index) => (
@ -254,6 +257,6 @@ export class Checkboxes extends React.PureComponent<CheckboxesProps, any> {
export default themeable(
uncontrollable(Checkboxes, {
value: 'onChange'
value: "onChange"
})
);

View File

@ -5,24 +5,24 @@
* @date 2017-11-07
*/
import uncontrollable = require('uncontrollable');
import React from 'react';
import 'react-datetime/css/react-datetime.css';
import Overlay from './Overlay';
import PopOver from './PopOver';
import Downshift, {ControllerStateAndHelpers} from 'downshift';
import {closeIcon, Icon} from './icons';
import uncontrollable = require("uncontrollable");
import React from "react";
import "react-datetime/css/react-datetime.css";
import Overlay from "./Overlay";
import PopOver from "./PopOver";
import Downshift, { ControllerStateAndHelpers } from "downshift";
import { closeIcon, Icon } from "./icons";
// @ts-ignore
import matchSorter from 'match-sorter';
import {noop, isObject} from '../utils/helper';
import find = require('lodash/find');
import isPlainObject = require('lodash/isPlainObject');
import union = require('lodash/union');
import {highlight} from '../renderers/Form/Options';
import {findDOMNode} from 'react-dom';
import {ClassNamesFn, themeable} from '../theme';
import Checkbox from './Checkbox';
import Input from './Input';
import matchSorter from "match-sorter";
import { noop, isObject } from "../utils/helper";
import find = require("lodash/find");
import isPlainObject = require("lodash/isPlainObject");
import union = require("lodash/union");
import { highlight } from "../renderers/Form/Options";
import { findDOMNode } from "react-dom";
import { ClassNamesFn, themeable } from "../theme";
import Checkbox from "./Checkbox";
import Input from "./Input";
export interface Option {
label?: string;
@ -46,7 +46,7 @@ export interface OptionProps {
delimiter?: string;
clearable?: boolean;
placeholder?: string;
autoFill?: {[propName: string]: any};
autoFill?: { [propName: string]: any };
creatable?: boolean;
onAdd?: (
idx?: number | Array<number>,
@ -68,8 +68,8 @@ export function value2array(
props: Partial<OptionProps>
): Array<Option> {
if (props.multi || props.multiple) {
if (typeof value === 'string') {
value = value.split(props.delimiter || ',');
if (typeof value === "string") {
value = value.split(props.delimiter || ",");
}
if (!Array.isArray(value)) {
@ -98,47 +98,53 @@ export function expandValue(
const valueType = typeof value;
if (
valueType !== 'string' &&
valueType !== 'number' &&
valueType !== 'boolean'
valueType !== "string" &&
valueType !== "number" &&
valueType !== "boolean"
) {
return value as Option;
}
let {options} = props;
let { options } = props;
if (!options) {
return null;
}
return find(options, optionValueCompare(value)) as Option;
return find(
options,
optionValueCompare(value, props.valueField || "value")
) as Option;
}
export function matchOptionValue(
a: OptionValue,
b: Option,
valueField: string = 'value'
valueField: string = "value"
) {
return isObject(a)
? a === b[valueField || 'value']
: String(b[valueField || 'value']) === String(a);
? a === b[valueField || "value"]
: String(b[valueField || "value"]) === String(a);
}
export function optionValueCompare(a: OptionValue) {
return (b: Option) => matchOptionValue(a, b);
export function optionValueCompare(
a: OptionValue,
valueField: string = "value"
) {
return (b: Option) => matchOptionValue(a, b, valueField);
}
export function normalizeOptions(
options: string | {[propName: string]: string} | Array<string> | Options
options: string | { [propName: string]: string } | Array<string> | Options
): Options {
if (typeof options === 'string') {
return options.split(',').map(item => ({
if (typeof options === "string") {
return options.split(",").map(item => ({
label: item,
value: item
}));
} else if (
Array.isArray(options as Array<string>) &&
typeof (options as Array<string>)[0] === 'string'
typeof (options as Array<string>)[0] === "string"
) {
return (options as Array<string>).map(item => ({
label: item,
@ -151,7 +157,7 @@ export function normalizeOptions(
value: item && item.value
};
if (typeof option.children !== 'undefined') {
if (typeof option.children !== "undefined") {
option.children = normalizeOptions(option.children);
}
@ -159,7 +165,7 @@ export function normalizeOptions(
});
} else if (isPlainObject(options)) {
return Object.keys(options).map(key => ({
label: (options as {[propName: string]: string})[key] as string,
label: (options as { [propName: string]: string })[key] as string,
value: key
}));
}
@ -217,20 +223,20 @@ export class Select extends React.Component<SelectProps, SelectState> {
multiple: false,
clearable: true,
creatable: false,
createBtnLabel: '新增选项',
searchPromptText: '输入内容进行检索',
loadingPlaceholder: '加载中..',
noResultsText: '未找到任何结果',
clearAllText: '移除所有',
clearValueText: '移除',
placeholder: '请选择',
valueField: 'value',
labelField: 'label',
spinnerClassName: 'fa fa-spinner fa-spin fa-1x fa-fw',
createBtnLabel: "新增选项",
searchPromptText: "输入内容进行检索",
loadingPlaceholder: "加载中..",
noResultsText: "未找到任何结果",
clearAllText: "移除所有",
clearValueText: "移除",
placeholder: "请选择",
valueField: "value",
labelField: "label",
spinnerClassName: "fa fa-spinner fa-spin fa-1x fa-fw",
inline: false,
disabled: false,
checkAll: false,
checkAllLabel: '全选',
checkAllLabel: "全选",
defaultCheckAll: false
};
@ -261,7 +267,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
this.state = {
isOpen: props.defaultOpen || false,
isFocused: false,
inputValue: '',
inputValue: "",
highlightedIndex: -1,
selection: value2array(props.value, props)
};
@ -276,7 +282,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
onChange,
simpleValue
} = this.props;
let {selection} = this.state;
let { selection } = this.state;
if (multiple && defaultCheckAll && options.length) {
selection = union(options, selection);
@ -290,7 +296,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
onChange(simpleValue ? selection.map(item => item.value) : selection);
}
loadOptions && loadOptions('');
loadOptions && loadOptions("");
}
componentWillReceiveProps(nextProps: SelectProps) {
@ -387,8 +393,8 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
toggleCheckAll() {
const {options, onChange, simpleValue} = this.props;
let {selection} = this.state;
const { options, onChange, simpleValue } = this.props;
let { selection } = this.state;
const optionsValues = options.map(option => option.value);
const selectionValues = selection.map(select => select.value);
const checkedAll = optionsValues.every(
@ -400,11 +406,11 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
removeItem(index: number, e?: React.MouseEvent<HTMLElement>) {
const {onChange, simpleValue, disabled} = this.props;
const { onChange, simpleValue, disabled } = this.props;
if (disabled) {
return;
}
let {selection: value} = this.state;
let { selection: value } = this.state;
e && e.stopPropagation();
value = Array.isArray(value) ? value.concat() : [value];
@ -414,7 +420,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
handleInputChange(evt: React.ChangeEvent<HTMLInputElement>) {
const {loadOptions} = this.props;
const { loadOptions } = this.props;
this.setState(
{
@ -425,8 +431,8 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
handleChange(selectItem: any) {
const {onChange, multiple, simpleValue} = this.props;
let {selection} = this.state;
const { onChange, multiple, simpleValue } = this.props;
let { selection } = this.state;
if (multiple) {
const selectionValues = selection.map(item => item.value);
@ -444,7 +450,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
handleStateChange(changes: any) {
const {multiple, checkAll} = this.props;
const { multiple, checkAll } = this.props;
let update: any = {};
const loadOptions = this.props.loadOptions;
let doLoad = false;
@ -474,13 +480,13 @@ export class Select extends React.Component<SelectProps, SelectState> {
if (Object.keys(update).length) {
this.setState(
update,
doLoad && loadOptions ? () => loadOptions('') : undefined
doLoad && loadOptions ? () => loadOptions("") : undefined
);
}
}
handleKeyPress(e: React.KeyboardEvent) {
if (e.key === ' ') {
if (e.key === " ") {
this.toggle();
}
}
@ -489,29 +495,29 @@ export class Select extends React.Component<SelectProps, SelectState> {
const onChange = this.props.onChange;
e.preventDefault();
e.stopPropagation();
onChange('');
onChange("");
}
handleAddClick() {
const {onAdd} = this.props;
const { onAdd } = this.props;
onAdd && onAdd();
}
handleEditClick(e: Event, item: any) {
const {onEdit} = this.props;
const { onEdit } = this.props;
e.preventDefault();
e.stopPropagation();
onEdit && onEdit(item);
}
handleDeleteClick(e: Event, item: any) {
const {onDelete} = this.props;
const { onDelete } = this.props;
e.preventDefault();
e.stopPropagation();
onDelete && onDelete(item);
}
renderValue({inputValue, isOpen}: ControllerStateAndHelpers<any>) {
renderValue({ inputValue, isOpen }: ControllerStateAndHelpers<any>) {
const {
multiple,
placeholder,
@ -534,18 +540,18 @@ export class Select extends React.Component<SelectProps, SelectState> {
multiple ? (
<div className={`${ns}Select-value`} key={index}>
<span
className={`${ns}Select-valueIcon ${disabled ? 'is-disabled' : ''}`}
className={`${ns}Select-valueIcon ${disabled ? "is-disabled" : ""}`}
onClick={this.removeItem.bind(this, index)}
>
×
</span>
<span className={`${ns}Select-valueLabel`}>
{item[labelField || 'label']}
{item[labelField || "label"]}
</span>
</div>
) : (
<div className={`${ns}Select-value`} key={index}>
{item[labelField || 'label']}
{item[labelField || "label"]}
</div>
)
);
@ -579,14 +585,14 @@ export class Select extends React.Component<SelectProps, SelectState> {
editable,
removable
} = this.props;
const {selection} = this.state;
const { selection } = this.state;
let checkedAll = false;
let checkedPartial = false;
let filtedOptions: Array<Option> =
inputValue && isOpen && !loadOptions
? matchSorter(options, inputValue, {
keys: [labelField || 'label', valueField || 'value']
keys: [labelField || "label", valueField || "value"]
})
: options.concat();
@ -603,11 +609,11 @@ export class Select extends React.Component<SelectProps, SelectState> {
}
const menu = (
<div ref={this.menu} className={cx('Select-menu')}>
<div ref={this.menu} className={cx("Select-menu")}>
{searchable ? (
<div
className={cx(`Select-input`, {
'is-focused': this.state.isFocused
"is-focused": this.state.isFocused
})}
>
<Icon icon="search" className="icon" />
@ -625,7 +631,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
) : null}
{multiple && checkAll && filtedOptions.length ? (
<div className={cx('Select-option')}>
<div className={cx("Select-option")}>
<Checkbox
checked={checkedPartial}
partial={checkedPartial && !checkedAll}
@ -645,7 +651,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
<div
{...getItemProps({
key:
typeof item.value === 'string'
typeof item.value === "string"
? `${item.label}-${item.value}`
: index,
index,
@ -653,9 +659,9 @@ export class Select extends React.Component<SelectProps, SelectState> {
disabled: item.disabled
})}
className={cx(`Select-option`, {
'is-disabled': item.disabled,
'is-highlight': highlightedIndex === index,
'is-active': checked
"is-disabled": item.disabled,
"is-highlight": highlightedIndex === index,
"is-active": checked
})}
>
{removable ? (
@ -690,7 +696,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
: highlight(
item[labelField],
inputValue as string,
cx('Select-option-hl')
cx("Select-option-hl")
)}
</Checkbox>
) : (
@ -700,7 +706,7 @@ export class Select extends React.Component<SelectProps, SelectState> {
: highlight(
item[labelField],
inputValue as string,
cx('Select-option-hl')
cx("Select-option-hl")
)}
{item.tip}
</span>
@ -709,11 +715,11 @@ export class Select extends React.Component<SelectProps, SelectState> {
);
})
) : (
<div className={cx('Select-noResult')}>{noResultsText}</div>
<div className={cx("Select-noResult")}>{noResultsText}</div>
)}
{creatable && !disabled ? (
<a className={cx('Select-addBtn')} onClick={this.handleAddClick}>
<a className={cx("Select-addBtn")} onClick={this.handleAddClick}>
<Icon icon="plus" className="icon" />
{createBtnLabel}
</a>
@ -729,8 +735,8 @@ export class Select extends React.Component<SelectProps, SelectState> {
>
<PopOver
overlay
className={cx('Select-popover')}
style={{minWidth: this.target ? this.target.offsetWidth : 'auto'}}
className={cx("Select-popover")}
style={{ minWidth: this.target ? this.target.offsetWidth : "auto" }}
onHide={this.close}
>
{menu}
@ -771,10 +777,10 @@ export class Select extends React.Component<SelectProps, SelectState> {
: this.handleChange
}
onStateChange={this.handleStateChange}
itemToString={item => (item ? item[labelField] : '')}
itemToString={item => (item ? item[labelField] : "")}
>
{(options: ControllerStateAndHelpers<any>) => {
const {isOpen} = options;
const { isOpen } = options;
return (
<div
tabIndex={disabled ? -1 : 0}
@ -788,9 +794,9 @@ export class Select extends React.Component<SelectProps, SelectState> {
[`Select--multi`]: multiple,
[`Select--inline`]: inline,
[`Select--searchable`]: searchable,
'is-opened': isOpen,
'is-focused': this.state.isFocused,
'is-disabled': disabled
"is-opened": isOpen,
"is-focused": this.state.isFocused,
"is-disabled": disabled
},
className
)}
@ -799,17 +805,17 @@ export class Select extends React.Component<SelectProps, SelectState> {
{this.renderValue(options)}
</div>
{clearable && !disabled && value && value.length ? (
<a onClick={this.clearValue} className={cx('Select-clear')}>
<a onClick={this.clearValue} className={cx("Select-clear")}>
<Icon icon="close" className="icon" />
</a>
) : null}
{loading ? (
<span className={cx('Select-spinner')}>
<span className={cx("Select-spinner")}>
<i className={spinnerClassName} />
</span>
) : null}
<span className={cx('Select-arrow')} />
<span className={cx("Select-arrow")} />
{isOpen ? this.renderOuter(options) : null}
</div>
);
@ -821,6 +827,6 @@ export class Select extends React.Component<SelectProps, SelectState> {
export default themeable(
uncontrollable(Select, {
value: 'onChange'
value: "onChange"
})
);

View File

@ -2,9 +2,9 @@
* @file SelectRadiosCheckboxes
* ListButtonGroup
*/
import {Api, Schema} from '../../types';
import {isEffectiveApi, isApiOutdated} from '../../utils/api';
import {isAlive} from 'mobx-state-tree';
import { Api, Schema } from "../../types";
import { isEffectiveApi, isApiOutdated } from "../../utils/api";
import { isAlive } from "mobx-state-tree";
import {
anyChanged,
autobind,
@ -13,29 +13,29 @@ import {
spliceTree,
findTreeIndex,
getTree
} from '../../utils/helper';
import {reaction} from 'mobx';
} from "../../utils/helper";
import { reaction } from "mobx";
import {
FormControlProps,
registerFormItem,
FormItemBasicConfig,
detectProps as itemDetectProps
} from './Item';
import {IFormItemStore} from '../../store/formItem';
} from "./Item";
import { IFormItemStore } from "../../store/formItem";
export type OptionsControlComponent = React.ComponentType<FormControlProps>;
import React from 'react';
import {resolveVariableAndFilter} from '../../utils/tpl-builtin';
import React from "react";
import { resolveVariableAndFilter } from "../../utils/tpl-builtin";
import {
Option,
OptionProps,
normalizeOptions,
optionValueCompare
} from '../../components/Select';
import {filter} from '../../utils/tpl';
import findIndex from 'lodash/findIndex';
} from "../../components/Select";
import { filter } from "../../utils/tpl";
import findIndex from "lodash/findIndex";
export {Option};
export { Option };
export interface OptionsBasicConfig extends FormItemBasicConfig {
autoLoadOptionsFromSource?: boolean;
@ -87,18 +87,18 @@ export interface OptionsProps extends FormControlProps, OptionProps {
}
export const detectProps = itemDetectProps.concat([
'options',
'size',
'buttons',
'columnsCount',
'multiple',
'hideRoot',
'checkAll',
'showIcon',
'showRadio',
'btnDisabled',
'joinValues',
'extractValue'
"options",
"size",
"buttons",
"columnsCount",
"multiple",
"hideRoot",
"checkAll",
"showIcon",
"showRadio",
"btnDisabled",
"joinValues",
"extractValue"
]);
export function registerOptionsControl(config: OptionsConfig) {
@ -107,15 +107,15 @@ export function registerOptionsControl(config: OptionsConfig) {
class FormOptionsItem extends React.Component<OptionsProps, any> {
static displayName = `OptionsControl(${config.type})`;
static defaultProps = {
delimiter: ',',
labelField: 'label',
valueField: 'value',
delimiter: ",",
labelField: "label",
valueField: "value",
joinValues: true,
extractValue: false,
multiple: false,
placeholder: '请选择',
resetValue: '',
deleteConfirmText: '确定要删除?',
placeholder: "请选择",
resetValue: "",
deleteConfirmText: "确定要删除?",
...Control.defaultProps
};
static propsList: any = (Control as any).propsList
@ -158,7 +158,7 @@ export function registerOptionsControl(config: OptionsConfig) {
if (/^\$(?:([a-z0-9_.]+)|{.+})$/.test(source as string) && formItem) {
formItem.setOptions(
normalizeOptions(
resolveVariableAndFilter(source as string, data, '| raw') || []
resolveVariableAndFilter(source as string, data, "| raw") || []
)
);
loadOptions = false;
@ -170,7 +170,7 @@ export function registerOptionsControl(config: OptionsConfig) {
.getSelectedOptions(value)
.map(
(selectedOption: Option) =>
selectedOption[valueField || 'value']
selectedOption[valueField || "value"]
)
: formItem.getSelectedOptions(value);
setPrinstineValue(
@ -182,7 +182,7 @@ export function registerOptionsControl(config: OptionsConfig) {
config.autoLoadOptionsFromSource !== false &&
(formInited
? this.reload()
: addHook && addHook(this.initOptions, 'init'));
: addHook && addHook(this.initOptions, "init"));
}
componentDidMount() {
@ -229,12 +229,12 @@ export function registerOptionsControl(config: OptionsConfig) {
const prevOptions = resolveVariableAndFilter(
prevProps.source as string,
prevProps.data,
'| raw'
"| raw"
);
const options = resolveVariableAndFilter(
props.source as string,
props.data,
'| raw'
"| raw"
);
prevOptions !== options &&
formItem.setOptions(normalizeOptions(options || []));
@ -260,7 +260,7 @@ export function registerOptionsControl(config: OptionsConfig) {
}
componentWillUnmount() {
this.props.removeHook && this.props.removeHook(this.reload, 'init');
this.props.removeHook && this.props.removeHook(this.reload, "init");
this.reaction && this.reaction();
}
@ -280,7 +280,7 @@ export function registerOptionsControl(config: OptionsConfig) {
if (
extractValue === false &&
(typeof value === 'string' || typeof value === 'number')
(typeof value === "string" || typeof value === "number")
) {
const selectedOptions = formItem.getSelectedOptions(value);
formItem.changeValue(
@ -292,16 +292,16 @@ export function registerOptionsControl(config: OptionsConfig) {
!(
(Array.isArray(value) &&
value.every(
val => typeof val === 'string' || typeof val === 'number'
val => typeof val === "string" || typeof val === "number"
)) ||
typeof value === 'string' ||
typeof value === 'number'
typeof value === "string" ||
typeof value === "number"
)
) {
const selectedOptions = formItem
.getSelectedOptions(value)
.map(
(selectedOption: Option) => selectedOption[valueField || 'value']
(selectedOption: Option) => selectedOption[valueField || "value"]
);
formItem.changeValue(
multiple ? selectedOptions.concat() : selectedOptions[0]
@ -342,8 +342,11 @@ export function registerOptionsControl(config: OptionsConfig) {
}
let valueArray = formItem.getSelectedOptions(value).concat();
const idx = findIndex(valueArray, optionValueCompare(option.value));
let newValue: string | Array<Option> | Option = '';
const idx = findIndex(
valueArray,
optionValueCompare(option.value, valueField || "value")
);
let newValue: string | Array<Option> | Option = "";
if (multiple) {
if (~idx) {
@ -356,11 +359,11 @@ export function registerOptionsControl(config: OptionsConfig) {
if (joinValues) {
newValue = (newValue as Array<any>)
.map(item => item[valueField || 'value'])
.map(item => item[valueField || "value"])
.join(delimiter);
} else if (extractValue) {
newValue = (newValue as Array<any>).map(
item => item[valueField || 'value']
item => item[valueField || "value"]
);
}
} else {
@ -373,7 +376,7 @@ export function registerOptionsControl(config: OptionsConfig) {
newValue = valueArray[0] || resetValue;
if (joinValues && newValue) {
newValue = (newValue as any)[valueField || 'value'];
newValue = (newValue as any)[valueField || "value"];
}
}
@ -404,25 +407,25 @@ export function registerOptionsControl(config: OptionsConfig) {
? []
: formItem.filteredOptions.concat();
let newValue: string | Array<Option> | Option = '';
let newValue: string | Array<Option> | Option = "";
if (multiple) {
newValue = valueArray;
if (joinValues) {
newValue = (newValue as Array<any>)
.map(item => item[valueField || 'value'])
.map(item => item[valueField || "value"])
.join(delimiter);
} else if (extractValue) {
newValue = (newValue as Array<any>).map(
item => item[valueField || 'value']
item => item[valueField || "value"]
);
}
} else {
newValue = valueArray[0] || resetValue;
if (joinValues && newValue) {
newValue = (newValue as any)[valueField || 'value'];
newValue = (newValue as any)[valueField || "value"];
}
}
@ -432,7 +435,7 @@ export function registerOptionsControl(config: OptionsConfig) {
// 当有 action 触发,如果指定了 reload 目标组件,有可能会来到这里面来
@autobind
reload() {
const {source, formItem, data, onChange} = this.props;
const { source, formItem, data, onChange } = this.props;
if (!formItem || !isEffectiveApi(source, data)) {
return;
@ -444,7 +447,7 @@ export function registerOptionsControl(config: OptionsConfig) {
@autobind
async initOptions(data: any) {
await this.reload();
const {formItem, name} = this.props;
const { formItem, name } = this.props;
if (!formItem) {
return;
}
@ -505,10 +508,10 @@ export function registerOptionsControl(config: OptionsConfig) {
if (!skipForm && (!Array.isArray(addControls) || !addControls.length)) {
addControls = [
{
type: 'text',
name: labelField || 'label',
type: "text",
name: labelField || "label",
label: false,
placeholder: '请输入名称'
placeholder: "请输入名称"
}
];
}
@ -526,10 +529,10 @@ export function registerOptionsControl(config: OptionsConfig) {
? ctx
: await onOpenDialog(
{
type: 'dialog',
title: createBtnLabel || `新增${optionLabel || '选项'}`,
type: "dialog",
title: createBtnLabel || `新增${optionLabel || "选项"}`,
body: {
type: 'form',
type: "form",
api: addApi,
controls: addControls
}
@ -541,11 +544,11 @@ export function registerOptionsControl(config: OptionsConfig) {
if (skipForm && addApi) {
try {
const payload = await env.fetcher(addApi!, result, {
method: 'post'
method: "post"
});
if (!payload.ok) {
env.notify('error', payload.msg || '新增失败,请仔细检查');
env.notify("error", payload.msg || "新增失败,请仔细检查");
result = null;
} else {
result = payload.data || result;
@ -553,7 +556,7 @@ export function registerOptionsControl(config: OptionsConfig) {
} catch (e) {
result = null;
console.error(e);
env.notify('error', e.message);
env.notify("error", e.message);
}
}
@ -563,10 +566,10 @@ export function registerOptionsControl(config: OptionsConfig) {
}
// 没走服务端的。
if (!result.hasOwnProperty(valueField || 'value')) {
if (!result.hasOwnProperty(valueField || "value")) {
result = {
...result,
[valueField || 'value']: result[labelField || 'label']
[valueField || "value"]: result[labelField || "label"]
};
}
@ -578,11 +581,11 @@ export function registerOptionsControl(config: OptionsConfig) {
// 否则直接前端变更 options
let options = model.options.concat();
if (Array.isArray(idx)) {
options = spliceTree(options, idx, 0, {...result});
options = spliceTree(options, idx, 0, { ...result });
} else {
~idx
? options.splice(idx, 0, {...result})
: options.push({...result});
? options.splice(idx, 0, { ...result })
: options.push({ ...result });
}
model.setOptions(options);
}
@ -614,10 +617,10 @@ export function registerOptionsControl(config: OptionsConfig) {
if (!skipForm && (!Array.isArray(editControls) || !editControls.length)) {
editControls = [
{
type: 'text',
name: labelField || 'label',
type: "text",
name: labelField || "label",
label: false,
placeholder: '请输入名称'
placeholder: "请输入名称"
}
];
}
@ -626,10 +629,10 @@ export function registerOptionsControl(config: OptionsConfig) {
? value
: await onOpenDialog(
{
type: 'dialog',
title: `编辑${optionLabel || '选项'}`,
type: "dialog",
title: `编辑${optionLabel || "选项"}`,
body: {
type: 'form',
type: "form",
api: editApi,
controls: editControls
}
@ -644,12 +647,12 @@ export function registerOptionsControl(config: OptionsConfig) {
editApi!,
createObject(data, result),
{
method: 'post'
method: "post"
}
);
if (!payload.ok) {
env.notify('error', payload.msg || '保存失败,请仔细检查');
env.notify("error", payload.msg || "保存失败,请仔细检查");
result = null;
} else {
result = payload.data || result;
@ -657,7 +660,7 @@ export function registerOptionsControl(config: OptionsConfig) {
} catch (e) {
result = null;
console.error(e);
env.notify('error', e.message);
env.notify("error", e.message);
}
}
@ -712,22 +715,22 @@ export function registerOptionsControl(config: OptionsConfig) {
// 通过 deleteApi 删除。
try {
if (!deleteApi) {
throw new Error('请配置 deleteApi');
throw new Error("请配置 deleteApi");
}
const result = await env.fetcher(deleteApi!, ctx, {
method: 'delete'
method: "delete"
});
if (!result.ok) {
env.notify('error', result.msg || '删除失败,请重试');
env.notify("error", result.msg || "删除失败,请重试");
} else if (source) {
this.reload();
} else {
const options = model.options.concat();
const idx = findIndex(
options,
item => item[valueField || 'value'] == value[valueField || 'value']
item => item[valueField || "value"] == value[valueField || "value"]
);
if (~idx) {
@ -737,7 +740,7 @@ export function registerOptionsControl(config: OptionsConfig) {
}
} catch (e) {
console.error(e);
env.notify('error', e.message);
env.notify("error", e.message);
}
}
@ -799,7 +802,7 @@ export function OptionsControl(config: OptionsBasicConfig) {
export function highlight(
text: string,
input?: string,
hlClassName: string = 'is-matched'
hlClassName: string = "is-matched"
) {
if (!input) {
return text;
@ -807,8 +810,8 @@ export function highlight(
text = String(text);
const reg = new RegExp(
input.replace(/([\$\^\*\+\-\?\.\(\)\|\[\]\\])/, '\\$1'),
'i'
input.replace(/([\$\^\*\+\-\?\.\(\)\|\[\]\\])/, "\\$1"),
"i"
);
if (!reg.test(text)) {
return text;

View File

@ -5,26 +5,26 @@ import {
flow,
getRoot,
hasParent
} from 'mobx-state-tree';
import {IFormStore} from './form';
import {str2rules, validate as doValidate} from '../utils/validations';
import {Api, Payload, fetchOptions} from '../types';
import {ComboStore, IComboStore, IUniqueGroup} from './combo';
import {evalExpression} from '../utils/tpl';
import findIndex = require('lodash/findIndex');
} from "mobx-state-tree";
import { IFormStore } from "./form";
import { str2rules, validate as doValidate } from "../utils/validations";
import { Api, Payload, fetchOptions } from "../types";
import { ComboStore, IComboStore, IUniqueGroup } from "./combo";
import { evalExpression } from "../utils/tpl";
import findIndex = require("lodash/findIndex");
import {
isArrayChildrenModified,
isObject,
createObject,
isObjectShallowModified,
findTree
} from '../utils/helper';
import {flattenTree} from '../utils/helper';
import {IRendererStore} from '.';
import {normalizeOptions, optionValueCompare} from '../components/Select';
import find = require('lodash/find');
import {SimpleMap} from '../utils/SimpleMap';
import memoize = require('lodash/memoize');
} from "../utils/helper";
import { flattenTree } from "../utils/helper";
import { IRendererStore } from ".";
import { normalizeOptions, optionValueCompare } from "../components/Select";
import find = require("lodash/find");
import { SimpleMap } from "../utils/SimpleMap";
import memoize = require("lodash/memoize");
interface IOption {
value?: string | number | null;
@ -35,16 +35,16 @@ interface IOption {
hidden?: boolean | null;
}
const ErrorDetail = types.model('ErrorDetail', {
msg: '',
tag: ''
const ErrorDetail = types.model("ErrorDetail", {
msg: "",
tag: ""
});
export const FormItemStore = types
.model('FormItemStore', {
.model("FormItemStore", {
identifier: types.identifier,
isFocused: false,
type: '',
type: "",
unique: false,
loading: false,
required: false,
@ -52,14 +52,14 @@ export const FormItemStore = types
messages: types.optional(types.frozen(), {}),
errorData: types.optional(types.array(ErrorDetail), []),
name: types.string,
id: '', // 因为 name 可能会重名,所以加个 id 进来,如果有需要用来定位具体某一个
id: "", // 因为 name 可能会重名,所以加个 id 进来,如果有需要用来定位具体某一个
unsetValueOnInvisible: false,
validated: false,
validating: false,
multiple: false,
delimiter: ',',
valueField: 'value',
labelField: 'label',
delimiter: ",",
valueField: "value",
labelField: "label",
joinValues: true,
extractValue: false,
options: types.optional(types.array(types.frozen()), []),
@ -84,7 +84,7 @@ export const FormItemStore = types
return self.selectedOptions[self.selectedOptions.length - 1].value;
}
return '';
return "";
}
function getErrors(): Array<string> {
@ -120,33 +120,33 @@ export const FormItemStore = types
},
getSelectedOptions: (value: any = getValue()) => {
if (typeof value === 'undefined') {
if (typeof value === "undefined") {
return [];
}
const selected = Array.isArray(value)
? value.map(item =>
item && item.hasOwnProperty(self.valueField || 'value')
? item[self.valueField || 'value']
item && item.hasOwnProperty(self.valueField || "value")
? item[self.valueField || "value"]
: item
)
: typeof value === 'string'
? value.split(self.delimiter || ',')
: typeof value === "string"
? value.split(self.delimiter || ",")
: [
value && value.hasOwnProperty(self.valueField || 'value')
? value[self.valueField || 'value']
value && value.hasOwnProperty(self.valueField || "value")
? value[self.valueField || "value"]
: value
];
// 保留原来的 label 信息,如果原始值中有 label。
if (
value &&
value.hasOwnProperty(self.labelField || 'label') &&
!selected[0].hasOwnProperty(self.labelField || 'label')
value.hasOwnProperty(self.labelField || "label") &&
!selected[0].hasOwnProperty(self.labelField || "label")
) {
selected[0] = {
[self.labelField || 'label']: value[self.labelField || 'label'],
[self.valueField || 'value']: value[self.valueField || 'value']
[self.labelField || "label"]: value[self.labelField || "label"],
[self.valueField || "value"]: value[self.valueField || "value"]
};
}
@ -155,7 +155,7 @@ export const FormItemStore = types
selected.forEach((item, index) => {
const matched = findTree(
self.filteredOptions,
optionValueCompare(item)
optionValueCompare(item, self.valueField || "value")
);
if (matched) {
@ -165,11 +165,11 @@ export const FormItemStore = types
if (
unMatched &&
(typeof unMatched === 'string' || typeof unMatched === 'number')
(typeof unMatched === "string" || typeof unMatched === "number")
) {
unMatched = {
[self.valueField || 'value']: item,
[self.labelField || 'label']: item
[self.valueField || "value"]: item,
[self.labelField || "label"]: item
};
}
@ -204,8 +204,8 @@ export const FormItemStore = types
required?: any;
unique?: any;
value?: any;
rules?: string | {[propName: string]: any};
messages?: {[propName: string]: string};
rules?: string | { [propName: string]: any };
messages?: { [propName: string]: string };
multiple?: boolean;
delimiter?: string;
valueField?: string;
@ -215,25 +215,25 @@ export const FormItemStore = types
type?: string;
id?: string;
}) {
if (typeof rules === 'string') {
if (typeof rules === "string") {
rules = str2rules(rules);
}
typeof type !== 'undefined' && (self.type = type);
typeof id !== 'undefined' && (self.id = id);
typeof messages !== 'undefined' && (self.messages = messages);
typeof required !== 'undefined' && (self.required = !!required);
typeof unique !== 'undefined' && (self.unique = !!unique);
typeof multiple !== 'undefined' && (self.multiple = !!multiple);
typeof joinValues !== 'undefined' && (self.joinValues = !!joinValues);
typeof extractValue !== 'undefined' &&
typeof type !== "undefined" && (self.type = type);
typeof id !== "undefined" && (self.id = id);
typeof messages !== "undefined" && (self.messages = messages);
typeof required !== "undefined" && (self.required = !!required);
typeof unique !== "undefined" && (self.unique = !!unique);
typeof multiple !== "undefined" && (self.multiple = !!multiple);
typeof joinValues !== "undefined" && (self.joinValues = !!joinValues);
typeof extractValue !== "undefined" &&
(self.extractValue = !!extractValue);
typeof delimiter !== 'undefined' &&
(self.delimiter = (delimiter as string) || ',');
typeof valueField !== 'undefined' &&
(self.valueField = (valueField as string) || 'value');
typeof labelField !== 'undefined' &&
(self.labelField = (labelField as string) || 'label');
typeof delimiter !== "undefined" &&
(self.delimiter = (delimiter as string) || ",");
typeof valueField !== "undefined" &&
(self.valueField = (valueField as string) || "value");
typeof labelField !== "undefined" &&
(self.labelField = (labelField as string) || "label");
rules = rules || {};
rules = {
@ -243,7 +243,7 @@ export const FormItemStore = types
if (isObjectShallowModified(rules, self.rules)) {
self.rules = rules;
clearError('bultin');
clearError("bultin");
self.validated = false;
}
@ -261,7 +261,7 @@ export const FormItemStore = types
}
function changeValue(value: any, isPrintine: boolean = false) {
if (typeof value === 'undefined' || value === '__undefined') {
if (typeof value === "undefined" || value === "__undefined") {
self.form.deleteValueByName(self.name);
} else {
self.form.setValueByName(self.name, value, isPrintine);
@ -289,7 +289,7 @@ export const FormItemStore = types
if (
self.unique &&
self.form.parentStore &&
self.form.parentStore.storeType === 'ComboStore'
self.form.parentStore.storeType === "ComboStore"
) {
const combo = self.form.parentStore as IComboStore;
const group = combo.uniques.get(self.name) as IUniqueGroup;
@ -307,12 +307,12 @@ export const FormItemStore = types
return self.valid;
});
function setError(msg: string | Array<string>, tag: string = 'bultin') {
function setError(msg: string | Array<string>, tag: string = "bultin") {
clearError();
addError(msg, tag);
}
function addError(msg: string | Array<string>, tag: string = 'bultin') {
function addError(msg: string | Array<string>, tag: string = "bultin") {
const msgs: Array<string> = Array.isArray(msg) ? msg : [msg];
msgs.forEach(item =>
self.errorData.push({
@ -385,8 +385,8 @@ export const FormItemStore = types
(options && options.errorMessage)}`
);
(getRoot(self) as IRendererStore).notify(
'error',
self.errors.join('')
"error",
self.errors.join("")
);
} else {
clearError();
@ -401,12 +401,12 @@ export const FormItemStore = types
options = normalizeOptions(options as any);
setOptions(options);
if (json.data && typeof (json.data as any).value !== 'undefined') {
if (json.data && typeof (json.data as any).value !== "undefined") {
onChange && onChange((json.data as any).value, false, true);
} else if (clearValue) {
self.selectedOptions.some((item: any) => item.__unmatched) &&
onChange &&
onChange('', false, true);
onChange("", false, true);
}
}
@ -414,7 +414,7 @@ export const FormItemStore = types
return json;
} catch (e) {
const root = getRoot(self) as IRendererStore;
if (root.storeType !== 'RendererStore') {
if (root.storeType !== "RendererStore") {
// 已经销毁了,不管这些数据了。
return;
}
@ -427,13 +427,13 @@ export const FormItemStore = types
console.error(e.stack);
getRoot(self) &&
(getRoot(self) as IRendererStore).notify('error', e.message);
(getRoot(self) as IRendererStore).notify("error", e.message);
return null;
}
} as any);
function syncOptions(originOptions?: Array<any>) {
if (!self.options.length && typeof self.value === 'undefined') {
if (!self.options.length && typeof self.value === "undefined") {
self.selectedOptions = [];
self.filteredOptions = [];
return;
@ -443,24 +443,24 @@ export const FormItemStore = types
const value = self.value;
const selected = Array.isArray(value)
? value.map(item =>
item && item.hasOwnProperty(self.valueField || 'value')
? item[self.valueField || 'value']
item && item.hasOwnProperty(self.valueField || "value")
? item[self.valueField || "value"]
: item
)
: typeof value === 'string'
? value.split(self.delimiter || ',')
: typeof value === "string"
? value.split(self.delimiter || ",")
: value === void 0
? []
: [
value && value.hasOwnProperty(self.valueField || 'value')
? value[self.valueField || 'value']
value && value.hasOwnProperty(self.valueField || "value")
? value[self.valueField || "value"]
: value
];
if (value && value.hasOwnProperty(self.labelField || 'label')) {
if (value && value.hasOwnProperty(self.labelField || "label")) {
selected[0] = {
[self.labelField || 'label']: value[self.labelField || 'label'],
[self.valueField || 'value']: value[self.valueField || 'value']
[self.labelField || "label"]: value[self.labelField || "label"],
[self.valueField || "value"]: value[self.valueField || "value"]
};
}
@ -497,7 +497,10 @@ export const FormItemStore = types
const selectedOptions: Array<any> = [];
selected.forEach((item, index) => {
let idx = findIndex(flattened, optionValueCompare(item));
let idx = findIndex(
flattened,
optionValueCompare(item, self.valueField || "value")
);
if (~idx) {
selectedOptions.push(flattened[idx]);
@ -506,20 +509,24 @@ export const FormItemStore = types
if (
unMatched &&
(typeof unMatched === 'string' || typeof unMatched === 'number')
(typeof unMatched === "string" || typeof unMatched === "number")
) {
unMatched = {
[self.valueField || 'value']: item,
[self.labelField || 'label']: item,
'__unmatched': true
[self.valueField || "value"]: item,
[self.labelField || "label"]: item,
__unmatched: true
};
const orgin: any =
originOptions && find(originOptions, optionValueCompare(item));
originOptions &&
find(
originOptions,
optionValueCompare(item, self.valueField || "value")
);
if (orgin) {
unMatched[self.labelField || 'label'] =
orgin[self.labelField || 'label'];
unMatched[self.labelField || "label"] =
orgin[self.labelField || "label"];
}
}
@ -565,7 +572,7 @@ export const FormItemStore = types
function reset() {
self.validated = false;
if (subStore && subStore.storeType === 'ComboStore') {
if (subStore && subStore.storeType === "ComboStore") {
const combo = subStore as IComboStore;
combo.forms.forEach(form => form.reset());
}