From 4def79dd515ebb4e84875bd0b425a724549fabb3 Mon Sep 17 00:00:00 2001 From: mortennordseth Date: Fri, 27 Sep 2024 10:14:39 +0200 Subject: [PATCH] feat: handle max file size --- .../contact/components/input/file.tsx | 33 +++++++++++++++---- src/translations/pages/contact.ts | 12 +++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/page-modules/contact/components/input/file.tsx b/src/page-modules/contact/components/input/file.tsx index 5e714083..cf52c94a 100644 --- a/src/page-modules/contact/components/input/file.tsx +++ b/src/page-modules/contact/components/input/file.tsx @@ -3,23 +3,24 @@ import style from './input.module.css'; import { Typo } from '@atb/components/typography'; import { Button } from '@atb/components/button'; import { MonoIcon } from '@atb/components/icon'; +import { PageText, useTranslation } from '@atb/translations'; export type FileInputProps = { label: string; onChange?: (files: File[]) => void; } & Omit; +const MAX_ALLOWED_FILE_SIZE = 10 * 1024 * 1024; // 10MB + export function FileInput({ onChange, label, name }: FileInputProps) { + const { t } = useTranslation(); const id = useId(); const [files, setFiles] = useState([]); const handleFileChange = (event: ChangeEvent) => { if (event.target.files) { const newFilesArray = Array.from(event.target.files); - setFiles((prevFiles) => [...prevFiles, ...newFilesArray]); - if (onChange) { - onChange([...files, ...newFilesArray]); - } + handleFileUpload(newFilesArray); } }; @@ -36,10 +37,28 @@ export function FileInput({ onChange, label, name }: FileInputProps) { if (event.dataTransfer.files) { const droppedFiles = Array.from(event.dataTransfer.files); - setFiles((prevFiles) => [...prevFiles, ...droppedFiles]); - if (onChange) { - onChange([...files, ...droppedFiles]); + handleFileUpload(droppedFiles); + } + }; + + const handleFileUpload = (uploadedFiles: File[]) => { + const filteredFiles = uploadedFiles.filter((file) => { + const isTooLarge = file.size > MAX_ALLOWED_FILE_SIZE; + if (isTooLarge) { + alert( + t( + PageText.Contact.components.fileinput.errorMessages.tooLarge( + file.name, + ), + ), + ); } + return !isTooLarge; + }); + + setFiles((prevFiles) => [...prevFiles, ...filteredFiles]); + if (onChange) { + onChange([...files, ...filteredFiles]); } }; diff --git a/src/translations/pages/contact.ts b/src/translations/pages/contact.ts index 58515a24..cfdf16ac 100644 --- a/src/translations/pages/contact.ts +++ b/src/translations/pages/contact.ts @@ -1011,4 +1011,16 @@ export const Contact = { 'Her gjekk vi på ei blemme og det skjedde ein feil. Kan du prøve igjen?', ), }, + components: { + fileinput: { + errorMessages: { + tooLarge: (fileName: string) => + _( + `Filen "${fileName}" er for stor. Maks 5 MB`, + `The file "${fileName}" is too large. Max 5 MB`, + `Fila "${fileName}" er for stor. Maks 5 MB`, + ), + }, + }, + }, };