Merge pull request #121 from SlimusMinus/feat-profile_photo_dragdrop
All checks were successful
deploy-frontend / deploy (push) Successful in 47s

Desktop: drag and drop profile photo; share drop-zone hook with post …
This commit is contained in:
SlimusMinus
2026-10-26 23:29:58 +03:00
committed by GitHub
9 changed files with 209 additions and 45 deletions

View File

@@ -24,15 +24,24 @@ function ImageUpload({
fileInputRef,
onFileChange,
onRemove,
// Перетаскивание фото (десктоп): обработчики зоны и «файл над зоной».
// Пустые props — перетаскивание выключено (мобильная раскладка).
dropZoneProps = {},
dragOver = false,
}) {
const { t } = useTranslation();
const dropEnabled = Object.keys(dropZoneProps).length > 0;
return (
<div className="f-m-group">
<div
className={`f-m-group${dropEnabled ? " f-img-drop-zone" : ""}${dragOver ? " is-dragover" : ""}`}
{...dropZoneProps}
>
<label className="f-m-label">{t('profile.photoLabel')}</label>
{displayImage ? (
<div className="f-img-preview-wrap">
<img src={displayImage} alt="profile" className="f-img-preview" />
{dragOver && <span className="f-img-drop-overlay">{t('profile.dropReplace')}</span>}
<button
className="f-img-remove"
onClick={onRemove}
@@ -52,7 +61,16 @@ function ImageUpload({
className="f-img-input"
disabled={compressing}
/>
{compressing ? <span>{t('profile.processing')}</span> : <span>{t('profile.addPhoto')}</span>}
{compressing ? (
<span>{t('profile.processing')}</span>
) : dragOver ? (
<span>{t('profile.dropRelease')}</span>
) : (
<span className="f-img-upload-text">
<span>{t('profile.addPhoto')}</span>
{dropEnabled && <span className="f-img-upload-sub">{t('profile.dropHint')}</span>}
</span>
)}
</label>
)}
{imgError && <p className="f-err-msg">{imgError}</p>}

View File

@@ -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 = {} }) {
<div
className="f-modal-bg"
onClick={e => e.target === e.currentTarget && !saving && onClose()}
{...strayDropProps}
>
<form
className="f-modal"
@@ -102,6 +115,8 @@ export default function ProfileModal({ onClose, initialData = {} }) {
fileInputRef={fileInputRef}
onFileChange={handleFileChange}
onRemove={handleRemoveImage}
dropZoneProps={zoneProps}
dragOver={dragOver}
/>
<LoginField

View File

@@ -0,0 +1,78 @@
/**
* Фото профиля на десктопе можно перетащить в окно (drag & drop).
* Аватар один: перетащенный файл заменяет текущее фото.
*/
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import ProfileModal from "./ProfileModal";
import { useIsDesktop } from "../../hooks/useIsDesktop";
import { compressImage } from "../../utils/compressImage";
import { useAuthContext } from "../../context/AuthContext";
import "../../i18n";
jest.mock("../../hooks/useIsDesktop", () => ({ 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(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
fireEvent.drop(photoLabel(), fileDrag([photo()]));
expect((await screen.findByAltText("profile")).getAttribute("src")).toBe("blob:preview-1");
});
test("на десктопе перетаскивание заменяет текущее фото", async () => {
useIsDesktop.mockReturnValue(true);
render(<ProfileModal onClose={jest.fn()} initialData={{ ...PROFILE, avatar: "old.jpg" }} />);
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(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
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(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
fireEvent.drop(photoLabel(), fileDrag([photo()]));
expect(compressImage).not.toHaveBeenCalled();
expect(screen.queryByText(/или перетащите фото сюда|or drag a photo here/)).toBeNull();
});

View File

@@ -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 };
}

View File

@@ -53,8 +53,12 @@ export function useImageUpload(existingUrls = []) {
/**
* Добавляет файлы к списку: проверка типа и размера, сжатие, превью.
* Общая точка для выбора через <input type="file"> и перетаскивания (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 {

View File

@@ -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",

View File

@@ -440,6 +440,9 @@
"deletePhoto": "Удалить фото",
"processing": "Обработка...",
"addPhoto": "📷 Добавить фото",
"dropHint": "или перетащите фото сюда",
"dropRelease": "Отпустите, чтобы добавить фото",
"dropReplace": "Отпустите, чтобы заменить фото",
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ",
"loginLabel": "Логин",
"nameLabel": "Имя",

View File

@@ -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 });

View File

@@ -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 {