initial commit (frontend)

This commit is contained in:
2026-09-20 15:08:32 +03:00
commit 04cc53e66d
84 changed files with 36264 additions and 0 deletions
+549
View File
@@ -0,0 +1,549 @@
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());
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);
}
};
// 🔧 ИСПРАВЛЕНО: handleHintClick теперь сохраняет ответ с hintUsed=true
const handleHintClick = async () => {
if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return;
setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true }));
setShowHint(true);
// Сохраняем ответ с подсказкой (правильный ответ, hintUsed=true)
const correctOption = currentQuestion.options.find(o => o.is_correct);
const correctAnswer = correctOption ? correctOption.option_key : '';
// 🔧 ИСПРАВЛЕНО: isFinalAnswer=true, hintUsed=true — система будет знать, что была подсказка
await saveAnswer(currentQuestion.question.question_id, correctAnswer, true, true);
// 🔧 НОВОЕ: также отмечаем ответ как выбранный, чтобы кнопка "Далее" стала активной
setSelectedAnswers(prev => ({ ...prev, [currentQuestion.question.question_id]: correctAnswer }));
};
const handleNext = async () => {
setShowHint(false);
if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) {
setCurrentQuestionIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
if (sessionId) {
try {
await completeLearningSession(sessionId);
} catch (e) {
console.error('Error completing session:', e);
}
}
navigate(`/lessons/topic/${topicId}`);
}
};
const handleBack = () => {
setShowHint(false);
if (currentQuestionIndex > 0) {
setCurrentQuestionIndex(prev => prev - 1);
setTextInputValue('');
startTimeRef.current = Date.now();
}
};
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;
const isTranslationQuestion = 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>
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>
{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;