feat(lesson): новая логика ответов + повторы + отчёт

Backend:
- saveLearningAnswer: параметр isRetry + типизация ответа
  (attempt_number, show_correct_answer, correct_answer)
- completeLearningSession: параметр lang + report
  (topic_name, percent, message, weak_skills, next_topic)

LessonViewPage:
- answerState: unanswered | correct | wrong | retrying
- 1-2 ошибка: «Ничего страшного! Посмотри урок ещё раз» + [Повторить] [Далее]
- 3+ ошибка: модалка с правильным ответом + [Повторить] [Продолжить]
- «Повторить урок» → скролл наверх, объяснение + примеры,
  все ответы разблокированы
- Убрана кнопка подсказки (показывала правильный ответ)
- Экран отчёта: круг с процентом, слабые навыки, кнопки
  [К теме] [Следующая тема]
This commit is contained in:
2026-10-02 13:22:22 +03:00
parent cae2443dda
commit c01eaa901e
2 changed files with 534 additions and 299 deletions
+39 -3
View File
@@ -520,7 +520,24 @@ export const startLearningSession = (levelCode: string, topicId: string, session
body: JSON.stringify({ level_code: levelCode, topic_id: topicId, session_type: sessionType }), body: JSON.stringify({ level_code: levelCode, topic_id: topicId, session_type: sessionType }),
}); });
export const saveLearningAnswer = (sessionId: number, questionId: string, answer: string, timeTakenMs: number = 0, isFinalAnswer: boolean = true, hintUsed: boolean = false) => // 🔧 ОБНОВЛЕНО (02.10.2026): saveLearningAnswer_is_retry_and_types —
// добавлен параметр is_retry для повторов, типизирован ответ
// (attempt_number, show_correct_answer, correct_answer).
export const saveLearningAnswer = (
sessionId: number,
questionId: string,
answer: string,
timeTakenMs: number = 0,
isFinalAnswer: boolean = true,
hintUsed: boolean = false,
isRetry: boolean = false,
): Promise<{
correct: boolean;
wrong_because: string | null;
attempt_number: number;
show_correct_answer: boolean;
correct_answer: string | null;
}> =>
fetchAPI('/learning/answer', { fetchAPI('/learning/answer', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
@@ -530,13 +547,32 @@ export const saveLearningAnswer = (sessionId: number, questionId: string, answer
time_taken_ms: timeTakenMs, time_taken_ms: timeTakenMs,
is_final_answer: isFinalAnswer, is_final_answer: isFinalAnswer,
hint_used: hintUsed, hint_used: hintUsed,
is_retry: isRetry,
}), }),
}); });
export const completeLearningSession = (sessionId: number) => // 🔧 ОБНОВЛЕНО (02.10.2026): completeLearningSession_report —
// добавлен параметр lang, типизирован ответ с report
// (topic_name, percent, message, weak_skills, next_topic).
export const completeLearningSession = (
sessionId: number,
lang: string = 'ru',
): Promise<{
status: string;
total: number;
correct_count: number;
report: {
topic_id: string;
topic_name: string | null;
percent: number;
message: string;
weak_skills: Array<{ skill_tag: string; name: string; errors: number }>;
next_topic: { topic_id: string; name: string } | null;
};
}> =>
fetchAPI('/learning/session/complete', { fetchAPI('/learning/session/complete', {
method: 'POST', method: 'POST',
body: JSON.stringify({ session_id: sessionId }), body: JSON.stringify({ session_id: sessionId, lang }),
}); });
export const getLearningProgress = () => export const getLearningProgress = () =>
+435 -236
View File
@@ -53,11 +53,28 @@ interface LessonData {
questions: Question[]; questions: Question[];
} }
interface ReportData {
topic_id: string;
topic_name: string | null;
percent: number;
message: string;
weak_skills: Array<{ skill_tag: string; name: string; errors: number }>;
next_topic: { topic_id: string; name: string } | null;
}
// Состояние ответа на текущий вопрос
type AnswerState =
| { kind: 'unanswered' } // ещё не ответил
| { kind: 'correct'; attempt: number } // ответил правильно
| { kind: 'wrong'; attempt: number; showCorrect: boolean; correctAnswer: string | null } // неправильно
| { kind: 'retrying' }; // нажал «Повторить урок», читает заново
const LessonViewPage: React.FC = () => { const LessonViewPage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { lessonId, topicId } = useParams<{ lessonId: string; topicId: string }>(); const { lessonId, topicId } = useParams<{ lessonId: string; topicId: string }>();
const { t } = useLanguage(); const { t, language } = useLanguage();
const getLocalized = useLocalized(); const getLocalized = useLocalized();
const [lesson, setLesson] = useState<LessonData | null>(null); const [lesson, setLesson] = useState<LessonData | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0); const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
@@ -65,13 +82,13 @@ const LessonViewPage: React.FC = () => {
const [textInputValue, setTextInputValue] = useState(''); const [textInputValue, setTextInputValue] = useState('');
const [sessionId, setSessionId] = useState<number | null>(null); const [sessionId, setSessionId] = useState<number | null>(null);
const [isCompleting, setIsCompleting] = useState(false); const [isCompleting, setIsCompleting] = useState(false);
const [hintUsed, setHintUsed] = useState<Record<string, boolean>>({});
const [showHint, setShowHint] = useState(false);
const startTimeRef = useRef<number>(Date.now()); const startTimeRef = useRef<number>(Date.now());
// 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — const topRef = useRef<HTMLDivElement>(null);
// экран результатов после последнего вопроса.
const [showResults, setShowResults] = useState(false); // 🔧 НОВОЕ (02.10.2026): новое состояние ответа + отчёт
const [sessionStats, setSessionStats] = useState<{ total: number; correct: number } | null>(null); const [answerState, setAnswerState] = useState<AnswerState>({ kind: 'unanswered' });
const [report, setReport] = useState<ReportData | null>(null);
const [saving, setSaving] = useState(false);
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
const textColor = '#1A1A2E'; const textColor = '#1A1A2E';
@@ -104,120 +121,173 @@ const LessonViewPage: React.FC = () => {
} }
}, [lessonId, topicId]); }, [lessonId, topicId]);
// 🔧 ИСПРАВЛЕНО: saveAnswer теперь принимает isFinalAnswer и hintUsed // 🔧 НОВОЕ (02.10.2026): сохраняем ответ с is_retry
const saveAnswer = async (questionId: string, answer: string, isFinalAnswer: boolean = true, usedHint: boolean = false) => { const saveAnswer = async (
questionId: string,
answer: string,
isRetry: boolean,
): Promise<{
correct: boolean;
attempt_number: number;
show_correct_answer: boolean;
correct_answer: string | null;
} | null> => {
const timeTaken = Date.now() - startTimeRef.current; const timeTaken = Date.now() - startTimeRef.current;
startTimeRef.current = Date.now(); startTimeRef.current = Date.now();
if (sessionId) { if (!sessionId) return null;
try { try {
await saveLearningAnswer(sessionId, questionId, answer, timeTaken, isFinalAnswer, usedHint); const res = await saveLearningAnswer(
sessionId,
questionId,
answer,
timeTaken,
true, // is_final_answer
false, // hint_used
isRetry, // 🔧 НОВОЕ
);
return res;
} catch (e) { } catch (e) {
console.error('Error saving answer:', e); console.error('Error saving answer:', e);
} return null;
} }
}; };
// 🔧 НОВОЕ (02.10.2026): выбор варианта — теперь с новой логикой
const handleAnswerSelect = async (questionId: string, optionKey: string) => { const handleAnswerSelect = async (questionId: string, optionKey: string) => {
// 🔧 ФИКС (01.10.2026): haptic_lesson_view — выбор варианта if (saving) return;
haptic.selection(); haptic.selection();
setSaving(true);
// Оптимистично показываем выбранный вариант
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey })); setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
// 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=false
await saveAnswer(questionId, optionKey, true, false); const isRetry = answerState.kind === 'retrying';
const res = await saveAnswer(questionId, optionKey, isRetry);
if (!res) {
setSaving(false);
return;
}
if (res.correct) {
haptic.success();
setAnswerState({
kind: 'correct',
attempt: res.attempt_number,
});
} else {
haptic.error();
setAnswerState({
kind: 'wrong',
attempt: res.attempt_number,
showCorrect: res.show_correct_answer,
correctAnswer: res.correct_answer,
});
}
setSaving(false);
}; };
const handleTextInputChange = async (questionId: string, value: string) => { // 🔧 НОВОЕ (02.10.2026): ввод текста — сохраняем через blur
const handleTextInputChange = (questionId: string, value: string) => {
setTextInputValue(value); setTextInputValue(value);
setSelectedAnswers(prev => ({ ...prev, [questionId]: value })); setSelectedAnswers(prev => ({ ...prev, [questionId]: value }));
}; };
const handleTextInputBlur = async (questionId: string) => { const handleTextInputBlur = async (questionId: string) => {
if (textInputValue.trim()) { if (!textInputValue.trim() || saving) return;
// 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=false
await saveAnswer(questionId, textInputValue.trim(), true, false); setSaving(true);
const isRetry = answerState.kind === 'retrying';
const res = await saveAnswer(questionId, textInputValue.trim(), isRetry);
if (!res) {
setSaving(false);
return;
} }
if (res.correct) {
haptic.success();
setAnswerState({ kind: 'correct', attempt: res.attempt_number });
} else {
haptic.error();
setAnswerState({
kind: 'wrong',
attempt: res.attempt_number,
showCorrect: res.show_correct_answer,
correctAnswer: res.correct_answer,
});
}
setSaving(false);
}; };
// 🔧 ФИКС (22.09.2026): подсказка больше НЕ засчитывается как ответ. // 🔧 НОВОЕ (02.10.2026): «Повторить урок» — скролл наверх,
// Было: saveAnswer(..., correctAnswer, true, true) + setSelectedAnswers(correctAnswer) // разблокируем ответы, показываем объяснение + примеры
// → ученик жал «💡 Hint», и вопрос засчитывался как правильный без решения. const handleRetry = () => {
// Стало: подсказка — только UI. Отправляем факт подсказки с isFinalAnswer=false, haptic.medium();
// пустым ответом. Вариант в UI НЕ выбирается автоматически. setAnswerState({ kind: 'retrying' });
// Кнопка «Далее» ждёт, пока ученик сам выберет ответ. setSelectedAnswers(prev => {
const handleHintClick = async () => { const copy = { ...prev };
if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return; if (lesson && lesson.questions[currentQuestionIndex]) {
delete copy[lesson.questions[currentQuestionIndex].question.question_id];
setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true })); }
setShowHint(true); return copy;
});
// 🔧 Логируем факт подсказки — но НЕ как финальный ответ. setTextInputValue('');
// Пустой answer, isFinalAnswer=false, usedHint=true. // Скролл наверх
await saveAnswer(currentQuestion.question.question_id, '', false, true); topRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
startTimeRef.current = Date.now();
}; };
// 🔧 НОВОЕ (02.10.2026): «Следующий вопрос» (пропустить ошибку)
const handleNext = async () => { const handleNext = async () => {
setShowHint(false); haptic.light();
if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) { if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) {
setCurrentQuestionIndex(prev => prev + 1); setCurrentQuestionIndex(prev => prev + 1);
setTextInputValue(''); setTextInputValue('');
setAnswerState({ kind: 'unanswered' });
startTimeRef.current = Date.now(); startTimeRef.current = Date.now();
topRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
} else { } else {
// 🔧 ФИКС (01.10.2026): haptic_lesson_view — завершение урока // Последний вопрос → завершаем урок, получаем отчёт
haptic.heavy(); haptic.heavy();
setIsCompleting(true); 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; let completionData: any = null;
if (sessionId) { if (sessionId) {
try { try {
completionData = await completeLearningSession(sessionId); completionData = await completeLearningSession(sessionId, language || 'ru');
} catch (e) { } catch (e) {
console.error('Error completing session:', e); console.error('Error completing session:', e);
} }
} }
// Если сервер вернул свои цифры — используем их if (completionData?.report) {
if (completionData?.total !== undefined) { setReport(completionData.report);
setSessionStats({
total: completionData.total,
correct: completionData.correct_count ?? completionData.correct ?? correct,
});
} }
setShowResults(true);
setIsCompleting(false); setIsCompleting(false);
} }
}; };
const handleBack = () => { const handleBack = () => {
// 🔧 ФИКС (01.10.2026): haptic_lesson_view — вибрация возврата
haptic.light(); haptic.light();
setShowHint(false);
if (currentQuestionIndex > 0) { if (currentQuestionIndex > 0) {
setCurrentQuestionIndex(prev => prev - 1); setCurrentQuestionIndex(prev => prev - 1);
setTextInputValue(''); setTextInputValue('');
setAnswerState({ kind: 'unanswered' });
startTimeRef.current = Date.now(); startTimeRef.current = Date.now();
} }
}; };
// 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — экран результатов. // ============ ЭКРАН ОТЧЁТА ============
if (showResults && sessionStats) { if (report) {
const percent = sessionStats.total > 0 const percent = report.percent;
? Math.round((sessionStats.correct / sessionStats.total) * 100) const emoji = percent >= 90 ? '🎉' : percent >= 75 ? '💪' : percent >= 60 ? '👍' : '📚';
: 0;
const isGood = percent >= 70;
return ( return (
<div style={{ <div style={{
@@ -236,72 +306,142 @@ const LessonViewPage: React.FC = () => {
<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={{ 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={{ <div style={{
...glass({ padding: '32px 24px', borderRadius: radius.lg, maxWidth: '400px', width: '100%' }), ...glass({ padding: '28px 22px', borderRadius: radius.lg, maxWidth: '420px', width: '100%' }),
position: 'relative', position: 'relative',
zIndex: 1, zIndex: 1,
textAlign: 'center', textAlign: 'center',
animation: 'fadeInUp 0.3s ease',
}}> }}>
<div style={{ fontSize: '56px', marginBottom: '12px' }}> <div style={{ fontSize: '56px', marginBottom: '8px' }}>{emoji}</div>
{isGood ? '🎉' : '💪'}
</div> <h2 style={{ fontSize: '20px', fontWeight: 800, color: textColor, margin: '0 0 6px 0' }}>
<h2 style={{ fontSize: '22px', fontWeight: 800, color: textColor, margin: '0 0 20px 0' }}> {report.topic_name || 'Тема'}
{t('teacherCompleted') || 'Lekcja ukończona!'}
</h2> </h2>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '20px' }}>
{t('lessonCompleted') || 'Урок завершён!'}
</div>
{/* Круг с процентом */}
<div style={{ <div style={{
width: '110px',
height: '110px',
borderRadius: '50%',
margin: '0 auto 20px',
background: `conic-gradient(${brandColor} ${percent * 3.6}deg, rgba(0,0,0,0.06) 0)`,
display: 'flex', display: 'flex',
alignItems: 'center',
justifyContent: 'center', justifyContent: 'center',
gap: '24px',
marginBottom: '24px',
}}> }}>
<div> <div style={{
<div style={{ fontSize: '32px', fontWeight: 800, color: brandColor }}> width: '90px',
{sessionStats.correct} height: '90px',
</div> borderRadius: '50%',
<div style={{ fontSize: '12px', color: subColor, textTransform: 'uppercase', letterSpacing: '1px' }}> background: '#FFFFFF',
{t('testCorrectAnswers') || 'poprawnych'} display: 'flex',
</div> alignItems: 'center',
</div> justifyContent: 'center',
<div style={{ width: '1px', background: 'rgba(0,0,0,0.1)' }} /> flexDirection: 'column',
<div> }}>
<div style={{ fontSize: '32px', fontWeight: 800, color: textColor }}> <div style={{ fontSize: '28px', fontWeight: 800, color: brandColor }}>
{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}% {percent}%
</div> </div>
<div style={{ fontSize: '12px', color: subColor, textTransform: 'uppercase', letterSpacing: '1px' }}> <div style={{ fontSize: '11px', color: subColor, marginTop: '-2px' }}>
% {report.weak_skills.length === 0 ? '✨' : ''}
</div> </div>
</div> </div>
</div> </div>
{/* Сообщение */}
<p style={{
fontSize: '15px',
color: textColor,
lineHeight: 1.5,
margin: '0 0 16px 0',
}}>
{report.message}
</p>
{/* Слабые навыки */}
{report.weak_skills.length > 0 && (
<div style={{
padding: '12px 14px',
background: 'rgba(249,71,30,0.06)',
borderRadius: radius.md,
marginBottom: '20px',
textAlign: 'left',
}}>
<div style={{
fontSize: '12px',
fontWeight: 700,
color: '#F9471E',
marginBottom: '8px',
textTransform: 'uppercase',
letterSpacing: '0.5px',
}}>
💡 {t('lessonRepeat') || 'Стоит повторить'}
</div>
{report.weak_skills.map((w, i) => (
<div key={i} style={{
fontSize: '13px',
color: textColor,
marginBottom: '4px',
display: 'flex',
justifyContent: 'space-between',
}}>
<span>• {w.name}</span>
<span style={{ color: '#F9471E', fontWeight: 700 }}>
{w.errors} {w.errors === 1 ? 'ошибка' : w.errors < 5 ? 'ошибки' : 'ошибок'}
</span>
</div>
))}
</div>
)}
{/* Кнопки */}
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button <button
onClick={() => navigate(`/lessons/topic/${topicId}`)} onClick={() => {
haptic.medium();
navigate(`/lessons/topic/${topicId}`);
}}
style={{ style={{
width: '100%', width: '100%',
padding: '16px', padding: '14px',
borderRadius: radius.md, borderRadius: radius.md,
border: 'none', border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`, background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', color: '#FFFFFF',
fontSize: '16px', fontSize: '15px',
fontWeight: 700, fontWeight: 700,
cursor: 'pointer', cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`, 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'} ✓ {t('testBackToTopic') || 'К теме'}
</button> </button>
{report.next_topic && (
<button
onClick={() => {
haptic.medium();
navigate(`/lessons/topic/${report.next_topic!.topic_id}`);
}}
style={{
width: '100%',
padding: '14px',
borderRadius: radius.md,
border: `1px solid ${brandColor}40`,
background: `${brandColor}10`,
color: brandColor,
fontSize: '15px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('lessonNextTopic') || 'Следующая тема'} →
</button>
)}
</div>
</div> </div>
</div> </div>
); );
@@ -329,22 +469,17 @@ const LessonViewPage: React.FC = () => {
const currentQuestion = lesson.questions[currentQuestionIndex]; const currentQuestion = lesson.questions[currentQuestionIndex];
const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1; const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1;
const isProduction = currentQuestion?.question.question_type === 'production'; 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; const optionsLanguage = (currentQuestion?.question as any)?.options_language;
// Fallback: если поле отсутствует — оставляем старое поведение const isTranslationQuestion = optionsLanguage === 'user';
const isTranslationQuestion =
optionsLanguage === 'user' ||
(optionsLanguage === undefined && currentQuestion?.question.skill_tag === 'how_are_you');
const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false; const isAnswered = answerState.kind === 'correct' || answerState.kind === 'wrong';
const correctOption = currentQuestion?.options.find(o => o.is_correct); const isRetrying = answerState.kind === 'retrying';
return ( return (
<div style={{ <div
ref={topRef}
style={{
minHeight: '100vh', minHeight: '100vh',
background: bgColor, background: bgColor,
color: textColor, color: textColor,
@@ -354,7 +489,8 @@ const LessonViewPage: React.FC = () => {
flexDirection: 'column', flexDirection: 'column',
position: 'relative', position: 'relative',
overflow: 'hidden', 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={{ 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>{` <style>{`
@@ -375,84 +511,92 @@ const LessonViewPage: React.FC = () => {
0% { transform: translateY(20px); opacity: 0; } 0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; } 100% { transform: translateY(0); opacity: 1; }
} }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
`}</style> `}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}> <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка подсказки */} {/* Модалка с правильным ответом (3-я ошибка) */}
{showHint && correctOption && ( {answerState.kind === 'wrong' && answerState.showCorrect && answerState.correctAnswer && (
<div <div
style={{ style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.25)', zIndex: 500, background: 'rgba(20,22,35,0.55)', zIndex: 500,
display: 'flex', alignItems: 'center', justifyContent: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center',
animation: 'modalFadeIn 0.2s ease', padding: '20px', animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
}} }}
onClick={(e) => { if (e.target === e.currentTarget) setShowHint(false); }}
> >
<div style={{ <div style={{
...glass({ ...glass({
borderRadius: radius.lg, borderRadius: radius.lg,
padding: '20px', padding: '24px',
width: '100%', width: '100%',
maxWidth: '360px', maxWidth: '360px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)', textAlign: 'center',
}), }),
animation: 'modalSlideUp 0.3s ease', animation: 'modalSlideUp 0.3s ease',
}}> }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}> <div style={{ fontSize: '48px', marginBottom: '8px' }}>💪</div>
<h3 style={{ margin: 0, fontSize: '16px', fontWeight: 700, color: textColor }}> <h3 style={{ margin: '0 0 8px 0', fontSize: '17px', fontWeight: 800, color: textColor }}>
💡 {t('hintButton')} {t('lessonTryAgain') || 'Уже 3 попытки!'}
</h3> </h3>
<p style={{ fontSize: '14px', color: subColor, margin: '0 0 16px 0', lineHeight: 1.5 }}>
{t('lessonShowCorrect') || 'Правильный ответ:'}
</p>
<div style={{
padding: '14px',
background: `${brandColor}15`,
borderRadius: radius.md,
marginBottom: '16px',
fontSize: '16px',
fontWeight: 700,
color: brandColor,
}}>
{answerState.correctAnswer}
</div>
<p style={{ fontSize: '13px', color: subColor, margin: '0 0 16px 0' }}>
{t('lessonReadExplanation') || 'Повтори урок внимательнее — там есть объяснение.'}
</p>
<div style={{ display: 'flex', gap: '8px' }}>
<button <button
onClick={() => setShowHint(false)} onClick={handleRetry}
style={{ style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }), flex: 1,
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer', padding: '12px',
borderRadius: radius.md,
border: `1px solid ${brandColor}40`,
background: `${brandColor}10`,
color: brandColor,
fontSize: '13px',
fontWeight: 700,
cursor: 'pointer',
}} }}
> >
✕ 📖 {t('lessonRetry') || 'Повторить'}
</button> </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 <button
onClick={() => setShowHint(false)} onClick={handleNext}
style={{ style={{
width: '100%', marginTop: '16px', padding: '12px', flex: 1,
borderRadius: radius.md, border: 'none', padding: '12px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`, background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '14px', fontWeight: 700, cursor: 'pointer', color: '#FFFFFF',
fontSize: '13px',
fontWeight: 700,
cursor: 'pointer',
}} }}
> >
{t('teacherClose')} → {isLastQuestion ? (t('testFinish') || 'Завершить') : (t('next') || 'Дальше')}
</button> </button>
</div> </div>
</div> </div>
</div>
)} )}
{/* Заголовок */} {/* Заголовок */}
@@ -466,18 +610,12 @@ const LessonViewPage: React.FC = () => {
<button <button
onClick={() => navigate(`/lessons/topic/${topicId}`)} onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{ style={{
...glass({ ...glass({ padding: '10px 18px', borderRadius: radius.md }),
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor, color: textColor,
fontSize: '14px', fontSize: '14px',
fontWeight: 600, fontWeight: 600,
cursor: 'pointer', 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')} ← {t('back')}
</button> </button>
@@ -491,16 +629,24 @@ const LessonViewPage: React.FC = () => {
{t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length} {t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length}
</div> </div>
{/* Объяснение (только на первом вопросе) */} {/* Объяснение + примеры (на первом вопросе ИЛИ при повторе) */}
{currentQuestionIndex === 0 && ( {(currentQuestionIndex === 0 || isRetrying) && (
<div style={{ <div style={{
...glass({ ...glass({ padding: '16px', borderRadius: radius.lg, marginBottom: '16px' }),
padding: '16px',
borderRadius: radius.lg,
marginBottom: '16px',
}),
animation: 'fadeInUp 0.3s ease 0.1s both', animation: 'fadeInUp 0.3s ease 0.1s both',
}}> }}>
{isRetrying && (
<div style={{
fontSize: '12px',
fontWeight: 700,
color: brandColor,
marginBottom: '10px',
textTransform: 'uppercase',
letterSpacing: '0.5px',
}}>
📖 {t('lessonReadCarefully') || 'Прочитай внимательно:'}
</div>
)}
<p style={{ fontSize: '14px', lineHeight: '1.6', margin: 0, color: textColor, whiteSpace: 'pre-line' }}> <p style={{ fontSize: '14px', lineHeight: '1.6', margin: 0, color: textColor, whiteSpace: 'pre-line' }}>
{getLocalized(lesson.lesson, 'explanation')} {getLocalized(lesson.lesson, 'explanation')}
</p> </p>
@@ -532,6 +678,7 @@ const LessonViewPage: React.FC = () => {
onChange={(e) => handleTextInputChange(currentQuestion.question.question_id, e.target.value)} onChange={(e) => handleTextInputChange(currentQuestion.question.question_id, e.target.value)}
onBlur={() => handleTextInputBlur(currentQuestion.question.question_id)} onBlur={() => handleTextInputBlur(currentQuestion.question.question_id)}
placeholder={t('teacherPlaceholder')} placeholder={t('teacherPlaceholder')}
disabled={isAnswered || saving}
style={{ style={{
width: '100%', width: '100%',
padding: '16px', padding: '16px',
@@ -545,11 +692,6 @@ const LessonViewPage: React.FC = () => {
outline: 'none', outline: 'none',
textAlign: 'center', textAlign: 'center',
transition: 'all 0.2s ease', 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>
@@ -557,11 +699,13 @@ const LessonViewPage: React.FC = () => {
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{currentQuestion.options.map((option) => { {currentQuestion.options.map((option) => {
const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key; const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key;
const disabled = (isAnswered && !isRetrying) || saving;
return ( return (
<button <button
key={option.option_key} key={option.option_key}
data-no-haptic="true" data-no-haptic="true"
disabled={disabled}
onClick={() => handleAnswerSelect(currentQuestion.question.question_id, option.option_key)} onClick={() => handleAnswerSelect(currentQuestion.question.question_id, option.option_key)}
style={{ style={{
padding: '14px 16px', padding: '14px 16px',
@@ -571,7 +715,8 @@ const LessonViewPage: React.FC = () => {
color: textColor, color: textColor,
fontSize: '15px', fontSize: '15px',
fontWeight: isSelected ? 700 : 500, fontWeight: isSelected ? 700 : 500,
cursor: 'pointer', cursor: disabled ? 'default' : 'pointer',
opacity: disabled && !isSelected ? 0.5 : 1,
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: '10px', gap: '10px',
@@ -579,8 +724,6 @@ const LessonViewPage: React.FC = () => {
transition: 'all 0.2s ease', transition: 'all 0.2s ease',
animation: isSelected ? 'optionSelect 0.3s ease' : 'none', 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={{ <span style={{
width: '20px', width: '20px',
@@ -596,9 +739,7 @@ const LessonViewPage: React.FC = () => {
{isSelected && <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFFFFF' }} />} {isSelected && <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFFFFF' }} />}
</span> </span>
<span> <span>
{isTranslationQuestion {isTranslationQuestion ? getLocalized(option, 'text') : option.text_pl}
? getLocalized(option, 'text')
: option.text_pl}
</span> </span>
</button> </button>
); );
@@ -608,88 +749,146 @@ const LessonViewPage: React.FC = () => {
</div> </div>
)} )}
{/* Кнопка подсказки */} {/* Обратная связь после ответа */}
<div style={{ marginTop: '12px', animation: 'fadeInUp 0.3s ease 0.2s both' }}> {answerState.kind === 'correct' && (
<button <div style={{
onClick={handleHintClick} marginTop: '16px',
disabled={isHintUsed} padding: '14px 16px',
style={{
width: '100%',
padding: '12px',
borderRadius: radius.md, borderRadius: radius.md,
border: isHintUsed ? '1px solid rgba(0,0,0,0.06)' : `1px solid ${brandColor}30`, background: `${brandColor}15`,
background: isHintUsed ? 'rgba(0,0,0,0.03)' : `${brandColor}10`, border: `1px solid ${brandColor}40`,
color: isHintUsed ? subColor : brandColor, animation: 'fadeInUp 0.3s ease',
fontSize: '13px', }}>
fontWeight: 600, <div style={{ fontSize: '15px', fontWeight: 700, color: brandColor }}>
cursor: isHintUsed ? 'default' : 'pointer', ✅ {t('lessonCorrect') || 'Правильно!'}
opacity: isHintUsed ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
{isHintUsed ? `🔒 ${t('hintUsed')}` : `💡 ${t('hintButton')}`}
</button>
</div> </div>
</div>
)}
{answerState.kind === 'wrong' && !answerState.showCorrect && (
<div style={{
marginTop: '16px',
padding: '14px 16px',
borderRadius: radius.md,
background: `${brandColor}10`,
border: `1px solid ${brandColor}30`,
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ fontSize: '15px', fontWeight: 700, color: textColor, marginBottom: '4px' }}>
💪 {t('lessonNoWorry') || 'Ничего страшного!'}
</div>
<div style={{ fontSize: '13px', color: subColor, lineHeight: 1.5 }}>
{t('lessonReadAgain') || 'Посмотри урок ещё раз и попробуй снова.'}
</div>
</div>
)}
{/* Кнопки навигации */} {/* Кнопки навигации */}
{!isRetrying && (
<div style={{ <div style={{
display: 'flex', display: 'flex',
gap: '12px', gap: '12px',
marginTop: '20px', marginTop: '20px',
animation: 'fadeInUp 0.3s ease 0.3s both', animation: 'fadeInUp 0.3s ease 0.3s both',
}}> }}>
{currentQuestionIndex > 0 && (
<button <button
onClick={handleBack} onClick={handleBack}
disabled={currentQuestionIndex === 0 || isCompleting} disabled={saving}
style={{ style={{
...glass({ ...glass({ padding: '14px 20px', borderRadius: radius.md }),
padding: '14px 20px', color: textColor,
borderRadius: radius.md,
}),
color: currentQuestionIndex === 0 ? subColor : textColor,
fontSize: '14px', fontSize: '14px',
fontWeight: 600, fontWeight: 600,
cursor: currentQuestionIndex === 0 ? 'default' : 'pointer', cursor: 'pointer',
opacity: currentQuestionIndex === 0 ? 0.5 : 1, opacity: saving ? 0.5 : 1,
transition: 'all 0.2s ease',
}} }}
> >
← {t('back')} ←
</button> </button>
)}
{answerState.kind === 'unanswered' && (
<button <button
onClick={handleNext} disabled
data-no-haptic="true"
disabled={!isCurrentAnswered || isCompleting}
style={{ style={{
flex: 1, flex: 1,
padding: '14px 20px', padding: '14px 20px',
borderRadius: radius.md, borderRadius: radius.md,
border: 'none', border: 'none',
background: isCurrentAnswered background: 'rgba(0,0,0,0.08)',
? `linear-gradient(135deg, ${brandColor}, #27AE60)`
: 'rgba(0,0,0,0.1)',
color: '#FFFFFF', color: '#FFFFFF',
fontSize: '14px', fontSize: '14px',
fontWeight: 700, fontWeight: 700,
cursor: isCurrentAnswered ? 'pointer' : 'default', opacity: 0.6,
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('lessonChooseAnswer') || 'Выбери ответ'}
? t('testChecking')
: isLastQuestion
? t('testFinish')
: `${t('next')} →`}
</button> </button>
)}
{answerState.kind === 'correct' && (
<button
onClick={handleNext}
disabled={isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
opacity: isCompleting ? 0.6 : 1,
}}
>
{isCompleting ? '...' : (isLastQuestion ? (t('testFinish') || 'Завершить') : `${t('next') || 'Далее'} →`)}
</button>
)}
{answerState.kind === 'wrong' && !answerState.showCorrect && (
<>
<button
onClick={handleRetry}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: `1px solid ${brandColor}40`,
background: `${brandColor}10`,
color: brandColor,
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
}}
>
📖 {t('lessonRetry') || 'Повторить урок'}
</button>
<button
onClick={handleNext}
disabled={isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
opacity: isCompleting ? 0.6 : 1,
}}
>
{isCompleting ? '...' : (isLastQuestion ? (t('testFinish') || 'Завершить') : `→ ${t('next') || 'Далее'}`)}
</button>
</>
)}
</div> </div>
)}
</div> </div>
</div> </div>
); );