Compare commits

..

2 Commits

Author SHA1 Message Date
SlimusMinus
93f00e2cb4 Merge pull request #82 from SlimusMinus/add-carousel
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
added carousel image on post on mainFeed
2026-10-09 01:21:47 +03:00
SlimusMinus
b924483231 added carousel image on post on mainFeed 2026-10-09 01:21:14 +03:00
12 changed files with 29 additions and 205 deletions

View File

@@ -170,7 +170,7 @@ src/
│ ├── admin/ PostsTab, AdvertisingCreate/EditModal, CampaignCreate/EditModal, ...
│ ├── landing/ Hero, Navbar, StepsSection, RadarBeacon, FinalCta, Footer, Icon
│ ├── icons/ NavIcons + Calendar/Close/Globe/Menu/Moon/Phone/Pin/Sun/Trash
│ └── … AuthModal, Toast, MapView, PostDetailModal, ImageViewer, AdCard, AdSlot, ...
│ └── … AuthModal, Toast, MapView, PostDetailModal, AdCard, AdSlot, ...
│
├── styles/
│ ├── index.css # Точка входа CSS

View File

@@ -1,142 +0,0 @@
import { useState, useCallback, useEffect, useRef, useMemo } from "react";
import { useTranslation } from 'react-i18next';
import CloseIcon from "./icons/CloseIcon";
import CheckIcon from "./icons/CheckIcon";
import Toast from "./Toast";
import { getImageUrl } from "../config/authConstants";
import { CATEGORY_PET } from "../config/feedConstants";
import { getFoundAt, formatFoundDate } from "../utils/foundAt";
import { useContactSeller } from "../hooks/useContactSeller";
import { useAuthContext } from "../context/AuthContext";
export default function ImageViewer({ images, initialIndex = 0, onClose, postData }) {
const { t, i18n } = useTranslation();
const [index, setIndex] = useState(initialIndex);
const touchStart = useRef(null);
const swiped = useRef(false);
const { isAuthenticated } = useAuthContext();
const { contactSeller, error: contactError, clearError } = useContactSeller(postData);
const urls = useMemo(() => images.map(u => getImageUrl(u)), [images]);
const next = useCallback(() => {
setIndex(i => (i + 1) % urls.length);
}, [urls.length]);
const prev = useCallback(() => {
setIndex(i => (i - 1 + urls.length) % urls.length);
}, [urls.length]);
const handleImgClick = useCallback(() => {
next();
}, [next]);
useEffect(() => {
const handleKey = (e) => {
if (e.key === "Escape") onClose();
if (e.key === "ArrowRight") next();
if (e.key === "ArrowLeft") prev();
};
window.addEventListener("keydown", handleKey);
return () => window.removeEventListener("keydown", handleKey);
}, [onClose, next, prev]);
useEffect(() => {
setIndex(initialIndex);
}, [initialIndex]);
const handleTouchStart = useCallback((e) => {
touchStart.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, []);
const handleTouchEnd = useCallback((e) => {
if (!touchStart.current) return;
const dx = e.changedTouches[0].clientX - touchStart.current.x;
const dy = e.changedTouches[0].clientY - touchStart.current.y;
const isHorizontal = Math.abs(dx) > Math.abs(dy);
if (isHorizontal && Math.abs(dx) > 50) {
swiped.current = true;
if (dx > 0) prev();
else next();
setTimeout(() => { swiped.current = false; }, 400);
}
touchStart.current = null;
}, [prev, next]);
const handleContact = useCallback(() => {
// Закрываем вьюер перед переходом в чат
contactSeller(onClose);
}, [contactSeller, onClose]);
const isClosed = postData?.status === 'CLOSED';
const showContact = isAuthenticated && postData && !postData.isOwner && !isClosed;
// Статус «найдено» держим на каждом слайде: перелистывая карусель, человек
// не должен терять из виду, что вещь/питомец уже вернулся к владельцу.
const foundText = postData?.category === CATEGORY_PET
? t('postCard.petFoundStatus')
: t('postCard.foundStatus');
const foundDate = isClosed ? formatFoundDate(getFoundAt(postData), i18n.language) : null;
const foundTitle = foundDate
? t('postCard.foundStatusWithDate', { status: foundText, date: foundDate })
: foundText;
if (!urls.length) return null;
return (
<div
className="f-viewer-bg"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
onClick={e => e.target === e.currentTarget && !swiped.current && onClose()}
>
<button type="button" className="f-viewer-close" onClick={onClose} aria-label={t('common.close')}>
<CloseIcon />
</button>
<div className="f-viewer">
{isClosed && (
<span className="f-viewer-found-badge" title={String(foundTitle)}>
<CheckIcon size={14}/>
<span>{foundText}</span>
</span>
)}
<div className="f-viewer-img-wrap" onClick={handleImgClick}>
<img
src={urls[index]}
alt=""
className={`f-viewer-img${isClosed ? ' f-viewer-img-closed' : ''}`}
/>
</div>
{showContact && (
<button type="button" className="f-viewer-contact" onClick={handleContact}>
{t('postCard.write')}
</button>
)}
{urls.length > 1 && (
<div className="f-viewer-dots">
{urls.map((_, i) => (
<button
type="button"
key={i}
className={`f-viewer-dot${i === index ? " active" : ""}`}
onClick={() => setIndex(i)}
aria-label={t('viewer.goToImage', { number: i + 1 })}
/>
))}
</div>
)}
</div>
{contactError && (
<Toast
message={contactError}
type="error"
onDismiss={clearError}
/>
)}
</div>
);
}

View File

@@ -6,7 +6,7 @@ import { useAuthContext } from "../context/AuthContext";
import PostOnFeed from "../pages/PostOnFeed";
import CloseIcon from "./icons/CloseIcon";
export default function PostDetailModal({ postId, onClose, onImageClick, onLocationClick, onAuthRequired }) {
export default function PostDetailModal({ postId, onClose, onLocationClick, onAuthRequired }) {
const { t } = useTranslation();
const { user } = useAuthContext();
const [post, setPost] = useState(null);
@@ -62,7 +62,6 @@ export default function PostDetailModal({ postId, onClose, onImageClick, onLocat
<PostOnFeed
ad={post}
isOwner={isOwner}
onImageClick={onImageClick}
onLocationClick={onLocationClick}
onAuthRequired={onAuthRequired}
compact

View File

@@ -3,7 +3,6 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import PostOnFeed from "../../pages/PostOnFeed";
import CreateUpdatePost from "../../pages/CreateUpdatePost";
import ImageViewer from "../ImageViewer";
import Toast from "../Toast";
import {
getAdminPosts,
@@ -66,7 +65,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
const [statusFilter, setStatusFilter] = useState("");
const [editing, setEditing] = useState(null);
const [viewer, setViewer] = useState(null);
const [busyId, setBusyId] = useState(null);
const [toast, setToast] = useState(null);
@@ -148,10 +146,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
showToast(t("adminPanel.postsUpdated"));
}, [load, page, showToast, t]);
const handleImageClick = useCallback((images, index, ad) => {
if (images?.length) setViewer({ images, index, ad });
}, []);
const contentStyle = useMemo(() => ({ opacity: busyId === null ? 1 : 0.75 }), [busyId]);
if (!isAdmin) return null;
@@ -234,7 +228,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
onDelete={handleDelete}
onMarkFound={(id) => setStatus(id, "CLOSED")}
onReopen={(id) => setStatus(id, "ACTIVE")}
onImageClick={handleImageClick}
/>
))}
</div>
@@ -261,15 +254,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
/>
)}
{viewer && (
<ImageViewer
images={viewer.images}
initialIndex={viewer.index}
postData={viewer.ad}
onClose={() => setViewer(null)}
/>
)}
{toast && <Toast message={toast.message} type={toast.type} onDismiss={() => setToast(null)} />}
</>
);

