diff --git a/src/components/TextInput/TextInput.tsx b/src/components/TextInput/TextInput.tsx index 6db3359500..2a4f9dbe4b 100644 --- a/src/components/TextInput/TextInput.tsx +++ b/src/components/TextInput/TextInput.tsx @@ -20,6 +20,7 @@ import type { import Animated from 'react-native-reanimated'; import type { AnimatedStyle } from 'react-native-reanimated'; +import type { TextInputMetrics } from './constants'; import { useTextInput } from './hooks'; import { styles } from './styles'; import TextInputErrorIcon from './TextInputErrorIcon'; @@ -88,6 +89,7 @@ export type TextInputVariant = 'filled' | 'outlined'; export type TextInputSharedApi = { input: React.RefObject | null>; theme: InternalTheme; + metrics: TextInputMetrics; isFocused: boolean; isHovered?: boolean; isRTL: boolean; @@ -117,6 +119,7 @@ export type FilledTextInputHookData = SharedTextInputStyleData & { hasError: boolean; hasSuffix: boolean; animatedLabelWrapperStyles: StyleProp>>; + labelStyles: StyleProp; containerStyles: StyleProp; fieldStyles: StyleProp; disabledBackgroundStyles: StyleProp | undefined; @@ -131,6 +134,7 @@ export type OutlinedTextInputHookData = SharedTextInputStyleData & { hasError: boolean; hasSuffix: boolean; animatedLabelWrapperStyles: StyleProp>>; + labelStyles: StyleProp; containerStyles: StyleProp; fieldStyles: StyleProp; disabledBackgroundStyles: undefined; @@ -165,6 +169,7 @@ export type TextInputHookReturn = SharedTextInputStyleData & { | StyleProp>> | undefined; animatedLabelWrapperStyles: StyleProp>>; + labelStyles: StyleProp; containerStyles: StyleProp; fieldStyles: StyleProp; disabledBackgroundStyles: StyleProp | undefined; @@ -360,6 +365,7 @@ function TextInput({ outlineStyles, animatedActiveOutlineStyles, animatedLabelWrapperStyles, + labelStyles, animatedLabelTextStyles, animatedAffixStyle, containerStyles, @@ -446,12 +452,15 @@ function TextInput({ {!!label && ( - - {label} - + + + {label} + + )} diff --git a/src/components/TextInput/constants.ts b/src/components/TextInput/constants.ts index a0b73af2e9..8074f159ab 100644 --- a/src/components/TextInput/constants.ts +++ b/src/components/TextInput/constants.ts @@ -1,13 +1,9 @@ -import { PixelRatio } from 'react-native'; - import { Easing } from 'react-native-reanimated'; import { tokens } from '../../theme/tokens'; import { motionDuration, motionEasing } from '../../theme/tokens/sys/motion'; import { defaultShapes } from '../../theme/tokens/sys/shape'; -export const fontScale = PixelRatio.getFontScale(); - /** * Common constants for the text input component. */ @@ -18,13 +14,6 @@ export const BASELINE_TEXT_INPUT_PADDING_VERTICAL = 8; export const TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL = 16; export const TEXT_INPUT_ACCESSORY_MARGIN_HORIZONTAL = 12; -export const TEXT_INPUT_HEIGHT = Math.ceil( - BASELINE_TEXT_INPUT_HEIGHT * fontScale -); -export const TEXT_INPUT_PADDING_VERTICAL = Math.ceil( - BASELINE_TEXT_INPUT_PADDING_VERTICAL * fontScale -); - export const TEXT_INPUT_BORDER_RADIUS = defaultShapes.corner.extraSmall; export const LABEL_START_OFFSET_WITHOUT_ACCESSORY = @@ -70,25 +59,8 @@ export const FILLED_LABEL_START_OFFSET_WITH_ACCESSORY = TEXT_INPUT_ACCESSORY_MARGIN_HORIZONTAL + TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL; -export const FILLED_ACTIVE_LABEL_TOP_POSITION = TEXT_INPUT_PADDING_VERTICAL; - -export const FILLED_INACTIVE_LABEL_TOP_POSITION = Math.ceil( - ((BASELINE_TEXT_INPUT_HEIGHT - - 2 * BASELINE_TEXT_INPUT_PADDING_VERTICAL - - INPUT_FONT_SIZE) / - 2 + - BASELINE_TEXT_INPUT_PADDING_VERTICAL) * - fontScale -); - -export const FILLED_MULTILINE_PADDING_TOP = - Math.ceil(ACTIVE_LABEL_FONT_SIZE * fontScale) + TEXT_INPUT_PADDING_VERTICAL; - export const FILLED_DISABLED_CONTAINER_OPACITY = 0.04; -export const FILLED_PADDING_BOTTOM = - TEXT_INPUT_PADDING_VERTICAL + FILLED_LINE_HEIGHT_DELTA; - /** * Constants for the outlined variant. */ @@ -97,15 +69,6 @@ const OUTLINED_LINE_HEIGHT_DELTA = 2; export const OUTLINED_DISABLED_OUTLINE_OPACITY = 0.12; -export const OUTLINED_MULTILINE_PADDING_TOP = Math.ceil( - ((BASELINE_TEXT_INPUT_HEIGHT - - 2 * BASELINE_TEXT_INPUT_PADDING_VERTICAL - - INPUT_FONT_SIZE) / - 2 - - OUTLINED_LINE_HEIGHT_DELTA) * - fontScale -); - export const OUTLINED_LABEL_PADDING_HORIZONTAL = 4; export const OUTLINED_LABEL_START_OFFSET_WITH_ACCESSORY = @@ -114,21 +77,6 @@ export const OUTLINED_LABEL_START_OFFSET_WITH_ACCESSORY = TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL - OUTLINED_LABEL_PADDING_HORIZONTAL; -export const OUTLINED_ACTIVE_LABEL_TOP_POSITION = Math.ceil( - (-BASELINE_TEXT_INPUT_PADDING_VERTICAL + OUTLINED_LINE_HEIGHT_DELTA) * - fontScale -); - -export const OUTLINED_INACTIVE_LABEL_TOP_POSITION = Math.ceil( - ((BASELINE_TEXT_INPUT_HEIGHT - - 2 * BASELINE_TEXT_INPUT_PADDING_VERTICAL - - INPUT_FONT_SIZE) / - 2 + - BASELINE_TEXT_INPUT_PADDING_VERTICAL - - OUTLINED_LINE_HEIGHT_DELTA) * - fontScale -); - /** Positive distance; apply sign in animation using `isRTL` from `useLocale`. */ export const OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY = ACCESSORY_SIZE + @@ -138,3 +86,64 @@ export const OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY = /** Positive distance; apply sign in animation using `isRTL` from `useLocale`. */ export const OUTLINED_LABEL_TRANSLATE_DISTANCE_WITHOUT_ACCESSORY = OUTLINED_LABEL_PADDING_HORIZONTAL; + +/** + * Label end offsets, measured from the field's end edge to the end of the + * input text, so a long label is cut off where the text is. + */ +export const LABEL_END_OFFSET_WITHOUT_ACCESSORY = + TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL; + +export const LABEL_END_OFFSET_WITH_ACCESSORY = + ACCESSORY_SIZE + + TEXT_INPUT_ACCESSORY_MARGIN_HORIZONTAL + + TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL; + +// Space between the input text and the resting label, scaled with the text. +const BASELINE_INACTIVE_LABEL_OFFSET = + (BASELINE_TEXT_INPUT_HEIGHT - + 2 * BASELINE_TEXT_INPUT_PADDING_VERTICAL - + INPUT_FONT_SIZE) / + 2 + + BASELINE_TEXT_INPUT_PADDING_VERTICAL; + +/** + * Sizes that grow with the user's text size. Read the current `fontScale` + * from `useWindowDimensions` so a text size change while the app runs resizes + * the field. + */ +export const getTextInputMetrics = (fontScale: number) => { + const paddingVertical = Math.ceil( + BASELINE_TEXT_INPUT_PADDING_VERTICAL * fontScale + ); + + return { + height: Math.ceil(BASELINE_TEXT_INPUT_HEIGHT * fontScale), + paddingVertical, + filled: { + activeLabelTop: paddingVertical, + inactiveLabelTop: Math.ceil(BASELINE_INACTIVE_LABEL_OFFSET * fontScale), + multilinePaddingTop: + Math.ceil(ACTIVE_LABEL_FONT_SIZE * fontScale) + paddingVertical, + paddingBottom: paddingVertical + FILLED_LINE_HEIGHT_DELTA, + }, + outlined: { + activeLabelTop: Math.ceil( + (-BASELINE_TEXT_INPUT_PADDING_VERTICAL + OUTLINED_LINE_HEIGHT_DELTA) * + fontScale + ), + inactiveLabelTop: Math.ceil( + (BASELINE_INACTIVE_LABEL_OFFSET - OUTLINED_LINE_HEIGHT_DELTA) * + fontScale + ), + multilinePaddingTop: Math.ceil( + (BASELINE_INACTIVE_LABEL_OFFSET - + BASELINE_TEXT_INPUT_PADDING_VERTICAL - + OUTLINED_LINE_HEIGHT_DELTA) * + fontScale + ), + }, + }; +}; + +export type TextInputMetrics = ReturnType; diff --git a/src/components/TextInput/hooks.ts b/src/components/TextInput/hooks.ts index 0f70ae6a88..ea1b7c4558 100644 --- a/src/components/TextInput/hooks.ts +++ b/src/components/TextInput/hooks.ts @@ -11,6 +11,7 @@ import { AccessibilityInfo, Platform, TextInput as NativeTextInput, + useWindowDimensions, } from 'react-native'; import type { BlurEvent, FocusEvent } from 'react-native'; @@ -26,9 +27,11 @@ import { scheduleOnRN } from 'react-native-worklets'; import { ACTIVE_LABEL_FONT_SIZE, ERROR_ANNOUNCEMENT_DELAY_MS, + getTextInputMetrics, INACTIVE_LABEL_FONT_SIZE, TIMING_CONFIG, } from './constants'; +import type { TextInputMetrics } from './constants'; import type { TextInputAnimationState, TextInputFlags, @@ -52,16 +55,20 @@ import type { InternalTheme } from '../../theme/types'; const useTextInputAnimation = ({ variant, + metrics, isRTL, isDisabled, hasAccessory, + hasEndAccessory, value, defaultValue, }: { variant: TextInputVariant; + metrics: TextInputMetrics; isRTL: boolean; isDisabled: boolean; hasAccessory: boolean; + hasEndAccessory: boolean; value: string | undefined; defaultValue: string | undefined; }): TextInputAnimationState & TextInputAnimationHandlers => { @@ -82,13 +89,20 @@ const useTextInputAnimation = ({ } ); - const { activeTop, inactiveTop, translateXEnd } = getTextInputAnimationLayout( - { - variant, - hasAccessory, - isRTL, - } - ); + const { + activeTop, + inactiveTop, + translateXEnd, + activeEnd, + inactiveEnd, + endKey, + } = getTextInputAnimationLayout({ + variant, + metrics, + hasAccessory, + hasEndAccessory, + isRTL, + }); const runFocusAnimation = (hasText: boolean) => { focusSV.value = withTiming(1, TIMING_CONFIG); @@ -110,13 +124,15 @@ const useTextInputAnimation = ({ const animatedLabelWrapperStyle = useAnimatedStyle(() => { const top = interpolate(floatSV.value, [0, 1], [inactiveTop, activeTop]); + const end = interpolate(floatSV.value, [0, 1], [inactiveEnd, activeEnd]); if (variant === 'filled') { - return { top }; + return { top, [endKey]: end }; } return { top, + [endKey]: end, transform: [ { translateX: interpolate(floatSV.value, [0, 1], [0, translateXEnd]) }, ], @@ -280,6 +296,7 @@ const useTextInputLayout = ({ props, input, theme, + metrics, flags, isFocused, isHovered, @@ -289,6 +306,7 @@ const useTextInputLayout = ({ props: TextInputProps; input: RefObject | null>; theme: InternalTheme; + metrics: TextInputMetrics; flags: TextInputFlags; isFocused: boolean; isHovered: boolean; @@ -313,6 +331,7 @@ const useTextInputLayout = ({ { input, theme, + metrics, isFocused, isHovered, isRTL, @@ -330,6 +349,7 @@ const useTextInputLayout = ({ { input, theme, + metrics, isFocused, isHovered, isRTL, @@ -364,6 +384,11 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => { const { direction } = useLocale(); + // Read the text size on every render, so a change while the app runs + // resizes the field. + const { fontScale } = useWindowDimensions(); + const metrics = getTextInputMetrics(fontScale); + const isControlled = props.value !== undefined; const isRTL = direction === 'rtl'; const hasAccessory = !!props.startAccessory; @@ -373,9 +398,12 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => { const animation = useTextInputAnimation({ variant, + metrics, isRTL, isDisabled: !!props.disabled, hasAccessory, + // The error icon takes the end accessory's place when there is none. + hasEndAccessory: !!props.endAccessory || !!props.error, value: props.value, defaultValue: props.defaultValue, }); @@ -450,6 +478,7 @@ export const useTextInput = (props: TextInputProps): TextInputHookReturn => { props, input, theme, + metrics, flags, isFocused, isHovered, diff --git a/src/components/TextInput/styles.ts b/src/components/TextInput/styles.ts index b45ab98e00..1eb2b5521f 100644 --- a/src/components/TextInput/styles.ts +++ b/src/components/TextInput/styles.ts @@ -8,9 +8,7 @@ import { SUPPORTING_TEXT_MARGIN_TOP, TEXT_INPUT_ACCESSORY_MARGIN_HORIZONTAL, TEXT_INPUT_BORDER_RADIUS, - TEXT_INPUT_HEIGHT, TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL, - TEXT_INPUT_PADDING_VERTICAL, } from './constants'; import { tokens } from '../../theme/tokens'; @@ -25,8 +23,15 @@ export const styles = StyleSheet.create({ }, field: { flexDirection: 'row', - minHeight: TEXT_INPUT_HEIGHT, - paddingVertical: TEXT_INPUT_PADDING_VERTICAL, + }, + // Spans the space the label may take, so a long label ends in an ellipsis. + labelWrapper: { + position: 'absolute', + alignItems: 'flex-start', + pointerEvents: 'none', + }, + label: { + maxWidth: '100%', }, addendum: { flexDirection: 'row', @@ -102,10 +107,6 @@ export const filledStyles = StyleSheet.create({ alignItems: 'flex-end', paddingHorizontal: TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL, }, - labelWrapper: { - position: 'absolute', - pointerEvents: 'none', - }, disabledBackground: { position: 'absolute', top: 0, @@ -133,9 +134,7 @@ export const outlinedStyles = StyleSheet.create({ alignItems: 'center', paddingHorizontal: TEXT_INPUT_INPUT_WRAPPER_PADDING_HORIZONTAL, }, - labelWrapper: { - position: 'absolute', + label: { paddingHorizontal: OUTLINED_LABEL_PADDING_HORIZONTAL, - pointerEvents: 'none', }, }); diff --git a/src/components/TextInput/utils.ts b/src/components/TextInput/utils.ts index 6d3c2b02f6..a0c08797dd 100644 --- a/src/components/TextInput/utils.ts +++ b/src/components/TextInput/utils.ts @@ -5,25 +5,22 @@ import type { AnimatedStyle } from 'react-native-reanimated'; import { ACTIVE_INDICATOR_SIZE, - FILLED_ACTIVE_LABEL_TOP_POSITION, - FILLED_INACTIVE_LABEL_TOP_POSITION, FILLED_LABEL_START_OFFSET_WITH_ACCESSORY, - FILLED_MULTILINE_PADDING_TOP, INACTIVE_INDICATOR_SIZE, INPUT_FONT_SIZE, + LABEL_END_OFFSET_WITHOUT_ACCESSORY, + LABEL_END_OFFSET_WITH_ACCESSORY, LABEL_START_OFFSET_WITHOUT_ACCESSORY, - OUTLINED_ACTIVE_LABEL_TOP_POSITION, OUTLINED_DISABLED_OUTLINE_OPACITY, - OUTLINED_INACTIVE_LABEL_TOP_POSITION, + OUTLINED_LABEL_PADDING_HORIZONTAL, OUTLINED_LABEL_START_OFFSET_WITH_ACCESSORY, OUTLINED_LABEL_TRANSLATE_DISTANCE_WITHOUT_ACCESSORY, OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY, - OUTLINED_MULTILINE_PADDING_TOP, PREFIX_END_PADDING, SUFFIX_START_PADDING, TEXT_INPUT_BORDER_RADIUS, - FILLED_PADDING_BOTTOM, } from './constants'; +import type { TextInputMetrics } from './constants'; import { filledStyles, outlinedStyles, styles } from './styles'; import type { FilledTextInputHookData, @@ -39,30 +36,54 @@ import type { InternalTheme } from '../../theme/types'; export const getTextInputAnimationLayout = ({ variant, + metrics, hasAccessory, + hasEndAccessory, isRTL, }: { variant: TextInputVariant; + metrics: TextInputMetrics; hasAccessory: boolean; + hasEndAccessory: boolean; isRTL: boolean; }) => { - const activeTop = + const { activeLabelTop: activeTop, inactiveLabelTop: inactiveTop } = + variant === 'filled' ? metrics.filled : metrics.outlined; + + // The outlined label's padding sits outside its text, like at the start. + const textEnd = hasEndAccessory + ? LABEL_END_OFFSET_WITH_ACCESSORY + : LABEL_END_OFFSET_WITHOUT_ACCESSORY; + const inactiveEnd = variant === 'filled' - ? FILLED_ACTIVE_LABEL_TOP_POSITION - : OUTLINED_ACTIVE_LABEL_TOP_POSITION; + ? textEnd + : textEnd - OUTLINED_LABEL_PADDING_HORIZONTAL; - const inactiveTop = + const distance = variant === 'filled' - ? FILLED_INACTIVE_LABEL_TOP_POSITION - : OUTLINED_INACTIVE_LABEL_TOP_POSITION; - - const distance = hasAccessory - ? OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY - : OUTLINED_LABEL_TRANSLATE_DISTANCE_WITHOUT_ACCESSORY; + ? 0 + : hasAccessory + ? OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY + : OUTLINED_LABEL_TRANSLATE_DISTANCE_WITHOUT_ACCESSORY; const translateXEnd = (isRTL ? 1 : -1) * distance; - return { activeTop, inactiveTop, translateXEnd }; + // The floated outlined label moves toward the start, so its box grows by the + // same distance to keep its end where the resting label's end is. + const activeEnd = inactiveEnd - distance; + + // On web the label is placed with `right` in RTL, so its end is `left`. + const endKey: 'end' | 'left' = + Platform.OS === 'web' && isRTL ? 'left' : 'end'; + + return { + activeTop, + inactiveTop, + translateXEnd, + activeEnd, + inactiveEnd, + endKey, + }; }; export const getAccentColors = ({ @@ -308,6 +329,7 @@ export const getFilledTextInputData = ( const { input, theme, + metrics, hasSuffix, isDisabled, hasAccessory, @@ -359,19 +381,23 @@ export const getFilledTextInputData = ( const animatedLabelWrapperStyles: StyleProp< AnimatedStyle> > = [ - filledStyles.labelWrapper, + styles.labelWrapper, Platform.OS === 'web' && shared.isRTL - ? { right: filledLabelOffset } + ? { right: filledLabelOffset, alignItems: 'flex-end' } : { start: filledLabelOffset }, animatedLabelWrapperStyle, ]; + const labelStyles: StyleProp = styles.label; + const containerStyles = filledStyles.container; const fieldStyles: StyleProp = [ styles.field, { - paddingBottom: FILLED_PADDING_BOTTOM, + minHeight: metrics.height, + paddingTop: metrics.paddingVertical, + paddingBottom: metrics.filled.paddingBottom, backgroundColor: fieldBackgroundColor, borderTopStartRadius: TEXT_INPUT_BORDER_RADIUS, borderTopEndRadius: TEXT_INPUT_BORDER_RADIUS, @@ -423,7 +449,7 @@ export const getFilledTextInputData = ( }, textInputProps.multiline && { height: 'auto', - paddingTop: FILLED_MULTILINE_PADDING_TOP, + paddingTop: metrics.filled.multilinePaddingTop, }, //@ts-expect-error - RN’s defs are narrower than CSS and RNW does not ship TS extensions that fix that Platform.OS === 'web' && { @@ -439,6 +465,7 @@ export const getFilledTextInputData = ( hasError, hasSuffix, animatedLabelWrapperStyles, + labelStyles, containerStyles, fieldStyles, disabledBackgroundStyles, @@ -458,6 +485,7 @@ export const getOutlinedTextInputData = ( const { input, theme, + metrics, isFocused, isDisabled, hasAccessory, @@ -498,6 +526,8 @@ export const getOutlinedTextInputData = ( const fieldStyles: StyleProp = [ styles.field, { + minHeight: metrics.height, + paddingVertical: metrics.paddingVertical, borderRadius: TEXT_INPUT_BORDER_RADIUS, }, textInputProps.multiline && { alignItems: 'flex-start' }, @@ -522,16 +552,21 @@ export const getOutlinedTextInputData = ( const animatedLabelWrapperStyles: StyleProp< AnimatedStyle> > = [ - outlinedStyles.labelWrapper, - { - ...(Platform.OS === 'web' && shared.isRTL - ? { right: outlinedLabelOffset } - : { start: outlinedLabelOffset }), - backgroundColor: labelBackgroundColor, - }, + styles.labelWrapper, + Platform.OS === 'web' && shared.isRTL + ? { right: outlinedLabelOffset, alignItems: 'flex-end' } + : { start: outlinedLabelOffset }, animatedLabelWrapperStyle, ]; + // The background sits on the label itself rather than on its full-width + // wrapper, so it only cuts the outline as wide as the label. + const labelStyles: StyleProp = [ + styles.label, + outlinedStyles.label, + { backgroundColor: labelBackgroundColor }, + ]; + const inputStyles: StyleProp = [ styles.input, { @@ -544,7 +579,7 @@ export const getOutlinedTextInputData = ( textInputProps.multiline && { height: 'auto', textAlignVertical: 'top', - paddingTop: OUTLINED_MULTILINE_PADDING_TOP, + paddingTop: metrics.outlined.multilinePaddingTop, }, //@ts-expect-error - RN’s defs are narrower than CSS and RNW does not ship TS extensions that fix that Platform.OS === 'web' && { @@ -560,6 +595,7 @@ export const getOutlinedTextInputData = ( hasError, hasSuffix, animatedLabelWrapperStyles, + labelStyles, containerStyles, fieldStyles, disabledBackgroundStyles: undefined, diff --git a/src/components/__tests__/TextInput.test.tsx b/src/components/__tests__/TextInput.test.tsx index fa1f39b695..5c827018ef 100644 --- a/src/components/__tests__/TextInput.test.tsx +++ b/src/components/__tests__/TextInput.test.tsx @@ -4,6 +4,7 @@ import { Platform, StyleSheet, TextInput as NativeTextInput, + useWindowDimensions, View, } from 'react-native'; import type { GestureResponderEvent } from 'react-native'; @@ -27,8 +28,12 @@ import { tokens } from '../../theme/tokens'; import TextInput from '../TextInput'; import { FILLED_LABEL_START_OFFSET_WITH_ACCESSORY, + LABEL_END_OFFSET_WITHOUT_ACCESSORY, + LABEL_END_OFFSET_WITH_ACCESSORY, LABEL_START_OFFSET_WITHOUT_ACCESSORY, + OUTLINED_LABEL_PADDING_HORIZONTAL, OUTLINED_LABEL_START_OFFSET_WITH_ACCESSORY, + OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY, } from '../TextInput/constants'; import type { TextInputRenderProps, @@ -82,6 +87,22 @@ afterEach(() => { I18nManager.isRTL = defaultI18nIsRTL; }); +/** The positioned box around the label, which bounds how wide the label gets. */ +const getLabelWrapper = (label: string) => { + const wrapper = screen.getByText(label, includeHiddenElements).parent?.parent; + + if (!wrapper) { + throw new Error(`Expected a wrapper around the "${label}" label`); + } + + return wrapper; +}; + +const mockFontScale = (fontScale: number) => + jest + .mocked(useWindowDimensions) + .mockReturnValue({ fontScale, width: 750, height: 1334, scale: 2 }); + function firstIndexOfTestIdInTree(tree: unknown, testID: string): number { const serialized = JSON.stringify(tree); const match = new RegExp(`"testID":\\s*"${testID}"`).exec(serialized); @@ -1384,7 +1405,7 @@ it('keeps the label at the field edge in RTL when only an EndAccessory is set', /> ); - expect(screen.getByText('Email', includeHiddenElements).parent).toHaveStyle({ + expect(getLabelWrapper('Email')).toHaveStyle({ start: LABEL_START_OFFSET_WITHOUT_ACCESSORY, }); }); @@ -1429,10 +1450,7 @@ describe('on web in RTL', () => { /> ); - const labelWrapper = screen.getByText( - 'Email', - includeHiddenElements - ).parent; + const labelWrapper = getLabelWrapper('Email'); expect(labelWrapper).toHaveStyle({ right: offset }); expect(labelWrapper).not.toHaveStyle({ start: offset }); } @@ -1452,12 +1470,174 @@ describe('on web in RTL', () => { /> ); - expect(screen.getByText('Email', includeHiddenElements).parent).toHaveStyle( - { right: LABEL_START_OFFSET_WITHOUT_ACCESSORY } + expect(getLabelWrapper('Email')).toHaveStyle({ + right: LABEL_START_OFFSET_WITHOUT_ACCESSORY, + }); + }); + + it('cuts a long label off before the EndAccessory on the left', async () => { + function EndAccessory() { + return ; + } + + await render( + {}} + endAccessory={EndAccessory} + /> + ); + + expect(getAnimatedStyle(getLabelWrapper('Email'))).toMatchObject({ + left: LABEL_END_OFFSET_WITH_ACCESSORY, + }); + }); +}); + +describe('with a long label', () => { + it('shows the label on one line, so it ends in an ellipsis', async () => { + await render( + {}} + /> + ); + + expect( + screen.getByText( + 'Confirm the new password you chose for your account', + includeHiddenElements + ) + ).toHaveProp('numberOfLines', 1); + }); + + it.each([ + { + variant: 'filled' as const, + endAccessory: false, + error: false, + end: LABEL_END_OFFSET_WITHOUT_ACCESSORY, + }, + { + variant: 'filled' as const, + endAccessory: true, + error: false, + end: LABEL_END_OFFSET_WITH_ACCESSORY, + }, + { + variant: 'filled' as const, + endAccessory: false, + error: true, + end: LABEL_END_OFFSET_WITH_ACCESSORY, + }, + { + variant: 'outlined' as const, + endAccessory: true, + error: false, + end: LABEL_END_OFFSET_WITH_ACCESSORY - OUTLINED_LABEL_PADDING_HORIZONTAL, + }, + ])( + 'ends the $variant label where the input text ends (end accessory: $endAccessory, error: $error)', + async ({ variant, endAccessory, error, end }) => { + function EndAccessory() { + return ; + } + + await render( + {}} + endAccessory={endAccessory ? EndAccessory : undefined} + /> + ); + + expect(getAnimatedStyle(getLabelWrapper('Email'))).toMatchObject({ + end, + }); + } + ); + + it('keeps the end of a floated outlined label in place as it moves to the start', async () => { + function StartAccessory() { + return ; + } + + await render( + {}} + startAccessory={StartAccessory} + /> ); + + const restingEnd = + LABEL_END_OFFSET_WITHOUT_ACCESSORY - OUTLINED_LABEL_PADDING_HORIZONTAL; + expect(getAnimatedStyle(getLabelWrapper('Email'))).toMatchObject({ + end: restingEnd, + }); + + await fireEvent(screen.getByLabelText('Email'), 'focus'); + await act(() => jest.advanceTimersByTimeAsync(1000)); + + // The box grows toward the end by as much as it moves toward the start. + expect(getAnimatedStyle(getLabelWrapper('Email'))).toMatchObject({ + end: restingEnd - OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY, + transform: [ + { translateX: -OUTLINED_LABEL_TRANSLATE_DISTANCE_WITH_ACCESSORY }, + ], + }); }); }); +describe('when the text size changes while the field is shown', () => { + afterEach(() => { + mockFontScale(1); + }); + + it.each(['filled', 'outlined'] as const)( + 'resizes the %s field like a field first shown at that size', + async (variant) => { + mockFontScale(1); + + // A new element each time, so React renders it again. + const field = () => ( + {}} + /> + ); + + await render(field()); + const getField = () => + getOuterTextInputPressable(screen.root).children[0]; + expect(getField()).toHaveStyle({ minHeight: 56 }); + + mockFontScale(2); + await screen.rerender(field()); + await act(() => jest.advanceTimersByTimeAsync(100)); + + expect(getField()).toHaveStyle({ minHeight: 112 }); + const resizedLabelTop = getAnimatedStyle(getLabelWrapper('Email')).top; + + await screen.unmount(); + await render(field()); + + expect(getAnimatedStyle(getLabelWrapper('Email')).top).toBe( + resizedLabelTop + ); + } + ); +}); + it('shows prefix and suffix when the field is floating and hides them after value is cleared while blurred', async () => { const { rerender } = await render( - - Search - + + Search + + - - Search - + + Search + + - - Search - + + Search + + - - Email - + + Email + + - - Search - + + Search + + - - Search - + + Search + + - - Password - + + Password + +