-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathField.ts
83 lines (76 loc) · 2.15 KB
/
Field.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
ChangeEventHandler,
ComponentProps,
ComponentType,
createElement,
Dispatch,
FC,
FocusEventHandler,
ReactElement,
ReactNode,
forwardRef,
useCallback,
} from 'react';
import { useField, FieldState, FieldAction } from '../hooks';
export interface FieldRenderer<TValue> {
(state: FieldState<TValue>, dispatch: Dispatch<FieldAction<TValue>>): ReactElement | null;
}
export interface FieldProps<TValue> {
children?: FieldRenderer<TValue> | ReactNode;
/**
* Debounce delay, by default 300ms
*/
debounceDelay?: number;
name: string;
removeOnUnmount?: boolean;
}
interface FieldComponent {
<TValue = any>(props: JSX.IntrinsicElements['input'] & FieldProps<TValue>): ReactElement | null;
<TValue = any, TAs extends keyof JSX.IntrinsicElements = any>(
props: { as: TAs } & JSX.IntrinsicElements[TAs] & FieldProps<TValue>,
): ReactElement | null;
<TValue = any, TAs extends ComponentType<any> = FC<{}>>(
props: { as: TAs } & ComponentProps<TAs> & FieldProps<TValue>,
): ReactElement | null;
displayName?: string;
}
export const Field: FieldComponent = forwardRef(
(
{
as = 'input',
children,
debounceDelay,
name,
removeOnUnmount,
...restProps
}: FieldProps<any> & { as: keyof JSX.IntrinsicElements },
ref,
) => {
const [fieldState, fieldDispatch] = useField<any>(name, debounceDelay, removeOnUnmount);
const onBlur: FocusEventHandler = useCallback(() => fieldDispatch({ type: 'BLUR' }), [
fieldDispatch,
]);
const onChange: ChangeEventHandler<HTMLInputElement> = useCallback(
e => fieldDispatch({ type: 'CHANGE', value: e.currentTarget.value }),
[fieldDispatch],
);
const onFocus: FocusEventHandler = useCallback(() => fieldDispatch({ type: 'FOCUS' }), [
fieldDispatch,
]);
if (typeof children === 'function') {
return children(fieldState, fieldDispatch);
}
return createElement(as, {
...restProps,
'aria-invalid': !fieldState.valid,
children,
name,
onBlur,
onChange,
onFocus,
ref,
value: fieldState.value,
});
},
) as any;
Field.displayName = 'Field';