-
Notifications
You must be signed in to change notification settings - Fork 186
/
useEnsuredControl.ts
87 lines (76 loc) · 2.3 KB
/
useEnsuredControl.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
84
85
86
87
import * as React from 'react';
import { isFunction } from '@vkontakte/vkjs';
import { useIsomorphicLayoutEffect } from '../lib/useIsomorphicLayoutEffect';
export interface UseEnsuredControlProps<V, E extends React.ChangeEvent<any>> {
value?: V;
defaultValue: V;
disabled?: boolean | undefined;
onChange?: (this: void, e: E) => any;
}
export function useEnsuredControl<V, E extends React.ChangeEvent<any>>({
onChange: onChangeProp,
disabled,
...props
}: UseEnsuredControlProps<V, E>): [V, (e: E) => any] {
const [value, onChangeValue] = useCustomEnsuredControl(props);
const onChange = React.useCallback(
(e: E) => {
if (disabled) {
return;
}
onChangeValue(e.target.value);
onChangeProp && onChangeProp(e);
},
[onChangeValue, onChangeProp, disabled],
);
return [value, onChange];
}
export interface UseCustomEnsuredControlProps<V> {
value?: V;
defaultValue: V;
disabled?: boolean | undefined;
onChange?: (this: void, v: V) => any;
}
export function useCustomEnsuredControl<V = any>({
value,
defaultValue,
disabled,
onChange: onChangeProp,
}: UseCustomEnsuredControlProps<V>): [V, React.Dispatch<React.SetStateAction<V>>] {
const isControlled = value !== undefined;
const [localValue, setLocalValue] = React.useState(defaultValue);
const preservedControlledValueRef = React.useRef<V>();
useIsomorphicLayoutEffect(() => {
preservedControlledValueRef.current = value;
});
const onChange = React.useCallback(
(nextValue: V | ((prevValue: any) => V)) => {
if (disabled) {
return;
}
if (isFunction(nextValue)) {
if (!isControlled) {
setLocalValue((prevValue) => {
const resolvedValue = nextValue(prevValue);
if (onChangeProp) {
onChangeProp(resolvedValue);
}
return resolvedValue;
});
} else if (onChangeProp) {
const resolvedValue = nextValue(preservedControlledValueRef.current);
onChangeProp(resolvedValue);
}
} else {
if (onChangeProp) {
onChangeProp(nextValue);
}
if (!isControlled) {
setLocalValue(nextValue);
}
}
},
[disabled, isControlled, onChangeProp],
);
return [isControlled ? value : localValue, onChange];
}