
+ {dragOver &&
{t('profile.dropReplace')}}
- {compressing ?
{t('profile.processing')} :
{t('profile.addPhoto')}}
+ {compressing ? (
+
{t('profile.processing')}
+ ) : dragOver ? (
+
{t('profile.dropRelease')}
+ ) : (
+
+ {t('profile.addPhoto')}
+ {dropEnabled && {t('profile.dropHint')}}
+
+ )}
)}
{imgError &&
{imgError}
}
diff --git a/src/components/profile/ProfileModal.jsx b/src/components/profile/ProfileModal.jsx
index db7f146..e16b315 100644
--- a/src/components/profile/ProfileModal.jsx
+++ b/src/components/profile/ProfileModal.jsx
@@ -4,6 +4,8 @@ import { formatPhone } from "../../utils/formatPhone";
import { useImageUpload } from "../../hooks/useImageUpload";
import { useUpdateProfile } from "../../hooks/useUpdateProfile";
import { useAuthContext } from "../../context/AuthContext";
+import { useIsDesktop } from "../../hooks/useIsDesktop";
+import { useFileDropZone } from "../../hooks/useFileDropZone";
import { validateProfileForm, initializeFormState } from "./profileValidation";
import {
ImageUpload,
@@ -30,11 +32,21 @@ export default function ProfileModal({ onClose, initialData = {} }) {
compressing,
fileInputRef,
handleFileChange,
+ addFiles,
removeImage,
getExistingUrlsToKeep,
getFilesForUpload,
} = useImageUpload(existingImages);
+ // Перетаскивание фото (только десктоп). Аватар один: перетащенный файл
+ // заменяет текущее фото, из нескольких берём первый.
+ const isDesktop = useIsDesktop();
+ const { dragOver, zoneProps, strayDropProps } = useFileDropZone({
+ enabled: isDesktop,
+ busy: compressing,
+ onFiles: files => addFiles(Array.from(files).slice(0, 1), { replace: true }),
+ });
+
const currentImage = images[0];
const displayImage = currentImage?.preview ?? null;
@@ -88,6 +100,7 @@ export default function ProfileModal({ onClose, initialData = {} }) {
e.target === e.currentTarget && !saving && onClose()}
+ {...strayDropProps}
>
({ useIsDesktop: jest.fn() }));
+jest.mock("../../hooks/useUpdateProfile", () => ({
+ useUpdateProfile: () => ({ updateProfile: jest.fn(), loading: false, error: null }),
+}));
+// Сжатие через canvas в jsdom не работает и тут не проверяется
+jest.mock("../../utils/compressImage", () => ({ compressImage: jest.fn() }));
+jest.mock("../../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
+
+const PROFILE = { login: "ivan", firstName: "Иван", lastName: "Петров", phone: "", email: "ivan@example.com" };
+
+// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
+beforeEach(() => {
+ compressImage.mockImplementation((file) => Promise.resolve(file));
+ useAuthContext.mockReturnValue({ user: { id: 1 }, updateUser: jest.fn(), logout: jest.fn() });
+ let n = 0;
+ URL.createObjectURL = jest.fn(() => `blob:preview-${++n}`);
+ URL.revokeObjectURL = jest.fn();
+});
+
+const photo = (name = "me.jpg") => new File(["x"], name, { type: "image/jpeg" });
+const fileDrag = (files) => ({ dataTransfer: { files, types: ["Files"], dropEffect: "none" } });
+const photoLabel = () => screen.getByText(/Фото профиля|Profile photo/);
+
+test("на десктопе перетащенное фото становится фото профиля", async () => {
+ useIsDesktop.mockReturnValue(true);
+ render();
+
+ fireEvent.drop(photoLabel(), fileDrag([photo()]));
+
+ expect((await screen.findByAltText("profile")).getAttribute("src")).toBe("blob:preview-1");
+});
+
+test("на десктопе перетаскивание заменяет текущее фото", async () => {
+ useIsDesktop.mockReturnValue(true);
+ render();
+
+ fireEvent.dragEnter(photoLabel(), fileDrag([]));
+ expect(screen.getByText(/Отпустите, чтобы заменить фото|Drop to replace the photo/)).toBeTruthy();
+
+ fireEvent.drop(photoLabel(), fileDrag([photo()]));
+
+ // Старое фото сразу на экране — ждём, пока превью сменится на новое
+ await waitFor(() => expect(screen.getByAltText("profile").getAttribute("src")).toBe("blob:preview-1"));
+ expect(screen.getAllByAltText("profile")).toHaveLength(1);
+});
+
+test("из нескольких перетащенных файлов берётся только первый", async () => {
+ useIsDesktop.mockReturnValue(true);
+ render();
+ const first = photo("first.jpg");
+
+ fireEvent.drop(photoLabel(), fileDrag([first, photo("second.jpg")]));
+
+ await screen.findByAltText("profile");
+ expect(compressImage).toHaveBeenCalledTimes(1);
+ expect(compressImage).toHaveBeenCalledWith(first);
+});
+
+test("на мобильном перетаскивание фото выключено", () => {
+ useIsDesktop.mockReturnValue(false);
+ render();
+
+ fireEvent.drop(photoLabel(), fileDrag([photo()]));
+
+ expect(compressImage).not.toHaveBeenCalled();
+ expect(screen.queryByText(/или перетащите фото сюда|or drag a photo here/)).toBeNull();
+});
diff --git a/src/hooks/useFileDropZone.js b/src/hooks/useFileDropZone.js
new file mode 100644
index 0000000..a6958ab
--- /dev/null
+++ b/src/hooks/useFileDropZone.js
@@ -0,0 +1,58 @@
+import { useRef, useState } from "react";
+
+const isFileDrag = (e) => Array.from(e.dataTransfer?.types || []).includes("Files");
+
+/**
+ * Зона для перетаскивания файлов (drag & drop).
+ *
+ * zoneProps вешаются на элемент-зону: подсветка (dragOver) и приём файлов
+ * в onFiles. strayDropProps — на всё окно: файл, отпущенный мимо зоны,
+ * браузер открыл бы вместо сайта, и введённые в форму данные пропали бы.
+ *
+ * dragenter/dragleave приходят и от дочерних элементов зоны, поэтому
+ * считаем глубину, иначе подсветка мигает при движении над содержимым.
+ *
+ * @param {{ enabled: boolean, busy?: boolean, onFiles: (files: FileList) => void }} options
+ * enabled — выключенная зона не вешает обработчики (мобильная раскладка);
+ * busy — файлы ещё обрабатываются: новый drop игнорируется.
+ */
+export function useFileDropZone({ enabled, busy = false, onFiles }) {
+ const [dragOver, setDragOver] = useState(false);
+ const depthRef = useRef(0);
+
+ if (!enabled) return { dragOver: false, zoneProps: {}, strayDropProps: {} };
+
+ const zoneProps = {
+ onDragEnter: (e) => {
+ if (!isFileDrag(e)) return;
+ e.preventDefault();
+ depthRef.current += 1;
+ setDragOver(true);
+ },
+ onDragOver: (e) => {
+ if (!isFileDrag(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = busy ? "none" : "copy";
+ },
+ onDragLeave: (e) => {
+ if (!isFileDrag(e)) return;
+ depthRef.current = Math.max(0, depthRef.current - 1);
+ if (depthRef.current === 0) setDragOver(false);
+ },
+ onDrop: (e) => {
+ if (!isFileDrag(e)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ depthRef.current = 0;
+ setDragOver(false);
+ if (!busy) onFiles(e.dataTransfer.files);
+ },
+ };
+
+ const strayDropProps = {
+ onDragOver: (e) => { if (isFileDrag(e)) e.preventDefault(); },
+ onDrop: (e) => { if (isFileDrag(e)) e.preventDefault(); },
+ };
+
+ return { dragOver, zoneProps, strayDropProps };
+}
diff --git a/src/hooks/useImageUpload.js b/src/hooks/useImageUpload.js
index 45d4b01..ed647c2 100644
--- a/src/hooks/useImageUpload.js
+++ b/src/hooks/useImageUpload.js
@@ -53,8 +53,12 @@ export function useImageUpload(existingUrls = []) {
/**
* Добавляет файлы к списку: проверка типа и размера, сжатие, превью.
* Общая точка для выбора через и перетаскивания (drop).
+ *
+ * replace — заменить текущие фото вместо добавления (одиночный аватар).
+ * Старые фото снимаются только после успешной обработки новых: при ошибке
+ * пользователь остаётся с прежним фото.
*/
- const addFiles = useCallback(async (fileList) => {
+ const addFiles = useCallback(async (fileList, { replace = false } = {}) => {
const files = Array.from(fileList || []);
if (!files.length) return;
setImgError("");
@@ -91,7 +95,13 @@ export function useImageUpload(existingUrls = []) {
isExisting: false,
serverUrl: null,
}));
- setImages(prev => [...prev, ...newImages]);
+ setImages(prev => {
+ if (!replace) return [...prev, ...newImages];
+ prev.forEach(img => {
+ if (!img.isExisting && img.preview) URL.revokeObjectURL(img.preview);
+ });
+ return newImages;
+ });
} catch {
setImgError(t('imageUpload.processingFailed'));
} finally {
diff --git a/src/locales/en.json b/src/locales/en.json
index 1d89e97..bf65f68 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -440,6 +440,9 @@
"deletePhoto": "Delete photo",
"processing": "Processing...",
"addPhoto": "📷 Add photo",
+ "dropHint": "or drag a photo here",
+ "dropRelease": "Drop to add the photo",
+ "dropReplace": "Drop to replace the photo",
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB",
"loginLabel": "Login",
"nameLabel": "First name",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index ad82e8f..301a9af 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -440,6 +440,9 @@
"deletePhoto": "Удалить фото",
"processing": "Обработка...",
"addPhoto": "📷 Добавить фото",
+ "dropHint": "или перетащите фото сюда",
+ "dropRelease": "Отпустите, чтобы добавить фото",
+ "dropReplace": "Отпустите, чтобы заменить фото",
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ",
"loginLabel": "Логин",
"nameLabel": "Имя",
diff --git a/src/pages/CreateUpdatePost.jsx b/src/pages/CreateUpdatePost.jsx
index 6411d53..03094a0 100644
--- a/src/pages/CreateUpdatePost.jsx
+++ b/src/pages/CreateUpdatePost.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useState } from "react";
import CloseIcon from "../components/icons/CloseIcon";
import RulesModal from "./RulesModal";
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
@@ -11,6 +11,7 @@ import MapModal from "./MapModal";
import ClearableField from "../components/ClearableField";
import AddressAutocomplete from "../components/AddressAutocomplete";
import { useIsDesktop } from "../hooks/useIsDesktop";
+import { useFileDropZone } from "../hooks/useFileDropZone";
import { useAuthContext } from "../context/AuthContext";
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
@@ -71,46 +72,12 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
getExistingUrlsToKeep,
} = useImageUpload(isEdit ? initialData.images : []);
- // Перетаскивание фото (drag & drop) — только на десктопе.
- // dragenter/dragleave приходят и от дочерних элементов зоны, поэтому
- // считаем глубину, иначе подсветка мигает при движении над превью.
- const [dragOver, setDragOver] = useState(false);
- const dragDepthRef = useRef(0);
- const isFileDrag = e => Array.from(e.dataTransfer?.types || []).includes("Files");
-
- const dropZoneHandlers = isDesktop ? {
- onDragEnter: e => {
- if (!isFileDrag(e)) return;
- e.preventDefault();
- dragDepthRef.current += 1;
- setDragOver(true);
- },
- onDragOver: e => {
- if (!isFileDrag(e)) return;
- e.preventDefault();
- e.dataTransfer.dropEffect = compressing ? "none" : "copy";
- },
- onDragLeave: e => {
- if (!isFileDrag(e)) return;
- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
- if (dragDepthRef.current === 0) setDragOver(false);
- },
- onDrop: e => {
- if (!isFileDrag(e)) return;
- e.preventDefault();
- e.stopPropagation();
- dragDepthRef.current = 0;
- setDragOver(false);
- if (!compressing) addFiles(e.dataTransfer.files);
- },
- } : {};
-
- // Файл, отпущенный мимо зоны, браузер открыл бы вместо сайта — гасим это
- // на всём окне формы, иначе введённые данные пропадут.
- const blockStrayDrop = isDesktop ? {
- onDragOver: e => { if (isFileDrag(e)) e.preventDefault(); },
- onDrop: e => { if (isFileDrag(e)) e.preventDefault(); },
- } : {};
+ // Перетаскивание фото (drag & drop) — только на десктопе
+ const { dragOver, zoneProps: dropZoneHandlers, strayDropProps: blockStrayDrop } = useFileDropZone({
+ enabled: isDesktop,
+ busy: compressing,
+ onFiles: addFiles,
+ });
const { save, loading: saving, error: apiError } = usePostMutation({ adminMode });
diff --git a/src/styles/modal.css b/src/styles/modal.css
index 31f414d..fd20385 100644
--- a/src/styles/modal.css
+++ b/src/styles/modal.css
@@ -125,6 +125,18 @@ select.f-m-field::selection { background: transparent; }
box-shadow: 0 0 0 4px rgba(var(--teal-rgb), .15);
}
.f-img-drop-zone.is-dragover .f-img-grid { opacity: .55; transition: opacity .2s; }
+/* Аватар уже есть: поверх превью — затемнение с подсказкой «заменить» */
+.f-img-drop-zone.is-dragover .f-img-preview-wrap {
+ box-shadow: 0 0 0 3px var(--teal), 0 0 0 7px rgba(var(--teal-rgb), .18);
+}
+.f-img-drop-overlay {
+ position: absolute; inset: 0; z-index: 1;
+ display: flex; align-items: center; justify-content: center;
+ padding: 8px; text-align: center;
+ background: rgba(0, 0, 0, .55);
+ color: #fff; font-size: .75rem; font-weight: 600; line-height: 1.3;
+ pointer-events: none;
+}
/* Profile Photo Preview */
.f-img-preview-wrap {