Files
filwordspl-frontend/src/components/FeedModal.tsx
T
Drobysh 87f482861b 🌊 Волна 15: frontend #5 — security + юзабилити (16 багов)
Security (XSS):
- feed_modal_javascript_url_xss: safeUrl валидация (FeedModal.tsx)
- feed_modal_telegram_url_xss: safeUrl валидация (FeedModal.tsx)

Данные:
- feed_composer_duplicate_post_on_upload_fail: isPublished флаг (FeedPostComposer.tsx)
- STRICTMODE_DOUBLE_REGISTER_RETRY: двойная защита + cleanup (App.tsx)
- RETRY_TIMEOUT_NOT_CLEANED: clearTimeout в cleanup (App.tsx)

Производительность:
- CONTENT_TYPE_ON_GET_TRIGGERS_PREFLIGHT: Content-Type только при body (api.ts)
- DUPLICATED_FETCH_LOGIC: fetchWithTimeout helper (api.ts)
- UNENCODED_PATH_PARAMS: encodeURIComponent для path (api.ts)

Юзабилити:
- content_editor_no_escape: Escape (ContentEditorMenu.tsx)
- lessons_editor_no_backdrop_close: Escape + backdrop (LessonsEditor.tsx)
- support_delete_ticket_no_confirm: модалка подтверждения (SupportChatModal.tsx)

Качество:
- GET_INIT_DATA_CONSOLE_SPAM: логируем один раз (telegram.ts)
- words_editor_dead_button: удалена мёртвая кнопка (WordsEditor.tsx)
- highlights_carousel_setstate_on_unmount: убран setState в cleanup (HighlightsCarousel.tsx)
- image_lightbox_timers_accumulate: очистка таймеров (ImageLightbox.tsx)
- typing_modal_timeout_not_cleared: clearTimeout (TypingModal.tsx)

Пропущено осознанно:
- INIT_DATA_IN_URL_DELETE_FEED (fallback для deleteFeedPost, Cloudflare preflight)

Аудит v3: Issue #4, frontend 17/18 задач
2026-09-24 19:21:24 +03:00

