Files
filwordspl-frontend/src/pages/LessonViewPage.tsx
T
Drobysh 597dab924d 🌊 Волна 21: frontend — локализация подсказок (2 файла)
- LessonViewPage: hint использует getLocalized для isTranslationQuestion
- PracticeViewPage: hint использует getLocalized всегда (как варианты)

Аудит v10 frontend: LESSON/PRACTICE_HINT_SHOWS_POLISH_ONLY
2026-09-25 20:10:09 +03:00

689 lines
27 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 } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { useLocalized } from '../hooks/useLocalized';
import { fonts, radius } from '../styles/theme';
import { getLearningLesson, startLearningSession, saveLearningAnswer, completeLearningSession } from '../api';
interface QuestionOption {
option_key: string;
text_pl: string;
text_ru: string;
text_uk: string;
text_en: string;
is_correct: boolean;
wrong_because: string | null;
}
interface Question {
question: {
question_id: string;
prompt_pl: string;
prompt_ru: string;
prompt_uk: string;
prompt_en: string;
question_type: string;
skill_tag: string;
difficulty: number;
};
options: QuestionOption[];
}
interface Example {
text_pl: string;
text_ru: string;
text_uk: string;
text_en: string;
}
interface LessonData {
lesson: {
lesson_id: string;
title_pl: string;
title_ru: string;
title_uk: string;
title_en: string;
explanation_pl: string;
explanation_ru: string;
explanation_uk: string;
explanation_en: string;
};
examples: Example[];
questions: Question[];
}
const LessonViewPage: React.FC = () => {
const navigate = useNavigate();
const { lessonId, topicId } = useParams<{ lessonId: string; topicId: string }>();
const { t } = useLanguage();
const getLocalized = useLocalized();
const [lesson, setLesson] = useState<LessonData | null>(null);
const [loading, setLoading] = useState(true);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [selectedAnswers, setSelectedAnswers] = useState<Record<string, string>>({});
const [textInputValue, setTextInputValue] = useState('');
const [sessionId, setSessionId] = useState<number | null>(null);
const [isCompleting, setIsCompleting] = useState(false);
const [hintUsed, setHintUsed] = useState<Record<string, boolean>>({});
const [showHint, setShowHint] = useState(false);
const startTimeRef = useRef<number>(Date.now());
// 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS —
// экран результатов после последнего вопроса.
const [showResults, setShowResults] = useState(false);
const [sessionStats, setSessionStats] = useState<{ total: number; correct: number } | null>(null);
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,
});
useEffect(() => {
if (lessonId && topicId) {
setLoading(true);
getLearningLesson(lessonId)
.then((data: any) => {
setLesson(data);
return startLearningSession('A1', topicId, 'lesson');
})
.then((sessionData: any) => {
setSessionId(sessionData.session_id);
})
.catch(() => {})
.finally(() => setLoading(false));
}
}, [lessonId, topicId]);
// 🔧 ИСПРАВЛЕНО: saveAnswer теперь принимает isFinalAnswer и hintUsed
const saveAnswer = async (questionId: string, answer: string, isFinalAnswer: boolean = true, usedHint: boolean = false) => {
const timeTaken = Date.now() - startTimeRef.current;
startTimeRef.current = Date.now();
if (sessionId) {
try {
await saveLearningAnswer(sessionId, questionId, answer, timeTaken, isFinalAnswer, usedHint);
} catch (e) {
console.error('Error saving answer:', e);
}
}
};
const handleAnswerSelect = async (questionId: string, optionKey: string) => {
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
// 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=false
await saveAnswer(questionId, optionKey, true, false);
};
const handleTextInputChange = async (questionId: string, value: string) => {
setTextInputValue(value);
setSelectedAnswers(prev => ({ ...prev, [questionId]: value }));
};
const handleTextInputBlur = async (questionId: string) => {
if (textInputValue.trim()) {
// 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=false
await saveAnswer(questionId, textInputValue.trim(), true, false);
}
};
// 🔧 ФИКС (22.09.2026): подсказка больше НЕ засчитывается как ответ.
// Было: saveAnswer(..., correctAnswer, true, true) + setSelectedAnswers(correctAnswer)
// → ученик жал «💡 Hint», и вопрос засчитывался как правильный без решения.
// Стало: подсказка — только UI. Отправляем факт подсказки с isFinalAnswer=false,
// пустым ответом. Вариант в UI НЕ выбирается автоматически.
// Кнопка «Далее» ждёт, пока ученик сам выберет ответ.
const handleHintClick = async () => {
if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return;
setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true }));
setShowHint(true);
// 🔧 Логируем факт подсказки — но НЕ как финальный ответ.
// Пустой answer, isFinalAnswer=false, usedHint=true.
await saveAnswer(currentQuestion.question.question_id, '', false, true);
};
const handleNext = async () => {
setShowHint(false);
if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) {
setCurrentQuestionIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
// 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS —
// считаем результаты ДО навигации и показываем экран.
const questions = lesson?.questions || [];
let correct = 0;
for (const q of questions) {
const selected = selectedAnswers[q.question.question_id];
const correctOpt = q.options.find(o => o.is_correct);
if (selected && correctOpt && selected === correctOpt.option_key) {
correct++;
}
}
setSessionStats({ total: questions.length, correct });
let completionData: any = null;
if (sessionId) {
try {
completionData = await completeLearningSession(sessionId);
} catch (e) {
console.error('Error completing session:', e);
}
}
// Если сервер вернул свои цифры — используем их
if (completionData?.total !== undefined) {
setSessionStats({
total: completionData.total,
correct: completionData.correct_count ?? completionData.correct ?? correct,
});
}
setShowResults(true);
setIsCompleting(false);
}
};
const handleBack = () => {
setShowHint(false);
if (currentQuestionIndex > 0) {
setCurrentQuestionIndex(prev => prev - 1);
setTextInputValue('');
startTimeRef.current = Date.now();
}
};
// 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — экран результатов.
if (showResults && sessionStats) {
const percent = sessionStats.total > 0
? Math.round((sessionStats.correct / sessionStats.total) * 100)
: 0;
const isGood = percent >= 70;
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '24px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: brandColor, opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{
...glass({ padding: '32px 24px', borderRadius: radius.lg, maxWidth: '400px', width: '100%' }),
position: 'relative',
zIndex: 1,
textAlign: 'center',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ fontSize: '56px', marginBottom: '12px' }}>
{isGood ? '🎉' : '💪'}
</div>
<h2 style={{ fontSize: '22px', fontWeight: 800, color: textColor, margin: '0 0 20px 0' }}>
{t('teacherCompleted') || 'Lekcja ukończona!'}
</h2>
<div style={{
display: 'flex',
justifyContent: 'center',
gap: '24px',
marginBottom: '24px',
}}>
<div>
<div style={{ fontSize: '32px', fontWeight: 800, color: brandColor }}>
{sessionStats.correct}
</div>
<div style={{ fontSize: '12px', color: subColor, textTransform: 'uppercase', letterSpacing: '1px' }}>
{t('testCorrectAnswers') || 'poprawnych'}
</div>
</div>
<div style={{ width: '1px', background: 'rgba(0,0,0,0.1)' }} />
<div>
<div style={{ fontSize: '32px', fontWeight: 800, color: textColor }}>
{sessionStats.total}
</div>
<div style={{ fontSize: '12px', color: subColor, textTransform: 'uppercase', letterSpacing: '1px' }}>
{t('testQuestion') || 'pytań'}
</div>
</div>
<div style={{ width: '1px', background: 'rgba(0,0,0,0.1)' }} />
<div>
<div style={{ fontSize: '32px', fontWeight: 800, color: isGood ? brandColor : '#F39C12' }}>
{percent}%
</div>
<div style={{ fontSize: '12px', color: subColor, textTransform: 'uppercase', letterSpacing: '1px' }}>
%
</div>
</div>
</div>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
width: '100%',
padding: '16px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('testBackToTopic') || 'Powrót do tematu'}
</button>
</div>
</div>
);
}
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>
);
}
if (!lesson) return null;
const currentQuestion = lesson.questions[currentQuestionIndex];
const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1;
const isProduction = currentQuestion?.question.question_type === 'production';
const isCurrentAnswered = currentQuestion ? !!selectedAnswers[currentQuestion.question.question_id] : false;
// 🔧 ФИКС (23.09.2026): LESSON_HARDCODED_SKILL_TAG — используем optionsLanguage
// из данных вопроса (как в TeacherChatPage), а не хардкод skill_tag.
// Для любого навыка с optionsLanguage='user' варианты локализуются.
const optionsLanguage = (currentQuestion?.question as any)?.options_language;
// Fallback: если поле отсутствует — оставляем старое поведение
const isTranslationQuestion =
optionsLanguage === 'user' ||
(optionsLanguage === undefined && currentQuestion?.question.skill_tag === 'how_are_you');
const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false;
const correctOption = currentQuestion?.options.find(o => o.is_correct);
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: brandColor, opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes optionSelect {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка подсказки */}
{showHint && correctOption && (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.25)', zIndex: 500,
display: 'flex', alignItems: 'center', justifyContent: 'center',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowHint(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '360px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
<h3 style={{ margin: 0, fontSize: '16px', fontWeight: 700, color: textColor }}>
💡 {t('hintButton')}
</h3>
<button
onClick={() => setShowHint(false)}
style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }),
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
}}
>
✕
</button>
</div>
<div style={{ padding: '12px', background: `${brandColor}10`, borderRadius: radius.md, marginBottom: '12px' }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('correctOption')}:
</div>
{/* 🔧 ФИКС (25.09.2026): LESSON_HINT_SHOWS_POLISH_ONLY (#20) —
раньше в подсказке всегда показывался correctOption.text_pl,
даже для RU/EN/UK-пользователей. Теперь для вопросов
с optionsLanguage='user' показываем локализованный вариант
через getLocalized — как и в кнопках вариантов ниже. */}
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>
{isTranslationQuestion
? getLocalized(correctOption, 'text')
: correctOption.text_pl}
</div>
</div>
{correctOption.wrong_because && (
<div style={{ padding: '12px', background: 'rgba(255,215,0,0.1)', borderRadius: radius.md }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('whyLabel')}:
</div>
<div style={{ fontSize: '14px', color: textColor }}>
{correctOption.wrong_because}
</div>
</div>
)}
<button
onClick={() => setShowHint(false)}
style={{
width: '100%', marginTop: '16px', padding: '12px',
borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '14px', fontWeight: 700, cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</div>
)}
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
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>
<h1 style={{ fontSize: '18px', fontWeight: 700, margin: 0, color: textColor, flex: 1, textAlign: 'center' }}>
{getLocalized(lesson.lesson, 'title')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '16px', color: subColor, fontSize: '13px' }}>
{t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length}
</div>
{/* Объяснение (только на первом вопросе) */}
{currentQuestionIndex === 0 && (
<div style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
marginBottom: '16px',
}),
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ fontSize: '14px', lineHeight: '1.6', margin: 0, color: textColor, whiteSpace: 'pre-line' }}>
{getLocalized(lesson.lesson, 'explanation')}
</p>
{lesson.examples.length > 0 && (
<div style={{ marginTop: '12px', padding: '12px', background: `${brandColor}10`, borderRadius: radius.md }}>
{lesson.examples.map((example, i) => (
<div key={i} style={{ marginBottom: '6px' }}>
<div style={{ fontSize: '15px', fontWeight: 700, color: brandColor }}>🇵🇱 {example.text_pl}</div>
<div style={{ fontSize: '13px', color: subColor }}>{getLocalized(example, 'text')}</div>
</div>
))}
</div>
)}
</div>
)}
{/* Вопрос */}
{currentQuestion && (
<div style={{ animation: 'fadeInUp 0.3s ease 0.15s both', flex: 1 }}>
<p style={{ fontSize: '16px', fontWeight: 600, color: textColor, marginBottom: '16px' }}>
{getLocalized(currentQuestion.question, 'prompt')}
</p>
{isProduction ? (
<div>
<input
type="text"
value={textInputValue}
onChange={(e) => handleTextInputChange(currentQuestion.question.question_id, e.target.value)}
onBlur={() => handleTextInputBlur(currentQuestion.question.question_id)}
placeholder={t('teacherPlaceholder')}
style={{
width: '100%',
padding: '16px',
borderRadius: radius.lg,
border: textInputValue.trim() ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
background: textInputValue.trim() ? `${brandColor}10` : cardBg,
color: textColor,
fontSize: '18px',
fontWeight: 600,
fontFamily: fonts.main,
outline: 'none',
textAlign: 'center',
transition: 'all 0.2s ease',
boxShadow: textInputValue.trim() ? `0 0 15px ${brandColor}30` : '0 2px 8px rgba(31,38,73,0.06)',
}}
onFocus={(e) => {
e.currentTarget.style.borderColor = brandColor;
e.currentTarget.style.boxShadow = `0 0 15px ${brandColor}30`;
}}
/>
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{currentQuestion.options.map((option) => {
const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key;
return (
<button
key={option.option_key}
onClick={() => handleAnswerSelect(currentQuestion.question.question_id, option.option_key)}
style={{
padding: '14px 16px',
borderRadius: radius.md,
border: isSelected ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
background: isSelected ? `${brandColor}15` : cardBg,
color: textColor,
fontSize: '15px',
fontWeight: isSelected ? 700 : 500,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '10px',
boxShadow: isSelected ? `0 0 10px ${brandColor}30` : '0 2px 8px rgba(31,38,73,0.06)',
transition: 'all 0.2s ease',
animation: isSelected ? 'optionSelect 0.3s ease' : 'none',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{
width: '20px',
height: '20px',
borderRadius: '50%',
border: isSelected ? `2px solid ${brandColor}` : '2px solid rgba(0,0,0,0.2)',
background: isSelected ? brandColor : 'transparent',
flexShrink: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
{isSelected && <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFFFFF' }} />}
</span>
<span>
{isTranslationQuestion
? getLocalized(option, 'text')
: option.text_pl}
</span>
</button>
);
})}
</div>
)}
</div>
)}
{/* Кнопка подсказки */}
<div style={{ marginTop: '12px', animation: 'fadeInUp 0.3s ease 0.2s both' }}>
<button
onClick={handleHintClick}
disabled={isHintUsed}
style={{
width: '100%',
padding: '12px',
borderRadius: radius.md,
border: isHintUsed ? '1px solid rgba(0,0,0,0.06)' : `1px solid ${brandColor}30`,
background: isHintUsed ? 'rgba(0,0,0,0.03)' : `${brandColor}10`,
color: isHintUsed ? subColor : brandColor,
fontSize: '13px',
fontWeight: 600,
cursor: isHintUsed ? 'default' : 'pointer',
opacity: isHintUsed ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
{isHintUsed ? `🔒 ${t('hintUsed')}` : `💡 ${t('hintButton')}`}
</button>
</div>
{/* Кнопки навигации */}
<div style={{
display: 'flex',
gap: '12px',
marginTop: '20px',
animation: 'fadeInUp 0.3s ease 0.3s both',
}}>
<button
onClick={handleBack}
disabled={currentQuestionIndex === 0 || isCompleting}
style={{
...glass({
padding: '14px 20px',
borderRadius: radius.md,
}),
color: currentQuestionIndex === 0 ? subColor : textColor,
fontSize: '14px',
fontWeight: 600,
cursor: currentQuestionIndex === 0 ? 'default' : 'pointer',
opacity: currentQuestionIndex === 0 ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
← {t('back')}
</button>
<button
onClick={handleNext}
disabled={!isCurrentAnswered || isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: isCurrentAnswered
? `linear-gradient(135deg, ${brandColor}, #27AE60)`
: 'rgba(0,0,0,0.1)',
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: isCurrentAnswered ? 'pointer' : 'default',
transition: 'all 0.2s ease',
boxShadow: isCurrentAnswered ? `0 4px 15px ${brandColor}40` : 'none',
opacity: isCompleting ? 0.7 : 1,
}}
onTouchStart={(e) => {
if (isCurrentAnswered && !isCompleting) {
e.currentTarget.style.transform = 'scale(0.96)';
}
}}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{isCompleting
? t('testChecking')
: isLastQuestion
? t('testFinish')
: `${t('next')} →`}
</button>
</div>
</div>
</div>
);
};
export default LessonViewPage;