Control · Inputs
Floating input
Screen
Colour scheme
Mode
Corners
Colours
Every state
- When
- Behaviour
Save these 2 files in components/mobilens/. They need only react-native (checked with Expo SDK 58).
// A single-line input whose label lifts when focused and stays visible while the field has a value.
import { useEffect, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { AccessibilityInfo, Animated, Easing, Platform, StyleSheet, Text, TextInput, View, useWindowDimensions, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type FloatingInputVariant = 'outlined' | 'underlined' | 'filled';
export type FloatingInputProps = {
/** Visible label and accessible name of the field. */
label: string;
/** Controlled text, including values inserted by paste or autofill. */
value: string;
/** Receives the text after an edit. */
onChangeText: (value: string) => void;
/** Use an outlined notch, a bottom line, or a filled surface. */
variant?: FloatingInputVariant;
/** Example shown inside the field once the label is raised. */
placeholder?: string;
/** Help message displayed below the field. */
helper?: string;
/** Validation message that replaces the helper. */
error?: string;
/** Prevents editing and dims the field. */
disabled?: boolean;
/** Maximum number of characters; also shows the current count. */
maxLength?: number;
/** Focus the input when mounted. */
autoFocus?: boolean;
/** Keyboard, autofill, return-key and input event settings. */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'placeholder' | 'maxLength' | 'autoFocus' | 'style' | 'multiline'>;
/** Native input handle for focus and blur. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function FloatingInput({
label, value, onChangeText, variant = 'outlined', placeholder, helper, error, disabled = false, maxLength, autoFocus, inputProps, ref, copyTestIDs,
}: FloatingInputProps & Pick<FloatingFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
return (
<FloatingFrame label={label} copyTestIDs={copyTestIDs} value={value} variant={variant} focused={!disabled && focused}
disabled={disabled} helper={helper} error={error} maxLength={maxLength}>
<TextInput
{...inputProps}
ref={ref}
value={value}
onChangeText={onChangeText}
onFocus={(event) => { setFocused(true); inputProps?.onFocus?.(event); }}
onBlur={(event) => { setFocused(false); inputProps?.onBlur?.(event); }}
editable={!disabled}
autoFocus={autoFocus}
maxLength={maxLength}
placeholder={focused && !disabled ? placeholder : undefined}
placeholderTextColor={colors.onSurfaceVariant}
underlineColorAndroid="transparent"
accessibilityLabel={label}
accessibilityHint={error || helper || inputProps?.accessibilityHint}
accessibilityState={{ ...inputProps?.accessibilityState, disabled }}
aria-invalid={!!error}
style={[styles.input, noWebRing, disabled && styles.muted]}
/>
</FloatingFrame>
);
}
type FloatingFrameProps = Pick<FloatingInputProps, 'label' | 'value' | 'variant' | 'disabled' | 'helper' | 'error' | 'maxLength'> & {
copyTestIDs?: { label?: string; helper?: string };
focused?: boolean;
children?: ReactNode;
};
export function FloatingFrame({ label, copyTestIDs, value, variant = 'outlined', focused = false, disabled, helper, error, maxLength, children }: FloatingFrameProps) {
const active = focused && !disabled;
const lifted = active || value.length > 0;
const outlined = variant === 'outlined';
const progress = useLabelPosition(lifted, !!children);
const { fontScale } = useWindowDimensions();
const height = Math.max(56, 42 * fontScale + 14);
const inset = variant === 'underlined' ? 2 : 14;
const restingColor = disabled ? colors.outlineVariant : colors.outline;
const accent = disabled ? restingColor : error ? colors.error : active ? colors.primary : restingColor;
const surface = disabled || variant === 'filled' ? colors.surfaceVariant : colors.surface;
const labelColor = !disabled && (error || active) ? accent : colors.onSurfaceVariant;
const note = error || helper;
return (
<View style={styles.root}>
<View style={[
styles.frame, { height, paddingHorizontal: inset, borderColor: accent },
outlined ? { backgroundColor: surface, borderWidth: 1, borderRadius: radius.md }
: { backgroundColor: variant === 'filled' || disabled ? surface : 'transparent', borderBottomWidth: active ? 2 : 1,
borderTopLeftRadius: variant === 'filled' ? radius.md : 0, borderTopRightRadius: variant === 'filled' ? radius.md : 0 },
]}>
<View style={[styles.inputArea, { paddingTop: outlined ? 0 : 14 * fontScale }]}>
{children ?? <Text numberOfLines={1} style={[styles.value, disabled && styles.muted]}>{value}</Text>}
</View>
<View pointerEvents="none" aria-hidden={true} importantForAccessibility="no-hide-descendants" style={StyleSheet.absoluteFill}>
<Animated.Text testID={copyTestIDs?.label} numberOfLines={1} ellipsizeMode="tail" style={[styles.label, {
start: inset - (outlined ? 4 : 0),
top: progress.interpolate({ inputRange: [0, 1], outputRange: [(height - 22 * fontScale) / 2, outlined ? -9 * fontScale : 3] }),
fontSize: progress.interpolate({ inputRange: [0, 1], outputRange: [16, 12] }),
lineHeight: progress.interpolate({ inputRange: [0, 1], outputRange: [22, 17] }),
paddingHorizontal: outlined ? 4 : 0,
backgroundColor: outlined ? surface : 'transparent',
color: labelColor,
}]}>{label}</Animated.Text>
</View>
</View>
{(note || maxLength !== undefined) && (
<View style={styles.foot}>
<Text testID={!error && helper ? copyTestIDs?.helper : undefined} accessibilityLiveRegion={error ? 'polite' : 'none'} style={[styles.help, error && styles.error]}>{note}</Text>
{maxLength !== undefined && <Text style={styles.count}>{value.length}/{maxLength}</Text>}
</View>
)}
</View>
);
}
function useLabelPosition(raised: boolean, interactive: boolean) {
const target = raised ? 1 : 0;
const [position] = useState(() => new Animated.Value(target));
const lastTarget = useRef(target);
const [reduceMotion, setReduceMotion] = useState(true);
useEffect(() => {
if (!interactive) return;
let mounted = true;
AccessibilityInfo.isReduceMotionEnabled().then((enabled) => { if (mounted) setReduceMotion(enabled); });
const listener = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduceMotion);
return () => { mounted = false; listener.remove(); };
}, [interactive]);
useEffect(() => {
if (!interactive || reduceMotion || lastTarget.current === target) {
position.setValue(target);
} else {
const animation = Animated.timing(position, { toValue: target, duration: 150, easing: Easing.out(Easing.quad), useNativeDriver: false });
animation.start();
lastTarget.current = target;
return () => animation.stop();
}
lastTarget.current = target;
}, [interactive, position, reduceMotion, target]);
return position;
}
const noWebRing = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : undefined;
const styles = StyleSheet.create({
root: { paddingTop: 9, gap: 5 },
frame: { justifyContent: 'center' },
inputArea: { flex: 1, justifyContent: 'center' },
input: { flex: 1, paddingHorizontal: 0, paddingVertical: 0, color: colors.onSurface, fontSize: 16 },
value: { color: colors.onSurface, fontSize: 16 },
label: { position: 'absolute', maxWidth: '90%', includeFontPadding: false },
muted: { color: colors.onSurfaceVariant },
foot: { flexDirection: 'row', justifyContent: 'space-between', gap: 10, paddingHorizontal: 4 },
help: { flex: 1, color: colors.onSurfaceVariant, fontSize: 13, lineHeight: 18 },
error: { color: colors.error },
count: { color: colors.onSurfaceVariant, fontSize: 13, fontVariant: ['tabular-nums'] },
});
// A single-line input whose label lifts when focused and stays visible while the field has a value.
import { useEffect, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { AccessibilityInfo, Animated, Easing, Platform, StyleSheet, Text, TextInput, View, useWindowDimensions, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type FloatingInputVariant = 'outlined' | 'underlined' | 'filled';
export type FloatingInputProps = {
/** Visible label and accessible name of the field. */
label: string;
/** Controlled text, including values inserted by paste or autofill. */
value: string;
/** Receives the text after an edit. */
onChangeText: (value: string) => void;
/** Use an outlined notch, a bottom line, or a filled surface. */
variant?: FloatingInputVariant;
/** Example shown inside the field once the label is raised. */
placeholder?: string;
/** Help message displayed below the field. */
helper?: string;
/** Validation message that replaces the helper. */
error?: string;
/** Prevents editing and dims the field. */
disabled?: boolean;
/** Maximum number of characters; also shows the current count. */
maxLength?: number;
/** Focus the input when mounted. */
autoFocus?: boolean;
/** Keyboard, autofill, return-key and input event settings. */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'placeholder' | 'maxLength' | 'autoFocus' | 'style' | 'multiline'>;
/** Native input handle for focus and blur. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function FloatingInput({
label, value, onChangeText, variant = 'outlined', placeholder, helper, error, disabled = false, maxLength, autoFocus, inputProps, ref, copyTestIDs,
}: FloatingInputProps & Pick<FloatingFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
return (
<FloatingFrame label={label} copyTestIDs={copyTestIDs} value={value} variant={variant} focused={!disabled && focused}
disabled={disabled} helper={helper} error={error} maxLength={maxLength}>
<TextInput
{...inputProps}
ref={ref}
value={value}
onChangeText={onChangeText}
onFocus={(event) => { setFocused(true); inputProps?.onFocus?.(event); }}
onBlur={(event) => { setFocused(false); inputProps?.onBlur?.(event); }}
editable={!disabled}
autoFocus={autoFocus}
maxLength={maxLength}
placeholder={focused && !disabled ? placeholder : undefined}
placeholderTextColor={colors.onSurfaceVariant}
underlineColorAndroid="transparent"
accessibilityLabel={label}
accessibilityHint={error || helper || inputProps?.accessibilityHint}
accessibilityState={{ ...inputProps?.accessibilityState, disabled }}
aria-invalid={!!error}
style={[styles.input, noWebRing, disabled && styles.muted]}
/>
</FloatingFrame>
);
}
type FloatingFrameProps = Pick<FloatingInputProps, 'label' | 'value' | 'variant' | 'disabled' | 'helper' | 'error' | 'maxLength'> & {
copyTestIDs?: { label?: string; helper?: string };
focused?: boolean;
children?: ReactNode;
};
export function FloatingFrame({ label, copyTestIDs, value, variant = 'outlined', focused = false, disabled, helper, error, maxLength, children }: FloatingFrameProps) {
const active = focused && !disabled;
const lifted = active || value.length > 0;
const outlined = variant === 'outlined';
const progress = useLabelPosition(lifted, !!children);
const { fontScale } = useWindowDimensions();
const height = Math.max(56, 42 * fontScale + 14);
const inset = variant === 'underlined' ? 2 : 14;
const restingColor = disabled ? colors.outlineVariant : colors.outline;
const accent = disabled ? restingColor : error ? colors.error : active ? colors.primary : restingColor;
const surface = disabled || variant === 'filled' ? colors.surfaceVariant : colors.surface;
const labelColor = !disabled && (error || active) ? accent : colors.onSurfaceVariant;
const note = error || helper;
return (
<View style={styles.root}>
<View style={[
styles.frame, { height, paddingHorizontal: inset, borderColor: accent },
outlined ? { backgroundColor: surface, borderWidth: 1, borderRadius: radius.md }
: { backgroundColor: variant === 'filled' || disabled ? surface : 'transparent', borderBottomWidth: active ? 2 : 1,
borderTopLeftRadius: variant === 'filled' ? radius.md : 0, borderTopRightRadius: variant === 'filled' ? radius.md : 0 },
]}>
<View style={[styles.inputArea, { paddingTop: outlined ? 0 : 14 * fontScale }]}>
{children ?? <Text numberOfLines={1} style={[styles.value, disabled && styles.muted]}>{value}</Text>}
</View>
<View pointerEvents="none" aria-hidden={true} importantForAccessibility="no-hide-descendants" style={StyleSheet.absoluteFill}>
<Animated.Text testID={copyTestIDs?.label} numberOfLines={1} ellipsizeMode="tail" style={[styles.label, {
start: inset - (outlined ? 4 : 0),
top: progress.interpolate({ inputRange: [0, 1], outputRange: [(height - 22 * fontScale) / 2, outlined ? -9 * fontScale : 3] }),
fontSize: progress.interpolate({ inputRange: [0, 1], outputRange: [16, 12] }),
lineHeight: progress.interpolate({ inputRange: [0, 1], outputRange: [22, 17] }),
paddingHorizontal: outlined ? 4 : 0,
backgroundColor: outlined ? surface : 'transparent',
color: labelColor,
}]}>{label}</Animated.Text>
</View>
</View>
{(note || maxLength !== undefined) && (
<View style={styles.foot}>
<Text testID={!error && helper ? copyTestIDs?.helper : undefined} accessibilityLiveRegion={error ? 'polite' : 'none'} style={[styles.help, error && styles.error]}>{note}</Text>
{maxLength !== undefined && <Text style={styles.count}>{value.length}/{maxLength}</Text>}
</View>
)}
</View>
);
}
function useLabelPosition(raised: boolean, interactive: boolean) {
const target = raised ? 1 : 0;
const [position] = useState(() => new Animated.Value(target));
const lastTarget = useRef(target);
const [reduceMotion, setReduceMotion] = useState(true);
useEffect(() => {
if (!interactive) return;
let mounted = true;
AccessibilityInfo.isReduceMotionEnabled().then((enabled) => { if (mounted) setReduceMotion(enabled); });
const listener = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduceMotion);
return () => { mounted = false; listener.remove(); };
}, [interactive]);
useEffect(() => {
if (!interactive || reduceMotion || lastTarget.current === target) {
position.setValue(target);
} else {
const animation = Animated.timing(position, { toValue: target, duration: 150, easing: Easing.out(Easing.quad), useNativeDriver: false });
animation.start();
lastTarget.current = target;
return () => animation.stop();
}
lastTarget.current = target;
}, [interactive, position, reduceMotion, target]);
return position;
}
const noWebRing = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : undefined;
const styles = StyleSheet.create({
root: { paddingTop: 9, gap: 5 },
frame: { justifyContent: 'center' },
inputArea: { flex: 1, justifyContent: 'center' },
input: { flex: 1, paddingHorizontal: 0, paddingVertical: 0, color: colors.onSurface, fontSize: 16 },
value: { color: colors.onSurface, fontSize: 16 },
label: { position: 'absolute', maxWidth: '90%', includeFontPadding: false },
muted: { color: colors.onSurfaceVariant },
foot: { flexDirection: 'row', justifyContent: 'space-between', gap: 10, paddingHorizontal: 4 },
help: { flex: 1, color: colors.onSurfaceVariant, fontSize: 13, lineHeight: 18 },
error: { color: colors.error },
count: { color: colors.onSurfaceVariant, fontSize: 13, fontVariant: ['tabular-nums'] },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
Usage
import { useState } from 'react';
import { FloatingInput } from '@/components/mobilens/FloatingInput';
export function ContactEmail({ onSubmit }: { onSubmit: (email: string) => void }) {
const [email, setEmail] = useState('');
const [error, setError] = useState<string>();
function validate() {
const valid = /^\S+@\S+\.\S+$/.test(email.trim());
setError(valid ? undefined : 'Enter a valid email address.');
return valid;
}
return (
<FloatingInput
variant="outlined"
label="Email"
value={email}
onChangeText={(next) => { setEmail(next); setError(undefined); }}
error={error}
placeholder="name@example.com"
inputProps={{
keyboardType: 'email-address', autoComplete: 'email', autoCapitalize: 'none', autoCorrect: false,
returnKeyType: 'done', onBlur: validate, onSubmitEditing: () => { if (validate()) onSubmit(email.trim()); },
}}
/>
);
}
import { useState } from 'react';
import { FloatingInput } from '@/components/mobilens/FloatingInput';
export function ContactEmail({ onSubmit }: { onSubmit: (email: string) => void }) {
const [email, setEmail] = useState('');
const [error, setError] = useState<string>();
function validate() {
const valid = /^\S+@\S+\.\S+$/.test(email.trim());
setError(valid ? undefined : 'Enter a valid email address.');
return valid;
}
return (
<FloatingInput
variant="outlined"
label="Email"
value={email}
onChangeText={(next) => { setEmail(next); setError(undefined); }}
error={error}
placeholder="name@example.com"
inputProps={{
keyboardType: 'email-address', autoComplete: 'email', autoCapitalize: 'none', autoCorrect: false,
returnKeyType: 'done', onBlur: validate, onSubmitEditing: () => { if (validate()) onSubmit(email.trim()); },
}}
/>
);
}
API
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | – | Visible label and accessible name of the field. |
| value | string | – | Controlled text, including values inserted by paste or autofill. |
| onChangeText | (value: string) => void | – | Receives the text after an edit. |
| variant? | FloatingInputVariant | 'outlined' | Use an outlined notch, a bottom line, or a filled surface. |
| placeholder? | string | – | Example shown inside the field once the label is raised. |
| helper? | string | – | Help message displayed below the field. |
| error? | string | – | Validation message that replaces the helper. |
| disabled? | boolean | false | Prevents editing and dims the field. |
| maxLength? | number | – | Maximum number of characters; also shows the current count. |
| autoFocus? | boolean | – | Focus the input when mounted. |
| inputProps? | Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'placeholder' | 'maxLength' | 'autoFocus' | 'style' | 'multiline'> | – | Keyboard, autofill, return-key and input event settings. |
| ref? | Ref<ComponentRef<typeof TextInput>> | – | Native input handle for focus and blur. |
Add the "Floating input" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them. FILES Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths. --- components/mobilens/theme.ts --- // Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app. export const colors = { background: '#fafafa', surface: '#ffffff', surfaceVariant: '#f4f4f5', onBackground: '#18181b', onSurface: '#18181b', onSurfaceVariant: '#6b6b74', outline: '#8a8a93', outlineVariant: '#e4e4e7', error: '#ba1a1a', success: '#296b2a', warning: '#b45309', shadow: '#000000', scrim: 'rgba(0,0,0,0.32)', primary: '#006c50', onPrimary: '#ffffff', primaryContainer: '#82f8cb', onPrimaryContainer: '#002116', secondary: '#3e6374', onSecondary: '#ffffff', secondaryContainer: '#d8dfe2', onSecondaryContainer: '#1c2d34', tertiary: '#1f6862', onTertiary: '#ffffff', tertiaryContainer: '#d3e0df', onTertiaryContainer: '#0e2f2c', onError: '#ffffff', onSuccess: '#ffffff', onWarning: '#ffffff', } as const; export const radius = { sm: 6, md: 12, lg: 20, } as const; --- end of theme.ts --- --- components/mobilens/FloatingInput.tsx --- // A single-line input whose label lifts when focused and stays visible while the field has a value. import { useEffect, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react'; import { AccessibilityInfo, Animated, Easing, Platform, StyleSheet, Text, TextInput, View, useWindowDimensions, type TextInputProps, type TextStyle } from 'react-native'; import { colors, radius } from './theme'; export type FloatingInputVariant = 'outlined' | 'underlined' | 'filled'; export type FloatingInputProps = { /** Visible label and accessible name of the field. */ label: string; /** Controlled text, including values inserted by paste or autofill. */ value: string; /** Receives the text after an edit. */ onChangeText: (value: string) => void; /** Use an outlined notch, a bottom line, or a filled surface. */ variant?: FloatingInputVariant; /** Example shown inside the field once the label is raised. */ placeholder?: string; /** Help message displayed below the field. */ helper?: string; /** Validation message that replaces the helper. */ error?: string; /** Prevents editing and dims the field. */ disabled?: boolean; /** Maximum number of characters; also shows the current count. */ maxLength?: number; /** Focus the input when mounted. */ autoFocus?: boolean; /** Keyboard, autofill, return-key and input event settings. */ inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'placeholder' | 'maxLength' | 'autoFocus' | 'style' | 'multiline'>; /** Native input handle for focus and blur. */ ref?: Ref<ComponentRef<typeof TextInput>>; }; export function FloatingInput({ label, value, onChangeText, variant = 'outlined', placeholder, helper, error, disabled = false, maxLength, autoFocus, inputProps, ref, copyTestIDs, }: FloatingInputProps & Pick<FloatingFrameProps, 'copyTestIDs'>) { const [focused, setFocused] = useState(false); return ( <FloatingFrame label={label} copyTestIDs={copyTestIDs} value={value} variant={variant} focused={!disabled && focused} disabled={disabled} helper={helper} error={error} maxLength={maxLength}> <TextInput {...inputProps} ref={ref} value={value} onChangeText={onChangeText} onFocus={(event) => { setFocused(true); inputProps?.onFocus?.(event); }} onBlur={(event) => { setFocused(false); inputProps?.onBlur?.(event); }} editable={!disabled} autoFocus={autoFocus} maxLength={maxLength} placeholder={focused && !disabled ? placeholder : undefined} placeholderTextColor={colors.onSurfaceVariant} underlineColorAndroid="transparent" accessibilityLabel={label} accessibilityHint={error || helper || inputProps?.accessibilityHint} accessibilityState={{ ...inputProps?.accessibilityState, disabled }} aria-invalid={!!error} style={[styles.input, noWebRing, disabled && styles.muted]} /> </FloatingFrame> ); } type FloatingFrameProps = Pick<FloatingInputProps, 'label' | 'value' | 'variant' | 'disabled' | 'helper' | 'error' | 'maxLength'> & { copyTestIDs?: { label?: string; helper?: string }; focused?: boolean; children?: ReactNode; }; export function FloatingFrame({ label, copyTestIDs, value, variant = 'outlined', focused = false, disabled, helper, error, maxLength, children }: FloatingFrameProps) { const active = focused && !disabled; const lifted = active || value.length > 0; const outlined = variant === 'outlined'; const progress = useLabelPosition(lifted, !!children); const { fontScale } = useWindowDimensions(); const height = Math.max(56, 42 * fontScale + 14); const inset = variant === 'underlined' ? 2 : 14; const restingColor = disabled ? colors.outlineVariant : colors.outline; const accent = disabled ? restingColor : error ? colors.error : active ? colors.primary : restingColor; const surface = disabled || variant === 'filled' ? colors.surfaceVariant : colors.surface; const labelColor = !disabled && (error || active) ? accent : colors.onSurfaceVariant; const note = error || helper; return ( <View style={styles.root}> <View style={[ styles.frame, { height, paddingHorizontal: inset, borderColor: accent }, outlined ? { backgroundColor: surface, borderWidth: 1, borderRadius: radius.md } : { backgroundColor: variant === 'filled' || disabled ? surface : 'transparent', borderBottomWidth: active ? 2 : 1, borderTopLeftRadius: variant === 'filled' ? radius.md : 0, borderTopRightRadius: variant === 'filled' ? radius.md : 0 }, ]}> <View style={[styles.inputArea, { paddingTop: outlined ? 0 : 14 * fontScale }]}> {children ?? <Text numberOfLines={1} style={[styles.value, disabled && styles.muted]}>{value}</Text>} </View> <View pointerEvents="none" aria-hidden={true} importantForAccessibility="no-hide-descendants" style={StyleSheet.absoluteFill}> <Animated.Text testID={copyTestIDs?.label} numberOfLines={1} ellipsizeMode="tail" style={[styles.label, { start: inset - (outlined ? 4 : 0), top: progress.interpolate({ inputRange: [0, 1], outputRange: [(height - 22 * fontScale) / 2, outlined ? -9 * fontScale : 3] }), fontSize: progress.interpolate({ inputRange: [0, 1], outputRange: [16, 12] }), lineHeight: progress.interpolate({ inputRange: [0, 1], outputRange: [22, 17] }), paddingHorizontal: outlined ? 4 : 0, backgroundColor: outlined ? surface : 'transparent', color: labelColor, }]}>{label}</Animated.Text> </View> </View> {(note || maxLength !== undefined) && ( <View style={styles.foot}> <Text testID={!error && helper ? copyTestIDs?.helper : undefined} accessibilityLiveRegion={error ? 'polite' : 'none'} style={[styles.help, error && styles.error]}>{note}</Text> {maxLength !== undefined && <Text style={styles.count}>{value.length}/{maxLength}</Text>} </View> )} </View> ); } function useLabelPosition(raised: boolean, interactive: boolean) { const target = raised ? 1 : 0; const [position] = useState(() => new Animated.Value(target)); const lastTarget = useRef(target); const [reduceMotion, setReduceMotion] = useState(true); useEffect(() => { if (!interactive) return; let mounted = true; AccessibilityInfo.isReduceMotionEnabled().then((enabled) => { if (mounted) setReduceMotion(enabled); }); const listener = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduceMotion); return () => { mounted = false; listener.remove(); }; }, [interactive]); useEffect(() => { if (!interactive || reduceMotion || lastTarget.current === target) { position.setValue(target); } else { const animation = Animated.timing(position, { toValue: target, duration: 150, easing: Easing.out(Easing.quad), useNativeDriver: false }); animation.start(); lastTarget.current = target; return () => animation.stop(); } lastTarget.current = target; }, [interactive, position, reduceMotion, target]); return position; } const noWebRing = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : undefined; const styles = StyleSheet.create({ root: { paddingTop: 9, gap: 5 }, frame: { justifyContent: 'center' }, inputArea: { flex: 1, justifyContent: 'center' }, input: { flex: 1, paddingHorizontal: 0, paddingVertical: 0, color: colors.onSurface, fontSize: 16 }, value: { color: colors.onSurface, fontSize: 16 }, label: { position: 'absolute', maxWidth: '90%', includeFontPadding: false }, muted: { color: colors.onSurfaceVariant }, foot: { flexDirection: 'row', justifyContent: 'space-between', gap: 10, paddingHorizontal: 4 }, help: { flex: 1, color: colors.onSurfaceVariant, fontSize: 13, lineHeight: 18 }, error: { color: colors.error }, count: { color: colors.onSurfaceVariant, fontSize: 13, fontVariant: ['tabular-nums'] }, }); --- end of FloatingInput.tsx --- HOW TO USE IT import { useState } from 'react'; import { FloatingInput } from '@/components/mobilens/FloatingInput'; export function ContactEmail({ onSubmit }: { onSubmit: (email: string) => void }) { const [email, setEmail] = useState(''); const [error, setError] = useState<string>(); function validate() { const valid = /^\S+@\S+\.\S+$/.test(email.trim()); setError(valid ? undefined : 'Enter a valid email address.'); return valid; } return ( <FloatingInput variant="outlined" label="Email" value={email} onChangeText={(next) => { setEmail(next); setError(undefined); }} error={error} placeholder="name@example.com" inputProps={{ keyboardType: 'email-address', autoComplete: 'email', autoCapitalize: 'none', autoCorrect: false, returnKeyType: 'done', onBlur: validate, onSubmitEditing: () => { if (validate()) onSubmit(email.trim()); }, }} /> ); } STATES: all 6 must work in the screen where you use it - Empty: when the field is empty and unfocused. The field name rests inside the input. - Focused: when the user taps an empty field. The label rises to make room for input. When the user leaves the field empty, it returns to its resting position. - With text: when text has been entered, pasted or supplied by the form. The label stays raised while the field has a value, including after focus leaves. - Error: when the user leaves the email field with an invalid address. Show the error beneath the field and keep the entered value available for correction. - Disabled: when the form disables a populated field. The field keeps its label and value and prevents editing. - At the limit: when the input reaches its character limit. Show the count and prevent the user from entering more characters. ACCESSIBILITY - The native input has the same accessible name while its label is resting and raised. - Use text to describe an error alongside the error colour. - Respect the system's reduced motion preference when moving the label. WHEN YOU FINISH List every state and rule above and say how you verified each one.