/
ArgControl.tsx
70 lines (60 loc) · 1.83 KB
/
ArgControl.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, { FC, useCallback, useState, useEffect } from 'react';
import { Args, ArgType } from './types';
import {
BooleanControl,
ColorControl,
DateControl,
FilesControl,
NumberControl,
ObjectControl,
OptionsControl,
RangeControl,
TextControl,
} from '../../controls';
export interface ArgControlProps {
row: ArgType;
arg: any;
updateArgs: (args: Args) => void;
}
const Controls: Record<string, FC> = {
array: ObjectControl,
object: ObjectControl,
boolean: BooleanControl,
color: ColorControl,
date: DateControl,
number: NumberControl,
check: OptionsControl,
'inline-check': OptionsControl,
radio: OptionsControl,
'inline-radio': OptionsControl,
select: OptionsControl,
'multi-select': OptionsControl,
range: RangeControl,
text: TextControl,
file: FilesControl,
};
const NoControl = () => <>-</>;
export const ArgControl: FC<ArgControlProps> = ({ row, arg, updateArgs }) => {
const { key, control } = row;
const [isFocused, setFocused] = useState(false);
const [value, setValue] = useState(() => arg);
useEffect(() => {
if (!isFocused) setValue(arg);
}, [isFocused, arg]);
const onChange = useCallback(
(argVal: any) => {
setValue(argVal);
updateArgs({ [key]: argVal });
return argVal;
},
[updateArgs, key]
);
const onBlur = useCallback(() => setFocused(false), []);
const onFocus = useCallback(() => setFocused(true), []);
if (!control || control.disable) return <NoControl />;
// row.name is a display name and not a suitable DOM input id or name - i might contain whitespace etc.
// row.key is a hash key and therefore a much safer choice
const props = { name: key, argType: row, value, onChange, onBlur, onFocus };
const Control = Controls[control.type] || NoControl;
return <Control {...props} {...control} controlType={control.type} />;
};