All files / src/components/auth/CodeInput CodeInput.tsx

93.75% Statements 45/48
88% Branches 22/25
100% Functions 9/9
100% Lines 42/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123                                  1x             23x 23x   23x 12x     12x   9x 9x 9x   9x 9x     12x 8x       32x 9x 1x       23x 13x   13x   1x 1x 1x 1x 1x       23x 3x   3x 3x     3x   2x 2x   2x 2x     3x 3x     3x 2x       23x     138x   276x   12x 13x                                                
/**
 * CodeInput Component
 * Story 1.2.4: Email Verification Flow - Task 6 (GREEN Phase)
 * 6-digit code input with auto-advance and paste support
 */
 
import React, { useRef, useState, KeyboardEvent, ClipboardEvent, ChangeEvent } from 'react';
import { Box, TextField } from '@mui/material';
 
interface CodeInputProps {
  length: number;
  onComplete: (code: string) => void;
  onCodeChange?: (code: string) => void;
  error?: boolean;
  disabled?: boolean;
}
 
export const CodeInput: React.FC<CodeInputProps> = ({
  length,
  onComplete,
  onCodeChange,
  error = false,
  disabled = false,
}) => {
  const [code, setCode] = useState<string[]>(Array(length).fill(''));
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
 
  const handleChange = (index: number, value: string) => {
    Iif (disabled) return;
 
    // Only allow digits
    if (!/^\d*$/.test(value)) return;
 
    const newCode = [...code];
    newCode[index] = value.slice(-1); // Only last digit
    setCode(newCode);
 
    const codeString = newCode.join('');
    onCodeChange?.(codeString);
 
    // Auto-advance to next box
    if (value && index < length - 1) {
      inputRefs.current[index + 1]?.focus();
    }
 
    // Auto-submit when complete (check if all digits are filled)
    const isComplete = newCode.every((digit) => digit !== '');
    if (isComplete) {
      onComplete(codeString);
    }
  };
 
  const handleKeyDown = (index: number, e: KeyboardEvent<HTMLInputElement>) => {
    Iif (disabled) return;
 
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      // Move to previous box on backspace
      inputRefs.current[index - 1]?.focus();
      const newCode = [...code];
      newCode[index - 1] = '';
      setCode(newCode);
      onCodeChange?.(newCode.join(''));
    }
  };
 
  const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
    Iif (disabled) return;
 
    e.preventDefault();
    const pastedData = e.clipboardData.getData('text').slice(0, length);
 
    // Only allow digits
    if (!/^\d+$/.test(pastedData)) return;
 
    const newCode = pastedData.split('').concat(Array(length).fill('')).slice(0, length);
    setCode(newCode);
 
    const codeString = newCode.join('');
    onCodeChange?.(codeString);
 
    // Focus last filled box or last box
    const lastFilledIndex = Math.min(pastedData.length - 1, length - 1);
    inputRefs.current[lastFilledIndex]?.focus();
 
    // Auto-submit if complete
    if (pastedData.length === length) {
      onComplete(codeString);
    }
  };
 
  return (
    <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
      {code.map((digit, index) => (
        <TextField
          key={index}
          inputRef={(el) => (inputRefs.current[index] = el)}
          value={digit}
          onChange={(e: ChangeEvent<HTMLInputElement>) => handleChange(index, e.target.value)}
          onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => handleKeyDown(index, e)}
          onPaste={handlePaste}
          disabled={disabled}
          inputProps={{
            maxLength: 1,
            style: { textAlign: 'center', fontSize: '24px' },
            inputMode: 'numeric' as const,
            'aria-label': `Digit ${index + 1}`,
          }}
          sx={{
            width: 56,
            '& input': {
              padding: '16px 0',
            },
          }}
          error={error}
          autoFocus={index === 0}
        />
      ))}
    </Box>
  );
};
 
export default CodeInput;