TDesignAccessibleControls.tsx
2.59 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
90
91
92
import { useEffect, useRef } from 'react';
import type { ComponentProps } from 'react';
import {
Form as TDesignForm,
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;
};
type AccessibleSelectProps = ComponentProps<typeof TDesignSelect> & {
'aria-label'?: string;
};
type AccessibleSwitchProps = ComponentProps<typeof TDesignSwitch> & {
'aria-label'?: string;
};
type AccessibleTextareaProps = ComponentProps<typeof TDesignTextarea> & {
'aria-label'?: string;
};
type FormItemProps = ComponentProps<typeof TDesignForm.FormItem>;
export function FormItem({ children, ...props }: FormItemProps) {
return (
<TDesignForm.FormItem {...props}>
<>{children}</>
</TDesignForm.FormItem>
);
}
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, inputProps, ...props }: AccessibleSelectProps) {
const selectRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const ref = selectRef.current as (HTMLDivElement & { currentElement?: HTMLDivElement }) | null;
const root = ref?.currentElement ?? ref;
if (!root || !ariaLabel) return;
root.setAttribute('aria-label', ariaLabel);
root.setAttribute('role', 'combobox');
}, [ariaLabel]);
return (
<TDesignSelect
{...props}
ref={selectRef}
inputProps={{
...inputProps,
...ariaLabel ? { 'aria-label': ariaLabel } : {},
}}
/>
);
}
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} />;
}