Props controls: Add optional validator function to Object control

This commit is contained in:
Michael Shilman 2020-05-04 11:22:03 +08:00
parent 22c594a5ad
commit 3c5e04b76d
3 changed files with 11 additions and 5 deletions

View File

@ -13,7 +13,10 @@ const inferControl = (argType: ArgType): Control => {
case 'array': {
const { value } = type;
if (value?.name && ['object', 'other'].includes(value.name)) {
return { type: 'object' };
return {
type: 'object',
validator: (obj: any) => Array.isArray(obj),
};
}
return { type: 'array' };
}

View File

@ -11,7 +11,7 @@ const parse = (value: string) => {
};
export type ObjectProps = ControlProps<ObjectValue> & ObjectConfig;
export const ObjectControl: FC<ObjectProps> = ({ name, value, onChange }) => {
export const ObjectControl: FC<ObjectProps> = ({ name, value, onChange, validator }) => {
const [valid, setValid] = useState(true);
const [text, setText] = useState(format(value));
@ -19,10 +19,11 @@ export const ObjectControl: FC<ObjectProps> = ({ name, value, onChange }) => {
(e: ChangeEvent<HTMLTextAreaElement>) => {
try {
const newVal = parse(e.target.value);
if (!deepEqual(value, newVal)) {
const newValid = !validator || validator(newVal);
if (newValid && !deepEqual(value, newVal)) {
onChange(name, newVal);
}
setValid(true);
setValid(newValid);
} catch (err) {
setValid(false);
}

View File

@ -30,7 +30,9 @@ export interface NumberConfig {
export type RangeConfig = NumberConfig;
export type ObjectValue = any;
export interface ObjectConfig {}
export interface ObjectConfig {
validator?: (obj: any) => boolean;
}
export type OptionsSingleSelection = any;
export type OptionsMultiSelection = any[];