diff --git a/src/hooks/useImageUpload.js b/src/hooks/useImageUpload.js
index 35f22f3..45d4b01 100644
--- a/src/hooks/useImageUpload.js
+++ b/src/hooks/useImageUpload.js
@@ -50,13 +50,19 @@ export function useImageUpload(existingUrls = []) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [existingUrlsKey, hasUserSelected]);
- const handleFileChange = useCallback(async (e) => {
- const files = Array.from(e.target.files || []);
+ /**
+ * Добавляет файлы к списку: проверка типа и размера, сжатие, превью.
+ * Общая точка для выбора через и перетаскивания (drop).
+ */
+ const addFiles = useCallback(async (fileList) => {
+ const files = Array.from(fileList || []);
if (!files.length) return;
setImgError("");
for (const file of files) {
- if (!file.type.startsWith("image/")) {
+ // Сверяем с ACCEPT, а не с "image/*": у тип отсекает окно выбора,
+ // а при перетаскивании может прилететь что угодно (GIF, HEIC, SVG)
+ if (!ACCEPT.split(",").includes(file.type)) {
setImgError(t('imageUpload.invalidType'));
return;
}
@@ -94,6 +100,8 @@ export function useImageUpload(existingUrls = []) {
}
}, [t]);
+ const handleFileChange = useCallback((e) => addFiles(e.target.files), [addFiles]);
+
const removeImage = useCallback((id) => {
setImages(prev => {
const img = prev.find(i => i.id === id);
@@ -136,6 +144,7 @@ export function useImageUpload(existingUrls = []) {
compressing,
fileInputRef,
handleFileChange,
+ addFiles,
removeImage,
getFilesForUpload,
getExistingUrlsToKeep,
diff --git a/src/locales/en.json b/src/locales/en.json
index ba22939..1d89e97 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -100,6 +100,8 @@
"processing": "Processing...",
"addMore": "➕ Add more",
"addPhoto": "📷 Add photo",
+ "dropHint": "or drag photos here",
+ "dropRelease": "Drop to add photos",
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB · multiple allowed",
"categoryLabel": "Category",
"mapLabel": "Location on map",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index d6cd5ec..ad82e8f 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -100,6 +100,8 @@
"processing": "Обработка...",
"addMore": "➕ Добавить ещё",
"addPhoto": "📷 Добавить фото",
+ "dropHint": "или перетащите фото сюда",
+ "dropRelease": "Отпустите, чтобы добавить фото",
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ · можно несколько",
"categoryLabel": "Категория",
"mapLabel": "Место на карте",
diff --git a/src/pages/CreateUpdatePost.jsx b/src/pages/CreateUpdatePost.jsx
index ee6cf69..4803e22 100644
--- a/src/pages/CreateUpdatePost.jsx
+++ b/src/pages/CreateUpdatePost.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useState } from "react";
+import { useCallback, useRef, useState } from "react";
import CloseIcon from "../components/icons/CloseIcon";
import RulesModal from "./RulesModal";
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
@@ -60,11 +60,53 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
compressing,
fileInputRef,
handleFileChange,
+ addFiles,
removeImage,
getFilesForUpload,
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(); },
+ } : {};
+
const { save, loading: saving, error: apiError } = usePostMutation({ adminMode });
const [resultModal, setResultModal] = useState(null); // null | "success" | "blocked"
@@ -160,6 +202,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
// На десктопе форма закрывается только крестиком: случайный клик мимо
// окна не должен терять заполненные поля
onClick={e => !isDesktop && e.target === e.currentTarget && !loading && onClose()}
+ {...blockStrayDrop}
>
@@ -228,8 +271,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
{errors.description &&
{errors.description}
}
- {/* Фотографии */}
-
+ {/* Фотографии: на десктопе вся группа — зона для перетаскивания */}
+
{uploadedImages.length > 0 && (
@@ -262,8 +308,13 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
/>
{compressing ? (
{t('post.processing')}
+ ) : dragOver ? (
+ {t('post.dropRelease')}
) : (
- {uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}
+
+ {uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}
+ {isDesktop && {t('post.dropHint')}}
+
)}
diff --git a/src/pages/CreateUpdatePost.test.jsx b/src/pages/CreateUpdatePost.test.jsx
index e652609..dd9c4e2 100644
--- a/src/pages/CreateUpdatePost.test.jsx
+++ b/src/pages/CreateUpdatePost.test.jsx
@@ -1,16 +1,33 @@
/**
* На десктопе форма объявления закрывается только крестиком: клик по фону
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
+ * Там же на десктопе фото можно перетащить в форму (drag & drop).
*/
import { render, screen, fireEvent } from "@testing-library/react";
import CreateUpdatePost from "./CreateUpdatePost";
import { useIsDesktop } from "../hooks/useIsDesktop";
+import { compressImage } from "../utils/compressImage";
import "../i18n";
jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
jest.mock("../hooks/usePostMutation", () => ({
usePostMutation: () => ({ save: jest.fn(), loading: false, error: null }),
}));
+// Сжатие через canvas в jsdom не работает и тут не проверяется
+jest.mock("../utils/compressImage", () => ({ compressImage: jest.fn() }));
+
+// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
+beforeEach(() => {
+ compressImage.mockImplementation((file) => Promise.resolve(file));
+ URL.createObjectURL = jest.fn(() => "blob:preview");
+ URL.revokeObjectURL = jest.fn();
+});
+
+const ADD_PHOTO = /Добавить фото|Add photo/;
+
+function fileDrag(files) {
+ return { dataTransfer: { files, types: ["Files"], dropEffect: "none" } };
+}
function renderForm() {
const onClose = jest.fn();
@@ -56,3 +73,46 @@ test("клик внутри окна не закрывает форму", () =>
expect(onClose).not.toHaveBeenCalled();
});
+
+test("на десктопе перетащенное фото добавляется в форму", async () => {
+ useIsDesktop.mockReturnValue(true);
+ renderForm();
+ const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
+
+ fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
+
+ // После добавления первого фото кнопка становится «Добавить ещё»
+ expect(await screen.findByText(/Добавить ещё|Add more/)).toBeTruthy();
+ expect(compressImage).toHaveBeenCalledWith(photo);
+});
+
+test("на десктопе файл над зоной подсвечивает её подсказкой", () => {
+ useIsDesktop.mockReturnValue(true);
+ renderForm();
+
+ fireEvent.dragEnter(screen.getByText(ADD_PHOTO), fileDrag([]));
+
+ expect(screen.getByText(/Отпустите, чтобы добавить фото|Drop to add photos/)).toBeTruthy();
+});
+
+test("перетащенный файл неподходящего типа не добавляется", async () => {
+ useIsDesktop.mockReturnValue(true);
+ renderForm();
+ const gif = new File(["x"], "anim.gif", { type: "image/gif" });
+
+ fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([gif]));
+
+ expect(await screen.findByText(/Только изображения|Images only/)).toBeTruthy();
+ expect(compressImage).not.toHaveBeenCalled();
+});
+
+test("на мобильном перетаскивание фото выключено", () => {
+ useIsDesktop.mockReturnValue(false);
+ renderForm();
+ const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
+
+ fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
+
+ expect(compressImage).not.toHaveBeenCalled();
+ expect(screen.queryByText(/или перетащите фото сюда|or drag photos here/)).toBeNull();
+});
diff --git a/src/styles/modal.css b/src/styles/modal.css
index ad7920c..31f414d 100644
--- a/src/styles/modal.css
+++ b/src/styles/modal.css
@@ -103,6 +103,28 @@ select.f-m-field::selection { background: transparent; }
}
.f-img-upload-label:hover { border-color: var(--teal); background: rgba(var(--teal-rgb), .05); color: var(--teal); }
.f-img-input { display: none; }
+.f-img-upload-text {
+ display: flex; flex-direction: column; align-items: center; gap: 4px;
+ text-align: center;
+}
+.f-img-upload-sub { font-size: .75rem; opacity: .8; }
+
+/* Перетаскивание фото (десктоп): над зоной файл — пунктир окрашивается,
+ поле подсвечивается и чуть «приподнимается», превью приглушаются,
+ чтобы взгляд шёл на место, куда отпустить файл. */
+.f-img-drop-zone .f-img-upload-label {
+ transition: border-color .2s, background .2s, color .2s, transform .2s, box-shadow .2s;
+}
+.f-img-drop-zone.is-dragover .f-img-upload-label {
+ border-color: var(--teal);
+ border-style: solid;
+ background: rgba(var(--teal-rgb), .1);
+ color: var(--teal);
+ font-weight: 600;
+ transform: scale(1.02);
+ 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; }
/* Profile Photo Preview */
.f-img-preview-wrap {