980 lines
36 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useEffect, useRef, useCallback } from 'react';
import { useLanguage } from '../i18n/LanguageContext';
import { radius } from '../styles/theme';
import { getFeedSection, deleteFeedPost, type FeedPostResponse } from '../api';
import FeedPostComposer from './FeedPostComposer';
import ImageLightbox from './ImageLightbox';
export type FeedSection = 'news' | 'partners' | 'contacts' | 'apps';
interface FeedModalProps {
isOpen: boolean;
onClose: () => void;
section: FeedSection;
/** Флаг админа — для админ-строки ввода */
isAdmin?: boolean;
}
type FeedPost = FeedPostResponse;
const SECTION_CONFIG: Record<FeedSection, {
icon: string;
titleKey: string;
accent: string;
}> = {
news: { icon: '📢', titleKey: 'carouselNews', accent: '#E8B93F' },
partners: { icon: '💼', titleKey: 'carouselPartners', accent: '#2ECC71' },
contacts: { icon: '📇', titleKey: 'carouselContacts', accent: '#8B5CF6' },
apps: { icon: '📲', titleKey: 'carouselApps', accent: '#4FA9E8' },
};
// 🔧 URL поддержки (единый аккаунт для заявок)
const SUPPORT_URL = 'https://t.me/fwpl_support';
// 🔧 API base для склейки относительных URL картинок (fallback для старых постов)
const API_BASE = 'https://api.filwordspl.com';
// 🔧 Внутренний отступ карточки поста (текстовый блок под картинкой)
const POST_PADDING = '16px';
const FeedModal: React.FC<FeedModalProps> = ({ isOpen, onClose, section, isAdmin = false }) => {
const { t, language } = useLanguage();
const [posts, setPosts] = useState<FeedPost[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const isMountedRef = useRef(true);
// 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change — счётчик запросов,
// чтобы старый ответ не перезаписал новый при быстрой смене секции.
const requestIdRef = useRef(0);
// 🔧 Шаг 6: состояния админ-режима
const [showComposer, setShowComposer] = useState(false);
const [editingPost, setEditingPost] = useState<FeedPost | null>(null);
const [deletingPost, setDeletingPost] = useState<FeedPost | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
// 🔧 Лайтбокс: какие картинки открыть + с какого индекса
const [lightboxOpen, setLightboxOpen] = useState(false);
const [lightboxImages, setLightboxImages] = useState<string[]>([]);
const [lightboxIndex, setLightboxIndex] = useState(0);
const config = SECTION_CONFIG[section];
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const cardBg = 'rgba(255,255,255,0.55)';
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: cardBg,
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
border: '1px solid rgba(255,255,255,0.7)',
boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)',
...extra,
});
// 🔧 Утилита: превращает относительный путь в полный URL
const fullImageUrl = (path: string): string =>
path.startsWith('http') ? path : `${API_BASE}${path}`;
// 🔧 ФИКС (24.09.2026): feed_modal_javascript_url_xss —
// валидация URL. Разрешаем только http(s) и tg://, отсекаем javascript: и data:.
const safeUrl = (url: string | null | undefined): string | null => {
if (!url) return null;
const trimmed = url.trim();
const lower = trimmed.toLowerCase();
// Разрешаем http, https, tg, mailto, tel
if (
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('tg://') ||
lower.startsWith('mailto:') ||
lower.startsWith('tel:')
) {
return trimmed;
}
// Блокируем всё остальное (javascript:, data:, vbscript: и т.д.)
return null;
};
const loadFeed = useCallback(() => {
setLoading(true);
setError(null);
// 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change
const currentRequestId = ++requestIdRef.current;
getFeedSection(section, language)
.then((data) => {
// 🔧 Игнорируем устаревшие ответы
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
setPosts(data.posts || []);
})
.catch((e) => {
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
console.error('Failed to load feed:', e);
setError('Failed to load feed');
setPosts([]);
})
.finally(() => {
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
setLoading(false);
});
}, [section, language]);
useEffect(() => {
if (!isOpen) return;
isMountedRef.current = true;
loadFeed();
return () => {
isMountedRef.current = false;
};
}, [isOpen, loadFeed]);
// Скролл вверх при открытии
useEffect(() => {
if (isOpen && scrollRef.current) {
scrollRef.current.scrollTop = 0;
}
}, [isOpen, section]);
// Escape для закрытия (только если не открыт composer/lightbox/delete)
useEffect(() => {
if (!isOpen) return;
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !showComposer && !deletingPost && !lightboxOpen) onClose();
};
window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey);
}, [isOpen, onClose, showComposer, deletingPost, lightboxOpen]);
// ============ Обработчики админа ============
const handleCreate = () => {
setEditingPost(null);
setShowComposer(true);
};
const handleEdit = (post: FeedPost) => {
setEditingPost(post);
setShowComposer(true);
};
const handleDeleteConfirm = async () => {
if (!deletingPost) return;
setIsDeleting(true);
setDeleteError(null);
try {
await deleteFeedPost(deletingPost.id);
setDeletingPost(null);
loadFeed();
} catch (e: any) {
const realMessage = e?.message || String(e);
setDeleteError(realMessage);
console.error('[handleDeleteConfirm] FAILED', realMessage);
} finally {
setIsDeleting(false);
}
};
const handleComposerSuccess = () => {
loadFeed();
};
// ============ Открытие лайтбокса ============
const openLightbox = (images: string[], startIndex: number = 0) => {
setLightboxImages(images.map(fullImageUrl));
setLightboxIndex(startIndex);
setLightboxOpen(true);
};
// ============ Автолинк ============
const renderTextWithLinks = (text: string) => {
const linkRegex = /(https?:\/\/[^\s]+)/g;
const phoneRegex = /(\+[\d\s\-()]{7,})/g;
type Match = { start: number; end: number; text: string; href: string; type: 'link' | 'phone' };
const matches: Match[] = [];
let m: RegExpExecArray | null;
const linkRegexGlobal = new RegExp(linkRegex.source, 'g');
while ((m = linkRegexGlobal.exec(text)) !== null) {
matches.push({
start: m.index,
end: m.index + m[0].length,
text: m[0],
href: m[0],
type: 'link',
});
}
const phoneRegexGlobal = new RegExp(phoneRegex.source, 'g');
while ((m = phoneRegexGlobal.exec(text)) !== null) {
const overlaps = matches.some(
(existing) => m!.index < existing.end && m!.index + m![0].length > existing.start
);
if (!overlaps) {
matches.push({
start: m.index,
end: m.index + m[0].length,
text: m[0],
href: `tel:${m[0].replace(/[\s\-()]/g, '')}`,
type: 'phone',
});
}
}
matches.sort((a, b) => a.start - b.start);
const result: React.ReactNode[] = [];
let lastIndex = 0;
matches.forEach((match, i) => {
if (match.start > lastIndex) {
result.push(text.slice(lastIndex, match.start));
}
result.push(
<a
key={`${match.type}-${i}`}
href={match.href}
target="_blank"
rel="noopener noreferrer"
style={{
color: config.accent,
textDecoration: 'underline',
wordBreak: 'break-word',
}}
onClick={(e) => e.stopPropagation()}
>
{match.text}
</a>
);
lastIndex = match.end;
});
if (lastIndex < text.length) {
result.push(text.slice(lastIndex));
}
return result;
};
const formatDate = (iso: string | null): string => {
if (!iso) return '';
try {
const date = new Date(iso);
const locales: Record<string, string> = {
pl: 'pl-PL',
ru: 'ru-RU',
uk: 'uk-UA',
en: 'en-US',
};
return date.toLocaleDateString(locales[language] || 'en-US', {
day: 'numeric',
month: 'short',
year: 'numeric',
});
} catch {
return iso;
}
};
const formatExpires = (iso: string | null | undefined): string | null => {
if (!iso) return null;
try {
const date = new Date(iso);
const locales: Record<string, string> = {
pl: 'pl-PL',
ru: 'ru-RU',
uk: 'uk-UA',
en: 'en-US',
};
return date.toLocaleDateString(locales[language] || 'en-US', {
day: 'numeric',
month: 'short',
});
} catch {
return null;
}
};
if (!isOpen) return null;
const showPartnersBanner = section === 'partners';
return (
<>
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.35)', zIndex: 1000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '20px',
backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
animation: 'feedModalFadeIn 0.2s ease',
}}
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
>
<style>{`
@keyframes feedModalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes feedModalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes feedPostIn {
0% { transform: translateY(8px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div
onClick={(e) => e.stopPropagation()}
style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '440px',
height: '85vh',
maxHeight: '720px',
display: 'flex',
flexDirection: 'column',
boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'feedModalSlideUp 0.3s ease',
}}
>
{/* ============ Шапка ============ */}
<div style={{
marginBottom: '16px',
paddingBottom: '12px',
borderBottom: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0,
}}>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '12px',
gap: '8px',
}}>
<button
onClick={onClose}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '13px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
display: 'flex',
alignItems: 'center',
gap: '4px',
whiteSpace: 'nowrap',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
← {t('back')}
</button>
<button
onClick={onClose}
aria-label="Close"
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
WebkitTapHighlightColor: 'transparent',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
✕
</button>
</div>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
}}>
<h3 style={{
margin: 0,
fontSize: '18px',
fontWeight: 800,
color: textColor,
whiteSpace: 'nowrap',
}}>
{config.icon} {t(config.titleKey)}
</h3>
</div>
</div>
{/* ============ Баннер «По вопросам рекламы» (только Партнёры) ============ */}
{showPartnersBanner && (
<div
onClick={() => window.open(SUPPORT_URL, '_blank')}
style={{
...glass({
padding: '14px 16px',
borderRadius: radius.md,
marginBottom: '12px',
}),
border: `1px solid ${config.accent}40`,
background: `${config.accent}10`,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
flexShrink: 0,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '24px' }}>📩</span>
<div style={{ flex: 1 }}>
<div style={{
fontSize: '14px',
fontWeight: 700,
color: config.accent,
marginBottom: '2px',
}}>
{t('feedPartnersBannerTitle') || 'По вопросам рекламы'}
</div>
<div style={{
fontSize: '12px',
color: subColor,
}}>
{t('feedPartnersBannerSubtitle') || 'Написать нам →'}
</div>
</div>
</div>
)}
{/* ============ Лента постов ============ */}
<div
ref={scrollRef}
style={{
flex: 1,
overflowY: 'auto',
overflowX: 'hidden',
display: 'flex',
flexDirection: 'column',
gap: '12px',
paddingBottom: '8px',
WebkitOverflowScrolling: 'touch',
minHeight: 0,
}}
>
{loading ? (
<div style={{
textAlign: 'center',
padding: '40px',
color: subColor,
fontSize: '14px',
}}>
{t('loading')}
</div>
) : error ? (
<div style={{
textAlign: 'center',
padding: '40px 20px',
color: subColor,
fontSize: '14px',
}}>
<div style={{ fontSize: '48px', marginBottom: '12px' }}>⚠️</div>
<div style={{ marginBottom: '16px' }}>
{t('feedError') || 'Не удалось загрузить. Попробуйте ещё раз.'}
</div>
<button
onClick={loadFeed}
style={{
...glass({
padding: '10px 20px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '13px',
fontWeight: 700,
cursor: 'pointer',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
↻ {t('retry') || 'Повторить'}
</button>
</div>
) : posts.length === 0 ? (
<div style={{
textAlign: 'center',
padding: '40px 20px',
color: subColor,
fontSize: '14px',
}}>
<div style={{ fontSize: '48px', marginBottom: '12px' }}>
{config.icon}
</div>
{t('feedEmpty') || 'Пока нет постов'}
</div>
) : (
posts.map((post, index) => {
const expiresLabel = formatExpires(post.expiresAt);
const hasImages = post.images.length > 0;
return (
<div
key={post.id}
style={{
...glass({
borderRadius: radius.md,
// 🔧 PADDING УБРАН отсюда — он теперь на внутренних блоках,
// чтобы картинка могла занять всю ширину карточки edge-to-edge
padding: 0,
overflow: 'hidden',
}),
border: post.isPinned
? `2px solid ${config.accent}50`
: '1px solid rgba(255,255,255,0.7)',
animation: `feedPostIn 0.3s ease ${index * 0.05}s both`,
position: 'relative',
flexShrink: 0,
}}
>
{/* ============ КАРТИНКА (всегда одна на превью, edge-to-edge) ============ */}
{/* 🔧 ФИКС (18.09.2026): на посте видна ТОЛЬКО первая картинка.
По клику открывается лайтбокс со ВСЕМИ картинками поста —
там можно свайпать влево/вправо (ImageLightbox). */}
{hasImages && (
<div
onClick={(e) => {
e.stopPropagation();
openLightbox(post.images, 0);
}}
style={{
position: 'relative',
width: '100%',
aspectRatio: '16 / 9',
background: '#f0f0f5',
cursor: 'pointer',
borderTopLeftRadius: radius.md,
borderTopRightRadius: radius.md,
overflow: 'hidden',
transition: 'transform 0.15s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.99)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{/* Всегда рендерим ТОЛЬКО первую картинку как превью */}
<img
src={fullImageUrl(post.images[0])}
alt=""
loading="lazy"
draggable={false}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = 'none';
}}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
userSelect: 'none',
WebkitUserSelect: 'none',
}}
/>
{/* 🔧 Бейдж «📷 N» — если картинок больше 1.
Показывает юзеру, что внутри ещё есть фото. */}
{post.images.length > 1 && (
<div style={{
position: 'absolute',
top: '10px',
right: '10px',
padding: '4px 10px',
borderRadius: '12px',
background: 'rgba(0, 0, 0, 0.55)',
color: '#FFFFFF',
fontSize: '12px',
fontWeight: 700,
backdropFilter: 'blur(10px)',
WebkitBackdropFilter: 'blur(10px)',
display: 'flex',
alignItems: 'center',
gap: '4px',
pointerEvents: 'none',
zIndex: 2,
}}>
📷 {post.images.length}
</div>
)}
</div>
)}
{/* ============ ТЕКСТОВЫЙ БЛОК (с padding) ============ */}
<div style={{ padding: POST_PADDING, position: 'relative' }}>
{/* Бейдж «Закреплено» */}
{post.isPinned && (
<div style={{
position: 'absolute',
top: POST_PADDING,
right: isAdmin ? '80px' : POST_PADDING,
fontSize: '10px',
fontWeight: 700,
color: '#FFFFFF',
background: config.accent,
padding: '3px 8px',
borderRadius: '8px',
letterSpacing: '0.3px',
zIndex: 2,
}}>
📌
</div>
)}
{/* 🔧 Шаг 6: админ-иконки ✏️ / 🗑️ */}
{isAdmin && (
<div style={{
position: 'absolute',
top: POST_PADDING,
right: POST_PADDING,
display: 'flex',
gap: '6px',
zIndex: 2,
}}>
<button
onClick={() => handleEdit(post)}
title={t('feedAdminEdit') || 'Edit'}
style={{
width: '28px',
height: '28px',
borderRadius: '50%',
border: `1px solid ${config.accent}40`,
background: `${config.accent}15`,
color: config.accent,
fontSize: '13px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
backdropFilter: 'blur(10px)',
WebkitBackdropFilter: 'blur(10px)',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
✏️
</button>
<button
onClick={() => setDeletingPost(post)}
title={t('feedAdminDelete') || 'Delete'}
style={{
width: '28px',
height: '28px',
borderRadius: '50%',
border: '1px solid rgba(231,76,60,0.4)',
background: 'rgba(231,76,60,0.1)',
color: '#E74C3C',
fontSize: '13px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
backdropFilter: 'blur(10px)',
WebkitBackdropFilter: 'blur(10px)',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🗑️
</button>
</div>
)}
{/* Заголовок */}
<div style={{
fontSize: '16px',
fontWeight: 800,
color: textColor,
lineHeight: '1.3',
marginBottom: '8px',
paddingRight: isAdmin ? '80px' : (post.isPinned ? '36px' : '0'),
}}>
{post.title}
</div>
{/* Текст поста */}
<div style={{
fontSize: '14px',
color: textColor,
lineHeight: '1.6',
whiteSpace: 'pre-line',
marginBottom: '12px',
wordBreak: 'break-word',
}}>
{renderTextWithLinks(post.body)}
</div>
{/* Ссылка */}
{post.linkUrl && safeUrl(post.linkUrl) && (
<a
href={safeUrl(post.linkUrl)!}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
padding: '8px 14px',
borderRadius: radius.sm,
background: `${config.accent}15`,
border: `1px solid ${config.accent}40`,
color: config.accent,
fontSize: '13px',
fontWeight: 700,
textDecoration: 'none',
marginBottom: '8px',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🔗 {t('feedOpenLink') || 'Открыть ссылку'}
</a>
)}
{/* Telegram-ссылка */}
{post.telegramUrl && safeUrl(post.telegramUrl) && (
<a
href={safeUrl(post.telegramUrl)!}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
padding: '8px 14px',
borderRadius: radius.sm,
background: `#0088cc15`,
border: `1px solid #0088cc40`,
color: '#0088cc',
fontSize: '13px',
fontWeight: 700,
textDecoration: 'none',
marginBottom: '8px',
marginLeft: post.linkUrl ? '8px' : '0',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
✈️ Telegram
</a>
)}
{/* Футер: дата + таймер */}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
fontSize: '11px',
color: subColor,
marginTop: '4px',
}}>
<span>🕐 {formatDate(post.createdAt)}</span>
{expiresLabel && (
<span style={{
color: '#E74C3C',
fontWeight: 700,
}}>
⏰ до {expiresLabel}
</span>
)}
</div>
</div>
</div>
);
})
)}
</div>
{/* ============ Админ-кнопка «Написать пост» ============ */}
{isAdmin && (
<div style={{
paddingTop: '12px',
marginTop: '4px',
borderTop: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0,
}}>
<button
onClick={handleCreate}
style={{
width: '100%',
padding: '12px 16px',
borderRadius: radius.md,
border: `2px dashed ${config.accent}80`,
background: `${config.accent}22`,
color: '#1A1A2E',
fontSize: '14px',
fontWeight: 800,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
transition: 'all 0.2s ease',
textShadow: '0 1px 0 rgba(255,255,255,0.6)',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
➕ {t('feedAdminSend') || 'Написать пост'}
</button>
</div>
)}
</div>
</div>
{/* ============ Composer (создание / редактирование) ============ */}
<FeedPostComposer
isOpen={showComposer}
onClose={() => {
setShowComposer(false);
setEditingPost(null);
}}
onSuccess={handleComposerSuccess}
section={section}
editingPost={editingPost}
/>
{/* ============ 🔧 Лайтбокс для просмотра картинок ============ */}
<ImageLightbox
isOpen={lightboxOpen}
images={lightboxImages}
initialIndex={lightboxIndex}
onClose={() => setLightboxOpen(false)}
/>
{/* ============ Модалка подтверждения удаления ============ */}
{deletingPost && (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.55)', zIndex: 2000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '20px',
backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
}}
onClick={(e) => { if (e.target === e.currentTarget && !isDeleting) setDeletingPost(null); }}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '360px',
textAlign: 'center',
}),
}}
>
<div style={{ fontSize: '48px', marginBottom: '12px' }}>🗑️</div>
<h3 style={{
margin: '0 0 8px 0',
fontSize: '17px',
fontWeight: 800,
color: textColor,
}}>
{t('feedAdminDeleteConfirm') || 'Удалить этот пост?'}
</h3>
<div style={{
fontSize: '13px',
color: subColor,
marginBottom: '20px',
padding: '8px 12px',
background: 'rgba(0,0,0,0.03)',
borderRadius: radius.sm,
fontWeight: 600,
}}>
{deletingPost.title}
</div>
{deleteError && (
<div style={{
padding: '8px 12px',
background: 'rgba(231,76,60,0.08)',
borderRadius: radius.sm,
color: '#E74C3C',
fontSize: '12px',
fontWeight: 600,
marginBottom: '12px',
wordBreak: 'break-word',
}}>
⚠️ {deleteError}
</div>
)}
<div style={{ display: 'flex', gap: '8px' }}>
<button
onClick={() => setDeletingPost(null)}
disabled={isDeleting}
style={{
flex: 1,
padding: '12px',
borderRadius: radius.md,
border: '1px solid rgba(0,0,0,0.08)',
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '13px',
fontWeight: 700,
cursor: isDeleting ? 'default' : 'pointer',
opacity: isDeleting ? 0.5 : 1,
}}
>
{t('feedAdminDeleteNo') || 'Нет'}
</button>
<button
onClick={handleDeleteConfirm}
disabled={isDeleting}
style={{
flex: 1,
padding: '12px',
borderRadius: radius.md,
border: 'none',
background: isDeleting ? 'rgba(231,76,60,0.4)' : '#E74C3C',
color: '#FFFFFF',
fontSize: '13px',
fontWeight: 700,
cursor: isDeleting ? 'default' : 'pointer',
}}
>
{isDeleting ? '...' : (t('feedAdminDeleteYes') || 'Да, удалить')}
</button>
</div>
</div>
</div>
)}
</>
);
};
export default FeedModal;