All files / src/components/speaker-portal PresentationUpload.tsx

78.94% Statements 75/95
70.83% Branches 34/48
62.5% Functions 10/16
78.94% Lines 75/95

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 378 379 380 381                                        2x 2x             2x                                     2x             33x   33x 33x 33x 33x 33x 33x     33x 33x     33x 29x 2x             33x 10x           33x     10x   10x   10x 1x 1x 1x 1x       9x 1x 1x 1x 1x     8x               33x     10x 10x     10x 2x       8x 8x   8x   8x 1x       5x 5x 5x 5x 5x     1x 1x 1x   1x 1x 1x                 33x   10x 10x 10x     10x               33x 1x 1x 1x     33x                 33x         33x                                 33x 2x 2x             33x                         33x               33x             33x 2x                                                         31x                                                   124x                                                                                                                                                          
/**
 * PresentationUpload Component
 * Story 6.3: Speaker Content Self-Submission Portal - AC7 (File Upload)
 *
 * Features:
 * - Drag-and-drop support (AC7.1)
 * - Click to browse (AC7.2)
 * - File type validation - PPTX, PDF, KEY (AC7.3)
 * - File size validation - max 50MB (AC7.4)
 * - Upload uses presigned URL (AC7.5)
 * - Progress indicator during upload (AC7.6)
 */
 
import { useState, useCallback, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Upload, FileText, X, AlertCircle, ExternalLink } from 'lucide-react';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { speakerPortalService } from '@/services/speakerPortalService';
 
// Constants
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB (AC7.4)
const ALLOWED_TYPES = [
  'application/vnd.openxmlformats-officedocument.presentationml.presentation', // PPTX
  'application/vnd.ms-powerpoint', // PPT
  'application/pdf', // PDF
  'application/x-iwork-keynote-sffkey', // Keynote (KEY)
  'application/vnd.apple.keynote', // Keynote alternative MIME
]; // (AC7.3)
const ALLOWED_EXTENSIONS = ['pptx', 'ppt', 'pdf', 'key'];
 
interface PresentationUploadProps {
  /** Story 11.E.3: event code (replaces magic-link token; Cognito session is automatic) */
  eventCode: string;
  /** Current material URL (null if none) */
  currentMaterialUrl: string | null;
  /** Current material file name (null if none) */
  currentMaterialName: string | null;
  /** Callback when material is successfully uploaded */
  onMaterialUploaded: (url: string, fileName: string) => void;
  /** Callback when an error occurs */
  onError: (error: { type: string; message: string }) => void;
}
 
/**
 * Presentation material upload component with drag-and-drop support.
 * Uses presigned URL pattern for direct S3 upload.
 */