View File

@@ -17,7 +17,6 @@ export default function FeedContent({
onDelete,
onMarkFound,
onReopen,
onImageClick,
onLocationClick,
onAuthRequired,
showAds = false,
@@ -91,7 +90,6 @@ export default function FeedContent({
onMarkFound={activeNav === "myads" ? onMarkFound : undefined}
onReopen={activeNav === "myads" ? onReopen : undefined}
isOwner={activeNav === "myads"}
onImageClick={onImageClick}
onLocationClick={onLocationClick}
onAuthRequired={onAuthRequired}
/>

View File

@@ -5,7 +5,7 @@ import { useChats } from "./useChats";
/**
* useContactSeller — общая логика открытия/создания чата с автором объявления.
* Используется в PostOnFeed (карточка в ленте) и ImageViewer (просмотр фото).
* Используется в PostOnFeed (карточка в ленте).
*
* @param {object} post — объявление: { id, userId, title, images, emoji }
* @returns {{

View File

@@ -4,7 +4,7 @@ import { useState, useCallback } from "react";
* Управляет всеми модалками MainFeed через единое состояние,
* чтобы гарантировать что открыта максимум одна модалка сразу.
*
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "viewer"
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "postDetail"
*/
export function useModals() {
const [modal, setModal] = useState(null); // { type, payload }

View File

@@ -142,7 +142,7 @@
"loading": "Loading ads...",
"loadError": "Failed to load feed",
"emptyMyAdsTitle": "You have no ads",
"emptyMyAdsSub": "Create your first one — click the button above",
"emptyMyAdsSub": "Create your first one — click the button + bellow",
"emptyAllTitle": "No ads yet",
"emptyAllSub": "Be the first — post an ad<br />about a loss or find",
"searchPromptTitle": "Enter search parameters",

View File

@@ -142,7 +142,7 @@
"loading": "Загружаем объявления...",
"loadError": "Не удалось загрузить ленту",
"emptyMyAdsTitle": "У вас нет объявлений",
"emptyMyAdsSub": "Создайте первое — нажмите кнопку выше",
"emptyMyAdsSub": "Создайте первое — нажмите кнопку + ниже",
"emptyAllTitle": "Объявлений пока нет",
"emptyAllSub": "Будьте первым — разместите объявление<br />о потере или находке",
"searchPromptTitle": "Введите параметры поиска",

View File

@@ -7,7 +7,6 @@ import Sidebar from "../components/Sidebar";
import BottomNav from "../components/nav/BottomNav";
import RightSidebar from "../components/RightSidebar";
import CreateUpdatePostLegacy from "./CreateUpdatePost";
import ImageViewer from "../components/ImageViewer";
import CityFilterLegacy from "../components/CityFilter";
import { ProfileModal } from "../components/profile";
import AuthModal from "../components/AuthModal";
@@ -240,10 +239,6 @@ export default function MainFeed() {
activeNav === "home" && selectedCities.length === 0 && feed.hasMore && !feed.loading && !feed.loadingMore
);
const handleImageClick = useCallback((images: string[], index: number, ad: Record<string, unknown>) => {
if (images?.length) modals.open("viewer", { images, index, ad });
}, [modals]);
const handleCreatePost = useCallback(() => {
if (!isAuthenticated) modals.open("auth");
else modals.open("create");
@@ -491,7 +486,6 @@ export default function MainFeed() {
onDelete={actions.handleDelete}
onMarkFound={actions.handleMarkFound}
onReopen={actions.handleReopen}
onImageClick={handleImageClick}
onLocationClick={handleLocationClick}
onAuthRequired={() => modals.open("auth")}
t={t}
@@ -552,22 +546,10 @@ export default function MainFeed() {
{modals.isOpen("rules") && <RulesModal onClose={modals.close} />}
{modals.isOpen("viewer") && (
<ImageViewer
images={modals.modal.payload.images}
initialIndex={modals.modal.payload.index}
onClose={modals.close}
postData={modals.modal.payload.ad}
/>
)}
{modals.isOpen("postDetail") && (
<PostDetailModal
postId={modals.modal.payload.postId}
onClose={modals.close}
onImageClick={(images: string[], index: number, ad: Record<string, unknown>) => {
modals.open("viewer", { images, index, ad });
}}
onLocationClick={(ad: Record<string, unknown>) => {
modals.close();
void handleLocationClick(ad);

View File

@@ -14,7 +14,7 @@ import RewardPopup from "../components/feed/RewardPopup";
import Toast from "../components/Toast";
import {useTranslation} from 'react-i18next';
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onImageClick, onLocationClick, onAuthRequired, compact }) {
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact }) {
const { t, i18n } = useTranslation();
const [showCalendar, setShowCalendar] = useState(false);
const [showReward, setShowReward] = useState(false);
@@ -25,7 +25,6 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
const rewardAnchorRef = useRef(null);
const descRef = useRef(null);
const imgTouchStartRef = useRef(null);
const imgSwipedRef = useRef(false);
const { isAuthenticated } = useAuthContext();
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
@@ -50,15 +49,17 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
};
const images = Array.isArray(ad.images) ? ad.images : [];
const hasMultipleImages = images.length > 1;
// Карусель только для карточек ленты (не для компактного вида в детальной
// модалке, где фото показывается целиком и overflow не скрыт).
const carousel = hasMultipleImages && !compact;
// Карусель включается для любого объявления с несколькими фото: листать
// можно и в ленте, и в детальной модалке. Полноэкранного просмотрщика нет.
const carousel = images.length > 1;
// Листание фото прямо в карточке: на телефоне — свайпом, на десктопе —
// стрелками и точками. Полноэкранный просмотр по-прежнему открывается по клику.
// стрелками и точками. Листание зациклено: с последнего кадра переходим на
// первый и наоборот.
const goToImage = (target) => {
setImgIndex(Math.max(0, Math.min(images.length - 1, target)));
const len = images.length;
if (!len) return;
setImgIndex(((target % len) + len) % len);
};
const handleImgTouchStart = (e) => {
@@ -75,19 +76,12 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
// Реагируем только на явно горизонтальный жест — вертикальный скролл ленты
// не должен переключать фото.
if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
imgSwipedRef.current = true;
setImgIndex(i => Math.max(0, Math.min(images.length - 1, dx < 0 ? i + 1 : i - 1)));
window.setTimeout(() => { imgSwipedRef.current = false; }, 350);
const len = images.length;
const step = dx < 0 ? 1 : -1;
setImgIndex(i => (i + step + len) % len);
}
};
const handleImgAreaClick = (e) => {
e.stopPropagation();
// После свайпа браузер может дослать click — не открываем просмотр.
if (imgSwipedRef.current) return;
if (onImageClick) onImageClick(images, imgIndex, ad);
};
const address = ad.address || ad.city || ad.district || ad.location;
const createdAt = ad.createdAt
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
@@ -135,7 +129,6 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
<div
className={`f-card-img${carousel ? " f-card-img-multi" : ""}`}
onClick={handleImgAreaClick}
onTouchStart={handleImgTouchStart}
onTouchEnd={handleImgTouchEnd}
>

View File

@@ -583,7 +583,10 @@ select.f-m-field::selection { background: transparent; }
}
.f-post-detail-modal .f-card-img {
max-height: none;
overflow: visible;
/* Раньше было overflow: visible для полноэкранного просмотра. Теперь фото
листается прямо в карточке (карусель), поэтому кадры должны обрезаться
по «окну». */
overflow: hidden;
flex-shrink: 0;
}
.f-post-detail-modal .f-card-img img {
@@ -591,6 +594,13 @@ select.f-m-field::selection { background: transparent; }
height: auto;
object-fit: contain;
}
/* Карусель в модалке: трек и кадры заполняют квадратное «окно», фото
вписывается целиком (contain). */
.f-post-detail-modal .f-card-img .f-card-img-track { height: 100%; }
.f-post-detail-modal .f-card-img .f-card-img-slide {
height: 100%;
object-fit: contain;
}
.f-post-detail-modal .f-card-caption {
padding: 8px 14px;
}