diff --git a/src/App.tsx b/src/App.tsx index 8b304ef..c2d34e1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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() { } /> } /> } /> - } /> - } /> - } /> - } /> - } /> } /> } /> } /> } /> + {/* 🔧 ФИКС (04.10.2026): LESSONS_LEGACY_ROUTES_REMOVED — + Уроки и тесты теперь идут через /teacher (TeacherChatPage). + Старые /lessons/* редиректим на /teacher, чтобы старые + закладки и ссылки не падали с 404. + /lessons/practice — оставляем, это отдельный флоу практики. */} + } /> + } /> + } /> + } /> + } /> {/* Дашборд админа — открывается через событие "open-dashboard" из MenuPage */} diff --git a/src/pages/LessonViewPage.tsx b/src/pages/LessonViewPage.tsx deleted file mode 100644 index ddb72fb..0000000 --- a/src/pages/LessonViewPage.tsx +++ /dev/null @@ -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(null); - const [loading, setLoading] = useState(true); - const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0); - const [selectedAnswers, setSelectedAnswers] = useState>({}); - const [textInputValue, setTextInputValue] = useState(''); - const [sessionId, setSessionId] = useState(null); - const [isCompleting, setIsCompleting] = useState(false); - const startTimeRef = useRef(Date.now()); - - // 🔧 НОВОЕ (04.10.2026): ref на блок вопроса — для scrollIntoView без прыжка наверх - const questionBlockRef = useRef(null); - - const [answerState, setAnswerState] = useState({ kind: 'unanswered' }); - const [report, setReport] = useState(null); - const [saving, setSaving] = useState(false); - - // 🔧 НОВОЕ (04.10.2026): результаты по заданиям + промежуточный экран + retry - const [results, setResults] = useState([]); - const [showIntermediate, setShowIntermediate] = useState(false); - const [retryMode, setRetryMode] = useState(false); - const [retryQuestions, setRetryQuestions] = useState([]); - - 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 ( -
-
- -
-
{emoji}
- -

- {report.topic_name || 'Тема'} -

- -
- {t('lessonCompleted')} -
- -
-
-
- {percent}% -
-
-
- -

- {report.message} -

- - {report.weak_skills.length > 0 && ( -
-
- 💡 {t('lessonRepeat')} -
- {report.weak_skills.map((w, i) => ( -
- • {w.name} - {w.errors} -
- ))} -
- )} - -
- - - {report.next_topic && ( - - )} -
-
-
- ); - } - - if (loading) { - return ( -
- {t('loading')} -
- ); - } - - 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 ( -
-
-
- {hasErrors ? '💪' : '🎉'} -
- -

- {t('lessonIntermediateTitle')} -

- -
- {correctCount} / {totalCount} -
-
- {t('lessonCorrectCount')} -
- -
- {hasErrors && ( - - )} - - -
-
-
- ); - } - - // ============ ЭКРАН ВОПРОСА ============ - 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 ( -
-
- -
- - {/* Модалка «3 попытки» — показываем правильный ответ */} - {answerState.kind === 'wrong' && answerState.showCorrect && answerState.correctAnswer && ( -
-
-
💪
-

- {t('lessonTryAgain')} -

-

- {t('lessonShowCorrect')} -

-
- {answerState.correctAnswer} -
- -
-
- )} - - {/* Заголовок */} -
- -

- {getLocalized(lesson.lesson, 'title')} -

-
- - {/* Счётчик задания */} -
- {t('testQuestion')} {currentQuestionIndex + 1} / {questionsList.length} - {retryMode && ( - - 🔄 {t('lessonRetryMode')} - - )} -
- - {/* Объяснение + примеры — ТОЛЬКО на первом вопросе и НЕ в retry */} - {showExplanation && ( -
-

- {getLocalized(lesson.lesson, 'explanation')} -

- {lesson.examples.length > 0 && ( -
- {lesson.examples.map((example, i) => ( -
-
🇵🇱 {example.text_pl}
-
{getLocalized(example, 'text')}
-
- ))} -
- )} -
- )} - - {/* Блок вопроса — ref для scrollIntoView */} -
-

