diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index 5cade18fe3..bb3aa8b085 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -856,6 +856,41 @@ import { TextInput, type TextInputProps } from 'react-native-paper';
/>
```
+`TextInput.Icon` without a press handler is decorative: it is hidden from
+assistive technology and is not a keyboard focus stop. An icon with `onPress`,
+`onLongPress`, `onPressIn` or `onPressOut` requires an `aria-label` or
+`accessibilityLabel` that names its action, and warns in development without
+one:
+
+```tsx
+const [value, setValue] = React.useState('');
+
+// Before (v5)
+}
+ right={ setValue('')} />}
+/>
+
+// After (v6)
+ }
+ endAccessory={(props) => (
+ setValue('')}
+ />
+ )}
+/>
+```
+
#### Label and supporting text
- **`label: React.Element | string`** → **`string`**
@@ -903,6 +938,39 @@ const GroupError = ({ visible }: { visible: boolean }) => {
};
```
+Supporting text, the character counter, `prefix` and `suffix` describe the field
+instead of becoming part of its accessible name, and the prefix and suffix are
+no longer read as separate text. On web, the input references them with
+`aria-describedby` (the prefix and suffix while they are shown), and IDs you
+pass in `aria-describedby` are kept. On Android and iOS, they are only exposed
+through `accessibilityHint`, alongside any hint you pass, and the visible text
+is hidden from assistive technology, so tests that find these texts with
+`getByText` need `{ includeHiddenElements: true }`. Users who turn hints off,
+for example with the VoiceOver Speak Hints setting, do not hear them. The
+placeholder of an empty field with a label stays blank until the label floats,
+so it describes the field as well: on web until the input shows it, and on
+Android and iOS in the hint. The input no longer sets `aria-valuenow` and
+`aria-valuemax` when the counter reaches `maxLength`.
+
+When no label or explicit accessible name is supplied, the placeholder names the
+field, including after text is entered. A disabled field always exposes its
+disabled state, even when `aria-disabled={false}` is supplied.
+
+On web, error supporting text uses `role="alert"`. On Android and iOS, a new or
+changed error message is announced through `AccessibilityInfo` once it has
+stayed the same for a second, so a message that changes on every keystroke is
+announced once it stops changing. An error that is already shown when the field
+mounts is not announced there. On web, explicit `aria-invalid` values are kept;
+when omitted, validity is derived from `error` and the character counter. Custom
+input renderers should forward the accessibility props they receive.
+
+The filled indicator uses `onSurfaceVariant` and the outlined border uses
+`outline` at rest. On web, both change to `onSurface` on hover, and an invalid
+field changes from `error` to `onErrorContainer`. Focus takes precedence over
+hover and uses `primary`, or `error` for an invalid field. A disabled field uses
+the disabled colors even when `error` is set. On web it keeps `aria-invalid`; on
+Android and iOS the error text stays in its hint.
+
#### Removed props
No direct `TextInput` equivalents for:
diff --git a/example/src/Examples/TextInputExample.tsx b/example/src/Examples/TextInputExample.tsx
index 95dfdb1f7f..b8212ba2a2 100644
--- a/example/src/Examples/TextInputExample.tsx
+++ b/example/src/Examples/TextInputExample.tsx
@@ -81,7 +81,12 @@ const TextInputDemo = ({ variant }: TextInputDemoProps) => {
);
const trailingIcon = (props: TextInputAccessoryProps) => (
- setValue('')} />
+ setValue('')}
+ />
);
const inputColor = theme.colors.onSurfaceVariant;
@@ -100,8 +105,8 @@ const TextInputDemo = ({ variant }: TextInputDemoProps) => {
{ label: 'Error', key: 'error' },
{ label: 'Disabled', key: 'disabled' },
{ label: 'Readonly', key: 'readOnly' },
- { label: 'Leading icon', key: 'leadingIcon' },
- { label: 'Trailing icon', key: 'trailingIcon' },
+ { label: 'Decorative leading icon', key: 'leadingIcon' },
+ { label: 'Clear text action', key: 'trailingIcon' },
{ label: 'Counter', key: 'counter' },
{ label: 'Prefix', key: 'showPrefix' },
{ label: 'Suffix', key: 'showSuffix' },
@@ -123,7 +128,11 @@ const TextInputDemo = ({ variant }: TextInputDemoProps) => {
variant={variant}
label={modifiers.label || undefined}
placeholder={modifiers.placeholder || undefined}
- supportingText={modifiers.helperText || undefined}
+ supportingText={
+ controls.error
+ ? 'Please check the entered text'
+ : modifiers.helperText || undefined
+ }
error={controls.error}
disabled={controls.disabled}
editable={!controls.readOnly}
diff --git a/src/components/TextInput/TextInput.tsx b/src/components/TextInput/TextInput.tsx
index a2759a90bd..6db3359500 100644
--- a/src/components/TextInput/TextInput.tsx
+++ b/src/components/TextInput/TextInput.tsx
@@ -1,5 +1,6 @@
import React from 'react';
import {
+ Platform,
Pressable,
Text,
TextInput as NativeTextInput,
@@ -28,8 +29,9 @@ import type { InternalTheme, ThemeProp } from '../../theme/types';
export type TextInputAnimationState = {
animatedLabelWrapperStyle: StyleProp>>;
animatedLabelTextStyle: StyleProp>>;
- animatedContainerStyle: StyleProp>>;
+ animatedAffixStyle: StyleProp>>;
animatedActiveOutlineStyle?: StyleProp>>;
+ isLabelFloated: boolean;
};
export type TextInputAnimationHandlers = {
@@ -57,17 +59,28 @@ export type TextInputColors = {
};
export type GetAccessibilityDataReturn = {
- input: AccessibilityProps & { 'aria-invalid'?: boolean };
- supportingText: AccessibilityProps;
- counter: AccessibilityProps;
+ input: AccessibilityProps & {
+ 'aria-invalid'?: TextInputProps['aria-invalid'];
+ 'aria-describedby'?: string;
+ };
+ label: { nativeID?: string };
+ placeholder: AccessibilityProps & { nativeID?: string };
+ prefix: AccessibilityProps & { nativeID?: string };
+ suffix: AccessibilityProps & { nativeID?: string };
+ supportingText: AccessibilityProps & { nativeID?: string };
+ counter: AccessibilityProps & { nativeID?: string };
};
export type GetAccessibilityDataProps = {
data: TextInputProps;
+ id: string;
inputLength: number;
hasError: boolean;
hasCounter: boolean;
+ hasPrefix: boolean;
+ hasSuffix: boolean;
isDisabled: boolean;
+ isPlaceholderShown: boolean;
};
export type TextInputVariant = 'filled' | 'outlined';
@@ -76,6 +89,7 @@ export type TextInputSharedApi = {
input: React.RefObject | null>;
theme: InternalTheme;
isFocused: boolean;
+ isHovered?: boolean;
isRTL: boolean;
isDisabled: boolean;
hasAccessory: boolean;
@@ -147,7 +161,9 @@ export type TextInputHookReturn = SharedTextInputStyleData & {
animatedActiveOutlineStyles:
| StyleProp>>
| undefined;
- animatedContainerStyle: StyleProp>>;
+ animatedAffixStyle:
+ | StyleProp>>
+ | undefined;
animatedLabelWrapperStyles: StyleProp>>;
containerStyles: StyleProp;
fieldStyles: StyleProp;
@@ -167,12 +183,16 @@ export type TextInputHookReturn = SharedTextInputStyleData & {
onFocus: (e: FocusEvent) => void;
onBlur: (e: BlurEvent) => void;
focusInput: () => void;
+ onHoverIn: () => void;
+ onHoverOut: () => void;
};
export type TextInputRenderProps = React.ComponentPropsWithoutRef<
typeof NativeTextInput
> & {
ref?: React.RefObject | null>;
+ 'aria-describedby'?: string;
+ 'aria-invalid'?: TextInputProps['aria-invalid'];
};
export type TextInputHandles = Pick<
@@ -181,6 +201,18 @@ export type TextInputHandles = Pick<
>;
export type TextInputProps = NativeTextInputProps & {
+ /**
+ * Overrides the field's invalid state on web, including grammar or spelling
+ * errors. Defaults to the error state or an exceeded character counter.
+ */
+ 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
+ /**
+ * Space-separated IDs of additional descriptions on web. The IDs of the
+ * rendered prefix, suffix, supporting text and character counter, and of the
+ * placeholder while the label covers it, are appended automatically.
+ * On Android and iOS, provide external descriptions with `accessibilityHint`.
+ */
+ 'aria-describedby'?: string;
/**
* Imperative handle exposing a subset of native `TextInput` methods
* with side-effect handling (e.g. `clear()` syncs internal state and animations).
@@ -204,11 +236,16 @@ export type TextInputProps = NativeTextInputProps & {
label?: string;
/**
* Supporting text to display below the input (Material Design 3).
+ * Associated with the field through `aria-describedby` on web and included
+ * in the native accessibility hint. When `error` is true, a new or changed
+ * message is announced. It does not become part of the field's accessible
+ * name.
*/
supportingText?: string;
/**
* When `true`, displays a character counter below the input on the trailing
* side, showing `currentLength/maxLength`. Requires `maxLength` to be set.
+ * Associated with the field alongside supporting text.
*/
counter?: boolean;
/**
@@ -324,7 +361,7 @@ function TextInput({
animatedActiveOutlineStyles,
animatedLabelWrapperStyles,
animatedLabelTextStyles,
- animatedContainerStyle,
+ animatedAffixStyle,
containerStyles,
inputStyles,
prefixStyles,
@@ -343,6 +380,8 @@ function TextInput({
onChangeText,
onFocus,
onBlur,
+ onHoverIn,
+ onHoverOut,
} = useTextInput({
ref,
error,
@@ -360,8 +399,32 @@ function TextInput({
});
return (
-
-
+
+ {
+ if (event.nativeEvent.pointerType !== 'touch') onHoverIn();
+ }
+ : undefined
+ }
+ onPointerLeave={
+ Platform.OS === 'web'
+ ? (event) => {
+ if (event.nativeEvent.pointerType !== 'touch') onHoverOut();
+ }
+ : undefined
+ }
+ >
{/* 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
@@ -383,12 +446,24 @@ function TextInput({
{!!label && (
-
+
{label}
)}
+ {!!accessibilityProps.placeholder.nativeID && (
+
+ {rest.placeholder}
+
+ )}
+
{renderLeadingAccessory
? renderLeadingAccessory({
style: leadingAccessoryStyles,
@@ -398,17 +473,26 @@ function TextInput({
})
: null}
-
- {hasPrefix && {prefix}}
+ {/* Keep the field visible to native accessibility even before focus. */}
+
+ {hasPrefix && (
+
+ {prefix}
+
+ )}
{render({
ref: input,
selectionColor,
cursorColor,
placeholderTextColor,
- ...accessibilityProps.input,
...rest,
+ ...accessibilityProps.input,
editable: isEditable,
+ readOnly: disabled ? true : rest.readOnly,
placeholder,
style: inputStyles,
onChangeText,
@@ -416,8 +500,15 @@ function TextInput({
onBlur,
})}
- {hasSuffix && {suffix}}
-
+ {hasSuffix && (
+
+ {suffix}
+
+ )}
+
{renderTrailingAccessory ? (
renderTrailingAccessory({
@@ -427,13 +518,18 @@ function TextInput({
multiline: !!rest.multiline,
})
) : hasError ? (
-
+
) : null}
{!!supportingText && (
diff --git a/src/components/TextInput/TextInputErrorIcon.tsx b/src/components/TextInput/TextInputErrorIcon.tsx
index b49e9d8db9..a0af0221d2 100644
--- a/src/components/TextInput/TextInputErrorIcon.tsx
+++ b/src/components/TextInput/TextInputErrorIcon.tsx
@@ -2,17 +2,20 @@ import { View } from 'react-native';
import type { StyleProp, ViewStyle } from 'react-native';
import { ACCESSORY_SIZE } from './constants';
+import { getIconColor } from './utils';
import { useInternalTheme } from '../../core/theming';
import type { ThemeProp } from '../../theme/types';
import Icon from '../Icon';
interface TextInputErrorIconProps {
style?: StyleProp;
+ disabled?: boolean;
theme?: ThemeProp;
}
const TextInputErrorIcon = ({
style: wrapperStyle,
+ disabled = false,
theme: themeOverride,
}: TextInputErrorIconProps) => {
const theme = useInternalTheme(themeOverride);
@@ -22,7 +25,7 @@ const TextInputErrorIcon = ({
);
diff --git a/src/components/TextInput/TextInputIcon.tsx b/src/components/TextInput/TextInputIcon.tsx
index b75b5dd658..c76650a193 100644
--- a/src/components/TextInput/TextInputIcon.tsx
+++ b/src/components/TextInput/TextInputIcon.tsx
@@ -1,3 +1,4 @@
+import * as React from 'react';
import { View } from 'react-native';
import type { StyleProp, ViewStyle } from 'react-native';
@@ -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: it is hidden from assistive technology, and a tap on it goes to
+ * the field. An actionable icon requires an `aria-label` (or
+ * `accessibilityLabel`) that names its action, such as "Clear text" or
+ * "Show password", and warns in development without one.
*
* ## Usage
* ```js
@@ -49,7 +52,7 @@ export type TextInputIconProps = TextInputAccessoryProps &
* );
*
* const clearAccessory = (props) => (
- * setText('')} />
+ * setText('')} />
* );
*
* return (
@@ -78,6 +81,7 @@ const TextInputIcon = ({
theme: themeOverride,
onPress,
hitSlop,
+ multiline: _multiline,
...rest
}: TextInputIconProps) => {
const theme = useInternalTheme(themeOverride);
@@ -91,19 +95,38 @@ 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
+ // Decides both the accessibility contract and `disabled`. A decorative icon
+ // is not a control, and forwarding `disabled` would turn it back into a
+ // disabled button. Must match TouchableRipple's predicate, or an icon with
// only `onLongPress` stays pressable on a disabled field.
const { onLongPress, onPressIn, onPressOut } = rest;
- const isInteractive = hasTouchHandler({
+ const actionable = hasTouchHandler({
onPress,
onLongPress,
onPressIn,
onPressOut,
});
+ const accessibleName = rest['aria-label'] ?? rest.accessibilityLabel;
+ React.useEffect(() => {
+ if (
+ process.env.NODE_ENV !== 'production' &&
+ actionable &&
+ !accessibleName?.trim()
+ ) {
+ console.warn(
+ 'TextInput.Icon: an actionable icon requires an aria-label or accessibilityLabel.'
+ );
+ }
+ }, [actionable, accessibleName]);
+
+ void _multiline;
return (
-
+
diff --git a/src/components/TextInput/constants.ts b/src/components/TextInput/constants.ts
index 524593278f..a0b73af2e9 100644
--- a/src/components/TextInput/constants.ts
+++ b/src/components/TextInput/constants.ts
@@ -48,6 +48,9 @@ export const SUPPORTING_TEXT_MARGIN_TOP = 4;
export const ANIMATION_DURATION_MS = motionDuration.short3;
+// How long an error must stay unchanged before Android and iOS announce it.
+export const ERROR_ANNOUNCEMENT_DELAY_MS = 1000;
+
export const ACTIVE_INDICATOR_SIZE = 2;
export const INACTIVE_INDICATOR_SIZE = 1;
diff --git a/src/components/TextInput/hooks.ts b/src/components/TextInput/hooks.ts
index c6109e4ce7..0fa4814e7b 100644
--- a/src/components/TextInput/hooks.ts
+++ b/src/components/TextInput/hooks.ts
@@ -1,23 +1,31 @@
import {
useEffect,
useImperativeHandle,
+ useId,
useRef,
useState,
type ComponentRef,
type RefObject,
} from 'react';
-import { TextInput as NativeTextInput } from 'react-native';
+import {
+ AccessibilityInfo,
+ Platform,
+ TextInput as NativeTextInput,
+} from 'react-native';
import type { BlurEvent, FocusEvent } from 'react-native';
import {
interpolate,
+ useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
+import { scheduleOnRN } from 'react-native-worklets';
import {
ACTIVE_LABEL_FONT_SIZE,
+ ERROR_ANNOUNCEMENT_DELAY_MS,
INACTIVE_LABEL_FONT_SIZE,
TIMING_CONFIG,
} from './constants';
@@ -39,17 +47,20 @@ import {
} from './utils';
import { useLocale } from '../../core/locale';
import { useInternalTheme } from '../../core/theming';
+import { tokens } from '../../theme/tokens';
import type { InternalTheme } from '../../theme/types';
const useTextInputAnimation = ({
variant,
isRTL,
+ isDisabled,
hasAccessory,
value,
defaultValue,
}: {
variant: TextInputVariant;
isRTL: boolean;
+ isDisabled: boolean;
hasAccessory: boolean;
value: string | undefined;
defaultValue: string | undefined;
@@ -58,6 +69,18 @@ const useTextInputAnimation = ({
const focusSV = useSharedValue(0);
const floatSV = useSharedValue(initialText.length > 0 ? 1 : 0);
+ const [isLabelFloated, setIsLabelFloated] = useState(initialText.length > 0);
+
+ // Track when the label has fully left its resting place, whichever animation
+ // moved it, so the placeholder does not show under the resting label.
+ useAnimatedReaction(
+ () => floatSV.value === 1,
+ (floated, previous) => {
+ if (previous !== null && floated !== previous) {
+ scheduleOnRN(setIsLabelFloated, floated);
+ }
+ }
+ );
const { activeTop, inactiveTop, translateXEnd } = getTextInputAnimationLayout(
{
@@ -108,8 +131,12 @@ const useTextInputAnimation = ({
),
}));
- const animatedContainerStyle = useAnimatedStyle(() => ({
- opacity: floatSV.value,
+ // The resting label covers the prefix and suffix, so they fade in as it
+ // floats. This opacity replaces the static one, so it carries the disabled
+ // dim of the prefix and suffix styles too.
+ const affixOpacity = isDisabled ? tokens.md.sys.state.opacity.disabled : 1;
+ const animatedAffixStyle = useAnimatedStyle(() => ({
+ opacity: floatSV.value * affixOpacity,
}));
const animatedActiveOutlineStyle = useAnimatedStyle(() => ({
@@ -119,9 +146,10 @@ const useTextInputAnimation = ({
return {
animatedLabelWrapperStyle,
animatedLabelTextStyle,
- animatedContainerStyle,
+ animatedAffixStyle,
animatedActiveOutlineStyle:
variant === 'filled' ? animatedActiveOutlineStyle : undefined,
+ isLabelFloated,
runFocusAnimation,
runBlurAnimation,
syncFloatToValue,
@@ -254,6 +282,7 @@ const useTextInputLayout = ({
theme,
flags,
isFocused,
+ isHovered,
animation,
}: {
variant: TextInputVariant;
@@ -262,6 +291,7 @@ const useTextInputLayout = ({
theme: InternalTheme;
flags: TextInputFlags;
isFocused: boolean;
+ isHovered: boolean;
animation: TextInputAnimationState;
}): TextInputLayoutState => {
const { isRTL, isDisabled, hasError, hasAccessory, hasSuffix } = flags;
@@ -284,6 +314,7 @@ const useTextInputLayout = ({
input,
theme,
isFocused,
+ isHovered,
isRTL,
isDisabled,
hasAccessory,
@@ -300,6 +331,7 @@ const useTextInputLayout = ({
input,
theme,
isFocused,
+ isHovered,
isRTL,
isDisabled,
hasAccessory,
@@ -324,6 +356,8 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
const { ref, variant = 'filled', theme: themeOverride } = props;
const input = useRef>(null);
+ const id = useId();
+ const [isHovered, setIsHovered] = useState(false);
const init = useRef(false);
const theme = useInternalTheme(themeOverride);
@@ -340,6 +374,7 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
const animation = useTextInputAnimation({
variant,
isRTL,
+ isDisabled: !!props.disabled,
hasAccessory,
value: props.value,
defaultValue: props.defaultValue,
@@ -417,17 +452,59 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
theme,
flags,
isFocused,
+ isHovered,
animation,
});
+ // With a label, show the placeholder only once the label has floated away
+ // from it.
+ const isPlaceholderShown =
+ !props.label || hasValue || (isFocused && animation.isLabelFloated);
+
const accessibilityProps = getAccessibilityData({
+ id,
hasError: flags.hasError,
hasCounter: flags.hasCounter,
+ hasPrefix: flags.hasPrefix,
+ hasSuffix: flags.hasSuffix,
isDisabled: flags.isDisabled,
+ isPlaceholderShown,
data: props,
inputLength,
});
+ // On native, the error is read from the input's hint and its text node is
+ // hidden, so a live region would not announce it. Announce changed errors
+ // instead, but not errors present on mount, so a screen that opens with
+ // several invalid fields does not queue an announcement for each of them.
+ // Wait until the error has stayed the same for ERROR_ANNOUNCEMENT_DELAY_MS,
+ // so a message that changes on every keystroke is announced once it stops
+ // changing, not once per change.
+ // Queue them so that fields becoming invalid together do not cut each other
+ // off on iOS.
+ const errorMessage = flags.hasError ? props.supportingText : undefined;
+ const announcedErrorMessage = useRef(errorMessage);
+ useEffect(() => {
+ if (
+ Platform.OS === 'web' ||
+ errorMessage === announcedErrorMessage.current
+ ) {
+ return;
+ }
+
+ const timeout = setTimeout(() => {
+ announcedErrorMessage.current = errorMessage;
+
+ if (errorMessage) {
+ AccessibilityInfo.announceForAccessibilityWithOptions(errorMessage, {
+ queue: true,
+ });
+ }
+ }, ERROR_ANNOUNCEMENT_DELAY_MS);
+
+ return () => clearTimeout(timeout);
+ }, [errorMessage]);
+
const counterText = `${inputLength}/${props.maxLength}`;
const renderLeadingAccessory = flags.isRTL
@@ -437,9 +514,9 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
? props.startAccessory
: props.endAccessory;
+ // A space keeps the iOS multiline placeholder updating:
// https://github.com/facebook/react-native/issues/31573
- const placeholder =
- isFocused || !props.label || hasValue ? props.placeholder : ' ';
+ const placeholder = isPlaceholderShown ? props.placeholder : ' ';
return {
input,
@@ -453,11 +530,8 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
selectionColor,
cursorColor,
animatedActiveOutlineStyles: undefined,
- // The input only fades out while a label rests in its place; without a
- // label the input and its placeholder stay visible.
- animatedContainerStyle: props.label
- ? animation.animatedContainerStyle
- : undefined,
+ // Without a label nothing covers the prefix and suffix.
+ animatedAffixStyle: props.label ? animation.animatedAffixStyle : undefined,
placeholder,
counterText,
accessibilityProps,
@@ -468,5 +542,7 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => {
onFocus,
onBlur,
focusInput,
+ onHoverIn: () => setIsHovered(true),
+ onHoverOut: () => setIsHovered(false),
};
};
diff --git a/src/components/TextInput/styles.ts b/src/components/TextInput/styles.ts
index 054728248f..b45ab98e00 100644
--- a/src/components/TextInput/styles.ts
+++ b/src/components/TextInput/styles.ts
@@ -31,6 +31,15 @@ export const styles = StyleSheet.create({
addendum: {
flexDirection: 'row',
},
+ // Keeps the placeholder in the DOM for aria-describedby without showing it.
+ placeholderDescription: {
+ position: 'absolute',
+ width: 1,
+ height: 1,
+ overflow: 'hidden',
+ opacity: 0,
+ pointerEvents: 'none',
+ },
supportingText: {
flex: 1,
marginTop: SUPPORTING_TEXT_MARGIN_TOP,
diff --git a/src/components/TextInput/utils.ts b/src/components/TextInput/utils.ts
index 5900c86f8b..2b910c778a 100644
--- a/src/components/TextInput/utils.ts
+++ b/src/components/TextInput/utils.ts
@@ -95,12 +95,12 @@ export const getLabelColor = ({
colors: { error, primary, onSurface, onSurfaceVariant },
} = theme;
- if (hasError) {
- return error;
- }
if (isDisabled) {
return onSurface;
}
+ if (hasError) {
+ return error;
+ }
if (isFocused) {
return primary;
}
@@ -120,12 +120,12 @@ export const getSupportingTextColor = ({
colors: { error, onSurface, onSurfaceVariant },
} = theme;
- if (hasError) {
- return error;
- }
if (isDisabled) {
return onSurface;
}
+ if (hasError) {
+ return error;
+ }
return onSurfaceVariant;
};
@@ -170,37 +170,33 @@ export const getIconColor = ({
};
/**
- * Returns the raw outline color for a filled field. The disabled state's
- * alpha is intentionally NOT baked in here — it is applied via the `opacity`
- * style on the (childless) outline View so the value can be a `PlatformColor`
- * on Android, which the `color` library cannot parse at runtime.
+ * Resolve the filled indicator or outlined border color. Disabled opacity is
+ * applied by the outline View so native PlatformColor values stay intact.
*/
export const getOutlineColor = ({
theme,
hasError,
isFocused,
isDisabled,
+ isHovered = false,
+ variant = 'outlined',
}: {
theme: InternalTheme;
isFocused: boolean;
hasError: boolean;
isDisabled: boolean;
+ isHovered?: boolean;
+ variant?: TextInputVariant;
}): ColorValue => {
- const {
- colors: { error, onSurface, primary, outline },
- } = theme;
+ const { colors } = theme;
+ if (isDisabled) return colors.onSurface;
if (hasError) {
- return error;
- }
- if (isDisabled) {
- return onSurface;
- }
- if (isFocused) {
- return primary;
+ return isHovered && !isFocused ? colors.onErrorContainer : colors.error;
}
-
- return outline;
+ if (isFocused) return colors.primary;
+ if (isHovered) return colors.onSurface;
+ return variant === 'filled' ? colors.onSurfaceVariant : colors.outline;
};
/**
@@ -316,6 +312,7 @@ export const getFilledTextInputData = (
isDisabled,
hasAccessory,
hasError,
+ isHovered,
animatedLabelWrapperStyle,
animatedActiveOutlineStyle,
} = api;
@@ -332,6 +329,8 @@ export const getFilledTextInputData = (
hasError,
isFocused: false,
isDisabled,
+ variant: 'filled',
+ isHovered,
});
const activeOutlineColor = getOutlineColor({
@@ -365,10 +364,7 @@ export const getFilledTextInputData = (
animatedLabelWrapperStyle,
];
- const containerStyles: StyleProp = [
- filledStyles.container,
- isDisabled && styles.disabled,
- ];
+ const containerStyles = filledStyles.container;
const fieldStyles: StyleProp = [
styles.field,
@@ -465,6 +461,7 @@ export const getOutlinedTextInputData = (
hasAccessory,
hasError,
hasSuffix,
+ isHovered,
animatedLabelWrapperStyle,
} = api;
@@ -481,6 +478,7 @@ export const getOutlinedTextInputData = (
isDisabled,
isFocused,
hasError,
+ isHovered,
});
/**
@@ -493,10 +491,7 @@ export const getOutlinedTextInputData = (
* Variant-specific styles
*/
- const containerStyles: StyleProp = [
- outlinedStyles.container,
- isDisabled && styles.disabled,
- ];
+ const containerStyles = outlinedStyles.container;
const fieldStyles: StyleProp = [
styles.field,
@@ -570,65 +565,111 @@ export const getOutlinedTextInputData = (
export const getAccessibilityData = ({
data,
+ id,
hasError,
hasCounter,
+ hasPrefix,
+ hasSuffix,
isDisabled,
+ isPlaceholderShown,
inputLength,
}: GetAccessibilityDataProps): GetAccessibilityDataReturn => {
- const { label, supportingText, ...props } = data;
-
- const maxLength = props.maxLength;
- const shouldEvaluateCounter = !!maxLength && hasCounter;
- const isEmptyString = inputLength === 0;
- const isCounterExceeded = shouldEvaluateCounter && inputLength > maxLength;
- const isCounterReached = shouldEvaluateCounter && inputLength === maxLength;
- const isInvalid = hasError || isCounterExceeded;
- const isSupportingTextHidden = !!(supportingText && !hasError);
-
- const chunks: string[] = [];
-
- if (label) {
- chunks.push(label);
- }
-
- if (isSupportingTextHidden) {
- chunks.push(supportingText);
- }
-
- if (isEmptyString && props.placeholder && !hasError) {
- chunks.push(props.placeholder);
- }
-
- const ariaLabel = chunks.length > 0 ? chunks.join(', ') : label;
-
- let hint: string | undefined;
-
- if (isCounterExceeded && !(hasError && supportingText)) {
- hint = `Character limit exceeded ${inputLength} of ${maxLength}`;
- }
-
- const counterAccessibilityLabel = shouldEvaluateCounter
+ const { label, supportingText, maxLength, prefix, suffix, ...props } = data;
+ const isCounterExceeded =
+ hasCounter && maxLength != null && inputLength > maxLength;
+ const counterAccessibilityLabel = hasCounter
? isCounterExceeded
? `Character limit exceeded ${inputLength} of ${maxLength}`
: `Characters entered ${inputLength} of ${maxLength}`
: undefined;
+ // A labelled field blanks its placeholder until the label floats away, so
+ // assistive technology moving to the empty field would not hear it.
+ const placeholderDescription =
+ label && inputLength === 0 ? props.placeholder : undefined;
+
+ // Generated IDs only link the label and descriptions on web.
+ const labelId = Platform.OS === 'web' ? `${id}-label` : undefined;
+ // The input exposes its own placeholder once it shows it, so only describe
+ // the field with it before then. Otherwise it is read twice.
+ const placeholderId =
+ Platform.OS === 'web' && placeholderDescription && !isPlaceholderShown
+ ? `${id}-placeholder`
+ : undefined;
+ const prefixId =
+ Platform.OS === 'web' && hasPrefix ? `${id}-prefix` : undefined;
+ const suffixId =
+ Platform.OS === 'web' && hasSuffix ? `${id}-suffix` : undefined;
+ const supportingTextId =
+ Platform.OS === 'web' && supportingText
+ ? `${id}-supporting-text`
+ : undefined;
+ const counterId =
+ Platform.OS === 'web' && hasCounter ? `${id}-counter` : undefined;
+ const describedBy =
+ [
+ props['aria-describedby'],
+ placeholderId,
+ prefixId,
+ suffixId,
+ supportingTextId,
+ counterId,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+ const explicitLabel = props['aria-label'] ?? props.accessibilityLabel;
+ const labelledBy =
+ props['aria-labelledby'] ??
+ (label && explicitLabel == null && !props.accessibilityLabelledBy
+ ? labelId
+ : undefined);
+
+ // React Native 0.88 does not implement described-by relationships on native.
+ // Expose the same description as a hint without changing the field's name.
+ const hint =
+ Platform.OS === 'web'
+ ? props.accessibilityHint
+ : [
+ props.accessibilityHint,
+ placeholderDescription,
+ prefix?.trim(),
+ suffix?.trim(),
+ supportingText,
+ counterAccessibilityLabel,
+ ]
+ .filter(Boolean)
+ .join(', ') || undefined;
+
return {
input: {
- 'aria-label': ariaLabel,
- 'aria-valuemax': isCounterReached ? maxLength : undefined,
- 'aria-valuenow': isCounterReached ? inputLength : undefined,
- 'aria-disabled': isDisabled,
- 'aria-invalid': isInvalid,
+ 'aria-label': explicitLabel ?? label ?? props.placeholder,
+ 'aria-labelledby': labelledBy,
+ 'aria-describedby': describedBy,
+ 'aria-disabled': isDisabled || (props['aria-disabled'] ?? false),
+ 'aria-invalid': props['aria-invalid'] ?? (hasError || isCounterExceeded),
accessibilityHint: hint,
},
+ label: { nativeID: labelId },
+ placeholder: { nativeID: placeholderId, 'aria-hidden': true },
+ // The prefix and suffix describe the value, so they are read with the
+ // field instead of as separate text next to it.
+ prefix: { nativeID: prefixId, 'aria-hidden': true },
+ suffix: { nativeID: suffixId, 'aria-hidden': true },
+ // On native, the hint above already contains these texts. Hide their nodes
+ // so they are not read twice or merged into the field wrapper's label.
supportingText: {
- 'aria-hidden': isSupportingTextHidden,
- 'aria-live': hasError && supportingText ? 'polite' : undefined,
+ nativeID: supportingTextId,
+ 'aria-hidden': Platform.OS !== 'web',
+ role:
+ Platform.OS === 'web' && hasError && supportingText
+ ? 'alert'
+ : undefined,
},
counter: {
+ nativeID: counterId,
+ 'aria-hidden': Platform.OS !== 'web',
'aria-label': counterAccessibilityLabel,
- 'aria-live': 'polite',
+ 'aria-live': Platform.OS === 'web' ? 'polite' : undefined,
},
};
};
diff --git a/src/components/__tests__/TextInput.test.tsx b/src/components/__tests__/TextInput.test.tsx
index 20bb647ba1..7fcdb7a4c3 100644
--- a/src/components/__tests__/TextInput.test.tsx
+++ b/src/components/__tests__/TextInput.test.tsx
@@ -15,6 +15,7 @@ import {
it,
jest,
} from '@jest/globals';
+import { getAnimatedStyle } from 'react-native-reanimated';
import type { TestInstance } from 'test-renderer';
import { act, fireEvent, render, screen, userEvent } from '../../test-utils';
@@ -162,7 +163,12 @@ it('renders filled TextInput with TextInput.Icon accessories when error is true'
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
)
@@ -184,7 +190,12 @@ it('renders outlined TextInput with TextInput.Icon accessories when error is tru
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
)
@@ -228,10 +239,20 @@ it('disables TextInput.Icon when the field is disabled', async () => {
onChangeText={() => {}}
disabled
startAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
);
@@ -255,6 +276,7 @@ it('does not expose a handler-less TextInput.Icon as a control when the field is
{}}
testID="clear"
/>
@@ -262,7 +284,7 @@ it('does not expose a handler-less TextInput.Icon as a control when the field is
/>
);
- const decorative = screen.getByTestId('decorative');
+ const decorative = screen.getByTestId('decorative', includeHiddenElements);
expect(decorative).toHaveProp('role', 'none');
expect(decorative).not.toBeDisabled();
@@ -288,7 +310,12 @@ it('dims a disabled TextInput with TextInput.Icon accessories exactly once', asy
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
)
@@ -309,7 +336,12 @@ it('uses the disabled color for every TextInput.Icon of a disabled field with an
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
);
@@ -336,6 +368,7 @@ it('uses the disabled color over iconColor for every TextInput.Icon of a disable
{...props}
icon="close"
iconColor="#6750A4"
+ aria-label="Clear"
onPress={() => {}}
/>
)}
@@ -361,6 +394,7 @@ it('disables a TextInput.Icon that only has onLongPress when the field is disabl
@@ -386,10 +420,20 @@ it('does not disable TextInput.Icon when the field is read-only (editable false)
onChangeText={() => {}}
editable={false}
startAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
endAccessory={(props: TextInputAccessoryProps) => (
- {}} />
+ {}}
+ />
)}
/>
);
@@ -414,7 +458,7 @@ it('renders supporting text below the field', async () => {
).toBeOnTheScreen();
});
-it('uses polite aria-live on error supporting text', async () => {
+it('marks the input invalid and describes the error supporting text', async () => {
await render(
{
/>
);
- expect(screen.getByText('Invalid')).toHaveProp('aria-live', 'polite');
- expect(screen.getByLabelText('Email')).toHaveProp('aria-invalid', true);
+ const input = screen.getByLabelText('Email');
+ expect(input).toHaveProp('aria-invalid', true);
+ expect(input).toHaveProp('accessibilityHint', 'Invalid');
});
it('marks the input invalid when error is true without supporting text', async () => {
@@ -446,7 +491,7 @@ 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 () => {
+it('describes helper supporting text without including it in the field name', async () => {
await render(
);
- const supportingText = screen.getByText('Optional', includeHiddenElements);
- expect(supportingText).toHaveProp('aria-hidden', true);
- expect(supportingText).not.toHaveProp('aria-live');
- expect(screen.getByLabelText('Email, Optional')).toBeOnTheScreen();
+ expect(screen.getByLabelText('Email')).toHaveProp(
+ 'accessibilityHint',
+ 'Optional'
+ );
+ expect(screen.getByText('Optional', includeHiddenElements)).not.toHaveProp(
+ 'aria-live'
+ );
});
-it('includes supporting text in aria-label when label is omitted', async () => {
+it('keeps supporting text separate when label is omitted', async () => {
await render(
{
/>
);
- expect(screen.getByLabelText('Helper only')).toBeOnTheScreen();
+ expect(screen.getByTestId('tf-input')).not.toHaveProp('aria-label');
+ expect(
+ screen.getByText('Helper only', includeHiddenElements)
+ ).toBeOnTheScreen();
});
it('does not mark the input as aria-disabled when editable is false (read-only)', async () => {
@@ -658,8 +709,10 @@ it('shows a character counter when counter is true and maxLength is set (filled)
/>
);
- expect(screen.getByText('5/100')).toBeOnTheScreen();
- expect(screen.queryByText('0/100')).not.toBeOnTheScreen();
+ expect(screen.getByText('5/100', includeHiddenElements)).toBeOnTheScreen();
+ expect(
+ screen.queryByText('0/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
});
it('shows a character counter when counter is true and maxLength is set (outlined)', async () => {
@@ -674,7 +727,7 @@ it('shows a character counter when counter is true and maxLength is set (outline
/>
);
- expect(screen.getByText('0/50')).toBeOnTheScreen();
+ expect(screen.getByText('0/50', includeHiddenElements)).toBeOnTheScreen();
});
it('updates the character counter when the value changes', async () => {
@@ -688,7 +741,7 @@ it('updates the character counter when the value changes', async () => {
/>
);
- expect(screen.getByText('1/10')).toBeOnTheScreen();
+ expect(screen.getByText('1/10', includeHiddenElements)).toBeOnTheScreen();
await rerender(
{
/>
);
- expect(screen.getByText('4/10')).toBeOnTheScreen();
+ expect(screen.getByText('4/10', includeHiddenElements)).toBeOnTheScreen();
});
it('does not show a character counter when counter is false', async () => {
@@ -713,7 +766,9 @@ it('does not show a character counter when counter is false', async () => {
/>
);
- expect(screen.queryByText('5/100')).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText('5/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
});
it('does not show a character counter when maxLength is missing', async () => {
@@ -721,8 +776,10 @@ it('does not show a character counter when maxLength is missing', async () => {
{}} counter />
);
- expect(screen.queryByText('5/100')).not.toBeOnTheScreen();
- expect(screen.queryByText(/\//)).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText('5/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
+ expect(screen.queryByText(/\//, includeHiddenElements)).not.toBeOnTheScreen();
});
it('invokes onFocus and onBlur on the TextInput', async () => {
@@ -912,7 +969,7 @@ it('renders the counter as a Text child', async () => {
/>
);
- expect(screen.getByText('2/80')).toBeOnTheScreen();
+ expect(screen.getByText('2/80', includeHiddenElements)).toBeOnTheScreen();
});
it('renders supporting text and counter separately when both are shown', async () => {
@@ -930,7 +987,7 @@ it('renders supporting text and counter separately when both are shown', async (
expect(
screen.getByText('Help text', includeHiddenElements)
).toBeOnTheScreen();
- expect(screen.getByText('1/10')).toBeOnTheScreen();
+ expect(screen.getByText('1/10', includeHiddenElements)).toBeOnTheScreen();
});
it('applies RTL text alignment and writing direction to the TextInput (filled)', async () => {
@@ -1075,7 +1132,7 @@ it('shows placeholder when unfocused and no label is given', async () => {
);
});
-it('shows placeholder when the TextInput is focused', async () => {
+it('shows placeholder when the TextInput is focused, once the label floats away', async () => {
await render(
{
await fireEvent(screen.getByTestId('tf-input'), 'focus');
+ // The label still rests over the input when the field takes focus.
+ // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion.
+ expect(screen.getByTestId('tf-input').props.placeholder).toBe(' ');
+
+ await act(() => jest.advanceTimersByTimeAsync(1000));
+
// eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion.
expect(screen.getByTestId('tf-input').props.placeholder).toBe(
'e.g. user@example.com'
);
});
-it('shows placeholder on multiline TextInput when focused', async () => {
+it('shows placeholder on multiline TextInput when focused, once the label floats away', async () => {
await render(
{
await fireEvent(screen.getByTestId('tf-multiline'), 'focus');
+ // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion.
+ expect(screen.getByTestId('tf-multiline').props.placeholder).toBe(' ');
+
+ await act(() => jest.advanceTimersByTimeAsync(1000));
+
// eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion.
expect(screen.getByTestId('tf-multiline').props.placeholder).toBe(
'Add a note…'
);
});
+it('shows placeholder at once when a focused TextInput with a floated label is cleared', async () => {
+ const { rerender } = await render(
+ {}}
+ placeholder="e.g. user@example.com"
+ />
+ );
+
+ await fireEvent(screen.getByLabelText('Email'), 'focus');
+ await rerender(
+ {}}
+ placeholder="e.g. user@example.com"
+ />
+ );
+
+ expect(
+ screen.getByPlaceholderText('e.g. user@example.com')
+ ).toBeOnTheScreen();
+});
+
it.each(['filled', 'outlined'] as const)(
'keeps an empty, unfocused %s TextInput without a label visible',
async (variant) => {
@@ -1133,17 +1226,23 @@ it.each(['filled', 'outlined'] as const)(
}
);
-it('hides the input of an empty, unfocused TextInput while its label rests in place', async () => {
+it('keeps the input of an empty, unfocused TextInput visible with a blank placeholder while its label rests in place', async () => {
await render(
{}}
+ placeholder="e.g. user@example.com"
testID="tf-input"
/>
);
- expect(screen.getByTestId('tf-input')).not.toBeVisible();
+ // Fading the input out would also remove it from the native accessibility
+ // tree, so the resting label covers a blank placeholder instead.
+ expect(screen.getByTestId('tf-input')).toBeVisible();
+ expect(
+ screen.queryByPlaceholderText('e.g. user@example.com')
+ ).not.toBeOnTheScreen();
});
it('does not expose the placeholder string again after the TextInput loses focus', async () => {
@@ -1216,8 +1315,8 @@ it('shows prefix and suffix when the field is floating and hides them after valu
/>
);
- expect(screen.getByText('$')).toBeOnTheScreen();
- expect(screen.getByText('/100')).toBeOnTheScreen();
+ expect(screen.getByText('$', includeHiddenElements)).toBeOnTheScreen();
+ expect(screen.getByText('/100', includeHiddenElements)).toBeOnTheScreen();
await rerender(
);
- expect(screen.queryByText('$')).not.toBeOnTheScreen();
- expect(screen.queryByText('/100')).not.toBeOnTheScreen();
+ expect(screen.queryByText('$', includeHiddenElements)).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText('/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
expect(screen.getByTestId('tf-ps')).toBeOnTheScreen();
});
@@ -1247,13 +1348,67 @@ it('renders prefix and suffix while focused even when value is empty', async ()
/>
);
- expect(screen.queryByText('$')).not.toBeOnTheScreen();
- expect(screen.queryByText(' kg')).not.toBeOnTheScreen();
+ expect(screen.queryByText('$', includeHiddenElements)).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText(' kg', includeHiddenElements)
+ ).not.toBeOnTheScreen();
await fireEvent(screen.getByTestId('tf-ps-focus'), 'focus');
- expect(screen.getByText('$')).toBeOnTheScreen();
- expect(screen.getByText(' kg')).toBeOnTheScreen();
+ expect(screen.getByText('$', includeHiddenElements)).toBeOnTheScreen();
+ expect(screen.getByText(' kg', includeHiddenElements)).toBeOnTheScreen();
+});
+
+it.each([
+ { affix: 'prefix', text: '$' },
+ { affix: 'suffix', text: ' kg' },
+] as const)(
+ 'fades the $affix in as the label floats away from it',
+ async ({ affix, text }) => {
+ await render(
+ {}}
+ {...{ [affix]: text }}
+ />
+ );
+
+ await fireEvent(screen.getByLabelText('Amount'), 'focus');
+
+ // The label still rests over it when the field takes focus.
+ expect(
+ getAnimatedStyle(screen.getByText(text, includeHiddenElements))
+ ).toMatchObject({ opacity: 0 });
+
+ await act(() => jest.advanceTimersByTimeAsync(1000));
+
+ expect(
+ getAnimatedStyle(screen.getByText(text, includeHiddenElements))
+ ).toMatchObject({
+ opacity: 1,
+ });
+ }
+);
+
+it('keeps the disabled dim on the prefix and suffix of a labelled field', async () => {
+ await render(
+ {}}
+ prefix="$"
+ suffix=" kg"
+ disabled
+ />
+ );
+
+ expect(screen.getByText('$', includeHiddenElements)).toHaveStyle({
+ opacity: stateOpacity.disabled,
+ });
+ expect(screen.getByText(' kg', includeHiddenElements)).toHaveStyle({
+ opacity: stateOpacity.disabled,
+ });
});
it('places prefix Text before the TextInput and suffix Text after it', async () => {
@@ -1348,10 +1503,18 @@ it('does not apply the TextInput style prop to prefix or suffix Text', async ()
letterSpacing: 9,
});
- expect(screen.getByText('$')).not.toHaveStyle({ fontSize: 40 });
- expect(screen.getByText('$')).not.toHaveStyle({ letterSpacing: 9 });
- expect(screen.getByText(']')).not.toHaveStyle({ fontSize: 40 });
- expect(screen.getByText(']')).not.toHaveStyle({ letterSpacing: 9 });
+ expect(screen.getByText('$', includeHiddenElements)).not.toHaveStyle({
+ fontSize: 40,
+ });
+ expect(screen.getByText('$', includeHiddenElements)).not.toHaveStyle({
+ letterSpacing: 9,
+ });
+ expect(screen.getByText(']', includeHiddenElements)).not.toHaveStyle({
+ fontSize: 40,
+ });
+ expect(screen.getByText(']', includeHiddenElements)).not.toHaveStyle({
+ letterSpacing: 9,
+ });
});
it('passes defaultValue to the native input when uncontrolled without counter', async () => {
@@ -1385,12 +1548,12 @@ it('updates the character counter for an uncontrolled field with counter enabled
/>
);
- expect(screen.getByText('1/10')).toBeOnTheScreen();
+ expect(screen.getByText('1/10', includeHiddenElements)).toBeOnTheScreen();
await user.type(screen.getByTestId('tf-uncontrolled-counter'), 'bcd');
expect(onChangeText).toHaveBeenCalledWith('abcd');
- expect(screen.getByText('4/10')).toBeOnTheScreen();
+ expect(screen.getByText('4/10', includeHiddenElements)).toBeOnTheScreen();
});
it('resets counter and hides prefix/suffix when clear() is called on uncontrolled field while blurred', async () => {
@@ -1407,17 +1570,19 @@ it('resets counter and hides prefix/suffix when clear() is called on uncontrolle
/>
);
- expect(screen.getByText('3/200')).toBeOnTheScreen();
- expect(screen.getByText('$')).toBeOnTheScreen();
- expect(screen.getByText('/100')).toBeOnTheScreen();
+ expect(screen.getByText('3/200', includeHiddenElements)).toBeOnTheScreen();
+ expect(screen.getByText('$', includeHiddenElements)).toBeOnTheScreen();
+ expect(screen.getByText('/100', includeHiddenElements)).toBeOnTheScreen();
await act(() => {
ref.current?.clear();
});
expect(screen.getByText('0/200', includeHiddenElements)).toBeOnTheScreen();
- expect(screen.queryByText('$')).not.toBeOnTheScreen();
- expect(screen.queryByText('/100')).not.toBeOnTheScreen();
+ expect(screen.queryByText('$', includeHiddenElements)).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText('/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
});
it('resets counter but keeps prefix/suffix visible when clear() is called on uncontrolled field while focused', async () => {
@@ -1504,8 +1669,10 @@ it('hides prefix/suffix when blurring after clear() was called while focused', a
await fireEvent(screen.getByTestId('tf-clear-then-blur'), 'blur');
// After blur with no text, prefix/suffix should be hidden
- expect(screen.queryByText('$')).not.toBeOnTheScreen();
- expect(screen.queryByText('/100')).not.toBeOnTheScreen();
+ expect(screen.queryByText('$', includeHiddenElements)).not.toBeOnTheScreen();
+ expect(
+ screen.queryByText('/100', includeHiddenElements)
+ ).not.toBeOnTheScreen();
});
it('keeps the 48dp TextInput.Icon target when a forwarded hitSlop is undefined', async () => {
@@ -1518,6 +1685,7 @@ it('keeps the 48dp TextInput.Icon target when a forwarded hitSlop is undefined',
{}}
hitSlop={undefined}
testID="clear-icon"
diff --git a/src/components/__tests__/TextInputAccessibility.test.tsx b/src/components/__tests__/TextInputAccessibility.test.tsx
new file mode 100644
index 0000000000..7cbdef5ea1
--- /dev/null
+++ b/src/components/__tests__/TextInputAccessibility.test.tsx
@@ -0,0 +1,932 @@
+import type { ComponentRef } from 'react';
+import {
+ AccessibilityInfo,
+ Text,
+ Platform,
+ TextInput as NativeTextInput,
+} from 'react-native';
+import type { View } from 'react-native';
+
+import { afterEach, expect, it, jest } from '@jest/globals';
+
+import { act, fireEvent, render, screen, userEvent } from '../../test-utils';
+import TextInput from '../TextInput';
+import { ERROR_ANNOUNCEMENT_DELAY_MS } from '../TextInput/constants';
+import type {
+ TextInputProps,
+ TextInputRenderProps,
+} from '../TextInput/TextInput';
+
+const renderInput = jest.fn((props: TextInputRenderProps) => (
+
+));
+
+afterEach(() => {
+ jest.restoreAllMocks();
+ renderInput.mockClear();
+});
+
+it.each(['filled', 'outlined'] as const)(
+ 'uses the placeholder as the name of an unlabelled %s field, including after typing',
+ async (variant) => {
+ await render();
+
+ const input = screen.getByLabelText('Search');
+ await userEvent.type(input, 'Paper');
+ expect(screen.getByLabelText('Search')).toHaveDisplayValue('Paper');
+ }
+);
+
+it.each([
+ { label: 'Search products' },
+ { 'aria-label': 'Search products' },
+ { accessibilityLabel: 'Search products' },
+])('prefers a supplied name over the placeholder: %j', async (props) => {
+ await render();
+
+ expect(screen.getByLabelText('Search products')).toBeOnTheScreen();
+ expect(screen.queryByLabelText('Search')).toBeNull();
+});
+
+it.each([
+ { disabled: true, 'aria-disabled': false, expectedDisabled: true },
+ { disabled: true, 'aria-disabled': true, expectedDisabled: true },
+ { disabled: false, 'aria-disabled': true, expectedDisabled: true },
+ { disabled: false, 'aria-disabled': false, expectedDisabled: false },
+])(
+ 'keeps the disabled semantics consistent: %j',
+ async ({ expectedDisabled, ...props }) => {
+ await render();
+
+ const input = screen.getByLabelText('Email');
+ expect(input).toHaveProp('aria-disabled', expectedDisabled);
+ }
+);
+
+it.each(['filled', 'outlined'] as const)(
+ 'keeps an empty unfocused %s field visible to assistive technology',
+ async (variant) => {
+ await render();
+
+ expect(screen.getByLabelText('Email')).toBeVisible();
+ await fireEvent(screen.getByLabelText('Email'), 'focus');
+ await fireEvent(screen.getByLabelText('Email'), 'blur');
+ expect(screen.getByLabelText('Email')).toBeVisible();
+ }
+);
+
+it('preserves accessory refs when switching between decoration and action', async () => {
+ const ref = jest.fn<(instance: ComponentRef | null) => void>();
+ const props = {
+ icon: 'magnify',
+ style: {},
+ disabled: false,
+ error: false,
+ multiline: false,
+ ref,
+ };
+ const { rerender, unmount } = await render();
+ expect(ref).toHaveBeenCalledTimes(1);
+ expect(ref).toHaveBeenLastCalledWith(
+ expect.objectContaining({ measure: expect.any(Function) })
+ );
+
+ await rerender(
+ {}} aria-label="Search" />
+ );
+ await rerender();
+ expect(ref).toHaveBeenCalledTimes(1);
+
+ await unmount();
+ expect(ref).toHaveBeenLastCalledWith(null);
+});
+
+it.each(['filled', 'outlined'] as const)(
+ 'associates helper and counter on web without changing the %s field name',
+ async (variant) => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+ const inputProps = renderInput.mock.lastCall?.[0];
+ const ids = inputProps?.['aria-describedby']?.split(' ');
+
+ expect(screen.getByLabelText('Email')).toBeOnTheScreen();
+ expect(inputProps?.['aria-describedby']).toEqual(expect.any(String));
+ expect(ids).toHaveLength(2);
+ expect(screen.getByText('Use a work address')).toHaveProp(
+ 'nativeID',
+ ids?.[0]
+ );
+ expect(screen.getByText('0/40')).toHaveProp('nativeID', ids?.[1]);
+ }
+);
+
+it('keeps generated IDs stable as helper text becomes an error and removes absent descriptions', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ const { rerender } = await render(
+
+ );
+ const describedBy = renderInput.mock.lastCall?.[0]['aria-describedby'];
+ expect(describedBy).toEqual(expect.any(String));
+
+ await rerender(
+
+ );
+ expect(screen.getByLabelText('Email')).toHaveProp(
+ 'aria-describedby',
+ describedBy
+ );
+ expect(screen.getByRole('alert')).toHaveTextContent('Invalid address');
+ expect(screen.getByRole('alert')).toHaveProp('nativeID', describedBy);
+
+ await rerender();
+ expect(screen.getByLabelText('Email')).not.toHaveProp('aria-describedby');
+ expect(screen.queryByRole('alert')).toBeNull();
+});
+
+it('gives different fields distinct description IDs even with the same test ID', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+ <>
+
+
+ >
+ );
+ const first = renderInput.mock.calls[0]?.[0]['aria-describedby'];
+ const second = renderInput.mock.calls[1]?.[0]['aria-describedby'];
+ expect(first).toEqual(expect.any(String));
+ expect(second).toEqual(expect.any(String));
+ expect(first).not.toBe(second);
+});
+
+it('merges external descriptions and preserves an explicit accessible name in a custom renderer', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+ const describedBy = renderInput.mock.lastCall?.[0]['aria-describedby'];
+ expect(describedBy).toMatch(/^privacy \S+$/);
+ expect(screen.getByLabelText('Work email')).toHaveProp(
+ 'aria-describedby',
+ describedBy
+ );
+ expect(screen.getByText('Use a work address')).toHaveProp(
+ 'nativeID',
+ describedBy?.split(' ')[1]
+ );
+});
+
+it.each(['ios', 'android'] as const)(
+ 'reads field descriptions only from the native hint on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ await render(
+
+ );
+ const input = screen.getByLabelText('Bio');
+ expect(input).toHaveProp(
+ 'accessibilityHint',
+ 'Double tap to edit, Keep it short, Characters entered 2 of 20'
+ );
+ expect(input).not.toHaveProp('aria-describedby');
+ expect(screen.queryByText('Keep it short')).toBeNull();
+ expect(screen.queryByText('2/20')).toBeNull();
+ for (const text of ['Keep it short', '2/20']) {
+ expect(
+ screen.getByText(text, { includeHiddenElements: true })
+ ).not.toHaveProp('nativeID');
+ }
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'reads the placeholder of an empty labelled field from the hint on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ await render(
+
+ );
+ const input = screen.getByLabelText('Email');
+ expect(input).toHaveProp(
+ 'accessibilityHint',
+ 'Signs you in, name@example.com, Use a work address'
+ );
+ expect(
+ screen.queryByText('name@example.com', { includeHiddenElements: true })
+ ).toBeNull();
+
+ await userEvent.type(input, 'a');
+ expect(input).toHaveProp(
+ 'accessibilityHint',
+ 'Signs you in, Use a work address'
+ );
+ }
+);
+
+it('describes an empty labelled field with its placeholder on web until the input shows it', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+ const input = screen.getByLabelText('Email');
+ const getDescriptionIds = () =>
+ renderInput.mock.lastCall?.[0]['aria-describedby']?.split(' ') ?? [];
+ const ids = getDescriptionIds();
+
+ expect(input).toHaveProp('placeholder', ' ');
+ expect(ids).toHaveLength(2);
+ expect(screen.queryByText('name@example.com')).toBeNull();
+ expect(
+ screen.getByText('name@example.com', { includeHiddenElements: true })
+ ).toHaveProp('nativeID', ids[0]);
+ expect(screen.getByText('Use a work address')).toHaveProp('nativeID', ids[1]);
+
+ await fireEvent(input, 'focus');
+ await act(() => jest.advanceTimersByTimeAsync(1000));
+
+ // The input exposes its own placeholder now, so it is not read twice.
+ expect(input).toHaveProp('placeholder', 'name@example.com');
+ expect(getDescriptionIds()).toEqual([ids[1]]);
+ expect(
+ screen.queryByText('name@example.com', { includeHiddenElements: true })
+ ).toBeNull();
+});
+
+it.each([
+ { label: 'Email', defaultValue: 'a' },
+ { 'aria-label': 'Email' },
+])(
+ 'does not describe the field with a placeholder the input shows on web: %j',
+ async (props) => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+
+ expect(renderInput.mock.lastCall?.[0]['aria-describedby']).toBeUndefined();
+ expect(
+ screen.queryByText('name@example.com', { includeHiddenElements: true })
+ ).toBeNull();
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'leaves the placeholder of an unlabelled field out of the hint on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ await render(
+
+ );
+ expect(screen.getByLabelText('Email')).not.toHaveProp('accessibilityHint');
+ }
+);
+
+it('describes the field on web with its prefix and suffix instead of exposing them', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+ const ids =
+ renderInput.mock.lastCall?.[0]['aria-describedby']?.split(' ') ?? [];
+
+ expect(ids).toHaveLength(3);
+ expect(screen.queryByText('~')).toBeNull();
+ expect(screen.queryByText(' kg')).toBeNull();
+ expect(screen.getByText('~', { includeHiddenElements: true })).toHaveProp(
+ 'nativeID',
+ ids[0]
+ );
+ expect(screen.getByText(' kg', { includeHiddenElements: true })).toHaveProp(
+ 'nativeID',
+ ids[1]
+ );
+ expect(screen.getByText('Packed weight')).toHaveProp('nativeID', ids[2]);
+});
+
+it('does not reference a prefix or suffix that is not rendered on web', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+
+ expect(screen.queryByText('~', { includeHiddenElements: true })).toBeNull();
+ expect(renderInput.mock.lastCall?.[0]['aria-describedby']).toBeUndefined();
+});
+
+it.each(['ios', 'android'] as const)(
+ 'reads the prefix and suffix from the hint instead of as separate text on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ await render(
+
+ );
+ const input = screen.getByLabelText('Weight');
+ expect(input).toHaveProp('accessibilityHint', '0.0, ~, kg, Packed weight');
+
+ await userEvent.type(input, '5');
+ expect(input).toHaveProp('accessibilityHint', '~, kg, Packed weight');
+ expect(screen.queryByText('~')).toBeNull();
+ expect(screen.queryByText(' kg')).toBeNull();
+ expect(
+ screen.getByText('~', { includeHiddenElements: true })
+ ).not.toHaveProp('nativeID');
+ }
+);
+
+it('uses web descriptions without duplicating them in a hint', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+
+ );
+ expect(screen.getByLabelText('Bio')).not.toHaveProp('accessibilityHint');
+ expect(screen.getByText('Keep it short')).toBeOnTheScreen();
+ expect(screen.getByLabelText('Characters entered 0 of 20')).toHaveProp(
+ 'aria-live',
+ 'polite'
+ );
+});
+
+it.each([true, false, 'true', 'false', 'grammar', 'spelling'] as const)(
+ 'preserves explicit aria-invalid=%s independently of the error prop',
+ async (invalid) => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ const { rerender } = await render(
+
+ );
+ expect(renderInput.mock.lastCall?.[0]['aria-invalid']).toBe(invalid);
+
+ await rerender(
+
+ );
+ expect(renderInput.mock.lastCall?.[0]['aria-invalid']).toBe(invalid);
+
+ await rerender();
+ expect(renderInput.mock.lastCall?.[0]['aria-invalid']).toBe(true);
+
+ await rerender();
+ expect(renderInput.mock.lastCall?.[0]['aria-invalid']).toBe(false);
+ }
+);
+
+const settleError = () =>
+ act(() => jest.advanceTimersByTime(ERROR_ANNOUNCEMENT_DELAY_MS));
+
+const spyOnAnnounce = () =>
+ jest
+ .spyOn(AccessibilityInfo, 'announceForAccessibilityWithOptions')
+ .mockClear();
+
+it.each(['ios', 'android'] as const)(
+ 'announces each changed error message once on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const { rerender } = await render(
+
+ );
+ await settleError();
+ expect(announce).not.toHaveBeenCalled();
+
+ await rerender(
+
+ );
+ await settleError();
+ expect(announce).toHaveBeenLastCalledWith('Invalid address', {
+ queue: true,
+ });
+ await rerender(
+
+ );
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(1);
+ await rerender(
+
+ );
+ await settleError();
+ expect(announce).toHaveBeenLastCalledWith('Address is required', {
+ queue: true,
+ });
+ await rerender();
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(2);
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'does not announce an error that is shown on mount on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const { rerender } = await render(
+
+ );
+ await settleError();
+ expect(announce).not.toHaveBeenCalled();
+
+ await rerender(
+
+ );
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(1);
+ expect(announce).toHaveBeenLastCalledWith('Address is required', {
+ queue: true,
+ });
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'waits for the error to stop changing and announces only the last one on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const { rerender } = await render();
+
+ for (const remaining of [5, 4, 3]) {
+ await rerender(
+
+ );
+ await act(() =>
+ jest.advanceTimersByTime(ERROR_ANNOUNCEMENT_DELAY_MS - 1)
+ );
+ }
+ expect(announce).not.toHaveBeenCalled();
+
+ await act(() => jest.advanceTimersByTime(1));
+ expect(announce.mock.calls).toEqual([
+ ['Enter 3 more digits', { queue: true }],
+ ]);
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'announces a message that stays the same while typing a second after it appears on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const invalid = (value: string) => (
+
+ );
+ const { rerender } = await render();
+
+ await rerender(invalid('a'));
+ await act(() => jest.advanceTimersByTime(ERROR_ANNOUNCEMENT_DELAY_MS - 1));
+ await rerender(invalid('ab'));
+ await act(() => jest.advanceTimersByTime(1));
+ expect(announce.mock.calls).toEqual([
+ ['Use at least 8 characters', { queue: true }],
+ ]);
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'does not announce an error that clears before it settles on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const { rerender, unmount } = await render();
+
+ await rerender(
+
+ );
+ await rerender();
+ await settleError();
+ expect(announce).not.toHaveBeenCalled();
+
+ await rerender(
+
+ );
+ await unmount();
+ await settleError();
+ expect(announce).not.toHaveBeenCalled();
+ }
+);
+
+it.each(['ios', 'android'] as const)(
+ 'announces an error again only after it stays cleared on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = spyOnAnnounce();
+ const invalid = (
+
+ );
+ const valid = ;
+ const { rerender } = await render(valid);
+
+ await rerender(invalid);
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(1);
+
+ await rerender(valid);
+ await rerender(invalid);
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(1);
+
+ await rerender(valid);
+ await settleError();
+ await rerender(invalid);
+ await settleError();
+ expect(announce).toHaveBeenCalledTimes(2);
+ }
+);
+
+const makeTwoFieldsInvalid = async () => {
+ const announce = spyOnAnnounce();
+ const { rerender } = await render(
+ <>
+
+
+ >
+ );
+
+ await rerender(
+ <>
+
+
+ >
+ );
+ await settleError();
+
+ return announce;
+};
+
+it.each(['ios', 'android'] as const)(
+ 'announces the error of each field that becomes invalid in the same update on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ const announce = await makeTwoFieldsInvalid();
+ expect(announce.mock.calls.map(([message]) => message)).toEqual([
+ 'Invalid address',
+ 'Password is required',
+ ]);
+ }
+);
+
+it('queues the error announcements on iOS so they do not cut each other off', async () => {
+ jest.replaceProperty(Platform, 'OS', 'ios');
+ const announce = await makeTwoFieldsInvalid();
+ expect(announce.mock.calls).toEqual([
+ ['Invalid address', { queue: true }],
+ ['Password is required', { queue: true }],
+ ]);
+});
+
+it('announces errors on web through the alert role', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ const announce = spyOnAnnounce();
+ const { rerender } = await render(
+
+ );
+ expect(screen.queryByRole('alert')).toBeNull();
+
+ await rerender(
+
+ );
+ expect(screen.getByRole('alert')).toHaveTextContent('Invalid address');
+ await settleError();
+ expect(announce).not.toHaveBeenCalled();
+});
+
+it('keeps a disabled native input read-only when readOnly is explicitly false', async () => {
+ await render(
+
+ );
+ expect(renderInput.mock.lastCall?.[0].editable).toBe(false);
+ expect(renderInput.mock.lastCall?.[0].readOnly).toBe(true);
+});
+
+it.each(['onLongPress', 'onPressIn', 'onPressOut'] as const)(
+ 'preserves an accessory using only %s',
+ async (handler) => {
+ const onAction = jest.fn<() => void>();
+ await render(
+ (
+
+ )}
+ />
+ );
+ await userEvent.longPress(
+ screen.getByRole('button', { name: 'Search action' })
+ );
+ expect(onAction).toHaveBeenCalledTimes(1);
+ }
+);
+
+const accessoryNameWarning =
+ 'TextInput.Icon: an actionable icon requires an aria-label or accessibilityLabel.';
+
+it.each([
+ { name: 'no', label: undefined },
+ { name: 'a blank', label: ' ' },
+])(
+ 'warns when an actionable accessory has $name accessible name',
+ async ({ label }) => {
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ await render(
+ (
+ {}}
+ />
+ )}
+ />
+ );
+ expect(warn).toHaveBeenCalledWith(accessoryNameWarning);
+ }
+);
+
+it.each<{
+ accessory: string;
+ endAccessory: NonNullable;
+}>([
+ {
+ accessory: 'a decorative accessory',
+ endAccessory: (props) => ,
+ },
+ {
+ accessory: 'a named actionable accessory',
+ endAccessory: (props) => (
+ {}}
+ />
+ ),
+ },
+])('does not warn for $accessory', async ({ endAccessory }) => {
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ await render();
+ expect(warn).not.toHaveBeenCalled();
+});
+
+it('does not warn for an unnamed actionable accessory in production', async () => {
+ jest.replaceProperty(process.env, 'NODE_ENV', 'production');
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ await render(
+ (
+ {}} />
+ )}
+ />
+ );
+ expect(warn).not.toHaveBeenCalled();
+});
+
+it.each(['ios', 'android', 'web'] as const)(
+ 'renders decorative accessories outside the accessibility tree without buttons on %s',
+ async (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform);
+ await render(
+ (
+
+ )}
+ endAccessory={(props) => (
+
+ )}
+ />
+ );
+ expect(screen.queryAllByRole('button')).toHaveLength(0);
+ expect(screen.queryAllByRole('img')).toHaveLength(0);
+ for (const testID of ['search-icon', 'account-icon']) {
+ expect(screen.queryByTestId(testID)).toBeNull();
+ const icon = screen.getByTestId(testID, { includeHiddenElements: true });
+ expect(icon).toBeOnTheScreen();
+ // Not a keyboard focus stop either.
+ expect(icon).not.toHaveProp('focusable', true);
+ expect(icon).not.toHaveProp('tabIndex', 0);
+ }
+ }
+);
+
+it('preserves decorative loading and content styles without accessible controls', async () => {
+ await render(
+ (
+
+ )}
+ />
+ );
+ expect(screen.queryAllByRole('button')).toHaveLength(0);
+ expect(screen.queryByRole('progressbar')).toBeNull();
+ expect(
+ screen.getByRole('progressbar', { includeHiddenElements: true })
+ ).toBeOnTheScreen();
+ expect(
+ screen.getByTestId('search-decoration', { includeHiddenElements: true })
+ ).toHaveStyle({ padding: 2 });
+});
+
+it('keeps a named disabled accessory inoperable', async () => {
+ const onPress = jest.fn<() => void>();
+ await render(
+ (
+
+ )}
+ />
+ );
+ const button = screen.getByRole('button', { name: 'Clear search' });
+ expect(button).toBeDisabled();
+ await userEvent.press(button);
+ expect(onPress).not.toHaveBeenCalled();
+});
+
+it('blocks every accessory activation handler when the field is disabled', async () => {
+ const onPress = jest.fn<() => void>();
+ const onLongPress = jest.fn<() => void>();
+ const onPressIn = jest.fn();
+ const onPressOut = jest.fn();
+ await render(
+ (
+
+ )}
+ />
+ );
+ const button = screen.getByRole('button', { name: 'Clear search' });
+ await userEvent.longPress(button);
+ expect(onPress).not.toHaveBeenCalled();
+ expect(onLongPress).not.toHaveBeenCalled();
+ expect(onPressIn).not.toHaveBeenCalled();
+ expect(onPressOut).not.toHaveBeenCalled();
+});
+
+it.each(['aria-labelledby', 'accessibilityLabelledBy'] as const)(
+ 'preserves caller %s relationships',
+ async (attribute) => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+ <>
+ Work address
+
+ >
+ );
+ expect(screen.getByLabelText('Work address')).toHaveProp(
+ attribute,
+ 'external-label'
+ );
+ expect(renderInput.mock.lastCall?.[0]['aria-describedby']).toEqual(
+ expect.any(String)
+ );
+ }
+);
+
+it('forwards decorative accessory layout callbacks and native IDs', async () => {
+ const onLayout = jest.fn();
+ await render(
+ (
+
+ )}
+ />
+ );
+ const icon = screen.getByTestId('decoration', {
+ includeHiddenElements: true,
+ });
+ expect(icon).toHaveProp('nativeID', 'search-icon');
+ expect(icon).toHaveProp('onLayout', onLayout);
+});
diff --git a/src/components/__tests__/TextInputStates.test.tsx b/src/components/__tests__/TextInputStates.test.tsx
new file mode 100644
index 0000000000..15e47691f7
--- /dev/null
+++ b/src/components/__tests__/TextInputStates.test.tsx
@@ -0,0 +1,107 @@
+import { Platform } from 'react-native';
+
+import { afterEach, describe, expect, it, jest } from '@jest/globals';
+
+import { fireEvent, render, screen } from '../../test-utils';
+import { LightTheme as theme } from '../../theme/schemes';
+import TextInput from '../TextInput';
+import { getOutlineColor } from '../TextInput/utils';
+
+afterEach(() => {
+ jest.restoreAllMocks();
+});
+
+type State = {
+ isFocused?: boolean;
+ isHovered?: boolean;
+ hasError?: boolean;
+ isDisabled?: boolean;
+};
+
+describe.each([
+ { variant: 'filled', restingRole: 'onSurfaceVariant' },
+ { variant: 'outlined', restingRole: 'outline' },
+] as const)('$variant indicator', ({ variant, restingRole }) => {
+ it.each<{ state: string; props: State; role: keyof typeof theme.colors }>([
+ { state: 'at rest', props: {}, role: restingRole },
+ { state: 'when hovered', props: { isHovered: true }, role: 'onSurface' },
+ { state: 'when focused', props: { isFocused: true }, role: 'primary' },
+ {
+ state: 'when focused and hovered',
+ props: { isFocused: true, isHovered: true },
+ role: 'primary',
+ },
+ { state: 'when invalid', props: { hasError: true }, role: 'error' },
+ {
+ state: 'when invalid and hovered',
+ props: { hasError: true, isHovered: true },
+ role: 'onErrorContainer',
+ },
+ {
+ state: 'when invalid, focused and hovered',
+ props: { hasError: true, isFocused: true, isHovered: true },
+ role: 'error',
+ },
+ { state: 'when disabled', props: { isDisabled: true }, role: 'onSurface' },
+ {
+ state: 'when disabled, invalid and hovered',
+ props: { isDisabled: true, hasError: true, isHovered: true },
+ role: 'onSurface',
+ },
+ ])('uses $role $state', ({ props, role }) => {
+ expect(
+ getOutlineColor({
+ theme,
+ variant,
+ isFocused: false,
+ hasError: false,
+ isDisabled: false,
+ ...props,
+ })
+ ).toBe(theme.colors[role]);
+ });
+});
+
+it('keeps the hover color on web when a touch leaves a field the mouse is over', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render();
+ const input = screen.getByLabelText('Email');
+ const pointer = (pointerType: string) => ({ nativeEvent: { pointerType } });
+ const getBorderColor = () =>
+ /"borderColor":"([^"]+)"/.exec(JSON.stringify(screen.toJSON()))?.[1];
+
+ await fireEvent(input, 'pointerEnter', pointer('mouse'));
+ expect(getBorderColor()).toBe(theme.colors.onSurface);
+
+ await fireEvent(input, 'pointerLeave', pointer('touch'));
+ expect(getBorderColor()).toBe(theme.colors.onSurface);
+
+ await fireEvent(input, 'pointerLeave', pointer('mouse'));
+ expect(getBorderColor()).toBe(theme.colors.outline);
+});
+
+it('uses the disabled colors for a disabled invalid field and keeps it invalid on web', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ await render(
+ }
+ />
+ );
+
+ // Label, supporting text, accessory icon and the default error icon.
+ for (const text of [
+ 'Email',
+ 'Enter a valid email',
+ 'email',
+ 'alert-circle',
+ ]) {
+ expect(screen.getByText(text, { includeHiddenElements: true })).toHaveStyle(
+ { color: theme.colors.onSurface }
+ );
+ }
+ expect(screen.getByLabelText('Email')).toHaveProp('aria-invalid', true);
+});
diff --git a/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap b/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap
index cdbe2843fe..9d998cf004 100644
--- a/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap
+++ b/src/components/__tests__/__snapshots__/TextInput.test.tsx.snap
@@ -161,6 +161,8 @@ exports[`dims a disabled TextInput with TextInput.Icon accessories exactly once