-
Notifications
You must be signed in to change notification settings - Fork 15
/
useField.ts
58 lines (51 loc) · 1.48 KB
/
useField.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
/**
* Copyright Zendesk, Inc.
*
* Use of this source code is governed under the Apache License, Version 2.0
* found at http://www.apache.org/licenses/LICENSE-2.0.
*/
import { useState } from 'react';
import { useUIDSeed } from 'react-uid';
export interface IUseFieldPropGetters {
getHintProps: <T>(options?: T) => T & React.HTMLProps<any>;
getLabelProps: <T>(options?: T) => T & React.HTMLProps<any>;
getInputProps: <T>(
options?: T,
isDescribedOptions?: { isDescribed: boolean }
) => T & React.HTMLProps<any>;
}
export function useField(idPrefix?: string): IUseFieldPropGetters {
const seed = useUIDSeed();
const [prefix] = useState(idPrefix || seed(`field_${PACKAGE_VERSION}`));
const inputId = `${prefix}--input`;
const labelId = `${prefix}--label`;
const hintId = `${prefix}--hint`;
const getLabelProps = ({ id = labelId, htmlFor = inputId, ...other } = {}) => {
return {
id,
htmlFor,
'data-garden-container-id': 'containers.field',
'data-garden-container-version': PACKAGE_VERSION,
...other
} as any;
};
const getInputProps = ({ id = inputId, ...other } = {}, { isDescribed = false } = {}) => {
return {
id,
'aria-labelledby': labelId,
'aria-describedby': isDescribed ? hintId : null,
...other
} as any;
};
const getHintProps = ({ id = hintId, ...other } = {}) => {
return {
id,
...other
} as any;
};
return {
getLabelProps,
getInputProps,
getHintProps
};
}