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

97.05% Statements 33/34
92.5% Branches 37/40
88.88% Functions 8/9
97.05% Lines 33/34

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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376                                                                                2x           2x           2x 213x 213x 213x     213x           213x     213x 213x 213x   213x 8x             8x 6x       213x 137x   89x   34x   14x       213x 137x   89x   34x   14x             213x                                                               213x                                                             213x   213x                       1x                                                                                                             15x                           1x                                                                                                                                                                               15x                                                                
/**
 * RegistrationStep1 Component
 * Story 1.2.3: Implement Account Creation Flow - Task 5 (GREEN Phase)
 * Story 12.6a: split single Full Name field into Given/Family name (no more fragile split heuristic)
 *
 * Step 1 of registration wizard: Personal Information
 * - Given name, Family name, Email, Password, Confirm Password fields
 * - Real-time password strength indicator
 * - Password requirement checklist
 * - Form validation with localized error messages
 */
 
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useFormContext } from 'react-hook-form';
import {
  Box,
  Divider,
  TextField,
  IconButton,
  InputAdornment,
  Typography,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  LinearProgress,
  Button,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  CheckCircle,
  RadioButtonUnchecked,
  Google,
} from '@mui/icons-material';
import { useFeature } from '@/contexts/useFeature';
import { authService } from '@/services/auth/authService';
import * as passwordStrength from '../../../utils/passwordStrength/passwordStrength';
 
const { checkPasswordRequirements, calculatePasswordStrength } = passwordStrength;
type PasswordStrength = passwordStrength.PasswordStrength;
 
// Story 12.6a: locales whose convention is family-name-first. The data mapping
// (firstName=given, lastName=family) never changes — only the visual field order
// flips for these locales. Currently only Japanese; extend the set as needed.
const FAMILY_NAME_FIRST_LOCALES = new Set(['ja']);
 
interface RegistrationStep1Props {
  onContinue: () => void;
}
 
