Compare commits
8 Commits
a657bd0762
...
113355c0ef
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
113355c0ef | ||
|
|
16b886081b | ||
|
|
abd6f83535 | ||
|
|
a2706944bd | ||
|
|
532b5b45f3 | ||
|
|
bb8f3263f8 | ||
|
|
a8a0292535 | ||
|
|
c0aaed7d28 |
@@ -24,15 +24,24 @@ function ImageUpload({
|
|||||||
fileInputRef,
|
fileInputRef,
|
||||||
onFileChange,
|
onFileChange,
|
||||||
onRemove,
|
onRemove,
|
||||||
|
// Перетаскивание фото (десктоп): обработчики зоны и «файл над зоной».
|
||||||
|
// Пустые props — перетаскивание выключено (мобильная раскладка).
|
||||||
|
dropZoneProps = {},
|
||||||
|
dragOver = false,
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const dropEnabled = Object.keys(dropZoneProps).length > 0;
|
||||||
|
|
||||||
return (
|
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>
|
<label className="f-m-label">{t('profile.photoLabel')}</label>
|
||||||
{displayImage ? (
|
{displayImage ? (
|
||||||
<div className="f-img-preview-wrap">
|
<div className="f-img-preview-wrap">
|
||||||
<img src={displayImage} alt="profile" className="f-img-preview" />
|
<img src={displayImage} alt="profile" className="f-img-preview" />
|
||||||
|
{dragOver && <span className="f-img-drop-overlay">{t('profile.dropReplace')}</span>}
|
||||||
<button
|
<button
|
||||||
className="f-img-remove"
|
className="f-img-remove"
|
||||||
onClick={onRemove}
|
onClick={onRemove}
|
||||||
@@ -52,7 +61,16 @@ function ImageUpload({
|
|||||||
className="f-img-input"
|
className="f-img-input"
|
||||||
disabled={compressing}
|
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>
|
</label>
|
||||||
)}
|
)}
|
||||||
{imgError && <p className="f-err-msg">{imgError}</p>}
|
{imgError && <p className="f-err-msg">{imgError}</p>}
|
||||||
@@ -99,10 +117,11 @@ function NameFieldsRow({ form, errors, onChange }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ─── Contact fields ─────────────────────────────────────────────────────────
|
// ─── Contact fields ─────────────────────────────────────────────────────────
|
||||||
function ContactFields({ form, errors, onChange, onPhoneChange }) {
|
// Email в окне профиля не показываем: он не редактируется здесь, но остаётся
|
||||||
|
// в состоянии формы и уходит при сохранении без изменений.
|
||||||
|
function ContactFields({ form, errors, onPhoneChange }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<InputField
|
<InputField
|
||||||
label={t('profile.phoneLabel')}
|
label={t('profile.phoneLabel')}
|
||||||
type="tel"
|
type="tel"
|
||||||
@@ -111,15 +130,6 @@ function ContactFields({ form, errors, onChange, onPhoneChange }) {
|
|||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
onChange={(e) => onPhoneChange(e.target.value)}
|
onChange={(e) => onPhoneChange(e.target.value)}
|
||||||
/>
|
/>
|
||||||
<InputField
|
|
||||||
label={t('profile.emailLabel')}
|
|
||||||
type="email"
|
|
||||||
placeholder="example@email.com"
|
|
||||||
value={form.email}
|
|
||||||
error={errors.email}
|
|
||||||
onChange={(e) => onChange("email", e.target.value)}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { formatPhone } from "../../utils/formatPhone";
|
|||||||
import { useImageUpload } from "../../hooks/useImageUpload";
|
import { useImageUpload } from "../../hooks/useImageUpload";
|
||||||
import { useUpdateProfile } from "../../hooks/useUpdateProfile";
|
import { useUpdateProfile } from "../../hooks/useUpdateProfile";
|
||||||
import { useAuthContext } from "../../context/AuthContext";
|
import { useAuthContext } from "../../context/AuthContext";
|
||||||
|
import { useIsDesktop } from "../../hooks/useIsDesktop";
|
||||||
|
import { useFileDropZone } from "../../hooks/useFileDropZone";
|
||||||
import { validateProfileForm, initializeFormState } from "./profileValidation";
|
import { validateProfileForm, initializeFormState } from "./profileValidation";
|
||||||
import {
|
import {
|
||||||
ImageUpload,
|
ImageUpload,
|
||||||
@@ -30,11 +32,21 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
|||||||
compressing,
|
compressing,
|
||||||
fileInputRef,
|
fileInputRef,
|
||||||
handleFileChange,
|
handleFileChange,
|
||||||
|
addFiles,
|
||||||
removeImage,
|
removeImage,
|
||||||
getExistingUrlsToKeep,
|
getExistingUrlsToKeep,
|
||||||
getFilesForUpload,
|
getFilesForUpload,
|
||||||
} = useImageUpload(existingImages);
|
} = 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 currentImage = images[0];
|
||||||
const displayImage = currentImage?.preview ?? null;
|
const displayImage = currentImage?.preview ?? null;
|
||||||
|
|
||||||
@@ -88,6 +100,7 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
|||||||
<div
|
<div
|
||||||
className="f-modal-bg"
|
className="f-modal-bg"
|
||||||
onClick={e => e.target === e.currentTarget && !saving && onClose()}
|
onClick={e => e.target === e.currentTarget && !saving && onClose()}
|
||||||
|
{...strayDropProps}
|
||||||
>
|
>
|
||||||
<form
|
<form
|
||||||
className="f-modal"
|
className="f-modal"
|
||||||
@@ -102,6 +115,8 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
|||||||
fileInputRef={fileInputRef}
|
fileInputRef={fileInputRef}
|
||||||
onFileChange={handleFileChange}
|
onFileChange={handleFileChange}
|
||||||
onRemove={handleRemoveImage}
|
onRemove={handleRemoveImage}
|
||||||
|
dropZoneProps={zoneProps}
|
||||||
|
dragOver={dragOver}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<LoginField
|
<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();
|
||||||
|
});
|
||||||
@@ -12,10 +12,6 @@ export function validateProfileForm(form) {
|
|||||||
errors.lastName = i18n.t('profile.validateSurnameRequired');
|
errors.lastName = i18n.t('profile.validateSurnameRequired');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (form.email && !form.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
|
|
||||||
errors.email = i18n.t('profile.validateEmailInvalid');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (form.phone && form.phone.replace(/\D/g, "").length < 11) {
|
if (form.phone && form.phone.replace(/\D/g, "").length < 11) {
|
||||||
errors.phone = i18n.t('profile.validatePhoneInvalid');
|
errors.phone = i18n.t('profile.validatePhoneInvalid');
|
||||||
}
|
}
|
||||||
|
|||||||
58
src/hooks/useFileDropZone.js
Normal file
58
src/hooks/useFileDropZone.js
Normal 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 };
|
||||||
|
}
|
||||||
@@ -50,13 +50,23 @@ 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).
|
||||||
|
*
|
||||||
|
* replace — заменить текущие фото вместо добавления (одиночный аватар).
|
||||||
|
* Старые фото снимаются только после успешной обработки новых: при ошибке
|
||||||
|
* пользователь остаётся с прежним фото.
|
||||||
|
*/
|
||||||
|
const addFiles = useCallback(async (fileList, { replace = false } = {}) => {
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
@@ -85,7 +95,13 @@ export function useImageUpload(existingUrls = []) {
|
|||||||
isExisting: false,
|
isExisting: false,
|
||||||
serverUrl: null,
|
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 {
|
} catch {
|
||||||
setImgError(t('imageUpload.processingFailed'));
|
setImgError(t('imageUpload.processingFailed'));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -94,6 +110,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 +154,7 @@ export function useImageUpload(existingUrls = []) {
|
|||||||
compressing,
|
compressing,
|
||||||
fileInputRef,
|
fileInputRef,
|
||||||
handleFileChange,
|
handleFileChange,
|
||||||
|
addFiles,
|
||||||
removeImage,
|
removeImage,
|
||||||
getFilesForUpload,
|
getFilesForUpload,
|
||||||
getExistingUrlsToKeep,
|
getExistingUrlsToKeep,
|
||||||
|
|||||||
@@ -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",
|
||||||
@@ -438,6 +440,9 @@
|
|||||||
"deletePhoto": "Delete photo",
|
"deletePhoto": "Delete photo",
|
||||||
"processing": "Processing...",
|
"processing": "Processing...",
|
||||||
"addPhoto": "📷 Add photo",
|
"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",
|
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB",
|
||||||
"loginLabel": "Login",
|
"loginLabel": "Login",
|
||||||
"nameLabel": "First name",
|
"nameLabel": "First name",
|
||||||
|
|||||||
@@ -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": "Место на карте",
|
||||||
@@ -438,6 +440,9 @@
|
|||||||
"deletePhoto": "Удалить фото",
|
"deletePhoto": "Удалить фото",
|
||||||
"processing": "Обработка...",
|
"processing": "Обработка...",
|
||||||
"addPhoto": "📷 Добавить фото",
|
"addPhoto": "📷 Добавить фото",
|
||||||
|
"dropHint": "или перетащите фото сюда",
|
||||||
|
"dropRelease": "Отпустите, чтобы добавить фото",
|
||||||
|
"dropReplace": "Отпустите, чтобы заменить фото",
|
||||||
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ",
|
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ",
|
||||||
"loginLabel": "Логин",
|
"loginLabel": "Логин",
|
||||||
"nameLabel": "Имя",
|
"nameLabel": "Имя",
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import MapModal from "./MapModal";
|
|||||||
import ClearableField from "../components/ClearableField";
|
import ClearableField from "../components/ClearableField";
|
||||||
import AddressAutocomplete from "../components/AddressAutocomplete";
|
import AddressAutocomplete from "../components/AddressAutocomplete";
|
||||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||||
|
import { useFileDropZone } from "../hooks/useFileDropZone";
|
||||||
|
import { useAuthContext } from "../context/AuthContext";
|
||||||
|
|
||||||
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
|
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
|
||||||
const TITLE_MAX_LENGTH = 255;
|
const TITLE_MAX_LENGTH = 255;
|
||||||
@@ -30,8 +32,12 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
|||||||
const isEdit = !!initialData;
|
const isEdit = !!initialData;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const isDesktop = useIsDesktop();
|
const isDesktop = useIsDesktop();
|
||||||
|
const { user } = useAuthContext();
|
||||||
|
// Телефон из профиля подставляем, чтобы не вводить его в каждом объявлении.
|
||||||
|
// В админ-режиме правится чужое объявление — телефон админа туда не нужен.
|
||||||
|
const profilePhone = !adminMode && user?.phone ? formatPhone(user.phone) : "";
|
||||||
|
|
||||||
const [form, setForm] = useState(
|
const [form, setForm] = useState(() => (
|
||||||
isEdit
|
isEdit
|
||||||
? {
|
? {
|
||||||
type: (initialData.type || "loss").toLowerCase(),
|
type: (initialData.type || "loss").toLowerCase(),
|
||||||
@@ -39,15 +45,15 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
|||||||
description: initialData.description || "",
|
description: initialData.description || "",
|
||||||
category: initialData.category || "",
|
category: initialData.category || "",
|
||||||
date: initialData.date || "",
|
date: initialData.date || "",
|
||||||
phone: initialData.phone || "",
|
phone: initialData.phone || profilePhone,
|
||||||
address: initialData.address || initialData.city || "",
|
address: initialData.address || initialData.city || "",
|
||||||
rulesAccepted: true,
|
rulesAccepted: true,
|
||||||
reward: initialData.reward ?? false,
|
reward: initialData.reward ?? false,
|
||||||
rewardText: initialData.rewardText
|
rewardText: initialData.rewardText
|
||||||
|| (initialData.reward ? t('post.rewardDefault') : "")
|
|| (initialData.reward ? t('post.rewardDefault') : "")
|
||||||
}
|
}
|
||||||
: EMPTY_FORM
|
: { ...EMPTY_FORM, phone: profilePhone }
|
||||||
);
|
));
|
||||||
|
|
||||||
const [rulesModalOpen, setRulesModalOpen] = useState(false);
|
const [rulesModalOpen, setRulesModalOpen] = useState(false);
|
||||||
const [mapModalOpen, setMapModalOpen] = useState(false);
|
const [mapModalOpen, setMapModalOpen] = useState(false);
|
||||||
@@ -60,11 +66,19 @@ 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) — только на десктопе
|
||||||
|
const { dragOver, zoneProps: dropZoneHandlers, strayDropProps: blockStrayDrop } = useFileDropZone({
|
||||||
|
enabled: isDesktop,
|
||||||
|
busy: compressing,
|
||||||
|
onFiles: addFiles,
|
||||||
|
});
|
||||||
|
|
||||||
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 +174,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 +243,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 +280,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 className="f-img-upload-text">
|
||||||
<span>{uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}</span>
|
<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>
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,37 @@
|
|||||||
/**
|
/**
|
||||||
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
||||||
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
||||||
|
* Там же на десктопе фото можно перетащить в форму (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 { useAuthContext } from "../context/AuthContext";
|
||||||
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() }));
|
||||||
|
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||||||
|
|
||||||
|
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
||||||
|
beforeEach(() => {
|
||||||
|
compressImage.mockImplementation((file) => Promise.resolve(file));
|
||||||
|
useAuthContext.mockReturnValue({ user: null });
|
||||||
|
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 +77,96 @@ 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();
|
||||||
|
});
|
||||||
|
|
||||||
|
const PROFILE_PHONE = "+7 (999) 111-22-33";
|
||||||
|
|
||||||
|
/** Рендерит форму и переходит на второй шаг, где находится поле «Телефон». */
|
||||||
|
function openPhoneStep(props = {}) {
|
||||||
|
useIsDesktop.mockReturnValue(true);
|
||||||
|
render(<CreateUpdatePost onClose={jest.fn()} {...props} />);
|
||||||
|
if (!props.initialData) {
|
||||||
|
fireEvent.change(screen.getByPlaceholderText(/Кошелёк|wallet/i), { target: { value: "Ключи" } });
|
||||||
|
fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } });
|
||||||
|
}
|
||||||
|
fireEvent.click(screen.getByText(/^(Далее|Next)/));
|
||||||
|
return screen.getByPlaceholderText("+7 (___) ___-__-__");
|
||||||
|
}
|
||||||
|
|
||||||
|
test("новое объявление: телефон подставляется из профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||||||
|
|
||||||
|
expect(openPhoneStep().value).toBe(PROFILE_PHONE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("новое объявление без телефона в профиле: поле пустое", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: "" } });
|
||||||
|
|
||||||
|
expect(openPhoneStep().value).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" };
|
||||||
|
|
||||||
|
test("редактирование: телефон объявления не заменяется телефоном профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
const phone = openPhoneStep({ initialData: { ...POST, phone: "+7 (900) 000-00-00" } });
|
||||||
|
|
||||||
|
expect(phone.value).toBe("+7 (900) 000-00-00");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("редактирование объявления без телефона: подставляется телефон профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
expect(openPhoneStep({ initialData: { ...POST, phone: "" } }).value).toBe(PROFILE_PHONE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("админ правит чужое объявление: свой телефон не подставляется", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
const phone = openPhoneStep({ initialData: { ...POST, phone: "" }, adminMode: true });
|
||||||
|
|
||||||
|
expect(phone.value).toBe("");
|
||||||
|
});
|
||||||
|
|||||||
@@ -103,6 +103,40 @@ 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; }
|
||||||
|
/* Аватар уже есть: поверх превью — затемнение с подсказкой «заменить» */
|
||||||
|
.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 */
|
/* Profile Photo Preview */
|
||||||
.f-img-preview-wrap {
|
.f-img-preview-wrap {
|
||||||
|
|||||||
Reference in New Issue
Block a user