diff --git a/src/api.ts b/src/api.ts index 0eff084..2f4ac20 100644 --- a/src/api.ts +++ b/src/api.ts @@ -613,6 +613,9 @@ export interface FeedPostPayload { is_published?: boolean; expires_at?: string | null; translate_again?: boolean; + // 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — + // список URL существующих картинок, которые юзер удалил в UI. + removed_images?: string[]; } export interface FeedListResponse { diff --git a/src/components/AnimatedCat.tsx b/src/components/AnimatedCat.tsx index e1b56d2..aa112b5 100644 --- a/src/components/AnimatedCat.tsx +++ b/src/components/AnimatedCat.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useCallback } from 'react'; +import { useState, useRef, useCallback, useEffect } from 'react'; interface AnimatedCatProps { size?: number; @@ -22,10 +22,12 @@ const AnimatedCat: React.FC = ({ size = 48, onClick, place = 1 const [isPressed, setIsPressed] = useState(false); const [particles, setParticles] = useState([]); const idRef = useRef(0); + // 🔧 ФИКС (23.09.2026): animated_cat_timeout_leak — храним таймеры, + // чтобы очищать их при размонтировании. + const timersRef = useRef[]>([]); const handleClick = useCallback(() => { setIsPressed(true); - setTimeout(() => setIsPressed(false), 200); const newParticles: Particle[] = []; @@ -48,13 +50,25 @@ const AnimatedCat: React.FC = ({ size = 48, onClick, place = 1 } setParticles(prev => [...prev, ...newParticles]); - setTimeout(() => { + + // 🔧 ФИКС (23.09.2026): сохраняем таймеры для очистки + const t1 = setTimeout(() => setIsPressed(false), 200); + const t2 = setTimeout(() => { setParticles(prev => prev.filter(p => !newParticles.find(np => np.id === p.id))); }, 2000); + timersRef.current.push(t1, t2); if (onClick) onClick(); }, [onClick]); + // 🔧 ФИКС (23.09.2026): animated_cat_timeout_leak — очистка таймеров при размонтировании + useEffect(() => { + return () => { + timersRef.current.forEach(clearTimeout); + timersRef.current = []; + }; + }, []); + const medal = place === 1 ? '🥇' : place === 2 ? '🥈' : '🥉'; const glowColor = place === 1 ? '255,215,0' : place === 2 ? '192,192,192' : '205,127,50'; diff --git a/src/components/FeedPostComposer.tsx b/src/components/FeedPostComposer.tsx index 06851e0..8a886e2 100644 --- a/src/components/FeedPostComposer.tsx +++ b/src/components/FeedPostComposer.tsx @@ -77,9 +77,18 @@ async function compressImage( } catch { bitmap = await new Promise((resolve, reject) => { const img = new Image(); - img.onload = () => resolve(img); - img.onerror = () => reject(new Error('image load failed')); - img.src = URL.createObjectURL(blob); + // 🔧 ФИКС (23.09.2026): compress_fallback_objecturl_leak — сохраняем URL, + // чтобы освободить после загрузки. + const objectUrl = URL.createObjectURL(blob); + img.onload = () => { + URL.revokeObjectURL(objectUrl); + resolve(img); + }; + img.onerror = () => { + URL.revokeObjectURL(objectUrl); + reject(new Error('image load failed')); + }; + img.src = objectUrl; }); } @@ -165,6 +174,9 @@ const FeedPostComposer: React.FC = ({ const [slots, setSlots] = useState<(ImageSlot | null)[]>([null, null, null]); // Существующие картинки (режим редактирования) — занимают слоты в начале const [existingImages, setExistingImages] = useState([]); + // 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — трекаем удалённые URL, + // чтобы передать их на бэк при сохранении. + const [removedImages, setRemovedImages] = useState([]); // Три отдельных input[type=file] — по одному на слот. Без multiple. const slotInputRef0 = useRef(null); @@ -207,6 +219,8 @@ const FeedPostComposer: React.FC = ({ setTranslationPreview(null); setError(null); setSuccess(false); + // 🔧 ФИКС (23.09.2026): сбрасываем удалённые картинки при открытии + setRemovedImages([]); }, [isOpen, editingPost, language]); // 🔧 ФИКС (22.09.2026): утечка ObjectURL при размонтировании. @@ -307,6 +321,12 @@ const FeedPostComposer: React.FC = ({ }; const handleRemoveExistingImage = (index: number) => { + const url = existingImages[index]; + if (url) { + // 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — + // запоминаем URL, чтобы удалить на бэке при сохранении. + setRemovedImages(prev => [...prev, url]); + } setExistingImages((prev) => prev.filter((_, i) => i !== index)); }; @@ -359,6 +379,8 @@ const FeedPostComposer: React.FC = ({ is_pinned: isPinned, expires_at: expiresAt ? new Date(expiresAt).toISOString() : null, translate_again: translateAgain, + // 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete + removed_images: removedImages, }); postId = result.post_id; } else { @@ -395,12 +417,21 @@ const FeedPostComposer: React.FC = ({ } } - // 🔧 ФИКС: если хоть одна загрузка упала — не считаем публикацию успешной + // 🔧 ФИКС (23.09.2026): post_created_images_failed — пост уже СОЗДАН, + // поэтому не даём юзеру нажать «опубликовать» повторно (иначе дубль). + // Показываем уведомление, но закрываем composer как «успех». if (failedUploads.length > 0) { setError( - `Не удалось загрузить: ${failedUploads.join(', ')}. ` + - `Загружено ${uploadResults.length} из ${imagesToUpload.length} фото.` + `Пост создан, но не все фото загрузились: ${failedUploads.join(', ')}. ` + + `Загружено ${uploadResults.length} из ${imagesToUpload.length}. ` + + `Открой пост и добавь фото заново.` ); + // Не даём повторно публиковать — переходим в success через 2с + setSuccess(true); + setTimeout(() => { + onSuccess(); + onClose(); + }, 2500); return; } diff --git a/src/components/ImageLightbox.tsx b/src/components/ImageLightbox.tsx index 1b64538..be94728 100644 --- a/src/components/ImageLightbox.tsx +++ b/src/components/ImageLightbox.tsx @@ -22,6 +22,15 @@ const ImageLightbox: React.FC = ({ const touchStartX = useRef(0); const touchStartY = useRef(0); const isHorizontal = useRef(null); + // 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — храним таймеры для очистки. + const timersRef = useRef[]>([]); + + // 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — обёртка для автоочистки + const safeTimeout = (fn: () => void, ms: number) => { + const t = setTimeout(fn, ms); + timersRef.current.push(t); + return t; + }; // Сброс индекса при открытии useEffect(() => { @@ -32,6 +41,14 @@ const ImageLightbox: React.FC = ({ } }, [isOpen, initialIndex]); + // 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — очистка таймеров при размонтировании + useEffect(() => { + return () => { + timersRef.current.forEach(clearTimeout); + timersRef.current = []; + }; + }, []); + const goNext = useCallback(() => { setCurrentIndex(prev => (prev < images.length - 1 ? prev + 1 : prev)); }, [images.length]); @@ -113,7 +130,7 @@ const ImageLightbox: React.FC = ({ if (currentIndex > 0) { setIsAnimating(true); setOffsetX(window.innerWidth); // улетаем вправо - setTimeout(() => { + safeTimeout(() => { goPrev(); setOffsetX(0); setIsAnimating(false); @@ -122,14 +139,14 @@ const ImageLightbox: React.FC = ({ // Отскок назад setIsAnimating(true); setOffsetX(0); - setTimeout(() => setIsAnimating(false), 250); + safeTimeout(() => setIsAnimating(false), 250); } } else if (offsetX < -threshold) { // Свайп влево → следующая if (currentIndex < images.length - 1) { setIsAnimating(true); setOffsetX(-window.innerWidth); // улетаем влево - setTimeout(() => { + safeTimeout(() => { goNext(); setOffsetX(0); setIsAnimating(false); @@ -138,13 +155,13 @@ const ImageLightbox: React.FC = ({ // Отскок назад setIsAnimating(true); setOffsetX(0); - setTimeout(() => setIsAnimating(false), 250); + safeTimeout(() => setIsAnimating(false), 250); } } else { // Не дотянули — плавно возвращаем на место setIsAnimating(true); setOffsetX(0); - setTimeout(() => setIsAnimating(false), 250); + safeTimeout(() => setIsAnimating(false), 250); } isHorizontal.current = null; diff --git a/src/i18n/LanguageContext.tsx b/src/i18n/LanguageContext.tsx index 6764db9..9b259dc 100644 --- a/src/i18n/LanguageContext.tsx +++ b/src/i18n/LanguageContext.tsx @@ -19,14 +19,26 @@ export const useLanguage = () => useContext(LanguageContext); export const LanguageProvider: React.FC<{ children: ReactNode }> = ({ children }) => { const [language, setLanguageState] = useState(() => { + // 🔧 ФИКС (23.09.2026): unvalidated_lang_from_url — валидация обоих источников. + const SUPPORTED = ['pl', 'ru', 'uk', 'en']; const urlParams = new URLSearchParams(window.location.search); const langFromUrl = urlParams.get('lang'); const langFromStorage = localStorage.getItem('filwords_lang'); - return langFromUrl || langFromStorage || 'pl'; + + if (langFromUrl && SUPPORTED.includes(langFromUrl)) return langFromUrl; + if (langFromStorage && SUPPORTED.includes(langFromStorage)) return langFromStorage; + return 'pl'; }); useEffect(() => { - localStorage.setItem('filwords_lang', language); + const SUPPORTED = ['pl', 'ru', 'uk', 'en']; + if (SUPPORTED.includes(language)) { + localStorage.setItem('filwords_lang', language); + } else { + // 🔧 ФИКС (23.09.2026): unvalidated_lang_from_url — очищаем мусор + localStorage.removeItem('filwords_lang'); + return; + } if (getUserId()) { setLanguage(language).catch(() => {}); } diff --git a/src/pages/LeaderboardPage.tsx b/src/pages/LeaderboardPage.tsx index 740f333..fc81d1c 100644 --- a/src/pages/LeaderboardPage.tsx +++ b/src/pages/LeaderboardPage.tsx @@ -219,6 +219,10 @@ const LeaderboardPage: React.FC = () => { return orderA - orderB; }); + // 🔧 ФИКС (23.09.2026): LEADERBOARD_O_N2_FILTER — выносим filter из .map(), + // чтобы не делать O(n²) на каждой строке. + const restEntries = entries.filter(e => e.rank > 3); + const labels: Record = { achievements: language === 'pl' ? 'Osiągnięcia' : language === 'ru' ? 'Достижения' : language === 'uk' ? 'Досягнення' : 'Achievements', unlocked: language === 'pl' ? 'odblokowano' : language === 'ru' ? 'получено' : language === 'uk' ? 'отримано' : 'unlocked', @@ -565,7 +569,7 @@ const LeaderboardPage: React.FC = () => { {t('score')} - {entries.filter(e => e.rank > 3).map((entry, index) => { + {restEntries.map((entry, index) => { const isCurrentUser = entry.telegram_id === currentUserId; const displayName = isCurrentUser ? 'You' : truncateName(entry.username, 15); @@ -577,7 +581,7 @@ const LeaderboardPage: React.FC = () => { gridTemplateColumns: '40px 1fr 80px', gap: '6px', padding: '12px 14px', - borderBottom: index < entries.filter(e => e.rank > 3).length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none', + borderBottom: index < restEntries.length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none', alignItems: 'center', fontSize: '13px', animation: `fadeInUp 0.3s ease ${0.3 + index * 0.02}s both`, diff --git a/src/pages/TeacherChatPage.tsx b/src/pages/TeacherChatPage.tsx index cdf1814..c785023 100644 --- a/src/pages/TeacherChatPage.tsx +++ b/src/pages/TeacherChatPage.tsx @@ -103,6 +103,8 @@ const TeacherChatPage: React.FC = () => { const messagesEndRef = useRef(null); const inputRef = useRef(null); const audioRef = useRef(null); + // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — храним URL для revoke. + const audioUrlRef = useRef(null); const idRef = useRef(messages.length > 0 ? Math.max(...messages.map(m => m.id)) + 1 : 0); const startTimeRef = useRef(Date.now()); @@ -277,7 +279,11 @@ const TeacherChatPage: React.FC = () => { audioRef.current.pause(); audioRef.current = null; } - + // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем предыдущий URL + if (audioUrlRef.current) { + try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } + audioUrlRef.current = null; + } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } @@ -287,12 +293,26 @@ const TeacherChatPage: React.FC = () => { try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); + audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke const audio = new Audio(audioUrl); audioRef.current = audio; - audio.onended = () => setIsPlaying(null); - audio.onerror = () => setIsPlaying(null); + audio.onended = () => { + setIsPlaying(null); + // 🔧 ФИКС (23.09.2026): освобождаем URL после воспроизведения + if (audioUrlRef.current === audioUrl) { + try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } + audioUrlRef.current = null; + } + }; + audio.onerror = () => { + setIsPlaying(null); + if (audioUrlRef.current === audioUrl) { + try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } + audioUrlRef.current = null; + } + }; await audio.play(); } catch (e) { @@ -314,6 +334,11 @@ const TeacherChatPage: React.FC = () => { audioRef.current.pause(); audioRef.current = null; } + // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS + if (audioUrlRef.current) { + try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } + audioUrlRef.current = null; + } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } @@ -323,10 +348,23 @@ const TeacherChatPage: React.FC = () => { try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); + audioUrlRef.current = audioUrl; const audio = new Audio(audioUrl); audioRef.current = audio; - audio.onended = () => setPlayingExampleLine(null); - audio.onerror = () => setPlayingExampleLine(null); + audio.onended = () => { + setPlayingExampleLine(null); + if (audioUrlRef.current === audioUrl) { + try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } + audioUrlRef.current = null; + } + }; + audio.onerror = () => { + setPlayingExampleLine(null); + if (audioUrlRef.current === audioUrl) { + try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } + audioUrlRef.current = null; + } + }; await audio.play(); } catch (e) { console.error('TTS error:', e); @@ -356,6 +394,11 @@ const TeacherChatPage: React.FC = () => { audioRef.current.pause(); audioRef.current = null; } + // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем URL при размонтировании + if (audioUrlRef.current) { + try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } + audioUrlRef.current = null; + } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } diff --git a/src/telegram.ts b/src/telegram.ts index d062e21..dcb179c 100644 --- a/src/telegram.ts +++ b/src/telegram.ts @@ -2,6 +2,11 @@ export const getInitData = (): string => { if (typeof window !== 'undefined' && window.Telegram?.WebApp?.initData) { return window.Telegram.WebApp.initData; } + // 🔧 ФИКС (23.09.2026): GET_INIT_DATA_EMPTY_STRING — логируем, + // чтобы понимать, что приложение открыто вне Telegram. + // Само значение "" оставляем для обратной совместимости с auth.py, + // который сам вернёт 401 "initData required" — это понятнее для дебага. + console.warn('[telegram] getInitData: no Telegram WebApp context'); return ""; };