export const MAX_IMAGE_BYTES = 10 * 1024 * 1024 export const ALLOWED_IMAGE_MIME_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'] export const ALLOWED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.svg'] export const IMAGE_TYPE_REJECTION_TEXT = 'Use a PNG, JPEG, WEBP or SVG image, up to 10 MB.' export type ImageRejectionKind = 'type' | 'size' export type ImageValidationResult = { ok: true } | { ok: false; kind: ImageRejectionKind } export function fileExtension(filename: string) { const index = filename.lastIndexOf('.') return index === -1 ? '' : filename.slice(index).toLowerCase() } export function validateImageFile(file: File): ImageValidationResult { if (file.size > MAX_IMAGE_BYTES) { return { ok: false, kind: 'size' } } const typeAllowed = ALLOWED_IMAGE_MIME_TYPES.includes(file.type) const extensionAllowed = ALLOWED_IMAGE_EXTENSIONS.includes(fileExtension(file.name)) if (!typeAllowed || !extensionAllowed) { return { ok: false, kind: 'type' } } return { ok: true } } export function formatMegabytes(bytes: number) { return (bytes / (1024 * 1024)).toFixed(1) } export function isSizeRejectionBody(body: string) { return body.toLowerCase().includes('exceed') } export function rejectionTitle(filename: string) { return `"${filename}" can't be used` } export function sizeRejectionText(filename: string, bytes: number) { return `${filename} is ${formatMegabytes(bytes)} MB. Images can be up to 10 MB.` } export function formatWholeKB(bytes: number): string { const kb = bytes / 1024 const rounded = Math.round(kb * 10) / 10 if (rounded === 0) { return '0.0' } return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1) } export function formatUploadProgress(loadedBytes: number, totalBytes: number): string { if (totalBytes < 1024 * 1024) { return `Uploading ${formatWholeKB(loadedBytes)} of ${formatWholeKB(totalBytes)} KB` } return `Uploading ${formatMegabytes(loadedBytes)} of ${formatMegabytes(totalBytes)} MB` }