-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathuseNativeSelect.ts
79 lines (74 loc) · 1.73 KB
/
useNativeSelect.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
import type {
KeyboardEventHandler,
MouseEventHandler,
SelectHTMLAttributes,
} from 'react';
import { useContext } from 'react';
import { FieldsetContext } from '../Fieldset/FieldsetContext';
import type { FormField } from '../useFormField';
import { useFormField } from '../useFormField';
import type { NativeSelectProps } from './NativeSelect';
type UseNativeSelect = (props: NativeSelectProps) => Omit<
FormField,
'inputProps'
> & {
selectProps: Pick<
SelectHTMLAttributes<HTMLSelectElement>,
| 'name'
| 'required'
| 'onClick'
| 'onChange'
| 'id'
| 'onKeyDown'
| 'onMouseDown'
>;
};
/** Handles props for `NativeSelect` in context with `Fieldset` */
export const useNativeSelect: UseNativeSelect = (props) => {
const fieldset = useContext(FieldsetContext);
const {
inputProps: selectProps,
readOnly = false,
size = fieldset?.size ?? 'md',
...rest
} = useFormField(props, 'select');
return {
...rest,
readOnly,
size,
selectProps: {
...selectProps,
readOnly,
onClick: (e) => {
if (readOnly) {
e.preventDefault();
return;
}
props?.onClick?.(e);
},
onKeyDown: (e) => {
if (readOnly) {
if (e.key === 'Tab') return;
e.preventDefault();
return;
}
props?.onKeyDown?.(e);
},
onMouseDown: (e) => {
if (readOnly) {
e.preventDefault();
if (e.target instanceof HTMLElement) e.target.focus();
return;
}
props?.onMouseDown?.(e);
},
onChange: (e) => {
if (readOnly) {
e.preventDefault();
return;
}
props?.onChange?.(e);
},
},
};
};