import React, { useEffect, useRef } from 'react'; import { Animated, Easing } from 'react-native'; import { StyledFloatingLabelContainer, StyledLabel } from './StyledTextInput'; import type { State } from './StyledTextInput'; import type { TextInputVariant } from './types'; import { useTheme } from '../../theme'; import { LABEL_ANIMATION_DURATION } from './constants'; interface FloatingLabelProps { /** The text to display in the label */ label: string; /** Input variant that affects animation positioning */ variant: TextInputVariant; /** Current input state for styling */ state: State; /** Whether the input is focused */ isFocused: boolean; /** Whether field is required (affects optional text) */ required?: boolean; /** Accessibility ID for screen readers */ accessibilityLabelledBy?: string; /** Whether the input value is empty */ isEmptyValue: boolean; /** Testing id of the input component. */ testID?: string; } /** * FloatingLabel Component * * Handles the animated floating label behavior for TextInput. * The label starts positioned over the input and animates to a smaller size above the input * when the field is focused or has content. * * Key Features: * - Smooth scale and translate animations using React Native Animated API * - Responds to focus state and content presence * - Automatically appends "(Optional)" text for non-required fields * - Supports different variants (text/textarea) with appropriate positioning * - Maintains accessibility features with proper IDs and test IDs * - Self-contained animation management * * Animation Behavior: * - Scale: 1.5 → 1 (label shrinks when floating) * - TranslateY: Variable based on variant → 0 (moves up) * - Uses bezier easing for smooth transitions * * @param props - The component props (see FloatingLabelProps for details) */ const FloatingLabel: React.FC = ({ label, variant, state, isFocused, required, accessibilityLabelledBy, isEmptyValue, testID, }) => { const theme = useTheme(); const shouldFloat = isFocused || !isEmptyValue; const focusAnimation = useRef( new Animated.Value(shouldFloat ? 1 : 0) ).current; useEffect(() => { Animated.timing(focusAnimation, { toValue: shouldFloat ? 1 : 0, duration: LABEL_ANIMATION_DURATION, easing: Easing.bezier(0.4, 0, 0.2, 1), useNativeDriver: true, }).start(); }, [shouldFloat, focusAnimation]); const testIDSuffix = testID ? `-${testID}` : ''; return ( {label} {!required ? ( {' (Optional)'} ) : null} ); }; FloatingLabel.displayName = 'FloatingLabel'; export default React.memo(FloatingLabel);