All files / src/components/shared/FileUpload FileUpload.tsx

92% Statements 69/75
81.11% Branches 73/90
91.66% Functions 11/12
92.42% Lines 61/66

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 377                                                                                                                                                            11x 7x 7x 2x       11x 7x       2x   5x 4x   1x 1x         11x                           326x 326x 326x     326x 326x   326x                                 326x 135x     326x     7x     7x   2x 2x 1x       1x       1x 2x 2x 2x                     5x 1x       1x     4x 4x 4x                 326x 326x 326x   1124x 847x 570x 294x 259x 28x 231x 210x 189x 168x   326x     326x             326x   4x 4x 4x   4x         326x                 7x           1x                                                                                                                                             3x                                                                                                                      
/**
 * FileUpload Component
 * Story 1.16.3: Generic File Upload Service
 * ADR-002: Generic File Upload Service Architecture
 *
 * Reusable file upload component with drag-and-drop support
 * Uses generic /api/v1/logos endpoints - works for any entity type
 *
 * Features:
 * - Drag-and-drop file upload
 * - File type and size validation
 * - Upload progress indicator
 * - Preview uploaded file
 * - Remove uploaded file
 * - Error handling with user-friendly messages
 *
 * Usage:
 * <FileUpload
 *   currentFileUrl={logoUrl}
 *   onUploadSuccess={(data) => setLogoUploadId(data.uploadId)}
 *   onUploadError={(error) => console.error(error)}
 * />
 */
 
import React, { useState, useCallback, useEffect } from 'react';
import { useDropzone } from 'react-dropzone';
import {
  Box,
  Typography,
  IconButton,
  LinearProgress,
  Alert,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
} from '@mui/material';
import {
  CloudUpload as CloudUploadIcon,
  Delete as DeleteIcon,
  Description as DescriptionIcon,
  PictureAsPdf as PdfIcon,
  VideoLibrary as VideoIcon,
  Slideshow as PresentationIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useFileUpload } from '@/hooks/useFileUpload/useFileUpload';
 
export interface UploadedFile {
  uploadId: string;
  fileName: string;
  fileSize: number;
  fileType: string;
}
 
interface FileUploadProps {
  currentFileUrl?: string;
  onUploadSuccess?: (data: {
    uploadId: string;
    tempFileUrl?: string;
    fileName?: string;
    fileSize?: number;
    fileType?: string;
  }) => void;
  onUploadError?: (error: { type: string; message: string }) => void;
  onFileRemove?: (uploadId?: string) => void; // Callback when file is removed (Story 2.5.3a, 5.9)
  maxFileSize?: number; // in bytes, default 5MB
  allowedTypes?: string[]; // MIME types
  altText?: string; // Alt text for the uploaded image
  removeButtonLabel?: string; // Aria label for the remove button
  // Story 5.9: Multiple files support
  multiple?: boolean; // Enable multiple file uploads
  maxFiles?: number; // Maximum number of files (default 10)
  uploadedFiles?: UploadedFile[]; // List of uploaded files (for multiple mode)
  uploadEndpoint?: string; // API endpoint for presigned URL (default: '/logos/presigned-url')
}
 