export const RegistrationStep1: React.FC<RegistrationStep1Props> = ({ onContinue }) => {
  const { t, i18n } = useTranslation('auth');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  // Story 12.9 follow-up: same flag-gated Google SSO entry as LoginForm — registering
  // via Google skips the whole wizard (JIT provisioning + ToS consent gate handle the rest).
  const ssoEnabled = useFeature('sso');
 
  const {
    register,
    watch,
    formState: { errors },
    trigger,
  } = useFormContext();
 
  const password = watch('password', '');
  const requirements = checkPasswordRequirements(password);
  const strength = calculatePasswordStrength(password);
 
  const handleContinue = async () => {
    const isValid = await trigger([
      'firstName',
      'lastName',
      'email',
      'password',
      'confirmPassword',
    ]);
    if (isValid) {
      onContinue();
    }
  };
 
  const getStrengthColor = (currentStrength: PasswordStrength): 'error' | 'warning' | 'success' => {
    switch (currentStrength) {
      case 'weak':
        return 'error';
      case 'medium':
        return 'warning';
      case 'strong':
        return 'success';
    }
  };
 
  const getStrengthValue = (currentStrength: PasswordStrength): number => {
    switch (currentStrength) {
      case 'weak':
        return 33;
      case 'medium':
        return 66;
      case 'strong':
        return 100;
    }
  };
 
  // Story 12.6a: two name fields. register names stay firstName/lastName (matches
  // authService.signUp + the DB columns) while labels say Given/Family (order-neutral).
  const givenNameField = (
    <TextField
      key="firstName"
      {...register('firstName', {
        required: t('register.errors.givenNameRequired'),
        minLength: {
          value: 2,
          message: t('register.errors.givenNameTooShort'),
        },
        maxLength: {
          value: 100,
          message: t('register.errors.givenNameTooLong'),
        },
        pattern: {
          // Accept any Unicode letter (handles é, è, à, ç, ñ, ş, ø, ł, …) plus
          // whitespace, dot, apostrophe, and hyphen. The backend slug service
          // normalises diacritics for the generated username; rejecting them
          // here used to silently strip required form fields (2026-05-18
          // incident: "René Strauss" / "Renée Gressly").
          value: /^[\p{L}\s.'-]+$/u,
          message: t('register.errors.givenNameInvalid'),
        },
      })}
      label={t('register.step1.givenNameLabel')}
      placeholder={t('register.step1.givenNamePlaceholder')}
      fullWidth
      margin="normal"
      error={!!errors.firstName}
      helperText={errors.firstName?.message as string}
    />
  );
 
  const familyNameField = (
    <TextField
      key="lastName"
      {...register('lastName', {
        required: t('register.errors.familyNameRequired'),
        minLength: {
          value: 2,
          message: t('register.errors.familyNameTooShort'),
        },
        maxLength: {
          value: 100,
          message: t('register.errors.familyNameTooLong'),
        },
        pattern: {
          // Accept any Unicode letter (handles é, è, à, ç, ñ, ş, ø, ł, …) plus
          // whitespace, dot, apostrophe, and hyphen. The backend slug service
          // normalises diacritics for the generated username; rejecting them
          // here used to silently strip required form fields (2026-05-18
          // incident: "René Strauss" / "Renée Gressly").
          value: /^[\p{L}\s.'-]+$/u,
          message: t('register.errors.familyNameInvalid'),
        },
      })}
      label={t('register.step1.familyNameLabel')}
      placeholder={t('register.step1.familyNamePlaceholder')}
      fullWidth
      margin="normal"
      error={!!errors.lastName}
      helperText={errors.lastName?.message as string}
    />
  );
 
  const familyNameFirst = FAMILY_NAME_FIRST_LOCALES.has(i18n.language);
 
  return (
    <Box>
      <Typography variant="h5" gutterBottom>
        {t('register.step1.title')}
      </Typography>
 
      {ssoEnabled && (
        <>
          <Button
            variant="outlined"
            fullWidth
            startIcon={<Google />}
            onClick={() => authService.signInWithFederated('Google')}
            sx={{ mt: 1, mb: 1 }}
            data-testid="register-with-google"
          >
            {t('login.continueWithGoogle')}
          </Button>
          <Divider sx={{ my: 2 }}>{t('login.orDivider')}</Divider>
        </>
      )}
 
      {familyNameFirst ? (
        <>
          {familyNameField}
          {givenNameField}
        </>
      ) : (
        <>
          {givenNameField}
          {familyNameField}
        </>
      )}
 
      <TextField
        {...register('email', {
          required: t('register.errors.emailRequired'),
          pattern: {
            value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            message: t('register.errors.emailInvalid'),
          },
          maxLength: {
            value: 255,
            message: t('register.errors.emailTooLong'),
          },
        })}
        label={t('register.step1.emailLabel')}
        placeholder={t('register.step1.emailPlaceholder')}
        type="email"
        fullWidth
        margin="normal"
        error={!!errors.email}
        helperText={errors.email?.message as string}
      />
 
      <TextField
        {...register('password', {
          required: t('register.errors.passwordRequired'),
          minLength: {
            value: 8,
            message: t('register.errors.passwordTooShort'),
          },
          maxLength: {
            value: 128,
            message: t('register.errors.passwordTooLong'),
          },
          validate: (value) =>
            checkPasswordRequirements(value).hasSpecialChar ||
            t('register.errors.passwordMissingSymbol'),
        })}
        label={t('register.step1.passwordLabel')}
        placeholder={t('register.step1.passwordPlaceholder')}
        type={showPassword ? 'text' : 'password'}
        fullWidth
        margin="normal"
        error={!!errors.password}
        helperText={errors.password?.message as string}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton
                onClick={() => setShowPassword(!showPassword)}
                edge="end"
                aria-label={t(
                  showPassword ? 'registration.hidePassword' : 'registration.showPassword'
                )}
              >
                {showPassword ? <VisibilityOff /> : <Visibility />}
              </IconButton>
            </InputAdornment>
          ),
        }}
      />
 
      {password && (
        <Box sx={{ mt: 1, mb: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
            <Typography variant="body2">{t(`register.passwordStrength.${strength}`)}</Typography>
            <LinearProgress
              variant="determinate"
              value={getStrengthValue(strength)}
              color={getStrengthColor(strength)}
              sx={{ flex: 1 }}
            />
          </Box>
 
          <Typography variant="caption" color="text.secondary">
            {t('register.passwordRequirements.title')}
          </Typography>
          <List dense>
            <ListItem>
              <ListItemIcon>
                {requirements.minLength ? (
                  <CheckCircle color="success" fontSize="small" />
                ) : (
                  <RadioButtonUnchecked fontSize="small" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('register.passwordRequirements.minLength')}
                primaryTypographyProps={{ variant: 'body2' }}
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                {requirements.hasUppercase && requirements.hasLowercase ? (
                  <CheckCircle color="success" fontSize="small" />
                ) : (
                  <RadioButtonUnchecked fontSize="small" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('register.passwordRequirements.hasUppercase')}
                primaryTypographyProps={{ variant: 'body2' }}
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                {requirements.hasNumber ? (
                  <CheckCircle color="success" fontSize="small" />
                ) : (
                  <RadioButtonUnchecked fontSize="small" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('register.passwordRequirements.hasNumber')}
                primaryTypographyProps={{ variant: 'body2' }}
              />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                {requirements.hasSpecialChar ? (
                  <CheckCircle color="success" fontSize="small" />
                ) : (
                  <RadioButtonUnchecked fontSize="small" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('register.passwordRequirements.hasSpecialChar')}
                primaryTypographyProps={{ variant: 'body2' }}
              />
            </ListItem>
          </List>
        </Box>
      )}
 
      <TextField
        {...register('confirmPassword', {
          required: t('register.errors.passwordRequired'),
          validate: (value) => value === password || t('register.errors.passwordMismatch'),
        })}
        label={t('register.step1.confirmPasswordLabel')}
        placeholder={t('register.step1.confirmPasswordPlaceholder')}
        type={showConfirmPassword ? 'text' : 'password'}
        fullWidth
        margin="normal"
        error={!!errors.confirmPassword}
        helperText={errors.confirmPassword?.message as string}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                edge="end"
                aria-label={t(
                  showConfirmPassword ? 'registration.hidePassword' : 'registration.showPassword'
                )}
              >
                {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
              </IconButton>
            </InputAdornment>
          ),
        }}
      />
 
      <Button variant="contained" fullWidth size="large" onClick={handleContinue} sx={{ mt: 3 }}>
        {t('register.step1.continueButton')}
      </Button>
    </Box>
  );
};