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