365 lines
15 KiB
JavaScript
365 lines
15 KiB
JavaScript
import {useRef, useState, useEffect} from "react";
|
||
import PinIcon from "../components/icons/PinIcon";
|
||
import CalendarIcon from "../components/icons/CalendarIcon";
|
||
import PhoneIcon from "../components/icons/PhoneIcon";
|
||
import TrashIcon from "../components/icons/TrashIcon";
|
||
import CheckIcon from "../components/icons/CheckIcon";
|
||
import {useContactSeller} from "../hooks/useContactSeller";
|
||
import {useAuthContext} from "../context/AuthContext";
|
||
import {getImageUrl} from "../config/authConstants";
|
||
import {CATEGORY_PET} from "../config/feedConstants";
|
||
import {getFoundAt, formatFoundDate} from "../utils/foundAt";
|
||
import DateCalendarPopup from "../components/DateCalendarPopup";
|
||
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, onLocationClick, onAuthRequired, compact }) {
|
||
const { t, i18n } = useTranslation();
|
||
const [showCalendar, setShowCalendar] = useState(false);
|
||
const [showReward, setShowReward] = useState(false);
|
||
const [descExpanded, setDescExpanded] = useState(false);
|
||
const [descTruncated, setDescTruncated] = useState(false);
|
||
const [imgIndex, setImgIndex] = useState(0);
|
||
const dateAnchorRef = useRef(null);
|
||
const rewardAnchorRef = useRef(null);
|
||
const descRef = useRef(null);
|
||
const imgTouchStartRef = useRef(null);
|
||
const { isAuthenticated, user } = useAuthContext();
|
||
// Своё объявление: писать самому себе нельзя (бэкенд отвечает 400), кнопку не показываем.
|
||
// isOwner тут не подходит — в общей ленте он false и для своих объявлений.
|
||
const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id);
|
||
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
|
||
|
||
useEffect(() => {
|
||
const check = () => {
|
||
if (!descExpanded && descRef.current) {
|
||
setDescTruncated(descRef.current.scrollHeight > descRef.current.clientHeight + 1);
|
||
}
|
||
};
|
||
check();
|
||
window.addEventListener("resize", check);
|
||
return () => window.removeEventListener("resize", check);
|
||
}, [descExpanded]);
|
||
|
||
const handleContact = (e) => {
|
||
e.stopPropagation();
|
||
if (!isAuthenticated) {
|
||
if (onAuthRequired) onAuthRequired();
|
||
return;
|
||
}
|
||
contactSeller();
|
||
};
|
||
|
||
const images = Array.isArray(ad.images) ? ad.images : [];
|
||
// Карусель включается для любого объявления с несколькими фото: листать
|
||
// можно и в ленте, и в детальной модалке. Полноэкранного просмотрщика нет.
|
||
const carousel = images.length > 1;
|
||
const hasImages = images.length > 0;
|
||
|
||
// Листание фото прямо в карточке: на телефоне — свайпом, на десктопе —
|
||
// стрелками и точками. Листание зациклено: с последнего кадра переходим на
|
||
// первый и наоборот.
|
||
const goToImage = (target) => {
|
||
const len = images.length;
|
||
if (!len) return;
|
||
setImgIndex(((target % len) + len) % len);
|
||
};
|
||
|
||
const handleImgTouchStart = (e) => {
|
||
if (!carousel) return;
|
||
imgTouchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
|
||
};
|
||
|
||
const handleImgTouchEnd = (e) => {
|
||
const start = imgTouchStartRef.current;
|
||
imgTouchStartRef.current = null;
|
||
if (!start || !carousel) return;
|
||
const dx = e.changedTouches[0].clientX - start.x;
|
||
const dy = e.changedTouches[0].clientY - start.y;
|
||
// Реагируем только на явно горизонтальный жест — вертикальный скролл ленты
|
||
// не должен переключать фото.
|
||
if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
|
||
const len = images.length;
|
||
const step = dx < 0 ? 1 : -1;
|
||
setImgIndex(i => (i + step + len) % len);
|
||
}
|
||
};
|
||
|
||
// На карточке показываем только город; полный адрес — запасной вариант,
|
||
// чтобы у старых объявлений без города не пропала кнопка карты
|
||
const address = ad.city || ad.district || ad.address || ad.location;
|
||
const createdAt = ad.createdAt
|
||
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
|
||
: null;
|
||
|
||
const isClosed = ad.status === 'CLOSED';
|
||
// Для питомцев «найдено» — это хорошая новость с воссоединением, поэтому
|
||
// формулировка эмоциональнее, чем сухое «Найдено».
|
||
const isPet = ad.category === CATEGORY_PET;
|
||
const foundText = isPet ? t('postCard.petFoundStatus') : t('postCard.foundStatus');
|
||
const foundDate = isClosed ? formatFoundDate(getFoundAt(ad), i18n.language) : null;
|
||
// aria-подпись собираем целиком: статус не должен читаться только цветом.
|
||
const foundAriaText = foundDate
|
||
? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate})
|
||
: foundText;
|
||
|
||
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
|
||
|
||
const typeBadge = (
|
||
<div className={`f-type-badge ${ad.type === "loss" ? "f-type-loss" : "f-type-found"}`}>
|
||
{ad.type === "loss" ? t('postCard.loss') : t('postCard.found')}
|
||
</div>
|
||
);
|
||
|
||
return (
|
||
<div className={`f-card${isClosed ? ' f-card-closed' : ''}${ad.type === "found" ? ' f-card-found' : ' f-card-loss'}`}
|
||
role="group"
|
||
aria-label={isClosed ? `${ad.title}. ${foundAriaText}` : ad.title}>
|
||
|
||
<div className={`f-card-head${headAccentClass}`}>
|
||
<div className="f-card-author">
|
||
<div
|
||
className="f-card-author-name"
|
||
>
|
||
{ad.title}
|
||
</div>
|
||
{authorLabel && (
|
||
<div className="f-card-author-sub">{authorLabel}</div>
|
||
)}
|
||
</div>
|
||
<div className="f-card-head-side">
|
||
{typeBadge}
|
||
</div>
|
||
</div>
|
||
|
||
<div
|
||
className={`f-card-img${carousel ? " f-card-img-multi" : ""}${hasImages ? " f-card-img-filled" : ""}`}
|
||
onTouchStart={handleImgTouchStart}
|
||
onTouchEnd={handleImgTouchEnd}
|
||
>
|
||
{images.length > 0 ? (
|
||
carousel ? (
|
||
<div
|
||
className="f-card-img-track"
|
||
style={{ transform: `translateX(-${imgIndex * 100}%)` }}
|
||
>
|
||
{images.map((raw, i) => (
|
||
<img
|
||
key={i}
|
||
src={getImageUrl(raw)}
|
||
alt={ad.title}
|
||
className="f-card-img-slide"
|
||
draggable={false}
|
||
loading="lazy"
|
||
decoding="async"
|
||
/>
|
||
))}
|
||
</div>
|
||
) : (
|
||
<img src={getImageUrl(images[0])} alt={ad.title} loading="lazy" decoding="async" />
|
||
)
|
||
) : (
|
||
<span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
||
)}
|
||
{/* Плашка статуса поверх фото: при быстром скролле шапка карточки
|
||
проезжает мимо, а фото с плашкой — нет. */}
|
||
{isClosed && (
|
||
<span className={`f-img-found-badge${isPet ? ' f-img-found-badge-pet' : ''}`}>
|
||
<CheckIcon size={12}/>
|
||
<span>{foundText}</span>
|
||
</span>
|
||
)}
|
||
{carousel && (
|
||
<>
|
||
<button
|
||
type="button"
|
||
className="f-img-nav f-img-nav-prev"
|
||
aria-label={t('viewer.prevImage')}
|
||
onClick={e => { e.stopPropagation(); goToImage(imgIndex - 1); }}
|
||
>
|
||
‹
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="f-img-nav f-img-nav-next"
|
||
aria-label={t('viewer.nextImage')}
|
||
onClick={e => { e.stopPropagation(); goToImage(imgIndex + 1); }}
|
||
>
|
||
›
|
||
</button>
|
||
<div className="f-img-dots">
|
||
{images.map((_, i) => (
|
||
<button
|
||
type="button"
|
||
key={i}
|
||
className={`f-img-dot${i === imgIndex ? " active" : ""}`}
|
||
aria-label={t('viewer.goToImage', { number: i + 1 })}
|
||
onClick={e => { e.stopPropagation(); goToImage(i); }}
|
||
/>
|
||
))}
|
||
</div>
|
||
</>
|
||
)}
|
||
</div>
|
||
|
||
{!compact && (
|
||
<div className="f-card-actions">
|
||
<div className="f-card-actions-left">
|
||
{address && (
|
||
<div
|
||
className="f-meta-pill f-loc-pill"
|
||
title={t('postCard.showOnMap', { address })}
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
onLocationClick?.(ad);
|
||
}}
|
||
>
|
||
<PinIcon/> {address}
|
||
</div>
|
||
)}
|
||
</div>
|
||
<div className="f-card-actions-right">
|
||
{onEdit && isOwner && (!isClosed || allowEditClosed) && (
|
||
<button type="button" className="f-card-edit-btn"
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
onEdit(ad);
|
||
}}>
|
||
✏️
|
||
</button>
|
||
)}
|
||
{onDelete && isOwner && (
|
||
<button type="button" className="f-card-delete-btn"
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
onDelete(ad.id);
|
||
}}>
|
||
<TrashIcon/>
|
||
</button>
|
||
)}
|
||
{createdAt && (
|
||
<div
|
||
className="f-meta-pill f-date-pill"
|
||
ref={dateAnchorRef}
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
setShowCalendar(s => !s);
|
||
}}
|
||
>
|
||
<CalendarIcon/> {createdAt}
|
||
{showCalendar && (
|
||
<DateCalendarPopup
|
||
date={ad.createdAt}
|
||
onClose={() => setShowCalendar(false)}
|
||
anchorRef={dateAnchorRef}
|
||
/>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
<div className="f-card-caption">
|
||
<span
|
||
ref={descRef}
|
||
className={`f-card-caption-text${descTruncated ? " f-truncatable" : ""}${descExpanded ? " f-expanded" : ""}`}
|
||
onClick={descTruncated ? () => setDescExpanded(v => !v) : undefined}
|
||
>
|
||
{ad.description}
|
||
</span>
|
||
</div>
|
||
|
||
{!compact && (
|
||
<div className="f-card-meta">
|
||
{ad.reward && (
|
||
<>
|
||
<button
|
||
ref={rewardAnchorRef}
|
||
type="button"
|
||
className="f-card-reward-text f-card-reward-btn"
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
setShowReward(s => !s);
|
||
}}
|
||
>
|
||
<span className="f-reward-btn-label">{t("postCard.reward")}</span>
|
||
</button>
|
||
{showReward && (
|
||
<RewardPopup
|
||
text={ad.rewardText || t("postCard.reward")}
|
||
anchorRef={rewardAnchorRef}
|
||
onClose={() => setShowReward(false)}
|
||
/>
|
||
)}
|
||
</>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
<div className="f-card-foot">
|
||
<div className="f-card-foot-left">
|
||
{ad.phone && (
|
||
<a className="f-card-phone" href={`tel:${ad.phone}`}
|
||
onClick={e => e.stopPropagation()}>
|
||
<PhoneIcon/> {ad.phone}
|
||
</a>
|
||
)}
|
||
</div>
|
||
<div className="f-card-foot-right">
|
||
{!isOwnAd && (
|
||
<button type="button" className="f-card-contact"
|
||
onClick={handleContact}>
|
||
{t('postCard.write')}
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
{onMarkFound && isOwner && !isClosed && (
|
||
<div className="f-card-found-wrap">
|
||
<button type="button" className="f-card-found-btn"
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
onMarkFound(ad.id);
|
||
}}>
|
||
{t('postCard.itemFound')}
|
||
</button>
|
||
</div>
|
||
)}
|
||
{isClosed && (
|
||
<div className="f-card-found-wrap">
|
||
{/* Кнопка «найдено» становится неактивной подтверждением: видно,
|
||
что действие уже применено, и повторно не нажать. */}
|
||
<button type="button" className="f-card-found-btn f-card-found-btn-done"
|
||
disabled
|
||
aria-label={foundAriaText}
|
||
title={foundAriaText}>
|
||
<CheckIcon size={14}/>
|
||
<span>{foundText}{foundDate ? ` ${foundDate}` : ''}</span>
|
||
</button>
|
||
{/* Отмена случайного нажатия — автору; в админ-панели это и есть
|
||
возврат объявления в ленту. */}
|
||
{onReopen && isOwner && (
|
||
<button type="button" className="f-card-found-undo"
|
||
onClick={e => {
|
||
e.stopPropagation();
|
||
onReopen(ad.id);
|
||
}}>
|
||
{t('postCard.undoFound')}
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{contactError && (
|
||
<Toast
|
||
message={contactError}
|
||
type="error"
|
||
onDismiss={clearError}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|