/** * Utility functions for the FileUpload component */ /** * Parse a file size string (e.g. "5MB", "500KB") to bytes. * Also accepts raw numbers (returned as-is). * * @example * parseFileSize("5MB") // 5242880 * parseFileSize("500KB") // 512000 * parseFileSize("1GB") // 1073741824 * parseFileSize(1024) // 1024 */ export const parseFileSize = (size: string | number): number => { if (typeof size === 'number') return size const match = size.trim().match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$/i) if (!match) { console.warn( `PktFileUpload: Invalid maxFileSize format "${size}". Use format like "5MB", "500KB", or a number in bytes.`, ) return 0 } const value = parseFloat(match[1]) const unit = match[2].toUpperCase() switch (unit) { case 'B': return value case 'KB': return value * 1024 case 'MB': return value * 1024 * 1024 case 'GB': return value * 1024 * 1024 * 1024 default: return value } } /** * Format bytes to a human-readable string (e.g. "5 MB", "500 KB"). * * @example * formatFileSize(5242880) // "5 MB" * formatFileSize(512000) // "500 KB" * formatFileSize(500) // "500 B" */ export const formatFileSize = (bytes: number): string => { if (bytes < 1024) return `${bytes} B` if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB` if (bytes < 1024 * 1024 * 1024) return `${Math.round(bytes / (1024 * 1024))} MB` return `${Math.round(bytes / (1024 * 1024 * 1024))} GB` }