- {getLocalized(currentQuestion.question, 'prompt')} -

- - {isProduction ? ( - 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', - }} - /> - ) : ( -
- {currentQuestion.options.map((option) => { - const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key; - const disabled = isAnswered || saving; - - return ( - - ); - })} -
- )} -
- - {/* Обратная связь */} - {answerState.kind === 'correct' && ( -
-
- ✅ {t('lessonCorrect')} -
-
- )} - - {answerState.kind === 'wrong' && !answerState.showCorrect && ( -
-
- 💪 {t('lessonNoWorry')} -
-
- {t('lessonReadAgain')} -
-
- )} - - {/* Кнопки навигации */} -
- {currentQuestionIndex > 0 && ( - - )} - - {answerState.kind === 'unanswered' && ( - - )} - - {isAnswered && ( - - )} -
-
-
- ); -}; - -export default LessonViewPage; \ No newline at end of file diff --git a/src/pages/LessonsPage.tsx b/src/pages/LessonsPage.tsx deleted file mode 100644 index e884532..0000000 --- a/src/pages/LessonsPage.tsx +++ /dev/null @@ -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([]); - const [selectedLevel, setSelectedLevel] = useState(null); - const [topics, setTopics] = useState([]); - 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 = { 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 = { 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 = {}; - 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 ( -
- {language === 'pl' ? 'Ładowanie...' : language === 'ru' ? 'Загрузка...' : language === 'uk' ? 'Завантаження...' : 'Loading...'} -
- ); - } - - return ( -
-
-
- - - -
- - {/* Заголовок */} -
- -

- 📚 {language === 'pl' ? 'Lekcje' : language === 'ru' ? 'Уроки' : language === 'uk' ? 'Уроки' : 'Lessons'} -

-
- - {!selectedLevel ? ( - /* Выбор уровня */ -
-

- {language === 'pl' ? 'Wybierz poziom' : language === 'ru' ? 'Выберите уровень' : language === 'uk' ? 'Виберіть рівень' : 'Select level'} -

- {levels.map((level, index) => ( - - ))} -
- ) : ( - /* Список тем */ -
-

- {selectedLevel} -

- {topics.length === 0 ? ( -

- {language === 'pl' ? 'Brak tematów' : language === 'ru' ? 'Нет тем' : language === 'uk' ? 'Немає тем' : 'No topics'} -

- ) : ( - topics.map((topic, index) => { - const isCompleted = topic.test_completed; - const isUnlocked = index === 0 || topics[index - 1]?.test_completed; - - return ( - - ); - }) - )} -
- )} -
-
- ); -}; - -export default LessonsPage; \ No newline at end of file diff --git a/src/pages/TeacherChatPage.tsx b/src/pages/TeacherChatPage.tsx index 7c70303..a258332 100644 --- a/src/pages/TeacherChatPage.tsx +++ b/src/pages/TeacherChatPage.tsx @@ -95,6 +95,9 @@ const TeacherChatPage: React.FC = () => { const startTimeRef = useRef(Date.now()); const contentRef = useRef(null); + // 🔧 НОВОЕ (04.10.2026): ref на блок задания — для scrollTo при смене вопроса + const questionBlockRef = useRef(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 = () => { )}
- {/* Объяснение + примеры (из lessonCard) */} - {currentLesson && ( + {/* 🔧 ФИКС (04.10.2026): SHOW_EXPLANATION_ONLY_ON_FIRST_QUESTION — + объяснение показываем только на первом задании (question_index === 0), + чтобы юзер не скроллил через него к 2-му и 3-му. */} + {currentLesson && (currentQuestion?.questionIndex === 0 || currentQuestion?.questionIndex === undefined) && (
{ {/* Задание (текущий вопрос) */} {currentQuestion && ( -
+
{ - const navigate = useNavigate(); - const { topicId } = useParams<{ topicId: string }>(); - const { t } = useLanguage(); - const getLocalized = useLocalized(); - const [questions, setQuestions] = useState([]); - const [loading, setLoading] = useState(true); - const [currentIndex, setCurrentIndex] = useState(0); - const [selectedAnswers, setSelectedAnswers] = useState>({}); - const [textInputValue, setTextInputValue] = useState(''); - const [sessionId, setSessionId] = useState(null); - const [isCompleting, setIsCompleting] = useState(false); - const [testResult, setTestResult] = useState<{ total: number; correct_count: number } | null>(null); - const startTimeRef = useRef(Date.now()); - - // 🔧 НОВОЕ: состояния для примеров и практики - const [showExamplesModal, setShowExamplesModal] = useState(false); - const [examplesText, setExamplesText] = useState(''); - const [isLoadingExamples, setIsLoadingExamples] = useState(false); - const [examplesError, setExamplesError] = useState(null); - const [isPlayingExamples, setIsPlayingExamples] = useState(false); - const [isStartingPractice, setIsStartingPractice] = useState(false); - // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert(). - const [toastMessage, setToastMessage] = useState(null); - // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — - // храним таймер для очистки. - const toastTimeoutRef = useRef | null>(null); - const audioRef = useRef(null); - // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke. - const audioUrlRef = useRef(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 ( -
- {t('loading')} -
- ); - } - - // Экран результатов - if (testResult) { - const total = testResult.total || 0; - const correct = testResult.correct_count || 0; - const percentage = total > 0 ? Math.round((correct / total) * 100) : 0; - - return ( -
- {/* 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() */} - {toastMessage && ( -
- {toastMessage} -
- )} - -
- {percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'} -
-

- {t('teacherCompleted')} -

-
-
= 70 ? '#2ECC71' : percentage >= 50 ? '#F39C12' : '#E74C3C' }}> - {percentage}% -
-
- {correct} / {total} -
-
- {t('testCorrectAnswers')} -
-
- - {/* 🔧 НОВОЕ: Кнопки "Дай примеры" и "Потренировать слабые темы" */} -
- - -
- - - - {/* 🔧 НОВОЕ: Модалка с примерами */} - {showExamplesModal && ( -
{ if (e.target === e.currentTarget) setShowExamplesModal(false); }} - > -
-

- 💡 {t('testExamplesTitle')} -

- - {isLoadingExamples ? ( -
- {t('loading')} -
- ) : examplesError ? ( -
- ⚠️ {examplesError} -
- ) : ( - <> -
- {examplesText} -
-
- - -
- - )} -
-
- )} -
- ); - } - - 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 ( -
-
- - - -
- - {/* Заголовок */} -
- -

- 🎓 {t('testTitle')} -

-
- - {/* Счётчик */} -
- {t('testQuestion')} {currentIndex + 1} / {questions.length} -
- - {/* Прогресс-бар */} -
-
-
- - {/* Вопрос */} - {currentQuestion && ( -
-

- {getLocalized(currentQuestion.question, 'prompt')} -

- - {isProduction ? ( -
- 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`; - }} - /> -
- ) : ( -
- {currentQuestion.options.map((option) => { - const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key; - - return ( - - ); - })} -
- )} -
- )} - - {/* Кнопки навигации */} -
- - -
-
-
- ); -}; - -export default TestViewPage; \ No newline at end of file diff --git a/src/pages/TopicLessonsPage.tsx b/src/pages/TopicLessonsPage.tsx deleted file mode 100644 index aac9ccc..0000000 --- a/src/pages/TopicLessonsPage.tsx +++ /dev/null @@ -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(null); - const [lessons, setLessons] = useState([]); - 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 ( -
- {t('loading')} -
- ); - } - - return ( -
-
-
- - - -
- - {/* Заголовок */} -
- -

- {topic ? getLocalized(topic, 'name') : ''} -

-
- - {/* Список уроков */} -
- {lessons.map((lesson, index) => { - const isUnlocked = index === 0 || lessons[index - 1]?.completed; - - return ( - - ); - })} -
- - {/* Кнопка финального теста */} -
- -
-
-
- ); -}; - -export default TopicLessonsPage; \ No newline at end of file