const PresentationUpload = ({
  eventCode,
  currentMaterialUrl,
  currentMaterialName,
  onMaterialUploaded,
  onError,
}: PresentationUploadProps) => {
  const { t } = useTranslation();
  // State
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [selectedFileName, setSelectedFileName] = useState<string | null>(null);
  const [showDropzone, setShowDropzone] = useState(!currentMaterialUrl);
 
  // Refs
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dropzoneRef = useRef<HTMLDivElement>(null);
 
  // Update showDropzone when currentMaterialUrl changes
  useEffect(() => {
    if (currentMaterialUrl && !isUploading) {
      setShowDropzone(false);
    }
  }, [currentMaterialUrl, isUploading]);
 
  /**
   * Get file extension from filename
   */
  const getFileExtension = (fileName: string): string => {
    return fileName.split('.').pop()?.toLowerCase() || '';
  };
 
  /**
   * Validate file type and size
   */
  const validateFile = useCallback(
    (file: File): boolean => {
      // Validate file type (AC7.3)
      const extension = getFileExtension(file.name);
      const isValidType =
        ALLOWED_TYPES.includes(file.type) || ALLOWED_EXTENSIONS.includes(extension);
 
      if (!isValidType) {
        const errorMsg = t('speakerPortal.upload.invalidFileType');
        setError(errorMsg);
        onError({ type: 'INVALID_FILE_TYPE', message: errorMsg });
        return false;
      }
 
      // Validate file size (AC7.4)
      if (file.size > MAX_FILE_SIZE) {
        const errorMsg = t('speakerPortal.upload.fileTooLarge');
        setError(errorMsg);
        onError({ type: 'FILE_TOO_LARGE', message: errorMsg });
        return false;
      }
 
      return true;
    },
    [onError, t]
  );
 
  /**
   * Handle file upload
   */
  const handleUpload = useCallback(
    async (file: File) => {
      // Reset state
      setError(null);
      setUploadProgress(0);
 
      // Validate file
      if (!validateFile(file)) {
        return;
      }
 
      // Set file name and start upload
      setSelectedFileName(file.name);
      setIsUploading(true);
 
      try {
        // Upload using service (3-phase presigned URL flow)
        const response = await speakerPortalService.uploadMaterial(eventCode, file, (progress) =>
          setUploadProgress(progress)
        );
 
        // Notify success
        setIsUploading(false);
        setUploadProgress(0);
        setSelectedFileName(null);
        setShowDropzone(false);
        onMaterialUploaded(response.cloudFrontUrl, response.fileName);
      } catch (err) {
        // Handle error
        setIsUploading(false);
        setUploadProgress(0);
        setSelectedFileName(null);
 
        const errorMsg = err instanceof Error ? err.message : 'Upload failed';
        setError(errorMsg);
        onError({ type: 'UPLOAD_FAILED', message: errorMsg });
      }
    },
    [eventCode, validateFile, onMaterialUploaded, onError]
  );
 
  /**
   * Handle file input change
   */
  const handleFileChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      Eif (file) {
        handleUpload(file);
      }
      // Reset input to allow selecting same file again
      event.target.value = '';
    },
    [handleUpload]
  );
 
  /**
   * Handle drag events
   */
  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);
 
  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    // Only set to false if we're leaving the dropzone entirely
    if (e.currentTarget === e.target) {
      setIsDragging(false);
    }
  }, []);
 
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);
 
  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDragging(false);
 
      const file = e.dataTransfer.files?.[0];
      if (file) {
        handleUpload(file);
      }
    },
    [handleUpload]
  );
 
  /**
   * Handle click on dropzone
   */
  const handleDropzoneClick = useCallback(() => {
    Eif (!isUploading) {
      fileInputRef.current?.click();
    }
  }, [isUploading]);
 
  /**
   * Handle keyboard activation of dropzone
   */
  const handleDropzoneKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        handleDropzoneClick();
      }
    },
    [handleDropzoneClick]
  );
 
  /**
   * Handle "Change" button click
   */
  const handleChangeFile = useCallback(() => {
    setShowDropzone(true);
    setError(null);
  }, []);
 
  /**
   * Handle "Cancel" button click
   */
  const handleCancel = useCallback(() => {
    setShowDropzone(false);
    setError(null);
    setSelectedFileName(null);
  }, []);
 
  // Render material display (when material exists and not changing)
  if (!showDropzone && currentMaterialUrl && currentMaterialName) {
    return (
      <div className="flex flex-col gap-4 p-4 bg-gray-700 rounded-lg">
        <div className="flex items-center gap-3">
          <FileText className="h-8 w-8 text-blue-400 flex-shrink-0" />
          <div className="flex-1 min-w-0">
            <a
              href={currentMaterialUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-400 hover:text-blue-300 transition-colors truncate block"
            >
              {currentMaterialName}
              <ExternalLink className="h-3 w-3 inline-block ml-1" />
            </a>
            <p className="text-sm text-gray-500">{t('speakerPortal.upload.presentationFile')}</p>
          </div>
        </div>
        <button
          type="button"
          onClick={handleChangeFile}
          className="text-sm text-blue-400 hover:text-blue-300 transition-colors self-start"
        >
          {t('speakerPortal.upload.changeFile')}
        </button>
      </div>
    );
  }
 
  // Render dropzone
  return (
    <div className="flex flex-col gap-4">
      {/* Dropzone (AC7.1, AC7.2) */}
      <div
        ref={dropzoneRef}
        data-testid="material-dropzone"
        role="button"
        tabIndex={0}
        aria-disabled={isUploading}
        onClick={handleDropzoneClick}
        onKeyDown={handleDropzoneKeyDown}
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        className={`
          p-8 flex flex-col items-center justify-center
          border-2 border-dashed rounded-lg transition-all cursor-pointer
          ${isDragging ? 'border-blue-500 bg-blue-900/20' : 'border-gray-600 hover:border-gray-500'}
          ${isUploading ? 'opacity-50 cursor-not-allowed' : ''}
        `}
      >
        {/* Hidden file input inside dropzone for test accessibility */}
        <input
          ref={fileInputRef}
          type="file"
          accept={[...ALLOWED_TYPES, ...ALLOWED_EXTENSIONS.map((ext) => `.${ext}`)].join(',')}
          onChange={handleFileChange}
          className="hidden"
          aria-label={t('speakerPortal.upload.uploadAria')}
        />
 
        {isUploading ? (
          <>
            <BATbernLoader size={96} />
            <p className="text-white font-medium">{selectedFileName}</p>
          </>
        ) : (
          <>
            <Upload className="h-12 w-12 text-gray-400 mb-4" />
            <p className="text-white font-medium mb-1">
              {t('speakerPortal.upload.dragDropPresentation')}
            </p>
            <p className="text-gray-400 text-sm">{t('speakerPortal.upload.orClickBrowse')}</p>
          </>
        )}
      </div>
 
      {/* Upload progress (AC7.6) */}
      {isUploading && (
        <div role="status" aria-live="polite">
          <div className="flex justify-between text-sm text-gray-400 mb-1">
            <span>{t('speakerPortal.upload.uploading')}</span>
            <span>{uploadProgress}%</span>
          </div>
          <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
            <div
              role="progressbar"
              aria-valuenow={uploadProgress}
              aria-valuemin={0}
              aria-valuemax={100}
              className="h-full bg-blue-500 transition-all duration-300"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        </div>
      )}
 
      {/* Instructions */}
      {!isUploading && (
        <p className="text-xs text-gray-500 text-center">
          {t('speakerPortal.upload.acceptedFormats')}
        </p>
      )}
 
      {/* Error message */}
      {error && (
        <div
          role="alert"
          className="flex items-center gap-2 text-sm text-red-400 bg-red-900/20 px-3 py-2 rounded-lg"
        >
          <AlertCircle className="h-4 w-4 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}
 
      {/* Cancel button (when changing existing material) */}
      {currentMaterialUrl && !isUploading && (
        <button
          type="button"
          onClick={handleCancel}
          className="flex items-center gap-1 text-sm text-gray-400 hover:text-gray-300 transition-colors self-center"
          aria-label={t('speakerPortal.photo.cancel')}
        >
          <X className="h-4 w-4" />
          {t('speakerPortal.photo.cancel')}
        </button>
      )}
    </div>
  );
};
 
export default PresentationUpload;