🌊 Волна 6: frontend данные + утечки (8 багов)
Утечки памяти: - animated_cat_timeout_leak: timersRef + cleanup (AnimatedCat.tsx) - compress_fallback_objecturl_leak: revokeObjectURL в onload/onerror (FeedPostComposer.tsx) - lightbox_timeout_leak: safeTimeout + timersRef (ImageLightbox.tsx) - OBJECT_URL_LEAK_TTS: audioUrlRef + revoke на onended/onerror (TeacherChatPage.tsx) Данные: - existing_image_removal_no_delete: removed_images в payload (FeedPostComposer.tsx + api.ts, ТРЕБУЕТ BACKEND) - post_created_images_failed: пост создан → не даём дубль (FeedPostComposer.tsx) - GET_INIT_DATA_EMPTY_STRING: логирование + безопасный fallback (telegram.ts) - unvalidated_lang_from_url: валидация ['pl','ru','uk','en'] (LanguageContext.tsx) Производительность: - LEADERBOARD_O_N2_FILTER: filter вынесен из map (LeaderboardPage.tsx) TTS_VOICE_NOT_ENCODED — уже сделано в Волне 4. Аудит: Issue #3, frontend 8/34 задач
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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<AnimatedCatProps> = ({ size = 48, onClick, place = 1
|
||||
const [isPressed, setIsPressed] = useState(false);
|
||||
const [particles, setParticles] = useState<Particle[]>([]);
|
||||
const idRef = useRef(0);
|
||||
// 🔧 ФИКС (23.09.2026): animated_cat_timeout_leak — храним таймеры,
|
||||
// чтобы очищать их при размонтировании.
|
||||
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
setIsPressed(true);
|
||||
setTimeout(() => setIsPressed(false), 200);
|
||||
|
||||
const newParticles: Particle[] = [];
|
||||
|
||||
@@ -48,13 +50,25 @@ const AnimatedCat: React.FC<AnimatedCatProps> = ({ 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';
|
||||
|
||||
|
||||
@@ -77,9 +77,18 @@ async function compressImage(
|
||||
} catch {
|
||||
bitmap = await new Promise<HTMLImageElement>((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<FeedPostComposerProps> = ({
|
||||
const [slots, setSlots] = useState<(ImageSlot | null)[]>([null, null, null]);
|
||||
// Существующие картинки (режим редактирования) — занимают слоты в начале
|
||||
const [existingImages, setExistingImages] = useState<string[]>([]);
|
||||
// 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — трекаем удалённые URL,
|
||||
// чтобы передать их на бэк при сохранении.
|
||||
const [removedImages, setRemovedImages] = useState<string[]>([]);
|
||||
|
||||
// Три отдельных input[type=file] — по одному на слот. Без multiple.
|
||||
const slotInputRef0 = useRef<HTMLInputElement>(null);
|
||||
@@ -207,6 +219,8 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
|
||||
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<FeedPostComposerProps> = ({
|
||||
};
|
||||
|
||||
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<FeedPostComposerProps> = ({
|
||||
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<FeedPostComposerProps> = ({
|
||||
}
|
||||
}
|
||||
|
||||
// 🔧 ФИКС: если хоть одна загрузка упала — не считаем публикацию успешной
|
||||
// 🔧 ФИКС (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;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
|
||||
const touchStartX = useRef(0);
|
||||
const touchStartY = useRef(0);
|
||||
const isHorizontal = useRef<boolean | null>(null);
|
||||
// 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — храним таймеры для очистки.
|
||||
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
|
||||
// 🔧 ФИКС (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<ImageLightboxProps> = ({
|
||||
}
|
||||
}, [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<ImageLightboxProps> = ({
|
||||
if (currentIndex > 0) {
|
||||
setIsAnimating(true);
|
||||
setOffsetX(window.innerWidth); // улетаем вправо
|
||||
setTimeout(() => {
|
||||
safeTimeout(() => {
|
||||
goPrev();
|
||||
setOffsetX(0);
|
||||
setIsAnimating(false);
|
||||
@@ -122,14 +139,14 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
|
||||
// Отскок назад
|
||||
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<ImageLightboxProps> = ({
|
||||
// Отскок назад
|
||||
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;
|
||||
|
||||
@@ -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(() => {});
|
||||
}
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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 = () => {
|
||||
<span style={{ textAlign: 'right' }}>{t('score')}</span>
|
||||
</div>
|
||||
|
||||
{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`,
|
||||
|
||||
@@ -103,6 +103,8 @@ const TeacherChatPage: React.FC = () => {
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
// 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — храним URL для revoke.
|
||||
const audioUrlRef = useRef<string | null>(null);
|
||||
const idRef = useRef(messages.length > 0 ? Math.max(...messages.map(m => m.id)) + 1 : 0);
|
||||
const startTimeRef = useRef<number>(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();
|
||||
}
|
||||
|
||||
@@ -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 "";
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user