Desktop: drag and drop profile photo; share drop-zone hook with post form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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>}
|
||||
|
||||
@@ -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
|
||||
|
||||
78
src/components/profile/ProfileModal.test.jsx
Normal file
78
src/components/profile/ProfileModal.test.jsx
Normal 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();
|
||||
});
|
||||
Reference in New Issue
Block a user