TDesignAccessibleControls.tsx
2.43 KB
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
88
89
import { useEffect, useRef } from 'react';
import type { ComponentProps } from 'react';
import {
Input as TDesignInput,
Select as TDesignSelect,
Switch as TDesignSwitch,
Textarea as TDesignTextarea,
} from 'tdesign-react';
import type { InputRef } from 'tdesign-react';
type AccessibleInputProps = ComponentProps<typeof TDesignInput> & {
'aria-label'?: string;
id?: string;
};
type AccessibleSelectProps = ComponentProps<typeof TDesignSelect> & {
'aria-label'?: string;
'aria-labelledby'?: string;
id?: string;
};
type AccessibleSwitchProps = ComponentProps<typeof TDesignSwitch> & {
'aria-label'?: string;
};
type AccessibleTextareaProps = ComponentProps<typeof TDesignTextarea> & {
'aria-label'?: string;
id?: string;
};
export function Input({ 'aria-label': ariaLabel, ...props }: AccessibleInputProps) {
const inputRef = useRef<InputRef>(null);
useEffect(() => {
if (!inputRef.current?.inputElement || !ariaLabel) return;
inputRef.current.inputElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignInput {...props} ref={inputRef} />;
}
export function Select({
'aria-label': ariaLabel,
id,
inputProps,
value,
options,
multiple,
disabled,
readonly,
readOnly,
onChange,
...props
}: AccessibleSelectProps) {
return (
<TDesignSelect
{...props}
inputProps={{
...(inputProps ?? {}),
...(id ? { id } : {}),
...(ariaLabel ? ({ 'aria-label': ariaLabel } as Record<string, unknown>) : {}),
} as ComponentProps<typeof TDesignSelect>['inputProps']}
multiple={multiple}
options={options}
readonly={readonly}
readOnly={readOnly}
disabled={disabled}
value={value}
onChange={(nextValue, context) => {
onChange?.(nextValue, context);
}}
/>
);
}
export function Switch({ 'aria-label': ariaLabel, value, ...props }: AccessibleSwitchProps) {
return <TDesignSwitch {...props} aria-checked={Boolean(value)} aria-label={ariaLabel} value={value} />;
}
export function Textarea({ 'aria-label': ariaLabel, ...props }: AccessibleTextareaProps) {
const textareaRef = useRef<{ currentElement: HTMLDivElement; textareaElement: HTMLTextAreaElement }>(null);
useEffect(() => {
if (!textareaRef.current?.textareaElement || !ariaLabel) return;
textareaRef.current.textareaElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignTextarea {...props} ref={textareaRef} />;
}