Files
filwordspl-frontend/src/pages/PronunciationPage.tsx
T
Drobysh f878411dce 🌊 Волна 12: frontend утечки + достижения (7 багов)
Утечки ObjectURL:
- URL_LEAK_FLASHCARDS: audioUrlRef + revoke (FlashcardsPage.tsx)
- URL_LEAK_PRONUNCIATION: audioUrlRef + revoke (PronunciationPage.tsx)
- URL_LEAK_TYPING: audioUrlRef + revoke (TypingPage.tsx)
- URL_LEAK_TESTVIEW: audioUrlRef + revoke (TestViewPage.tsx)

UI:
- ALERT_IN_TELEGRAM_MINIAPP: toast вместо alert() в TestViewPage (3 места)

Достижения:
- achievements_queue_overwrite_loses_new_items: функциональный update очереди (useAchievements.ts)
- achievements_reset_does_not_clear_timeout: clearTimeout в reset (useAchievements.ts)

Аудит v2: Issue #4, frontend 7/14 задач
2026-09-24 12:44:32 +03:00

487 lines
16 KiB
TypeScript

import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getNextPronunciationWord, trackPronunciationOpened, getTTS } from '../api';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface PronunciationWord {
word_pl: string;
translation: string;
level: string;
}
const levelColors: Record<string, string> = {
A1: '#2ECC71',
A2: '#27AE60',
B1: '#F39C12',
B2: '#E67E22',
C1: '#E74C3C',
C2: '#C0392B',
};
const PronunciationPage: React.FC = () => {
const navigate = useNavigate();
const { t } = useLanguage();
const [currentWord, setCurrentWord] = useState<PronunciationWord | null>(null);
const [loading, setLoading] = useState(true);
const [isPlaying, setIsPlaying] = useState(false);
const [showRules, setShowRules] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const isMountedRef = useRef(true);
const rulesShownRef = useRef(false);
const trackedRef = useRef(false);
const { activeAchievement, showAchievement } = useAchievements();
const brandColor = '#2ECC71';
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const bgColor = '#F4F5F7';
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,
});
const playWord = async (word: string) => {
// Останавливаем предыдущее аудио
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Останавливаем Web Speech API, если он что-то говорит
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlaying(true);
try {
// Пробуем Edge TTS через бэкенд
const audioBlob = await getTTS(word, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => {
if (isMountedRef.current) setIsPlaying(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
// 🔧 Освобождаем URL перед fallback
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Edge TTS не сработал — пробуем Web Speech API
playWebSpeech(word);
};
await audio.play();
} catch (e) {
console.error('Edge TTS error:', e);
// Edge TTS не сработал — пробуем Web Speech API
playWebSpeech(word);
}
};
const playWebSpeech = (word: string) => {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(word);
utterance.lang = 'pl-PL';
utterance.onend = () => {
if (isMountedRef.current) setIsPlaying(false);
};
utterance.onerror = () => {
if (isMountedRef.current) setIsPlaying(false);
};
window.speechSynthesis.speak(utterance);
} else {
if (isMountedRef.current) setIsPlaying(false);
}
};
const fetchWord = useCallback(() => {
setLoading(true);
getNextPronunciationWord()
.then((data: any) => {
if (isMountedRef.current) {
setCurrentWord(data);
}
})
.catch(() => {
if (isMountedRef.current) {
navigate('/menu');
}
})
.finally(() => {
if (isMountedRef.current) {
setLoading(false);
}
});
}, [navigate]);
useEffect(() => {
isMountedRef.current = true;
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_pronunciation');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_pronunciation', '1');
}
}, 500);
}
}
// Трекинг открытия Произношения
if (!trackedRef.current) {
trackedRef.current = true;
trackPronunciationOpened()
.then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
})
.catch(() => {});
}
fetchWord();
return () => {
isMountedRef.current = false;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем URL при unmount
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Останавливаем Web Speech API при уходе со страницы
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, [fetchWord, showAchievement]);
const levelColor = currentWord?.level ? levelColors[currentWord.level] || brandColor : brandColor;
if (loading) {
return (
<div style={{
minHeight: '100vh',
background: bgColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: subColor,
fontFamily: fonts.main,
fontSize: '18px',
}}>
{t('loading')}...
</div>
);
}
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '24px',
display: 'flex',
flexDirection: 'column',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: levelColor, opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.14, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
@keyframes soundWave {
0%, 100% { height: 8px; }
50% { height: 24px; }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('pronunciationRulesTitle') || '🔊 Pronunciation Rules'}
content={t('pronunciationRulesContent') || 'Rules content loading...'}
/>
{activeAchievement && (
<div style={{
position: 'fixed', top: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF', padding: '14px 20px', borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex', alignItems: 'center', gap: '12px',
minWidth: '250px', maxWidth: '90vw', animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
{/* Верхняя панель */}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button
onClick={() => navigate('/menu')}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
← {t('back')}
</button>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: textColor,
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{
fontSize: '14px',
fontWeight: 800,
color: levelColor,
background: `${levelColor}15`,
padding: '4px 10px',
borderRadius: radius.sm,
border: `1px solid ${levelColor}40`,
}}>
{currentWord?.level}
</div>
</div>
{/* Заголовок */}
<div style={{
textAlign: 'center',
marginBottom: '32px',
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
<h1 style={{
fontSize: '28px',
fontWeight: 900,
margin: 0,
color: textColor,
}}>
🔊 {t('pronunciation') || 'Pronunciation'}
</h1>
<p style={{
color: subColor,
fontSize: '14px',
marginTop: '8px',
}}>
{t('tapToListen') || 'Tap the word to listen'}
</p>
</div>
{/* Карточка со словом */}
{currentWord && (
<div style={{
flex: 1,
...glass({
borderRadius: radius.lg,
padding: '32px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
gap: '20px',
minHeight: '300px',
}),
border: `2px solid ${levelColor}30`,
animation: 'fadeInUp 0.3s ease 0.1s both',
cursor: 'pointer',
}}
onClick={() => playWord(currentWord.word_pl)}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{/* Иконка динамика */}
<div style={{
width: '80px',
height: '80px',
borderRadius: '50%',
background: `${levelColor}20`,
border: `2px solid ${levelColor}50`,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
animation: isPlaying ? 'pulse 1s ease infinite' : 'none',
}}>
<span style={{ fontSize: '36px' }}>🔊</span>
</div>
{/* Польское слово */}
<div style={{
fontSize: '36px',
fontWeight: 900,
color: textColor,
textAlign: 'center',
letterSpacing: '1px',
}}>
{currentWord.word_pl}
</div>
{/* Разделитель */}
<div style={{
width: '60px',
height: '2px',
background: `${levelColor}40`,
borderRadius: '1px',
}} />
{/* Перевод */}
<div style={{
fontSize: '18px',
color: subColor,
textAlign: 'center',
fontWeight: 400,
}}>
{currentWord.translation}
</div>
{/* Индикатор воспроизведения */}
{isPlaying && (
<div style={{ display: 'flex', gap: '4px', alignItems: 'flex-end', height: '24px' }}>
{[0, 1, 2, 3, 4].map((i) => (
<div
key={i}
style={{
width: '4px',
height: '8px',
background: levelColor,
borderRadius: '2px',
animation: `soundWave 0.6s ease infinite ${i * 0.1}s`,
}}
/>
))}
</div>
)}
</div>
)}
{/* Кнопка Далее */}
<button
onClick={fetchWord}
style={{
marginTop: '20px',
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(180deg, ${levelColor}E6, ${levelColor}CC)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 8px 24px ${levelColor}50`,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('next') || 'Next'} →
</button>
</div>
</div>
);
};
export default PronunciationPage;