Desktop: drag and drop photos into the post form

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-26 22:51:53 +03:00
parent a657bd0762
commit c0aaed7d28
6 changed files with 153 additions and 7 deletions

View File

@@ -50,13 +50,19 @@ export function useImageUpload(existingUrls = []) {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [existingUrlsKey, hasUserSelected]); }, [existingUrlsKey, hasUserSelected]);
const handleFileChange = useCallback(async (e) => { /**
const files = Array.from(e.target.files || []); * Добавляет файлы к списку: проверка типа и размера, сжатие, превью.
* Общая точка для выбора через <input type="file"> и перетаскивания (drop).
*/
const addFiles = useCallback(async (fileList) => {
const files = Array.from(fileList || []);
if (!files.length) return; if (!files.length) return;
setImgError(""); setImgError("");
for (const file of files) { for (const file of files) {
if (!file.type.startsWith("image/")) { // Сверяем с ACCEPT, а не с "image/*": у <input> тип отсекает окно выбора,
// а при перетаскивании может прилететь что угодно (GIF, HEIC, SVG)
if (!ACCEPT.split(",").includes(file.type)) {
setImgError(t('imageUpload.invalidType')); setImgError(t('imageUpload.invalidType'));
return; return;
} }
@@ -94,6 +100,8 @@ export function useImageUpload(existingUrls = []) {
} }
}, [t]); }, [t]);
const handleFileChange = useCallback((e) => addFiles(e.target.files), [addFiles]);
const removeImage = useCallback((id) => { const removeImage = useCallback((id) => {
setImages(prev => { setImages(prev => {
const img = prev.find(i => i.id === id); const img = prev.find(i => i.id === id);
@@ -136,6 +144,7 @@ export function useImageUpload(existingUrls = []) {
compressing, compressing,
fileInputRef, fileInputRef,
handleFileChange, handleFileChange,
addFiles,
removeImage, removeImage,
getFilesForUpload, getFilesForUpload,
getExistingUrlsToKeep, getExistingUrlsToKeep,

View File

@@ -100,6 +100,8 @@
"processing": "Processing...", "processing": "Processing...",
"addMore": "➕ Add more", "addMore": "➕ Add more",
"addPhoto": "📷 Add photo", "addPhoto": "📷 Add photo",
"dropHint": "or drag photos here",
"dropRelease": "Drop to add photos",
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB · multiple allowed", "photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB · multiple allowed",
"categoryLabel": "Category", "categoryLabel": "Category",
"mapLabel": "Location on map", "mapLabel": "Location on map",

View File

@@ -100,6 +100,8 @@
"processing": "Обработка...", "processing": "Обработка...",
"addMore": "➕ Добавить ещё", "addMore": "➕ Добавить ещё",
"addPhoto": "📷 Добавить фото", "addPhoto": "📷 Добавить фото",
"dropHint": "или перетащите фото сюда",
"dropRelease": "Отпустите, чтобы добавить фото",
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ · можно несколько", "photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ · можно несколько",
"categoryLabel": "Категория", "categoryLabel": "Категория",
"mapLabel": "Место на карте", "mapLabel": "Место на карте",

View File

@@ -1,4 +1,4 @@
import { useCallback, useState } from "react"; import { useCallback, useRef, useState } from "react";
import CloseIcon from "../components/icons/CloseIcon"; import CloseIcon from "../components/icons/CloseIcon";
import RulesModal from "./RulesModal"; import RulesModal from "./RulesModal";
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants"; import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
@@ -60,11 +60,53 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
compressing, compressing,
fileInputRef, fileInputRef,
handleFileChange, handleFileChange,
addFiles,
removeImage, removeImage,
getFilesForUpload, getFilesForUpload,
getExistingUrlsToKeep, getExistingUrlsToKeep,
} = useImageUpload(isEdit ? initialData.images : []); } = 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 { save, loading: saving, error: apiError } = usePostMutation({ adminMode });
const [resultModal, setResultModal] = useState(null); // null | "success" | "blocked" 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()} onClick={e => !isDesktop && e.target === e.currentTarget && !loading && onClose()}
{...blockStrayDrop}
> >
<div className="f-modal"> <div className="f-modal">
@@ -228,8 +271,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
{errors.description && <p className="f-err-msg">{errors.description}</p>} {errors.description && <p className="f-err-msg">{errors.description}</p>}
</div> </div>
{/* Фотографии */} {/* Фотографии: на десктопе вся группа — зона для перетаскивания */}
<div className="f-m-group"> <div
className={`f-m-group${isDesktop ? " f-img-drop-zone" : ""}${dragOver ? " is-dragover" : ""}`}
{...dropZoneHandlers}
>
<label className="f-m-label">{t('post.photosLabel')}</label> <label className="f-m-label">{t('post.photosLabel')}</label>
{uploadedImages.length > 0 && ( {uploadedImages.length > 0 && (
@@ -262,8 +308,13 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
/> />
{compressing ? ( {compressing ? (
<span>{t('post.processing')}</span> <span>{t('post.processing')}</span>
) : dragOver ? (
<span>{t('post.dropRelease')}</span>
) : ( ) : (
<span>{uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}</span> <span className="f-img-upload-text">
<span>{uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}</span>
{isDesktop && <span className="f-img-upload-sub">{t('post.dropHint')}</span>}
</span>
)} )}
</label> </label>

View File

@@ -1,16 +1,33 @@
/** /**
* На десктопе форма объявления закрывается только крестиком: клик по фону * На десктопе форма объявления закрывается только крестиком: клик по фону
* не должен терять заполненные поля. На мобильном клик по фону закрывает. * не должен терять заполненные поля. На мобильном клик по фону закрывает.
* Там же на десктопе фото можно перетащить в форму (drag & drop).
*/ */
import { render, screen, fireEvent } from "@testing-library/react"; import { render, screen, fireEvent } from "@testing-library/react";
import CreateUpdatePost from "./CreateUpdatePost"; import CreateUpdatePost from "./CreateUpdatePost";
import { useIsDesktop } from "../hooks/useIsDesktop"; import { useIsDesktop } from "../hooks/useIsDesktop";
import { compressImage } from "../utils/compressImage";
import "../i18n"; import "../i18n";
jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() })); jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
jest.mock("../hooks/usePostMutation", () => ({ jest.mock("../hooks/usePostMutation", () => ({
usePostMutation: () => ({ save: jest.fn(), loading: false, error: null }), 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() { function renderForm() {
const onClose = jest.fn(); const onClose = jest.fn();
@@ -56,3 +73,46 @@ test("клик внутри окна не закрывает форму", () =>
expect(onClose).not.toHaveBeenCalled(); 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();
});

View File

@@ -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-upload-label:hover { border-color: var(--teal); background: rgba(var(--teal-rgb), .05); color: var(--teal); }
.f-img-input { display: none; } .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 */ /* Profile Photo Preview */
.f-img-preview-wrap { .f-img-preview-wrap {