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
+626
View File
@@ -0,0 +1,626 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { useLocalized } from '../hooks/useLocalized';
import { fonts, radius } from '../styles/theme';
import { saveLearningAnswer, completeLearningSession } from '../api';
interface PracticeQuestion {
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: Array<{
option_key: string;
text_pl: string;
text_ru: string;
text_uk: string;
text_en: string;
is_correct: boolean;
wrong_because: string | null;
}>;
}
interface PracticeExplanation {
skill_tag: string;
name: string;
explanation_pl?: string;
explanation_ru?: string;
explanation_uk?: string;
explanation_en?: string;
}
const PracticeViewPage: React.FC = () => {
const navigate = useNavigate();
const location = useLocation();
const { t } = useLanguage();
const getLocalized = useLocalized();
const [questions, setQuestions] = useState<PracticeQuestion[]>([]);
const [explanations, setExplanations] = useState<PracticeExplanation[]>([]);
const [sessionId, setSessionId] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedAnswers, setSelectedAnswers] = useState<Record<string, string>>({});
const [textInputValue, setTextInputValue] = useState('');
const [isCompleting, setIsCompleting] = useState(false);
const [hintUsed, setHintUsed] = useState<Record<string, boolean>>({});
const [showHint, setShowHint] = useState(false);
const [practiceResult, setPracticeResult] = useState<{ total: number; correct_count: number } | null>(null);
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(() => {
const state = location.state as any;
if (state && state.sessionId && state.questions) {
setSessionId(state.sessionId);
setQuestions(state.questions);
setExplanations(state.explanations || []);
setLoading(false);
} else {
navigate('/menu');
}
}, [location.state, navigate]);
// 🔧 ИСПРАВЛЕНО: saveAnswer теперь принимает isFinalAnswer и usedHint
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);
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 (currentIndex < questions.length - 1) {
setCurrentIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
const currentQ = questions[currentIndex];
const answer = selectedAnswers[currentQ.question.question_id];
if (answer && sessionId) {
const timeTaken = Date.now() - startTimeRef.current;
// 🔧 ИСПРАВЛЕНО: проверяем, была ли подсказка для этого вопроса
const wasHintUsed = !!hintUsed[currentQ.question.question_id];
try {
await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true, wasHintUsed);
} catch (e) {
console.error('Error saving final answer:', e);
}
}
await new Promise(resolve => setTimeout(resolve, 300));
if (sessionId) {
try {
const result = await completeLearningSession(sessionId);
setPracticeResult(result);
} catch (e) {
console.error('Error completing practice:', e);
}
}
}
};
const handleBack = () => {
setShowHint(false);
if (currentIndex > 0) {
setCurrentIndex(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 (practiceResult) {
const total = practiceResult.total || 0;
const correct = practiceResult.correct_count || 0;
const percentage = total > 0 ? Math.round((correct / total) * 100) : 0;
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: '24px',
}}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>
{percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'}
</div>
<h1 style={{ fontSize: '24px', fontWeight: 900, margin: '0 0 8px 0', textAlign: 'center' }}>
{t('practiceCompleted')}
</h1>
<div style={{
...glass({
padding: '20px',
borderRadius: radius.lg,
textAlign: 'center',
marginTop: '16px',
width: '100%',
maxWidth: '300px',
}),
}}>
<div style={{ fontSize: '48px', fontWeight: 900, color: percentage >= 70 ? '#2ECC71' : percentage >= 50 ? '#F39C12' : '#E74C3C' }}>
{percentage}%
</div>
<div style={{ fontSize: '18px', color: subColor, marginTop: '8px', fontWeight: 600 }}>
{correct} / {total}
</div>
<div style={{ fontSize: '12px', color: subColor, marginTop: '4px' }}>
{t('practiceCorrectAnswers')}
</div>
</div>
<button
onClick={() => navigate('/menu')}
style={{
marginTop: '20px',
padding: '16px 32px',
borderRadius: radius.lg,
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.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('backToMenu')}
</button>
</div>
);
}
if (questions.length === 0) return null;
const currentQuestion = questions[currentIndex];
const isLastQuestion = currentIndex === questions.length - 1;
const isProduction = currentQuestion?.question.question_type === 'production';
const isCurrentAnswered = currentQuestion ? !!selectedAnswers[currentQuestion.question.question_id] : false;
const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false;
const correctOption = currentQuestion?.options.find(o => o.is_correct);
const currentSkillTag = currentQuestion?.question.skill_tag;
const currentExplanation = explanations.find(e => e.skill_tag === currentSkillTag);
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('/menu')}
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' }}>
💪 {t('practiceTitle')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '12px', color: subColor, fontSize: '13px' }}>
{t('testQuestion')} {currentIndex + 1} / {questions.length}
</div>
{/* Прогресс-бар */}
<div style={{
width: '100%',
height: '4px',
background: 'rgba(0,0,0,0.06)',
borderRadius: '2px',
marginBottom: '16px',
overflow: 'hidden',
}}>
<div style={{
width: `${((currentIndex + 1) / questions.length) * 100}%`,
height: '100%',
background: `linear-gradient(90deg, ${brandColor}, #27AE60)`,
borderRadius: '2px',
transition: 'width 0.3s ease',
}} />
</div>
{/* Объяснение навыка (если есть) */}
{currentExplanation && (
<div style={{
...glass({
padding: '14px',
borderRadius: radius.lg,
marginBottom: '12px',
}),
border: `1px solid ${brandColor}30`,
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<div style={{ fontSize: '13px', fontWeight: 700, color: brandColor, marginBottom: '6px' }}>
📖 {currentExplanation.name}
</div>
{currentExplanation.explanation_ru && (
<div style={{ fontSize: '12px', color: subColor, lineHeight: '1.5' }}>
{getLocalized(currentExplanation, 'explanation')}
</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>{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={currentIndex === 0 || isCompleting}
style={{
...glass({
padding: '14px 20px',
borderRadius: radius.md,
}),
color: currentIndex === 0 ? subColor : textColor,
fontSize: '14px',
fontWeight: 600,
cursor: currentIndex === 0 ? 'default' : 'pointer',
opacity: currentIndex === 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('loading')
: isLastQuestion
? t('testFinish')
: `${t('next')} →`}
</button>
</div>
</div>
</div>
);
};
export default PracticeViewPage;