refactor(lessons): убрал дублирующие страницы /lessons, уроки через /teacher

- Удалены: LessonsPage, TopicLessonsPage, LessonViewPage, TestViewPage
  (дублировали TeacherChatPage, который уже делает и уроки, и тесты через orchestrator)
- App.tsx: /lessons/* → редирект на /teacher; /lessons/practice оставлен для практики
- App.tsx: глобальный скролл-фикс теперь проверяет /teacher (не /lessons/)
- TeacherChatPage: скролл к блоку задания вместо scrollTop=0
- TeacherChatPage: объяснение показывается только на первом задании
This commit is contained in:
2026-10-04 16:08:44 +03:00
parent 8ed822d30e
commit 5d0395b52d
6 changed files with 50 additions and 2183 deletions
+16 -18
View File
@@ -1,5 +1,5 @@
import { useEffect, useState, useRef } from 'react';
import { BrowserRouter, Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import { BrowserRouter, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import { LanguageProvider, useLanguage } from './i18n/LanguageContext';
import LanguageSelectPage from './pages/LanguageSelectPage';
import MenuPage from './pages/MenuPage';
@@ -10,10 +10,6 @@ import FlashcardsPage from './pages/FlashcardsPage';
import WordQuizPage from './pages/WordQuizPage';
import BubbleWordsPage from './pages/BubbleWordsPage';
import PronunciationPage from './pages/PronunciationPage';
import LessonsPage from './pages/LessonsPage';
import TopicLessonsPage from './pages/TopicLessonsPage';
import LessonViewPage from './pages/LessonViewPage';
import TestViewPage from './pages/TestViewPage';
import PracticeViewPage from './pages/PracticeViewPage';
import TeacherChatPage from './pages/TeacherChatPage';
import TypingPage from './pages/TypingPage';
@@ -207,17 +203,14 @@ function AppContent() {
}
}, [showDashboard, isAdmin, isAdminResolved]);
// 🔧 ФИКС (04.10.2026): GLOBAL_SCROLL_BREAKS_LESSON_NAV —
// не скроллим вверх, если мы внутри урока (смена вопроса).
// Оставляем глобальный сброс только при реальной смене route.
// 🔧 ФИКС (04.10.2026): GLOBAL_SCROLL_BREAKS_TEACHER_NAV —
// на странице /teacher не сбрасываем глобальный скролл:
// TeacherChatPage сам управляет скроллом к заданию через
// scrollIntoView. Иначе прыжок вверх на каждый ответ.
useEffect(() => {
// Пропускаем, если мы на странице урока — там свой scrollIntoView.
// 🔧 ДИАГНОСТИКА (04.10.2026): логирование на 1 минуту для проверки.
if (location.pathname.includes('/lessons/')) {
console.log('[App] skip scroll for lesson route');
if (location.pathname === '/teacher') {
return;
}
console.log('[App] scrolling to top for', location.pathname);
window.scrollTo(0, 0);
document.documentElement.scrollTop = 0;
@@ -255,15 +248,20 @@ function AppContent() {
<Route path="/bubble" element={<BubbleWordsPage />} />
<Route path="/pronunciation" element={<PronunciationPage />} />
<Route path="/typing" element={<TypingPage />} />
<Route path="/lessons" element={<LessonsPage />} />
<Route path="/lessons/topic/:topicId" element={<TopicLessonsPage />} />
<Route path="/lessons/topic/:topicId/lesson/:lessonId" element={<LessonViewPage />} />
<Route path="/lessons/test/:topicId" element={<TestViewPage />} />
<Route path="/lessons/practice" element={<PracticeViewPage />} />
<Route path="/teacher" element={<TeacherChatPage />} />
<Route path="/learning" element={<LearningPage />} />
<Route path="/lectures" element={<LecturesPage />} />
<Route path="/settings" element={<SettingsPage />} />
{/* 🔧 ФИКС (04.10.2026): LESSONS_LEGACY_ROUTES_REMOVED —
Уроки и тесты теперь идут через /teacher (TeacherChatPage).
Старые /lessons/* редиректим на /teacher, чтобы старые
закладки и ссылки не падали с 404.
/lessons/practice — оставляем, это отдельный флоу практики. */}
<Route path="/lessons/practice" element={<PracticeViewPage />} />
<Route path="/lessons" element={<Navigate to="/teacher" replace />} />
<Route path="/lessons/topic/:topicId" element={<Navigate to="/teacher" replace />} />
<Route path="/lessons/topic/:topicId/lesson/:lessonId" element={<Navigate to="/teacher" replace />} />
<Route path="/lessons/test/:topicId" element={<Navigate to="/teacher" replace />} />
</Routes>
{/* Дашборд админа — открывается через событие "open-dashboard" из MenuPage */}
-794
View File
@@ -1,794 +0,0 @@
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 { haptic } from '../haptic';
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_language?: string;
};
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[];
}
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 };
// 🔧 НОВОЕ (04.10.2026): результат по заданию для промежуточного экрана
interface QuestionResult {
question_id: string;
correct: boolean;
selected: string;
}
const LessonViewPage: React.FC = () => {
const navigate = useNavigate();
const { lessonId, topicId } = useParams<{ lessonId: string; topicId: string }>();
const { t, language } = 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 startTimeRef = useRef<number>(Date.now());
// 🔧 НОВОЕ (04.10.2026): ref на блок вопроса — для scrollIntoView без прыжка наверх
const questionBlockRef = useRef<HTMLDivElement>(null);
const [answerState, setAnswerState] = useState<AnswerState>({ kind: 'unanswered' });
const [report, setReport] = useState<ReportData | null>(null);
const [saving, setSaving] = useState(false);
// 🔧 НОВОЕ (04.10.2026): результаты по заданиям + промежуточный экран + retry
const [results, setResults] = useState<QuestionResult[]>([]);
const [showIntermediate, setShowIntermediate] = useState(false);
const [retryMode, setRetryMode] = useState(false);
const [retryQuestions, setRetryQuestions] = useState<Question[]>([]);
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]);
// 🔧 ФИКС (04.10.2026): SCROLL_TO_QUESTION_VIA_WINDOW —
// scrollIntoView не работал при overflow:hidden на корне,
// потому что скроллил внутренний контейнер, а не window.
// Считаем позицию блока вручную и скроллим window.
// Задержка 100мс — ждём, пока браузер пересчитает layout после
// исчезновения explanation (страница становится короче).
useEffect(() => {
if (showIntermediate || !questionBlockRef.current) return;
const timer = setTimeout(() => {
const el = questionBlockRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const absoluteTop = window.scrollY + rect.top;
// Отступ 80px сверху — чтобы вопрос был виден, но не прилипал к краю
window.scrollTo({
top: Math.max(0, absoluteTop - 80),
behavior: 'smooth',
});
}, 100);
return () => clearTimeout(timer);
}, [currentQuestionIndex, retryMode, showIntermediate]);
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;
startTimeRef.current = Date.now();
if (!sessionId) return null;
try {
const res = await saveLearningAnswer(
sessionId,
questionId,
answer,
timeTaken,
true,
false,
isRetry,
);
// 🔧 НОВОЕ (04.10.2026): записываем результат для промежуточного экрана
setResults(prev => {
const filtered = prev.filter(r => r.question_id !== questionId);
return [...filtered, { question_id: questionId, correct: res.correct, selected: answer }];
});
return res;
} catch (e) {
console.error('Error saving answer:', e);
return null;
}
};
const handleAnswerSelect = async (questionId: string, optionKey: string) => {
if (saving) return;
haptic.selection();
setSaving(true);
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
const res = await saveAnswer(questionId, optionKey, retryMode);
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 = (questionId: string, value: string) => {
setTextInputValue(value);
setSelectedAnswers(prev => ({ ...prev, [questionId]: value }));
};
const handleTextInputBlur = async (questionId: string) => {
if (!textInputValue.trim() || saving) return;
setSaving(true);
const res = await saveAnswer(questionId, textInputValue.trim(), retryMode);
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);
};
// 🔧 НОВОЕ (04.10.2026): «Повторить ошибки» — берём только те вопросы,
// где юзер ошибся. Используется ТОЛЬКО на промежуточном экране.
const handleRetryWrong = () => {
haptic.medium();
if (!lesson) return;
const questionsList = retryMode ? retryQuestions : lesson.questions;
const wrongQuestions = questionsList.filter(q => {
const r = results.find(rr => rr.question_id === q.question.question_id);
return r && !r.correct;
});
if (wrongQuestions.length === 0) {
setShowIntermediate(false);
return;
}
// 🔧 Чистим results от старых записей по этим вопросам, чтобы
// при повторной ошибке результаты перезаписались корректно.
setResults(prev =>
prev.filter(r => !wrongQuestions.some(w => w.question.question_id === r.question_id))
);
setRetryQuestions(wrongQuestions);
setRetryMode(true);
setCurrentQuestionIndex(0);
setSelectedAnswers({});
setTextInputValue('');
setAnswerState({ kind: 'unanswered' });
setShowIntermediate(false);
startTimeRef.current = Date.now();
};
// 🔧 НОВОЕ (04.10.2026): «Далее» — без скролла вверх. На последнем
// вопросе показываем промежуточный экран.
const handleNext = () => {
haptic.light();
const questionsList = retryMode ? retryQuestions : (lesson?.questions || []);
const isLast = currentQuestionIndex >= questionsList.length - 1;
if (!isLast) {
setCurrentQuestionIndex(prev => prev + 1);
setTextInputValue('');
setAnswerState({ kind: 'unanswered' });
startTimeRef.current = Date.now();
} else {
haptic.heavy();
setShowIntermediate(true);
}
};
// 🔧 НОВОЕ (04.10.2026): «Завершить» — отправляем сессию и показываем отчёт
const handleFinish = async () => {
haptic.heavy();
setIsCompleting(true);
let completionData: any = null;
if (sessionId) {
try {
completionData = await completeLearningSession(sessionId, language || 'ru');
} catch (e) {
console.error('Error completing session:', e);
}
}
if (completionData?.report) {
setReport(completionData.report);
}
setIsCompleting(false);
};
const handleBack = () => {
haptic.light();
if (currentQuestionIndex > 0) {
setCurrentQuestionIndex(prev => prev - 1);
setTextInputValue('');
setAnswerState({ kind: 'unanswered' });
startTimeRef.current = Date.now();
}
};
// ============ ЭКРАН ФИНАЛЬНОГО ОТЧЁТА ============
if (report) {
const percent = report.percent;
const emoji = percent >= 90 ? '🎉' : percent >= 75 ? '💪' : percent >= 60 ? '👍' : '📚';
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: '28px 22px', borderRadius: radius.lg, maxWidth: '420px', width: '100%' }),
position: 'relative', zIndex: 1, textAlign: 'center',
}}>
<div style={{ fontSize: '56px', marginBottom: '8px' }}>{emoji}</div>
<h2 style={{ fontSize: '20px', fontWeight: 800, color: textColor, margin: '0 0 6px 0' }}>
{report.topic_name || 'Тема'}
</h2>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '20px' }}>
{t('lessonCompleted')}
</div>
<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', alignItems: 'center', justifyContent: 'center',
}}>
<div style={{
width: '90px', height: '90px', borderRadius: '50%', background: '#FFFFFF',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<div style={{ fontSize: '28px', fontWeight: 800, color: brandColor }}>
{percent}%
</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}</span>
</div>
))}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button
onClick={() => { haptic.medium(); navigate(`/lessons/topic/${topicId}`); }}
style={{
width: '100%', padding: '14px', borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '15px', fontWeight: 700, cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
}}
>
✓ {t('testBackToTopic')}
</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>
);
}
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;
// ============ ПРОМЕЖУТОЧНЫЙ ЭКРАН ============
if (showIntermediate) {
const questionsList = retryMode ? retryQuestions : lesson.questions;
const correctCount = questionsList.filter(q => {
const r = results.find(rr => rr.question_id === q.question.question_id);
return r && r.correct;
}).length;
const totalCount = questionsList.length;
const hasErrors = correctCount < totalCount;
return (
<div style={{
minHeight: '100vh', background: bgColor, color: textColor,
fontFamily: fonts.main, padding: '24px',
display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center',
}}>
<div style={{
...glass({ padding: '28px 22px', borderRadius: radius.lg, maxWidth: '420px', width: '100%' }),
textAlign: 'center',
}}>
<div style={{ fontSize: '56px', marginBottom: '8px' }}>
{hasErrors ? '💪' : '🎉'}
</div>
<h2 style={{ fontSize: '20px', fontWeight: 800, color: textColor, margin: '0 0 20px 0' }}>
{t('lessonIntermediateTitle')}
</h2>
<div style={{
fontSize: '48px', fontWeight: 800,
color: hasErrors ? '#F39C12' : brandColor,
marginBottom: '8px',
}}>
{correctCount} / {totalCount}
</div>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '24px' }}>
{t('lessonCorrectCount')}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{hasErrors && (
<button
onClick={handleRetryWrong}
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('lessonRetryWrong')}
</button>
)}
<button
onClick={handleFinish}
disabled={isCompleting}
style={{
width: '100%', padding: '14px', borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '15px', fontWeight: 700,
cursor: isCompleting ? 'default' : 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
opacity: isCompleting ? 0.6 : 1,
}}
>
{isCompleting ? '...' : t('lessonFinish')}
</button>
</div>
</div>
</div>
);
}
// ============ ЭКРАН ВОПРОСА ============
const questionsList = retryMode ? retryQuestions : lesson.questions;
const currentQuestion = questionsList[currentQuestionIndex];
if (!currentQuestion) return null;
const isLastQuestion = currentQuestionIndex === questionsList.length - 1;
const isProduction = currentQuestion.question.question_type === 'production';
const optionsLanguage = currentQuestion.question.options_language;
const isTranslationQuestion = optionsLanguage === 'user';
const isAnswered = answerState.kind === 'correct' || answerState.kind === 'wrong';
// Показывать объяснение только на первом вопросе И не в retry-режиме.
const showExplanation = currentQuestionIndex === 0 && !retryMode;
return (
<div style={{
minHeight: '100vh', background: bgColor, color: textColor,
fontFamily: fonts.main, padding: '24px',
display: 'flex', flexDirection: 'column',
position: 'relative',
// 🔧 ФИКС (04.10.2026): LESSON_OVERFLOW_HIDDEN_BREAKS_SCROLL —
// overflow:hidden на корне заставлял браузер сбрасывать скролл
// родителя к 0 при ре-рендере (когда explanation исчезал).
// Убрали — теперь scrollIntoView работает.
}}>
<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: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка «3 попытки» — показываем правильный ответ */}
{answerState.kind === 'wrong' && answerState.showCorrect && answerState.correctAnswer && (
<div style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.55)', zIndex: 500,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '20px',
backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
}}>
<div style={{
...glass({ borderRadius: radius.lg, padding: '24px', width: '100%', maxWidth: '360px', textAlign: 'center' }),
}}>
<div style={{ fontSize: '48px', marginBottom: '8px' }}>💪</div>
<h3 style={{ margin: '0 0 8px 0', fontSize: '17px', fontWeight: 800, color: textColor }}>
{t('lessonTryAgain')}
</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>
<button
onClick={handleNext}
style={{
width: '100%', padding: '12px', borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '14px', fontWeight: 700, cursor: 'pointer',
}}
>
→ {isLastQuestion ? t('lessonFinish') : t('next')}
</button>
</div>
</div>
)}
{/* Заголовок */}
<div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '20px' }}>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
...glass({ padding: '10px 18px', borderRadius: radius.md }),
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
}}
>
← {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} / {questionsList.length}
{retryMode && (
<span style={{ marginLeft: '8px', color: brandColor, fontWeight: 700 }}>
🔄 {t('lessonRetryMode')}
</span>
)}
</div>
{/* Объяснение + примеры — ТОЛЬКО на первом вопросе и НЕ в retry */}
{showExplanation && (
<div style={{
...glass({ padding: '16px', borderRadius: radius.lg, marginBottom: '16px' }),
}}>
<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>
)}
{/* Блок вопроса — ref для scrollIntoView */}
<div ref={questionBlockRef} style={{ flex: 1 }}>
<p style={{ fontSize: '16px', fontWeight: 600, color: textColor, marginBottom: '16px' }}>
{getLocalized(currentQuestion.question, 'prompt')}
</p>
{isProduction ? (
<input
type="text"
value={textInputValue}
onChange={(e) => handleTextInputChange(currentQuestion.question.question_id, e.target.value)}
onBlur={() => handleTextInputBlur(currentQuestion.question.question_id)}
placeholder={t('teacherPlaceholder')}
disabled={isAnswered || saving}
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',
boxSizing: 'border-box',
}}
/>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{currentQuestion.options.map((option) => {
const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key;
const disabled = isAnswered || saving;
return (
<button
key={option.option_key}
data-no-haptic="true"
disabled={disabled}
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: disabled ? 'default' : 'pointer',
opacity: disabled && !isSelected ? 0.5 : 1,
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',
}}
>
<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>
{/* Обратная связь */}
{answerState.kind === 'correct' && (
<div style={{
marginTop: '16px', padding: '14px 16px', borderRadius: radius.md,
background: `${brandColor}15`, border: `1px solid ${brandColor}40`,
}}>
<div style={{ fontSize: '15px', fontWeight: 700, color: brandColor }}>
✅ {t('lessonCorrect')}
</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`,
}}>
<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>
)}
{/* Кнопки навигации */}
<div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
{currentQuestionIndex > 0 && (
<button
onClick={handleBack}
disabled={saving}
style={{
...glass({ padding: '14px 20px', borderRadius: radius.md }),
color: textColor, fontSize: '14px', fontWeight: 600,
cursor: 'pointer', opacity: saving ? 0.5 : 1,
}}
>
←
</button>
)}
{answerState.kind === 'unanswered' && (
<button
disabled
style={{
flex: 1, padding: '14px 20px', borderRadius: radius.md, border: 'none',
background: 'rgba(0,0,0,0.08)', color: '#FFFFFF',
fontSize: '14px', fontWeight: 700, opacity: 0.6,
}}
>
{t('lessonChooseAnswer')}
</button>
)}
{isAnswered && (
<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('lessonCheck') : `${t('next')} →`)}
</button>
)}
</div>
</div>
</div>
);
};
export default LessonViewPage;
-302
View File
@@ -1,302 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { haptic } from '../haptic';
import { getLearningLevels, getLearningTopics, getLearningProgress } from '../api';
interface LearningLevel {
code: string;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
}
interface LearningTopic {
topic_id: string;
level_code: string;
order_number: number;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
lessons_completed?: number;
test_completed?: boolean;
test_score?: number;
topic_mastery?: number;
}
const LessonsPage: React.FC = () => {
const navigate = useNavigate();
const { language } = useLanguage();
const [levels, setLevels] = useState<LearningLevel[]>([]);
const [selectedLevel, setSelectedLevel] = useState<string | null>(null);
const [topics, setTopics] = useState<LearningTopic[]>([]);
const [loading, setLoading] = useState(true);
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 getLevelName = (level: LearningLevel): string => {
const map: Record<string, string> = { pl: level.name_pl, ru: level.name_ru, uk: level.name_uk, en: level.name_en };
return map[language] || level.name_en;
};
const getTopicName = (topic: LearningTopic): string => {
const map: Record<string, string> = { pl: topic.name_pl, ru: topic.name_ru, uk: topic.name_uk, en: topic.name_en };
return map[language] || topic.name_en;
};
useEffect(() => {
setLoading(true);
getLearningLevels()
.then((data: any) => {
setLevels(data.levels || []);
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const handleLevelSelect = useCallback(async (levelCode: string) => {
setSelectedLevel(levelCode);
setLoading(true);
try {
const progressData = await getLearningProgress();
const topicsData = await getLearningTopics(levelCode);
// Объединяем прогресс с темами
const progressMap: Record<string, any> = {};
if (progressData.progress) {
progressData.progress.forEach((p: any) => {
progressMap[p.topic_id] = p;
});
}
const mergedTopics = (topicsData.topics || []).map((topic: any) => ({
...topic,
lessons_completed: progressMap[topic.topic_id]?.lessons_completed || 0,
test_completed: progressMap[topic.topic_id]?.test_completed || false,
test_score: progressMap[topic.topic_id]?.test_score,
topic_mastery: progressMap[topic.topic_id]?.topic_mastery,
}));
setTopics(mergedTopics);
} catch (e) {
console.error('Error loading topics:', e);
setTopics([]);
} finally {
setLoading(false);
}
}, []);
if (loading) {
return (
<div style={{
minHeight: '100vh',
background: bgColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: subColor,
fontFamily: fonts.main,
fontSize: '18px',
}}>
{language === 'pl' ? 'Ładowanie...' : language === 'ru' ? 'Загрузка...' : language === 'uk' ? 'Завантаження...' : '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: brandColor, 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: '#4FA9E8', 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; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_lessons_page — вибрация навигации
haptic.selection();
if (selectedLevel) {
setSelectedLevel(null);
} else {
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)'; }}
>
← {language === 'pl' ? 'Powrót' : language === 'ru' ? 'Назад' : language === 'uk' ? 'Назад' : 'Back'}
</button>
<h1 style={{ fontSize: '26px', fontWeight: 900, margin: 0, color: textColor }}>
📚 {language === 'pl' ? 'Lekcje' : language === 'ru' ? 'Уроки' : language === 'uk' ? 'Уроки' : 'Lessons'}
</h1>
</div>
{!selectedLevel ? (
/* Выбор уровня */
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ textAlign: 'center', fontSize: '15px', color: subColor, marginBottom: '8px' }}>
{language === 'pl' ? 'Wybierz poziom' : language === 'ru' ? 'Выберите уровень' : language === 'uk' ? 'Виберіть рівень' : 'Select level'}
</p>
{levels.map((level, index) => (
<button
key={level.code}
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_lessons_page — вибрация выбора уровня
haptic.selection();
handleLevelSelect(level.code);
}}
style={{
padding: '18px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
transition: 'all 0.2s ease',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.05}s both`,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '22px', fontWeight: 800 }}>{level.code}</span>
<span style={{ fontSize: '14px', opacity: 0.9 }}>{getLevelName(level)}</span>
</button>
))}
</div>
) : (
/* Список тем */
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ textAlign: 'center', fontSize: '15px', color: brandColor, fontWeight: 700, marginBottom: '8px' }}>
{selectedLevel}
</p>
{topics.length === 0 ? (
<p style={{ textAlign: 'center', color: subColor }}>
{language === 'pl' ? 'Brak tematów' : language === 'ru' ? 'Нет тем' : language === 'uk' ? 'Немає тем' : 'No topics'}
</p>
) : (
topics.map((topic, index) => {
const isCompleted = topic.test_completed;
const isUnlocked = index === 0 || topics[index - 1]?.test_completed;
return (
<button
key={topic.topic_id}
onClick={() => {
if (isUnlocked) {
// 🔧 ФИКС (01.10.2026): haptic_lessons_page — вибрация выбора темы
haptic.selection();
navigate(`/lessons/topic/${topic.topic_id}`);
}
}}
disabled={!isUnlocked}
style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
display: 'flex',
alignItems: 'center',
gap: '12px',
}),
opacity: isUnlocked ? 1 : 0.5,
cursor: isUnlocked ? 'pointer' : 'default',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.05}s both`,
border: isCompleted ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
}}
onTouchStart={(e) => { if (isUnlocked) e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '24px', flexShrink: 0 }}>
{isCompleted ? '✅' : isUnlocked ? '📖' : '🔒'}
</span>
<div style={{ flex: 1, textAlign: 'left' }}>
<div style={{ fontSize: '15px', fontWeight: 700, color: textColor }}>
{index + 1}. {getTopicName(topic)}
</div>
{isCompleted && topic.topic_mastery && (
<div style={{ fontSize: '12px', color: brandColor, marginTop: '2px' }}>
{language === 'pl' ? 'Wynik' : language === 'ru' ? 'Результат' : language === 'uk' ? 'Результат' : 'Score'}: {topic.topic_mastery}%
</div>
)}
</div>
{isUnlocked && !isCompleted && (
<span style={{ fontSize: '18px', color: brandColor }}>→</span>
)}
</button>
);
})
)}
</div>
)}
</div>
</div>
);
};
export default LessonsPage;
+34 -8
View File
@@ -95,6 +95,9 @@ const TeacherChatPage: React.FC = () => {
const startTimeRef = useRef<number>(Date.now());
const contentRef = useRef<HTMLDivElement>(null);
// 🔧 НОВОЕ (04.10.2026): ref на блок задания — для scrollTo при смене вопроса
const questionBlockRef = useRef<HTMLDivElement>(null);
// ============ ЦВЕТА ============
const brandColor = '#2ECC71';
const teacherColor = '#8B5CF6';
@@ -344,11 +347,29 @@ const TeacherChatPage: React.FC = () => {
};
}, []);
// ============ СКРОЛЛ НАВЕРХ ПРИ СМЕНЕ ЭКРАНА ============
// 🔧 ФИКС (04.10.2026): SCROLL_TO_QUESTION_NOT_TOP —
// раньше при смене вопроса скроллили контейнер в 0,
// и юзер оказывался в начале страницы (объяснение сверху,
// задание далеко внизу). Теперь при смене вопроса
// скроллим к блоку задания. При смене экрана (start → lesson →
// after-answer) — всё ещё в 0, потому что это новая "страница".
useEffect(() => {
if (contentRef.current) {
if (!contentRef.current) return;
// На экране start/completed — всегда в начало
if (screen.kind !== 'lesson') {
contentRef.current.scrollTop = 0;
return;
}
// На экране lesson — скролл к блоку задания (плавно, с задержкой на layout)
const timer = setTimeout(() => {
if (questionBlockRef.current && contentRef.current) {
const container = contentRef.current;
const el = questionBlockRef.current;
const offset = el.offsetTop - container.offsetTop - 16;
container.scrollTo({ top: Math.max(0, offset), behavior: 'smooth' });
}
}, 100);
return () => clearTimeout(timer);
}, [screen.kind, currentQuestionId]);
// ============ HANDLERS ============
@@ -945,8 +966,10 @@ const TeacherChatPage: React.FC = () => {
)}
</div>
{/* Объяснение + примеры (из lessonCard) */}
{currentLesson && (
{/* 🔧 ФИКС (04.10.2026): SHOW_EXPLANATION_ONLY_ON_FIRST_QUESTION —
объяснение показываем только на первом задании (question_index === 0),
чтобы юзер не скроллил через него к 2-му и 3-му. */}
{currentLesson && (currentQuestion?.questionIndex === 0 || currentQuestion?.questionIndex === undefined) && (
<div style={{
...glass({ borderRadius: radius.lg, padding: '20px' }),
animation: 'fadeInUp 0.3s ease 0.1s both',
@@ -996,10 +1019,13 @@ const TeacherChatPage: React.FC = () => {
{/* Задание (текущий вопрос) */}
{currentQuestion && (
<div style={{
...glass({ borderRadius: radius.lg, padding: '20px' }),
animation: 'fadeInUp 0.3s ease 0.2s both',
}}>
<div
ref={questionBlockRef}
style={{
...glass({ borderRadius: radius.lg, padding: '20px' }),
animation: 'fadeInUp 0.3s ease 0.2s both',
}}
>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: '12px',
-844
View File
@@ -1,844 +0,0 @@
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 { haptic } from '../haptic';
import { getTopicTest, startLearningSession, saveLearningAnswer, completeLearningSession, teacherExamples, getLearningAnalytics, startWeakSkillsPractice, getTTS } 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 TestQuestion {
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[];
}
const TestViewPage: React.FC = () => {
const navigate = useNavigate();
const { topicId } = useParams<{ topicId: string }>();
const { t } = useLanguage();
const getLocalized = useLocalized();
const [questions, setQuestions] = useState<TestQuestion[]>([]);
const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = 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 [testResult, setTestResult] = useState<{ total: number; correct_count: number } | null>(null);
const startTimeRef = useRef<number>(Date.now());
// 🔧 НОВОЕ: состояния для примеров и практики
const [showExamplesModal, setShowExamplesModal] = useState(false);
const [examplesText, setExamplesText] = useState('');
const [isLoadingExamples, setIsLoadingExamples] = useState(false);
const [examplesError, setExamplesError] = useState<string | null>(null);
const [isPlayingExamples, setIsPlayingExamples] = useState(false);
const [isStartingPractice, setIsStartingPractice] = useState(false);
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert().
const [toastMessage, setToastMessage] = useState<string | null>(null);
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP —
// храним таймер для очистки.
const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const brandColor = '#A970D6';
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,
});
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast.
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — сохраняем таймер.
const showToast = (msg: string) => {
setToastMessage(msg);
if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500);
};
useEffect(() => {
if (topicId) {
setLoading(true);
getTopicTest(topicId)
.then((data: any) => {
if (data.test && data.test.length > 0) {
setQuestions(data.test);
return startLearningSession('A1', topicId, 'topic_test');
} else {
throw new Error('No test questions');
}
})
.then((sessionData: any) => {
setSessionId(sessionData.session_id);
})
.catch((e) => {
console.error('Error loading test:', e);
navigate(`/lessons/topic/${topicId}`);
})
.finally(() => setLoading(false));
}
}, [topicId]);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — cleanup при unmount.
useEffect(() => {
return () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP
if (toastTimeoutRef.current) {
clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, []);
// 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS — сигнатура
// приведена к общему виду (isFinalAnswer, usedHint) — как в LessonViewPage
// и PracticeViewPage. Раньше тест не передавал 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) => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — выбор варианта
haptic.selection();
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
// 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=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()) {
// 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=false
await saveAnswer(questionId, textInputValue.trim(), true, false);
}
};
const handleNext = async () => {
if (currentIndex < questions.length - 1) {
setCurrentIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
// 🔧 ФИКС (01.10.2026): haptic_test_view — завершение теста
haptic.heavy();
setIsCompleting(true);
// 🔧 ФИКС (24.09.2026): TESTVIEW_DUPLICATE_SAVE —
// ответ последнего вопроса уже сохранён в handleAnswerSelect /
// handleTextInputBlur. Повторно НЕ сохраняем — убираем дубль.
// (как в PracticeViewPage)
// Небольшая задержка для сохранения
await new Promise(resolve => setTimeout(resolve, 300));
if (sessionId) {
try {
const result = await completeLearningSession(sessionId);
setTestResult(result);
} catch (e) {
console.error('Error completing test:', e);
}
}
}
};
const handleBack = () => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация возврата
haptic.light();
if (currentIndex > 0) {
setCurrentIndex(prev => prev - 1);
setTextInputValue('');
startTimeRef.current = Date.now();
}
};
// 🔧 НОВОЕ: загрузка примеров по теме
const handleLoadExamples = async () => {
if (isLoadingExamples) return;
setIsLoadingExamples(true);
setExamplesError(null);
setExamplesText('');
setShowExamplesModal(true);
try {
const data = await teacherExamples('', '', topicId || '');
if (data.limit_exceeded && data.message) {
setExamplesError(data.message);
} else if (data.response) {
setExamplesText(data.response);
} else {
setExamplesError(t('testNoExamples'));
}
} catch (e) {
console.error('Error loading examples:', e);
setExamplesError(t('teacherAIError'));
} finally {
setIsLoadingExamples(false);
}
};
// 🔧 НОВОЕ: озвучка примеров (первый польский пример)
const handlePlayExamples = async () => {
if (!examplesText || isPlayingExamples) return;
// Извлекаем первый польский пример
const lines = examplesText.split('\n');
let polishText = '';
for (const line of lines) {
if (line.includes('🇵🇱')) {
polishText = line.split('🇵🇱')[1]?.split('→')[0]?.trim() || '';
break;
}
}
if (!polishText) return;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlayingExamples(true);
try {
const audioBlob = await getTTS(polishText, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => {
setIsPlayingExamples(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
setIsPlayingExamples(false);
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
await audio.play();
} catch (e) {
console.error('TTS error:', e);
setIsPlayingExamples(false);
}
};
// 🔧 НОВОЕ: практика слабых тем
const handleStartPractice = async () => {
if (isStartingPractice) return;
setIsStartingPractice(true);
try {
// Проверяем, есть ли слабые темы
const analytics = await getLearningAnalytics();
if (!analytics.has_practice_available) {
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert()
showToast(t('testPracticeNoWeak'));
setIsStartingPractice(false);
return;
}
const data = await startWeakSkillsPractice();
if (data.has_weak_skills && data.session_id) {
navigate('/lessons/practice', {
state: {
sessionId: data.session_id,
questions: data.questions,
explanations: data.explanations,
},
});
} else {
// 🔧 ФИКС (24.09.2026): toast вместо alert()
showToast(data.message || t('testPracticeNoWeak'));
setIsStartingPractice(false);
}
} catch (e) {
console.error('Error starting practice:', e);
// 🔧 ФИКС (24.09.2026): toast вместо alert()
showToast(t('teacherAIError'));
setIsStartingPractice(false);
}
};
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 (testResult) {
const total = testResult.total || 0;
const correct = testResult.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',
}}>
{/* 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() */}
{toastMessage && (
<div style={{
position: 'fixed',
top: '20px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 999,
padding: '12px 20px',
background: 'rgba(26,26,46,0.95)',
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 600,
borderRadius: radius.md,
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
maxWidth: '90vw',
textAlign: 'center',
}}>
{toastMessage}
</div>
)}
<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('teacherCompleted')}
</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('testCorrectAnswers')}
</div>
</div>
{/* 🔧 НОВОЕ: Кнопки "Дай примеры" и "Потренировать слабые темы" */}
<div style={{ marginTop: '20px', width: '100%', maxWidth: '300px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация загрузки примеров
haptic.medium();
handleLoadExamples();
}}
data-no-haptic="true"
disabled={isLoadingExamples}
style={{
width: '100%',
padding: '14px 20px',
borderRadius: radius.lg,
border: 'none',
background: isLoadingExamples
? 'rgba(0,0,0,0.1)'
: `linear-gradient(135deg, #4FA9E8, #3B82F6)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: isLoadingExamples ? 'default' : 'pointer',
boxShadow: isLoadingExamples ? 'none' : '0 4px 15px rgba(79,169,232,0.4)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
}}
onTouchStart={(e) => { if (!isLoadingExamples) e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
💡 {t('testExamplesButton')}
</button>
<button
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация старта практики
haptic.medium();
handleStartPractice();
}}
data-no-haptic="true"
disabled={isStartingPractice}
style={{
width: '100%',
padding: '14px 20px',
borderRadius: radius.lg,
border: 'none',
background: isStartingPractice
? 'rgba(0,0,0,0.1)'
: `linear-gradient(135deg, #2ECC71, #27AE60)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: isStartingPractice ? 'default' : 'pointer',
boxShadow: isStartingPractice ? 'none' : '0 4px 15px rgba(46,204,113,0.4)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
}}
onTouchStart={(e) => { if (!isStartingPractice) e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🎯 {t('testPracticeButton')}
</button>
</div>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
marginTop: '12px',
padding: '16px 32px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #8B5CF6)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
width: '100%',
maxWidth: '300px',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('testBackToTopic')}
</button>
{/* 🔧 НОВОЕ: Модалка с примерами */}
{showExamplesModal && (
<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',
padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowExamplesModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '400px',
maxHeight: '80vh',
overflow: 'auto',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 800,
textAlign: 'center',
color: textColor,
}}>
💡 {t('testExamplesTitle')}
</h3>
{isLoadingExamples ? (
<div style={{ textAlign: 'center', padding: '30px', color: subColor, fontSize: '14px' }}>
{t('loading')}
</div>
) : examplesError ? (
<div style={{ textAlign: 'center', padding: '20px', color: '#E74C3C', fontSize: '14px', fontWeight: 600 }}>
⚠️ {examplesError}
</div>
) : (
<>
<div style={{
padding: '16px',
background: 'rgba(79,169,232,0.08)',
borderRadius: radius.md,
fontSize: '14px',
lineHeight: '1.7',
color: textColor,
whiteSpace: 'pre-line',
marginBottom: '16px',
}}>
{examplesText}
</div>
<div style={{ display: 'flex', gap: '10px' }}>
<button
onClick={handlePlayExamples}
disabled={isPlayingExamples}
style={{
padding: '12px 16px',
borderRadius: radius.md,
border: `1px solid ${brandColor}40`,
background: isPlayingExamples ? `${brandColor}30` : 'rgba(255,255,255,0.8)',
color: brandColor,
fontSize: '14px',
fontWeight: 700,
cursor: isPlayingExamples ? 'default' : 'pointer',
flexShrink: 0,
}}
>
🔊
</button>
<button
onClick={() => setShowExamplesModal(false)}
style={{
flex: 1,
padding: '12px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, #4FA9E8, #3B82F6)`,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</>
)}
</div>
</div>
)}
</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;
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); }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<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' }}>
🎓 {t('testTitle')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '16px', 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: '20px',
overflow: 'hidden',
}}>
<div style={{
width: `${((currentIndex + 1) / questions.length) * 100}%`,
height: '100%',
background: `linear-gradient(90deg, ${brandColor}, #8B5CF6)`,
borderRadius: '2px',
transition: 'width 0.3s ease',
}} />
</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}
data-no-haptic="true"
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={{
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}
data-no-haptic="true"
disabled={!isCurrentAnswered || isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: isCurrentAnswered
? `linear-gradient(135deg, ${brandColor}, #8B5CF6)`
: '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 TestViewPage;
-217
View File
@@ -1,217 +0,0 @@
import { useState, useEffect } 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 { getLearningTopic } from '../api';
interface Lesson {
lesson_id: string;
order_number: number;
skill_tag: string;
title_pl: string;
title_ru: string;
title_uk: string;
title_en: string;
completed?: boolean;
}
interface TopicData {
topic_id: string;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
}
const TopicLessonsPage: React.FC = () => {
const navigate = useNavigate();
const { topicId } = useParams<{ topicId: string }>();
const { t } = useLanguage();
const getLocalized = useLocalized();
const [topic, setTopic] = useState<TopicData | null>(null);
const [lessons, setLessons] = useState<Lesson[]>([]);
const [loading, setLoading] = useState(true);
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 (topicId) {
setLoading(true);
getLearningTopic(topicId)
.then((data: any) => {
setTopic(data.topic);
setLessons(data.lessons || []);
})
.catch(() => {})
.finally(() => setLoading(false));
}
}, [topicId]);
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: brandColor, 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: '#A970D6', 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; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate('/lessons')}
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: '22px', fontWeight: 900, margin: 0, color: textColor }}>
{topic ? getLocalized(topic, 'name') : ''}
</h1>
</div>
{/* Список уроков */}
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '10px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
{lessons.map((lesson, index) => {
const isUnlocked = index === 0 || lessons[index - 1]?.completed;
return (
<button
key={lesson.lesson_id}
onClick={() => {
if (isUnlocked) {
navigate(`/lessons/topic/${topicId}/lesson/${lesson.lesson_id}`);
}
}}
disabled={!isUnlocked}
style={{
...glass({
padding: '14px 16px',
borderRadius: radius.lg,
display: 'flex',
alignItems: 'center',
gap: '12px',
}),
opacity: isUnlocked ? 1 : 0.5,
cursor: isUnlocked ? 'pointer' : 'default',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.04}s both`,
}}
onTouchStart={(e) => { if (isUnlocked) e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '20px', flexShrink: 0 }}>
{lesson.completed ? '✅' : isUnlocked ? '📝' : '🔒'}
</span>
<div style={{ flex: 1, textAlign: 'left' }}>
<div style={{ fontSize: '14px', fontWeight: 700, color: textColor }}>
{t('topicLesson')} {index + 1}
</div>
<div style={{ fontSize: '13px', color: subColor, marginTop: '2px' }}>
{getLocalized(lesson, 'title')}
</div>
</div>
{isUnlocked && !lesson.completed && (
<span style={{ fontSize: '18px', color: brandColor }}>→</span>
)}
</button>
);
})}
</div>
{/* Кнопка финального теста */}
<div style={{ marginTop: '20px', animation: 'fadeInUp 0.3s ease 0.5s both' }}>
<button
onClick={() => navigate(`/lessons/test/${topicId}`)}
style={{
width: '100%',
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, #A970D6, #8B5CF6)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: '0 4px 15px rgba(169,112,214,0.4)',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🎓 {t('topicFinalTest')}
</button>
</div>
</div>
</div>
);
};
export default TopicLessonsPage;