Files
nahodka-front/src/hooks/useImageUpload.js
2026-10-15 01:29:07 +03:00

143 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useRef, useEffect, useCallback } from "react";
import { useTranslation } from 'react-i18next';
import { compressImage } from "../utils/compressImage";
import { getImageUrl } from "../config/authConstants";
// Лимит бэкенда на один файл — его должен выдерживать уже сжатый файл
export const MAX_SIZE_MB = 10;
// Лимит на исходное фото: оно всё равно сжимается перед отправкой, поэтому
// можно больше, чем MAX_SIZE_MB (фото с айфона легко весят 10+ МБ)
export const MAX_SOURCE_SIZE_MB = 30;
export const ACCEPT = "image/jpeg,image/png,image/webp";
/**
* Генератор уникального id для превью изображения.
* crypto.randomUUID доступен во всех современных браузерах;
* для страховки — fallback на timestamp + random.
*/
function generateImageId() {
if (typeof crypto !== "undefined" && crypto.randomUUID) {
return `img-${crypto.randomUUID()}`;
}
return `img-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export function useImageUpload(existingUrls = []) {
const { t } = useTranslation();
const [images, setImages] = useState([]);
const [imgError, setImgError] = useState("");
const [compressing, setCompressing] = useState(false);
const fileInputRef = useRef(null);
const existingUrlList = Array.isArray(existingUrls) ? existingUrls : [];
const existingUrlsKey = existingUrlList.join("\u0000");
// Синхронизируем существующие изображения при изменениях извне (например,
// когда свежие данные профиля подтягиваются с бэка уже после монтирования).
// Не перезаписываем стейт, если пользователь успел выбрать новые файлы.
const hasUserSelected = images.some(img => !img.isExisting);
useEffect(() => {
if (existingUrlList.length > 0 && !hasUserSelected) {
setImages(existingUrlList.map((url, i) => ({
id: `existing-${i}`,
file: null,
preview: getImageUrl(url),
isExisting: true,
serverUrl: url,
})));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [existingUrlsKey, hasUserSelected]);
const handleFileChange = useCallback(async (e) => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setImgError("");
for (const file of files) {
if (!file.type.startsWith("image/")) {
setImgError(t('imageUpload.invalidType'));
return;
}
if (file.size > MAX_SOURCE_SIZE_MB * 1024 * 1024) {
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SOURCE_SIZE_MB }));
return;
}
}
setCompressing(true);
try {
// По одному, а не Promise.all: декодирование нескольких 12-мегапиксельных
// фото разом может не уместиться в память на телефоне
const compressedFiles = [];
for (const f of files) {
compressedFiles.push(await compressImage(f));
}
if (compressedFiles.some(f => f.size > MAX_SIZE_MB * 1024 * 1024)) {
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SIZE_MB }));
return;
}
const newImages = compressedFiles.map(file => ({
id: generateImageId(),
file,
preview: URL.createObjectURL(file),
isExisting: false,
serverUrl: null,
}));
setImages(prev => [...prev, ...newImages]);
} catch {
setImgError(t('imageUpload.processingFailed'));
} finally {
setCompressing(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}, [t]);
const removeImage = useCallback((id) => {
setImages(prev => {
const img = prev.find(i => i.id === id);
if (img && !img.isExisting && img.preview) {
URL.revokeObjectURL(img.preview);
}
return prev.filter(i => i.id !== id);
});
}, []);
const getFilesForUpload = useCallback(() => {
return images.filter(i => !i.isExisting).map(i => i.file);
}, [images]);
const getExistingUrlsToKeep = useCallback(() => {
return images.filter(i => i.isExisting).map(i => i.serverUrl);
}, [images]);
// Ref нужен, чтобы cleanup при размонтировании видел АКТУАЛЬНЫЙ список
// изображений, а не тот, что был на момент первого рендера (иначе
// object URL'ы для реально загруженных файлов никогда не отзываются).
const imagesRef = useRef(images);
useEffect(() => {
imagesRef.current = images;
}, [images]);
useEffect(() => {
return () => {
imagesRef.current.forEach(img => {
if (!img.isExisting && img.preview) {
URL.revokeObjectURL(img.preview);
}
});
};
}, []);
return {
images,
imgError,
compressing,
fileInputRef,
handleFileChange,
removeImage,
getFilesForUpload,
getExistingUrlsToKeep,
};
}