diff --git a/src/components/TextInput/TextInput.tsx b/src/components/TextInput/TextInput.tsx index a2759a90bd..04ada1a329 100644 --- a/src/components/TextInput/TextInput.tsx +++ b/src/components/TextInput/TextInput.tsx @@ -8,6 +8,7 @@ import { import type { TextInputProps as NativeTextInputProps } from 'react-native'; import type { AccessibilityProps, + PressableStateCallbackType, BlurEvent, ColorValue, FocusEvent, @@ -23,8 +24,12 @@ import { useTextInput } from './hooks'; import { styles } from './styles'; import TextInputErrorIcon from './TextInputErrorIcon'; import type { TextInputAccessoryProps } from './TextInputIcon'; +import { mergeAccessibilityText } from './utils'; import type { InternalTheme, ThemeProp } from '../../theme/types'; +// React Native Web adds `hovered` to the Pressable state; React Native omits it. +type PressableState = PressableStateCallbackType & { hovered?: boolean }; + export type TextInputAnimationState = { animatedLabelWrapperStyle: StyleProp>>; animatedLabelTextStyle: StyleProp>>; @@ -57,9 +62,12 @@ export type TextInputColors = { }; export type GetAccessibilityDataReturn = { - input: AccessibilityProps & { 'aria-invalid'?: boolean }; - supportingText: AccessibilityProps; - counter: AccessibilityProps; + input: AccessibilityProps & { + 'aria-invalid'?: boolean; + 'aria-describedby'?: string; + }; + supportingText: AccessibilityProps & { nativeID: string }; + counter: AccessibilityProps & { nativeID: string }; }; export type GetAccessibilityDataProps = { @@ -68,6 +76,8 @@ export type GetAccessibilityDataProps = { hasError: boolean; hasCounter: boolean; isDisabled: boolean; + supportingTextId: string; + counterId: string; }; export type TextInputVariant = 'filled' | 'outlined'; @@ -107,6 +117,7 @@ export type FilledTextInputHookData = SharedTextInputStyleData & { fieldStyles: StyleProp; disabledBackgroundStyles: StyleProp | undefined; outlineStyles: StyleProp; + hoveredOutlineStyles: StyleProp | undefined; animatedActiveOutlineStyles: StyleProp>>; inputStyles: StyleProp; }; @@ -121,6 +132,7 @@ export type OutlinedTextInputHookData = SharedTextInputStyleData & { fieldStyles: StyleProp; disabledBackgroundStyles: undefined; outlineStyles: StyleProp; + hoveredOutlineStyles: undefined; inputStyles: StyleProp; }; @@ -153,6 +165,7 @@ export type TextInputHookReturn = SharedTextInputStyleData & { fieldStyles: StyleProp; disabledBackgroundStyles: StyleProp | undefined; outlineStyles: StyleProp; + hoveredOutlineStyles: StyleProp | undefined; inputStyles: StyleProp; placeholder: string | undefined; counterText: string; @@ -321,6 +334,7 @@ function TextInput({ fieldStyles, disabledBackgroundStyles, outlineStyles, + hoveredOutlineStyles, animatedActiveOutlineStyles, animatedLabelWrapperStyles, animatedLabelTextStyles, @@ -361,92 +375,110 @@ function TextInput({ return ( - - {/* Disabled tint overlay — filled variant only. A childless + {({ hovered }: PressableState) => ( + <> + + {/* Disabled tint overlay — filled variant only. A childless absolutely-positioned View whose translucent fill is applied via the `opacity` style, so it never affects label/input rendering and works with PlatformColor on Android. */} - {!!disabledBackgroundStyles && ( - - )} + {!!disabledBackgroundStyles && ( + + )} - {/* Inactive indicator — always-visible 1px bottom border (filled) or + {/* Inactive indicator — always-visible 1px bottom border (filled) or full border (outlined); height and color reflect error/disabled state but do not change on focus */} - - - {/* Active indicator — filled variant only; 2px bar that expands from + + + {/* Active indicator — filled variant only; 2px bar that expands from the center outward via scaleX (0 → 1) on focus and collapses on blur */} - {!!animatedActiveOutlineStyles && ( - - )} - - {!!label && ( - - - {label} - - - )} - - {renderLeadingAccessory - ? renderLeadingAccessory({ - style: leadingAccessoryStyles, - error: hasError, - disabled: isDisabled, - multiline: !!rest.multiline, - }) - : null} - - - {hasPrefix && {prefix}} - - {render({ - ref: input, - selectionColor, - cursorColor, - placeholderTextColor, - ...accessibilityProps.input, - ...rest, - editable: isEditable, - placeholder, - style: inputStyles, - onChangeText, - onFocus, - onBlur, - })} - - {hasSuffix && {suffix}} - - - {renderTrailingAccessory ? ( - renderTrailingAccessory({ - style: trailingAccessoryStyles, - error: hasError, - disabled: isDisabled, - multiline: !!rest.multiline, - }) - ) : hasError ? ( - - ) : null} - - - - {!!supportingText && ( - - {supportingText} - - )} - - {hasCounter && ( - - {counterText} - - )} - + {!!animatedActiveOutlineStyles && ( + + )} + + {!!label && ( + + + {label} + + + )} + + {renderLeadingAccessory + ? renderLeadingAccessory({ + style: leadingAccessoryStyles, + error: hasError, + disabled: isDisabled, + multiline: !!rest.multiline, + }) + : null} + + + {hasPrefix && {prefix}} + + {render({ + ref: input, + selectionColor, + cursorColor, + placeholderTextColor, + ...accessibilityProps.input, + ...rest, + accessibilityHint: mergeAccessibilityText( + ', ', + rest.accessibilityHint, + accessibilityProps.input.accessibilityHint + ), + editable: isEditable, + placeholder, + style: inputStyles, + onChangeText, + onFocus, + onBlur, + })} + + {hasSuffix && {suffix}} + + + {renderTrailingAccessory ? ( + renderTrailingAccessory({ + style: trailingAccessoryStyles, + error: hasError, + disabled: isDisabled, + multiline: !!rest.multiline, + }) + ) : hasError ? ( + + ) : null} + + + + {!!supportingText && ( + + {supportingText} + + )} + + {hasCounter && ( + + {counterText} + + )} + + + )} ); } diff --git a/src/components/TextInput/TextInputIcon.tsx b/src/components/TextInput/TextInputIcon.tsx index b75b5dd658..d127720da3 100644 --- a/src/components/TextInput/TextInputIcon.tsx +++ b/src/components/TextInput/TextInputIcon.tsx @@ -7,6 +7,7 @@ import { getIconColor } from './utils'; import { useInternalTheme } from '../../core/theming'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import Icon from '../Icon'; import IconButton from '../IconButton/IconButton'; import type { Props as IconButtonProps } from '../IconButton/IconButton'; @@ -33,8 +34,10 @@ export type TextInputIconProps = TextInputAccessoryProps & * `TextInputAccessoryProps`, which TextInput passes into those render props. * * Without `onPress`, `onLongPress`, `onPressIn` or `onPressOut`, the icon is - * decorative: a plain element that keeps its label but isn't a control, and a - * tap on it goes to the field. + * decorative: a plain element, not an `IconButton`, so it has no button role + * and isn't a focus stop. It is hidden from assistive tech unless you pass + * `aria-label`, and a tap on it goes to the field. An icon with a handler is a + * control and needs `aria-label` (or `accessibilityLabel`). * * ## Usage * ```js @@ -91,9 +94,9 @@ const TextInputIcon = ({ isDisabled: disabled, }); - // A decorative icon is not a control, so `disabled` would only announce it as - // a disabled button. Must match TouchableRipple's predicate, or an icon with - // only `onLongPress` stays pressable on a disabled field. + // Decorative icons render no button at all. Must match TouchableRipple's + // predicate, or an icon with only `onLongPress` would count as decorative + // and stay pressable on a disabled field. const { onLongPress, onPressIn, onPressOut } = rest; const isInteractive = hasTouchHandler({ onPress, @@ -102,6 +105,23 @@ const TextInputIcon = ({ onPressOut, }); + const accessibleName = rest['aria-label'] ?? rest.accessibilityLabel; + + if (!isInteractive) { + return ( + + + + ); + } + return ( diff --git a/src/components/TextInput/hooks.ts b/src/components/TextInput/hooks.ts index c6109e4ce7..2f24958876 100644 --- a/src/components/TextInput/hooks.ts +++ b/src/components/TextInput/hooks.ts @@ -1,5 +1,6 @@ import { useEffect, + useId, useImperativeHandle, useRef, useState, @@ -323,6 +324,7 @@ const useTextInputLayout = ({ export const useTextInput = (props: TextInputProps): TextInputHookReturn => { const { ref, variant = 'filled', theme: themeOverride } = props; + const id = useId(); const input = useRef>(null); const init = useRef(false); @@ -421,6 +423,8 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => { }); const accessibilityProps = getAccessibilityData({ + supportingTextId: `${id}-supporting-text`, + counterId: `${id}-counter`, hasError: flags.hasError, hasCounter: flags.hasCounter, isDisabled: flags.isDisabled, diff --git a/src/components/TextInput/utils.ts b/src/components/TextInput/utils.ts index 5900c86f8b..7fbe32ca3b 100644 --- a/src/components/TextInput/utils.ts +++ b/src/components/TextInput/utils.ts @@ -177,17 +177,21 @@ export const getIconColor = ({ */ export const getOutlineColor = ({ theme, + variant, hasError, isFocused, isDisabled, + isHovered = false, }: { theme: InternalTheme; + variant: TextInputVariant; isFocused: boolean; + isHovered?: boolean; hasError: boolean; isDisabled: boolean; }): ColorValue => { const { - colors: { error, onSurface, primary, outline }, + colors: { error, onSurface, onSurfaceVariant, primary, outline }, } = theme; if (hasError) { @@ -199,6 +203,9 @@ export const getOutlineColor = ({ if (isFocused) { return primary; } + if (variant === 'filled') { + return isHovered ? onSurface : onSurfaceVariant; + } return outline; }; @@ -329,13 +336,24 @@ export const getFilledTextInputData = ( const outlineColor = getOutlineColor({ theme, + variant: 'filled', hasError, isFocused: false, isDisabled, }); + const hoveredOutlineColor = getOutlineColor({ + theme, + variant: 'filled', + hasError, + isFocused: false, + isDisabled, + isHovered: true, + }); + const activeOutlineColor = getOutlineColor({ theme, + variant: 'filled', hasError, isFocused: true, isDisabled, @@ -402,6 +420,13 @@ export const getFilledTextInputData = ( isDisabled && styles.disabled, ]; + /* Same indicator with the hover color. TextInput swaps it in while the + field is hovered (web only). */ + const hoveredOutlineStyles: StyleProp = [ + outlineStyles, + { backgroundColor: hoveredOutlineColor }, + ]; + const animatedActiveOutlineStyles: StyleProp< AnimatedStyle> > = [ @@ -445,6 +470,7 @@ export const getFilledTextInputData = ( fieldStyles, disabledBackgroundStyles, outlineStyles, + hoveredOutlineStyles, animatedActiveOutlineStyles, inputStyles, ...shared, @@ -478,6 +504,7 @@ export const getOutlinedTextInputData = ( const outlineColor = getOutlineColor({ theme, + variant: 'outlined', isDisabled, isFocused, hasError, @@ -563,17 +590,34 @@ export const getOutlinedTextInputData = ( fieldStyles, disabledBackgroundStyles: undefined, outlineStyles, + hoveredOutlineStyles: undefined, inputStyles, ...shared, }; }; +/** + * Joins the non-empty parts, or returns `undefined` when there are none. Used + * to merge a consumer's `accessibilityHint` with the one TextInput computes, + * instead of one replacing the other. + */ +export const mergeAccessibilityText = ( + separator: string, + ...parts: (string | undefined)[] +): string | undefined => { + const joined = parts.filter(Boolean).join(separator); + + return joined || undefined; +}; + export const getAccessibilityData = ({ data, hasError, hasCounter, isDisabled, inputLength, + supportingTextId, + counterId, }: GetAccessibilityDataProps): GetAccessibilityDataReturn => { const { label, supportingText, ...props } = data; @@ -583,7 +627,11 @@ export const getAccessibilityData = ({ const isCounterExceeded = shouldEvaluateCounter && inputLength > maxLength; const isCounterReached = shouldEvaluateCounter && inputLength === maxLength; const isInvalid = hasError || isCounterExceeded; - const isSupportingTextHidden = !!(supportingText && !hasError); + + const isWeb = Platform.OS === 'web'; + const isSupportingTextName = !label && !!supportingText && !hasError; + const isSupportingTextInHint = + !isWeb && !!supportingText && !hasError && !isSupportingTextName; const chunks: string[] = []; @@ -591,7 +639,7 @@ export const getAccessibilityData = ({ chunks.push(label); } - if (isSupportingTextHidden) { + if (isSupportingTextName) { chunks.push(supportingText); } @@ -601,32 +649,52 @@ export const getAccessibilityData = ({ const ariaLabel = chunks.length > 0 ? chunks.join(', ') : label; - let hint: string | undefined; + const counterExceededHint = `Character limit exceeded ${inputLength} of ${maxLength}`; + + const hints: string[] = []; + + if (isSupportingTextInHint) { + hints.push(supportingText); + } if (isCounterExceeded && !(hasError && supportingText)) { - hint = `Character limit exceeded ${inputLength} of ${maxLength}`; + hints.push(counterExceededHint); + } + + const describedBy: string[] = []; + + if (isWeb && supportingText && !isSupportingTextName) { + describedBy.push(supportingTextId); + } + + if (isWeb && shouldEvaluateCounter) { + describedBy.push(counterId); } const counterAccessibilityLabel = shouldEvaluateCounter ? isCounterExceeded - ? `Character limit exceeded ${inputLength} of ${maxLength}` + ? counterExceededHint : `Characters entered ${inputLength} of ${maxLength}` : undefined; return { input: { 'aria-label': ariaLabel, + 'aria-describedby': + describedBy.length > 0 ? describedBy.join(' ') : undefined, 'aria-valuemax': isCounterReached ? maxLength : undefined, 'aria-valuenow': isCounterReached ? inputLength : undefined, 'aria-disabled': isDisabled, 'aria-invalid': isInvalid, - accessibilityHint: hint, + accessibilityHint: hints.length > 0 ? hints.join(', ') : undefined, }, supportingText: { - 'aria-hidden': isSupportingTextHidden, - 'aria-live': hasError && supportingText ? 'polite' : undefined, + nativeID: supportingTextId, + 'aria-hidden': isSupportingTextInHint || isSupportingTextName, + role: hasError && supportingText ? 'alert' : undefined, }, counter: { + nativeID: counterId, 'aria-label': counterAccessibilityLabel, 'aria-live': 'polite', }, diff --git a/src/components/__tests__/TextInput.test.tsx b/src/components/__tests__/TextInput.test.tsx index 20bb647ba1..e436d38868 100644 --- a/src/components/__tests__/TextInput.test.tsx +++ b/src/components/__tests__/TextInput.test.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import { I18nManager, + Platform, StyleSheet, TextInput as NativeTextInput, View, @@ -11,6 +12,7 @@ import { afterAll, afterEach, beforeAll, + describe, expect, it, jest, @@ -241,13 +243,12 @@ it('disables TextInput.Icon when the field is disabled', async () => { expect(buttons[1]).toBeDisabled(); }); -it('does not expose a handler-less TextInput.Icon as a control when the field is disabled', async () => { +it('renders a handler-less TextInput.Icon as a plain element', async () => { await render( {}} - disabled startAccessory={(props: TextInputAccessoryProps) => ( )} @@ -256,20 +257,56 @@ it('does not expose a handler-less TextInput.Icon as a control when the field is {...props} icon="close" onPress={() => {}} - testID="clear" + aria-label="Clear" /> )} /> ); - const decorative = screen.getByTestId('decorative'); - expect(decorative).toHaveProp('role', 'none'); - expect(decorative).not.toBeDisabled(); + expect(screen.getAllByRole('button')).toHaveLength(1); + expect(screen.getByRole('button', { name: 'Clear' })).toBeOnTheScreen(); + expect(screen.getByTestId('decorative', includeHiddenElements)).toHaveProp( + 'aria-hidden', + true + ); +}); + +it('focuses the field when a handler-less TextInput.Icon is tapped', async () => { + const focusSpy = jest.spyOn(NativeTextInput.prototype, 'focus'); - // control: a real handler still gets disabled - const clear = screen.getByTestId('clear'); - expect(clear).toHaveProp('role', 'button'); - expect(clear).toBeDisabled(); + await render( + {}} + startAccessory={(props: TextInputAccessoryProps) => ( + + )} + /> + ); + + await userEvent.press( + screen.getByTestId('decorative', includeHiddenElements) + ); + + expect(focusSpy).toHaveBeenCalled(); + focusSpy.mockRestore(); +}); + +it('does not expose a handler-less TextInput.Icon of a disabled field as a control', async () => { + await render( + {}} + disabled + startAccessory={(props: TextInputAccessoryProps) => ( + + )} + /> + ); + + expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); it('dims a disabled TextInput with TextInput.Icon accessories exactly once', async () => { @@ -414,7 +451,7 @@ it('renders supporting text below the field', async () => { ).toBeOnTheScreen(); }); -it('uses polite aria-live on error supporting text', async () => { +it('announces error supporting text as an alert', async () => { await render( { /> ); - expect(screen.getByText('Invalid')).toHaveProp('aria-live', 'polite'); + const supportingText = screen.getByText('Invalid'); + expect(supportingText).toHaveProp('role', 'alert'); + expect(supportingText).not.toHaveProp('aria-live'); + expect(supportingText).not.toHaveProp('aria-hidden', true); expect(screen.getByLabelText('Email')).toHaveProp('aria-invalid', true); }); @@ -446,34 +486,135 @@ it('marks the input invalid when error is true without supporting text', async ( expect(input).not.toHaveProp('accessibilityHint'); }); -it('hides helper supporting text from the accessibility tree and omits aria-live', async () => { - await render( - {}} - supportingText="Optional" - testID="tf-input" - /> - ); +const getNativeID = (element: TestInstance): string => + // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. + element.props.nativeID; - const supportingText = screen.getByText('Optional', includeHiddenElements); - expect(supportingText).toHaveProp('aria-hidden', true); - expect(supportingText).not.toHaveProp('aria-live'); - expect(screen.getByLabelText('Email, Optional')).toBeOnTheScreen(); -}); +describe('supporting text association', () => { + const originalOS = Platform.OS; -it('includes supporting text in aria-label when label is omitted', async () => { - await render( - {}} - supportingText="Helper only" - testID="tf-input" - /> - ); + afterEach(() => { + Platform.OS = originalOS; + }); - expect(screen.getByLabelText('Helper only')).toBeOnTheScreen(); + it('reads helper text as the input hint on native', async () => { + await render( + {}} + supportingText="Optional" + /> + ); + + const input = screen.getByLabelText('Email'); + expect(input).toHaveProp('accessibilityHint', 'Optional'); + expect(input).not.toHaveProp('aria-describedby'); + expect(screen.getByText('Optional', includeHiddenElements)).toHaveProp( + 'aria-hidden', + true + ); + }); + + it('describes the input by the supporting text and counter on web', async () => { + Platform.OS = 'web'; + + await render( + {}} + supportingText="Optional" + maxLength={10} + counter + /> + ); + + const input = screen.getByLabelText('Email'); + const supportingText = screen.getByText('Optional'); + const counter = screen.getByText('2/10'); + + expect(input).toHaveProp( + 'aria-describedby', + `${getNativeID(supportingText)} ${getNativeID(counter)}` + ); + expect(getNativeID(supportingText)).not.toBe(getNativeID(counter)); + expect(input).not.toHaveProp('accessibilityHint'); + expect(supportingText).not.toHaveProp('aria-hidden', true); + }); + + it('uses the supporting text as the name when the label is omitted', async () => { + await render( + {}} + supportingText="Helper only" + /> + ); + + const input = screen.getByLabelText('Helper only'); + expect(input).toBeOnTheScreen(); + expect(input).not.toHaveProp('accessibilityHint'); + expect(screen.queryByText('Helper only')).toBeNull(); + }); + + it('does not describe a web input by the supporting text used as its name', async () => { + Platform.OS = 'web'; + + await render( + {}} + supportingText="Helper only" + /> + ); + + expect(screen.getByLabelText('Helper only')).not.toHaveProp( + 'aria-describedby' + ); + }); + + it('merges a passed accessibilityHint with the supporting text hint on native', async () => { + await render( + {}} + supportingText="Helper" + accessibilityHint="Custom hint" + /> + ); + + expect(screen.getByLabelText('Name')).toHaveProp( + 'accessibilityHint', + 'Custom hint, Helper' + ); + }); + + it('gives each field its own ids', async () => { + Platform.OS = 'web'; + + await render( + <> + {}} + supportingText="a" + /> + {}} + supportingText="b" + /> + + ); + + expect(getNativeID(screen.getByText('a'))).not.toBe( + getNativeID(screen.getByText('b')) + ); + }); }); it('does not mark the input as aria-disabled when editable is false (read-only)', async () => { diff --git a/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap b/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap index cdbe2843fe..c76c667dc3 100644 --- a/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap @@ -161,34 +161,13 @@ exports[`dims a disabled TextInput with TextInput.Icon accessories exactly once - - + - - - magnify - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + magnify + - - + - - - magnify - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + magnify + - - + - - - close - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + close + - - + - - - magnify - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + magnify + - - + - - - magnify - - - - + "backgroundColor": "transparent", + }, + ], + ] + } + > + magnify + - - + - - - close - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + close + - - + - - - magnify - - - - + ], + }, + { + "backgroundColor": "transparent", + }, + ], + ] + } + > + magnify +