Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,16 @@
"types": {
"photo": "photo"
},
"limit": "no more than {{maxFileMBSize}}mb"
"error": {
"weight": "The file size exceeds {{maxFileKBSize}}kb",
"size": "Upload error: Image must be square",
"crop": "You can crop the image here:",
"compress": "You can compress the image here:"
},
"uploaded": "Image added successfully",
"limit": "no more than {{maxFileKBSize}}kb",
"size": "Recommended size — 800х800 px",
"square": "We accept only square images."
},
"validation": {
"required": "This field is required to be completed",
Expand Down
11 changes: 10 additions & 1 deletion public/locales/ru/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,16 @@
"types": {
"photo": "фото"
},
"limit": "не более {{maxFileMBSize}}мб"
"error": {
"weight": "Размер файла превышает {{maxFileKBSize}}КБ",
"size": "Ошибка загрузки: изображение должно быть квадратным",
"crop": "Вы можете обрезать изображение здесь:",
"compress": "Вы можете сжать изображение здесь:"
},
"uploaded": "Изображение добавлено успешно",
"limit": "максимальный размер файла {{maxFileKBSize}}КБ",
"size": "Рекомендуемый размер — 800х800 px",
"square": "Принимаем только квадратные картинки"
},
"validation": {
"required": "Это поле обязательно для заполнения",
Expand Down
4 changes: 4 additions & 0 deletions src/shared/assets/icons/checkSquare.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions src/shared/config/i18n/i18nTranslations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,14 @@ export enum Translation {
FILE_LOADER_LINK = 'file.loader.link',
FILE_LOADER_TEXT = 'file.loader.text',
FILE_LOADER_TYPES_PHOTO = 'file.loader.types.photo',
FILE_LOADER_UPLOADED = 'file.loader.uploaded',
FILE_LOADER_LIMIT = 'file.loader.limit',
FILE_LOADER_SIZE = 'file.loader.size',
FILE_LOADER_SQUARE = 'file.loader.square',
FILE_LOADER_ERROR_WEIGHT = 'file.loader.error.weight',
FILE_LOADER_ERROR_SIZE = 'file.loader.error.size',
FILE_LOADER_ERROR_CROP = 'file.loader.error.crop',
FILE_LOADER_ERROR_COMPRESS = 'file.loader.error.compress',

SETTINGS = 'settings',
CRUMBS_PROFILE = 'crumbs.profile',
Expand Down
41 changes: 41 additions & 0 deletions src/shared/ui/FileLoader/FileLoader.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,44 @@
cursor: not-allowed;
opacity: 0.6;
}

.file-upload-container.error{
border: 2px dashed var(--color-red-600);
}

.file-upload-container.is-uploaded {
border: 2px dashed var(--color-green-900);
}

.file-link{
color: var(--color-purple-700);
text-decoration: underline;
cursor: pointer;
font-size: var( --font-size-h-xxs);
}

.file-link:hover,
.file-link:focus {
text-decoration: none;
}


.warning-icon{
flex-shrink: 0;
width: 28px;
height: 25px;
}

.warning-icon path {
fill: var(--color-red-600);
}

.check-square-icon{
flex-shrink: 0;
width: 28px;
height: 28px;
}

.check-square-icon path {
fill: var(--color-green-900);
}
150 changes: 138 additions & 12 deletions src/shared/ui/FileLoader/FileLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import classNames from 'classnames';
import { DragEvent, RefObject, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import CheckSquare from '@/shared/assets/icons/checkSquare.svg';
import Warning from '@/shared/assets/icons/warning.svg';
import Gallery from '@/shared/assets/images/Gallery.avif';
import { i18Namespace } from '@/shared/config/i18n';
import { Translation } from '@/shared/config/i18n/i18nTranslations';
Expand All @@ -17,7 +19,7 @@ import { Accept, Extension } from './types';
export interface FileLoaderProps {
accept: Accept;
multiply?: boolean;
maxFileMBSize?: number;
maxFileKBSize?: number;
fileTypeText: string;
className?: string;
extensionsText: Extension;
Expand All @@ -30,7 +32,7 @@ export const FileLoader = ({
className,
accept,
fileTypeText,
maxFileMBSize,
maxFileKBSize,
extensionsText,
multiply = false,
onChange,
Expand All @@ -40,6 +42,8 @@ export const FileLoader = ({
const uploaderRef: RefObject<HTMLInputElement> = useRef(null);

const [files, setFiles] = useState<globalThis.File[]>([]);
const [error, setError] = useState<null | 'ErrorSize' | 'ErrorWeight'>(null);
const [isUploaded, setIsUploaded] = useState<boolean>(false);

const { t } = useTranslation(i18Namespace.translation);

Expand All @@ -50,19 +54,55 @@ export const FileLoader = ({
input.value = '';
};

const handleChange = () => {
const getImageDimensions = (file: File): Promise<{ width: number; height: number }> => {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();

reader.onload = (e) => {
img.onload = () => resolve({ width: img.width, height: img.height });
img.onerror = reject;
img.src = e.target?.result as string;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
};

const handleChange = async () => {
setIsUploaded(false);
setError(null);
if (disabled) return null;
if (uploaderRef.current) {
const refFiles = uploaderRef?.current.files;
if (refFiles && refFiles.length > 0) {
const file = Array.from(refFiles);

if (maxFileKBSize && file[0].size / 1024 > maxFileKBSize) {
setError('ErrorWeight');
clearInputState(uploaderRef.current);
return;
}

if (!multiply) {
try {
const { width, height } = await getImageDimensions(file[0]);
if (width !== height) {
setError('ErrorSize');
clearInputState(uploaderRef.current);
return;
}
} catch {
setError('ErrorSize');
clearInputState(uploaderRef.current);
return;
}

setFiles([file[0]]);
onChange([file[0]]);

clearInputState(uploaderRef.current);

setIsUploaded(true);
return;
}

Expand All @@ -76,7 +116,9 @@ export const FileLoader = ({
}
};

const onDrop = (e: DragEvent<HTMLDivElement>) => {
const onDrop = async (e: DragEvent<HTMLDivElement>) => {
setIsUploaded(false);
setError(null);
if (disabled) return null;
e.preventDefault();
const transferFiles = e.dataTransfer.files;
Expand All @@ -86,8 +128,24 @@ export const FileLoader = ({
const file = Array.from(transferFiles);

if (!multiply) {
if (maxFileKBSize && file[0].size / 1024 > maxFileKBSize) {
setError('ErrorWeight');
return;
}
try {
const { width, height } = await getImageDimensions(file[0]);
if (width !== height) {
setError('ErrorSize');
return;
}
} catch {
setError('ErrorSize');
return;
}

setFiles([file[0]]);
onChange([file[0]]);
setIsUploaded(true);
return;
}

Expand Down Expand Up @@ -115,15 +173,22 @@ export const FileLoader = ({
{
[style.active]: isDragActive,
[style.disabled]: disabled,
[style.error]: error,
[style['is-uploaded']]: isUploaded,
},
className,
)}
>
{isDragDropEnabled && (
<>
<div>
<img src={Gallery} alt={t(Translation.FILE_LOADER_TYPES_PHOTO)} loading="lazy" />
</div>
{!isUploaded && !error && (
<div>
<img src={Gallery} alt={t(Translation.FILE_LOADER_TYPES_PHOTO)} loading="lazy" />
</div>
)}

{error && <Warning aria-hidden="true" className={style['warning-icon']} />}
{isUploaded && <CheckSquare aria-hidden="true" className={style['check-square-icon']} />}
<Flex align="center" gap="4" justify="center" wrap="wrap">
<Text variant="body2" color="purple-700" isNoWrap>
{t(Translation.FILE_LOADER_LINK)}
Expand All @@ -132,10 +197,71 @@ export const FileLoader = ({
{t(Translation.FILE_LOADER_TEXT)} {fileTypeText}
</Text>
</Flex>
<Text variant="body1" color="black-300">
{extensionsText}
{maxFileMBSize && ` (${t(Translation.FILE_LOADER_LIMIT, { maxFileMBSize })})`}
</Text>
<Flex direction="column">
{error === 'ErrorWeight' && (
<>
<Text variant="body1" color="red-600">
{t(Translation.FILE_LOADER_ERROR_WEIGHT, { maxFileKBSize })}
</Text>
<Flex align="center" gap="4">
<Text variant="body1" color="black-300">
{t(Translation.FILE_LOADER_ERROR_COMPRESS)}
</Text>
<a
className={style['file-link']}
href="https://www.iloveimg.com/compress-image"
target="_blank"
onClick={(e) => e.stopPropagation()}
rel="noopener noreferrer"
>
iloveimg.com/compress-image
</a>
</Flex>
</>
)}
{error === 'ErrorSize' && (
<>
<Text variant="body1" color="red-600">
{t(Translation.FILE_LOADER_ERROR_SIZE)}
</Text>
<Flex align="center" gap="4">
<Text variant="body1" color="black-300">
{t(Translation.FILE_LOADER_ERROR_CROP)}
</Text>
<a
className={style['file-link']}
href="https://www.iloveimg.com/crop-image"
target="_blank"
onClick={(e) => e.stopPropagation()}
rel="noopener noreferrer"
>
iloveimg.com/crop-image
</a>
</Flex>
</>
)}

{!error && (
<>
{isUploaded && (
<Text variant="body1" color="green-900">
{t(Translation.FILE_LOADER_UPLOADED)}
</Text>
)}

<Text variant="body1" color="black-300">
{extensionsText}
{maxFileKBSize && ` (${t(Translation.FILE_LOADER_LIMIT, { maxFileKBSize })})`}
</Text>
<Text variant="body1" color="black-300">
{t(Translation.FILE_LOADER_SIZE)}
</Text>
<Text variant="body1" color="black-300">
{t(Translation.FILE_LOADER_SQUARE)}
</Text>
</>
)}
</Flex>
</>
)}
<input
Expand Down
2 changes: 1 addition & 1 deletion src/shared/ui/ImageLoader/ImageLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export const ImageLoader = ({
</Flex>
<div className={styles['file-loader']} ref={uploaderRef}>
<FileLoader
maxFileMBSize={maxMBSize}
maxFileKBSize={maxMBSize}
accept={Accept.IMAGE}
fileTypeText={t(Translation.FILE_LOADER_TYPES_PHOTO, {
ns: i18Namespace.translation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

.file-loader {
padding: 14px 0;
min-height: 114px;
max-height: 114px;
min-height: 160px;
max-height: 160px;
line-height: 120%;
font-size: var(--font-size-p-s);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ interface ImageLoaderWithoutCropperProps {
export const ImageLoaderWithoutCropper = ({
changeImage,
removeImage,
maxMBSize,
maxMBSize = 150,
initialSrc: src,
disabled,
}: ImageLoaderWithoutCropperProps) => {
Expand Down Expand Up @@ -80,7 +80,7 @@ export const ImageLoaderWithoutCropper = ({
<FileLoader
disabled={disabled}
className={styles['file-loader']}
maxFileMBSize={maxMBSize}
maxFileKBSize={maxMBSize}
accept={Accept.IMAGE}
fileTypeText={t(Translation.FILE_LOADER_TYPES_PHOTO)}
extensionsText={Extension.IMAGE}
Expand Down