TDesignAccessibleControls.tsx 2.59 KB
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} />;
}