// Helper function to format file size
const formatFileSize = (bytes: number): string => {
  Iif (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};
 
// Helper function to get file type icon
const getFileTypeIcon = (mimeType: string): React.ReactNode => {
  if (
    mimeType.startsWith('application/vnd.openxmlformats-officedocument.presentationml') ||
    mimeType.startsWith('application/vnd.ms-powerpoint')
  ) {
    return <PresentationIcon data-testid="file-icon-presentation" />;
  }
  if (mimeType === 'application/pdf') {
    return <PdfIcon data-testid="file-icon-document" />;
  }
  Eif (mimeType.startsWith('video/')) {
    return <VideoIcon data-testid="file-icon-video" />;
  }
  return <DescriptionIcon data-testid="file-icon-document" />;
};
 
export const FileUpload: React.FC<FileUploadProps> = ({
  currentFileUrl,
  onUploadSuccess,
  onUploadError,
  onFileRemove,
  maxFileSize = 5 * 1024 * 1024, // 5MB
  allowedTypes = ['image/png', 'image/jpeg', 'image/svg+xml'],
  altText,
  removeButtonLabel,
  multiple = false,
  maxFiles = 10,
  uploadedFiles = [],
  uploadEndpoint = '/logos/presigned-url', // Default to logos for backward compatibility
}) => {
  const { t } = useTranslation('common');
  const [fileUrl, setFileUrl] = useState<string | undefined>(currentFileUrl);
  const [, setUploadId] = useState<string | undefined>();
 
  // Use i18n translations with fallback to props or default values
  const translatedAltText = altText || t('fileUpload.altText');
  const translatedRemoveButtonLabel = removeButtonLabel || t('fileUpload.removeFile');
 
  const { uploadFile, isUploading, uploadProgress, error, reset } = useFileUpload({
    maxFileSize,
    allowedTypes,
    onUploadSuccess: (data) => {
      setFileUrl(data.tempFileUrl);
      setUploadId(data.uploadId);
      // Only call parent's onUploadSuccess for single file mode
      // Multiple file mode handles this in onDrop with full metadata
      if (!multiple) {
        onUploadSuccess?.(data);
      }
    },
    onUploadError,
    uploadEndpoint, // Pass through the endpoint
  });
 
  // Sync fileUrl with currentFileUrl prop
  useEffect(() => {
    setFileUrl(currentFileUrl);
  }, [currentFileUrl]);
 
  const onDrop = useCallback(
    async (acceptedFiles: File[]) => {
      // Reset error state
      reset();
 
      // Story 5.9: Handle multiple files mode
      if (multiple) {
        // Check if exceeding maxFiles limit
        const totalFiles = uploadedFiles.length + acceptedFiles.length;
        if (totalFiles > maxFiles) {
          onUploadError?.({
            type: 'TOO_MANY_FILES',
            message: `You can only upload a maximum of ${maxFiles} files. Current: ${uploadedFiles.length}, Attempting to add: ${acceptedFiles.length}`,
          });
          return;
        }
 
        // Upload all accepted files sequentially to capture metadata
        for (const file of acceptedFiles) {
          const uploadId = await uploadFile(file);
          Eif (uploadId && onUploadSuccess) {
            onUploadSuccess({
              uploadId,
              tempFileUrl: undefined,
              fileName: file.name,
              fileSize: file.size,
              fileType: file.type,
            });
          }
        }
      } else {
        // Original behavior: single file only
        if (acceptedFiles.length > 1) {
          onUploadError?.({
            type: 'MULTIPLE_FILES',
            message: t('fileUpload.errors.multipleFiles'),
          });
          return;
        }
 
        const file = acceptedFiles[0];
        Eif (file) {
          await uploadFile(file);
        }
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [uploadFile, reset, onUploadError, multiple, maxFiles, uploadedFiles.length, t]
  );
 
  // Build accept object dynamically from allowed types
  const buildAcceptObject = (types: string[]) => {
    const acceptObj: Record<string, string[]> = {};
    types.forEach((type) => {
      // Map MIME types to extensions
      if (type === 'image/png') acceptObj[type] = ['.png'];
      else if (type === 'image/jpeg') acceptObj[type] = ['.jpg', '.jpeg'];
      else if (type === 'image/svg+xml') acceptObj[type] = ['.svg'];
      else if (type === 'application/pdf') acceptObj[type] = ['.pdf'];
      else if (type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation')
        acceptObj[type] = ['.pptx'];
      else if (type === 'application/vnd.ms-powerpoint') acceptObj[type] = ['.ppt'];
      else if (type === 'video/mp4') acceptObj[type] = ['.mp4'];
      else if (type === 'video/quicktime') acceptObj[type] = ['.mov'];
      else acceptObj[type] = []; // Accept without specific extension
    });
    return acceptObj;
  };
 
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: buildAcceptObject(allowedTypes),
    multiple: true, // Always allow multiple file selection, handle limits in onDrop
    disabled: isUploading,
  });
 
  const handleRemoveFile = useCallback(
    (uploadId?: string) => {
      setFileUrl(undefined);
      setUploadId(undefined);
      reset();
      // Notify parent component that file was removed (Story 2.5.3a, 5.9)
      onFileRemove?.(uploadId);
    },
    [reset, onFileRemove]
  );
 
  return (
    <Box sx={{ width: '100%' }}>
      {/* Story 5.9: Multiple files mode */}
      {multiple ? (
        <>
          {/* Display uploaded files list */}
          {uploadedFiles.length > 0 && (
            <List sx={{ mb: 2 }}>
              {uploadedFiles.map((file) => (
                <ListItem
                  key={file.uploadId}
                  secondaryAction={
                    <IconButton
                      edge="end"
                      aria-label={t('actions.delete')}
                      onClick={() => handleRemoveFile(file.uploadId)}
                      disabled={isUploading}
                    >
                      <DeleteIcon />
                    </IconButton>
                  }
                >
                  <ListItemIcon>{getFileTypeIcon(file.fileType)}</ListItemIcon>
                  <ListItemText primary={file.fileName} secondary={formatFileSize(file.fileSize)} />
                </ListItem>
              ))}
            </List>
          )}
 
          {/* Always show dropzone in multiple mode */}
          <Box
            {...getRootProps()}
            data-testid="file-dropzone"
            aria-disabled={isUploading}
            className={isDragActive ? 'dropzone-active' : ''}
            sx={{
              border: '2px dashed',
              borderColor: isDragActive ? 'primary.main' : 'grey.400',
              borderRadius: 2,
              padding: 4,
              textAlign: 'center',
              cursor: isUploading ? 'not-allowed' : 'pointer',
              backgroundColor: isDragActive ? 'action.hover' : 'background.paper',
              transition: 'all 0.2s ease-in-out',
              '&:hover': {
                borderColor: isUploading ? 'grey.400' : 'primary.main',
                backgroundColor: isUploading ? 'background.paper' : 'action.hover',
              },
            }}
          >
            <input {...getInputProps()} />
            <CloudUploadIcon sx={{ fontSize: 48, color: 'grey.500', mb: 2 }} />
            <Typography variant="body1" color="textSecondary">
              {isDragActive ? t('fileUpload.dragActive') : t('fileUpload.dragDropMultiple')}
            </Typography>
            <Typography variant="caption" color="textSecondary" sx={{ mt: 1 }}>
              {t('fileUpload.acceptedFormatsMultiple', {
                maxSize: (maxFileSize / (1024 * 1024)).toFixed(0),
              })}
            </Typography>
          </Box>
        </>
      ) : /* Original single file mode */
      fileUrl ? (
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2,
          }}
        >
          <Box
            component="img"
            src={fileUrl}
            alt={translatedAltText}
            sx={{
              maxWidth: '200px',
              maxHeight: '200px',
              objectFit: 'contain',
              border: '1px solid #e0e0e0',
              borderRadius: 1,
              padding: 2,
            }}
          />
          <IconButton
            onClick={() => handleRemoveFile()}
            color="error"
            aria-label={translatedRemoveButtonLabel}
            disabled={isUploading}
          >
            <DeleteIcon />
          </IconButton>
        </Box>
      ) : (
        <Box
          {...getRootProps()}
          data-testid="file-dropzone"
          aria-disabled={isUploading}
          className={isDragActive ? 'dropzone-active' : ''}
          sx={{
            border: '2px dashed',
            borderColor: isDragActive ? 'primary.main' : 'grey.400',
            borderRadius: 2,
            padding: 4,
            textAlign: 'center',
            cursor: isUploading ? 'not-allowed' : 'pointer',
            backgroundColor: isDragActive ? 'action.hover' : 'background.paper',
            transition: 'all 0.2s ease-in-out',
            '&:hover': {
              borderColor: isUploading ? 'grey.400' : 'primary.main',
              backgroundColor: isUploading ? 'background.paper' : 'action.hover',
            },
          }}
        >
          <input {...getInputProps()} />
          <CloudUploadIcon sx={{ fontSize: 48, color: 'grey.500', mb: 2 }} />
          <Typography variant="body1" color="textSecondary">
            {isDragActive ? t('fileUpload.dragActive') : t('fileUpload.dragDrop')}
          </Typography>
          <Typography variant="caption" color="textSecondary" sx={{ mt: 1 }}>
            {t('fileUpload.acceptedFormats', {
              maxSize: (maxFileSize / (1024 * 1024)).toFixed(0),
            })}
          </Typography>
        </Box>
      )}
 
      {isUploading && (
        <Box sx={{ width: '100%', mt: 2 }}>
          <Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
            {t('fileUpload.uploading', { progress: uploadProgress })}
          </Typography>
          <LinearProgress variant="determinate" value={uploadProgress} role="progressbar" />
        </Box>
      )}
 
      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
    </Box>
  );
};