|
| 1 | +import { memo } from 'react'; |
| 2 | +import { Pressable, Text, StyleSheet } from 'react-native'; |
| 3 | +import { useTextInputOTP } from '../hooks/use-text-input-otp'; |
| 4 | +import type { |
| 5 | + TextInputOTPSlotInternalProps, |
| 6 | + TextInputOTPSlotProps, |
| 7 | +} from '../types'; |
| 8 | +import { useSlotBorderStyles } from '../hooks/use-slot-border-styles'; |
| 9 | +import { useThemeColor } from '../theme/use-theme-color'; |
| 10 | +import { theme } from '../theme/theme'; |
| 11 | +import { AnimatedCaret } from './animated-caret'; |
| 12 | +import { SLOT_HEIGHT, SLOT_WIDTH } from '../constants'; |
| 13 | + |
| 14 | +function TextInputOTPSlotComponent({ |
| 15 | + index, |
| 16 | + isFirst, |
| 17 | + isLast, |
| 18 | + focusedSlotStyles, |
| 19 | + focusedSlotTextStyles, |
| 20 | + slotStyles, |
| 21 | + slotTextStyles, |
| 22 | + ...rest |
| 23 | +}: TextInputOTPSlotProps & TextInputOTPSlotInternalProps) { |
| 24 | + const { code, currentIndex, handlePress } = useTextInputOTP(); |
| 25 | + const isFocused = currentIndex === index; |
| 26 | + const borderStyles = useSlotBorderStyles({ isFocused, isFirst, isLast }); |
| 27 | + const slotTextColor = useThemeColor({ |
| 28 | + light: theme.colorBlack, |
| 29 | + dark: theme.colorWhite, |
| 30 | + }); |
| 31 | + |
| 32 | + return ( |
| 33 | + <Pressable |
| 34 | + style={StyleSheet.flatten([ |
| 35 | + styles.slot, |
| 36 | + borderStyles, |
| 37 | + isFocused ? focusedSlotStyles : slotStyles, |
| 38 | + ])} |
| 39 | + onPress={() => handlePress(index)} |
| 40 | + {...rest} |
| 41 | + > |
| 42 | + {code[index] && ( |
| 43 | + <Text |
| 44 | + style={StyleSheet.flatten([ |
| 45 | + styles.slotText, |
| 46 | + { color: slotTextColor }, |
| 47 | + isFocused ? focusedSlotTextStyles : slotTextStyles, |
| 48 | + ])} |
| 49 | + > |
| 50 | + {code[index]} |
| 51 | + </Text> |
| 52 | + )} |
| 53 | + |
| 54 | + {isFocused && !code[index] && <AnimatedCaret />} |
| 55 | + </Pressable> |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +export const TextInputOTPSlot = memo(TextInputOTPSlotComponent); |
| 60 | + |
| 61 | +const styles = StyleSheet.create({ |
| 62 | + slot: { |
| 63 | + width: SLOT_WIDTH, |
| 64 | + height: SLOT_HEIGHT, |
| 65 | + justifyContent: 'center', |
| 66 | + alignItems: 'center', |
| 67 | + }, |
| 68 | + slotText: { |
| 69 | + fontSize: 14, |
| 70 | + fontWeight: 'bold', |
| 71 | + }, |
| 72 | +}); |
0 commit comments