From 00f734592c19e7cbbcb86f224ffd1335c8fc375f Mon Sep 17 00:00:00 2001 From: Drobysh Date: Sat, 26 Sep 2026 20:08:17 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9A=20=D0=A3=D1=80=D0=BE=D0=BA=D0=B8:?= =?UTF-8?q?=20=D1=81=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D0=B0=20=D0=B2?= =?UTF-8?q?=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D0=BB=D0=B5=D0=BD=D1=82=D1=8B?= =?UTF-8?q?=20+=20=D1=87=D0=B8=D1=81=D1=82=D0=BA=D0=B0=20TS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Изменено: - Страница урока вместо ленты - Заголовок: A1 · Тема · Урок N/M - Карточки объяснения и задания - Кнопка «Следующий вопрос» после ответа - Экран «Урок завершён» - Убраны неиспользуемые: useCallback, loadTeacherHistory, teacherFreeMessage, wrongAnswerText, explanationText, handleFreeMessage --- src/pages/TeacherChatPage.tsx | 1606 +++++++++++++-------------------- 1 file changed, 632 insertions(+), 974 deletions(-) diff --git a/src/pages/TeacherChatPage.tsx b/src/pages/TeacherChatPage.tsx index 2e9f57a..f4659aa 100644 --- a/src/pages/TeacherChatPage.tsx +++ b/src/pages/TeacherChatPage.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useRef, useCallback } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { useLanguage } from '../i18n/LanguageContext'; import { useLocalized } from '../hooks/useLocalized'; @@ -7,13 +7,11 @@ import { teacherStart, teacherResume, teacherAnswer, - teacherFreeMessage, teacherExamples, getLearningAnalytics, startWeakSkillsPractice, getTTS, saveTeacherHistory, - loadTeacherHistory, clearTeacherHistory, } from '../api'; import TeacherMenuModal from '../components/TeacherMenuModal'; @@ -49,76 +47,57 @@ interface TeacherMessage { isLessonCard?: boolean; } -const STORAGE_KEY = 'filwords_teacher_chat'; +// Экран: что показываем сейчас +type ScreenState = + | { kind: 'start' } + | { kind: 'lesson' } + | { kind: 'after-answer' } + | { kind: 'completed'; correct: number; total: number }; + +const STORAGE_KEY = 'filwords_teacher_chat_v2'; const TeacherChatPage: React.FC = () => { const navigate = useNavigate(); const { t } = useLanguage(); const getLocalized = useLocalized(); - const [messages, setMessages] = useState(() => { - try { - const saved = localStorage.getItem(STORAGE_KEY); - if (saved) { - const parsed = JSON.parse(saved); - if (Array.isArray(parsed) && parsed.length > 0) { - return parsed; - } - } - } catch (e) { - // ignore - } - return []; - }); + + // ============ СОСТОЯНИЕ ============ + const [messages, setMessages] = useState([]); + const [screen, setScreen] = useState({ kind: 'start' }); const [inputValue, setInputValue] = useState(''); const [isLoading, setIsLoading] = useState(false); const [sessionId, setSessionId] = useState(null); const [currentLessonId, setCurrentLessonId] = useState(''); const [currentTopicId, setCurrentTopicId] = useState(''); const [currentTopicName, setCurrentTopicName] = useState(''); + const [currentLevel, setCurrentLevel] = useState('A1'); const [currentQuestionId, setCurrentQuestionId] = useState(''); const [isPlaying, setIsPlaying] = useState(null); - const [isStarted, setIsStarted] = useState(false); - const [showExplanationModal, setShowExplanationModal] = useState(false); const [showMenuModal, setShowMenuModal] = useState(false); - - // 🔧 НОВОЕ: модалки «Произношение» и «Печать» (открываются из меню учителя) const [showTyping, setShowTyping] = useState(false); const [showPronunciation, setShowPronunciation] = useState(false); - - const [explanationData, setExplanationData] = useState<{ - wrongAnswer: string; - correctAnswer: string; - explanation: string; - } | null>(null); - const [showExamplesModal, setShowExamplesModal] = useState(false); const [examplesText, setExamplesText] = useState(''); const [isLoadingExamples, setIsLoadingExamples] = useState(false); const [examplesError, setExamplesError] = useState(null); const [isStartingPractice, setIsStartingPractice] = useState(false); const [playingExampleLine, setPlayingExampleLine] = useState(null); - // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — заменяем alert() на кастомный toast const [toastMessage, setToastMessage] = useState(null); - const messagesEndRef = useRef(null); + // ============ REFS ============ const inputRef = useRef(null); const audioRef = useRef(null); - // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — храним URL для revoke. const audioUrlRef = useRef(null); - // 🔧 ФИКС (24.09.2026): TEACHER_IDREF_O_N — - // раньше idRef инициализировался через Math.max(...messages.map(...)) - // на КАЖДЫЙ рендер — O(n) при длинном чате. Теперь useRef(0), - // а актуальное значение ставится один раз при загрузке истории (в useEffect). const idRef = useRef(0); - // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP — - // храним таймер для очистки. const toastTimeoutRef = useRef | null>(null); - // 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE const historySaveTimeoutRef = useRef | null>(null); const startTimeRef = useRef(Date.now()); + const contentRef = useRef(null); + // ============ ЦВЕТА ============ const brandColor = '#2ECC71'; const teacherColor = '#8B5CF6'; + const lectureColor = '#4FA9E8'; const textColor = '#1A1A2E'; const subColor = '#6B7280'; const bgColor = '#F4F5F7'; @@ -133,172 +112,39 @@ const TeacherChatPage: React.FC = () => { ...extra, }); + // ============ HELPERS ============ + const showToast = (msg: string) => { + setToastMessage(msg); + if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); + toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500); + }; + const hasPolishContent = (text: string): boolean => { return text.includes('🇵🇱') || text.includes('→') || /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/.test(text); }; - // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast вместо alert() - // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP — сохраняем таймер. - const showToast = (msg: string) => { - setToastMessage(msg); - if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); - toastTimeoutRef.current = setTimeout(() => { - setToastMessage(null); - }, 2500); - }; - - const isFreeQuestion = (text: string): boolean => { - const trimmed = text.trim(); - if (trimmed.endsWith('?')) return true; - if (trimmed.length > 50) return true; - const questionWords = [ - 'почему', 'зачем', 'как', 'что', 'кто', 'где', 'когда', - 'dlaczego', 'czemu', 'jak', 'co', 'kto', 'gdzie', 'kiedy', - 'чому', 'навіщо', 'як', 'що', 'хто', 'де', 'коли', - 'why', 'how', 'what', 'who', 'where', 'when', - ]; - const lower = trimmed.toLowerCase(); - return questionWords.some(word => lower.startsWith(word + ' ') || lower.includes(' ' + word + ' ')); - }; - - useEffect(() => { - loadTeacherHistory() - .then((data) => { - if (data.messages && data.messages.length > 0) { - setMessages(data.messages); - const maxId = Math.max(...data.messages.map((m: TeacherMessage) => m.id)); - idRef.current = maxId + 1; - - const lastMsg = data.messages[data.messages.length - 1]; - const hasActiveQuestion = data.messages.some((m: TeacherMessage) => m.isQuestion); - - if (lastMsg && lastMsg.isCompleted) { - setIsStarted(false); - setSessionId(null); - setCurrentQuestionId(''); - } else if (hasActiveQuestion) { - const lastQuestion = [...data.messages].reverse().find(m => m.isQuestion); - if (lastQuestion) { - setCurrentQuestionId(lastQuestion.questionId || ''); - setSessionId(lastQuestion.sessionId || null); - setCurrentLessonId(lastQuestion.lessonId || ''); - setCurrentTopicId(lastQuestion.topicId || ''); - setCurrentTopicName(lastQuestion.topicName || ''); - setIsStarted(true); - } - } else { - setIsStarted(false); - setSessionId(null); - setCurrentQuestionId(''); - } - } - }) - .catch(() => {}); - - teacherResume() - .then((resumeData) => { - if (resumeData.has_active_session && resumeData.question) { - setSessionId(resumeData.session_id || null); - setCurrentTopicId(resumeData.topic_id || ''); - setIsStarted(true); - - const questionId = resumeData.question.question.question_id; - - // 🔧 ФИКС (22.09.2026): НЕ перезаписываем currentQuestionId, - // если активный вопрос уже в истории. Иначе localStorage и resume - // расходятся (UI показывает один вопрос, state хранит другой). - setMessages(prev => { - const existingQuestion = [...prev].reverse().find(m => m.isQuestion); - - if (existingQuestion) { - // Уже есть активный вопрос в истории — используем ЕГО ID. - setCurrentQuestionId(existingQuestion.questionId || questionId); - return prev; - } - - // Иначе — используем ID из resume. - setCurrentQuestionId(questionId); - - const questionMsg: TeacherMessage = { - id: idRef.current++, - type: 'bot', - text: getLocalized(resumeData.question.question, 'prompt'), - isQuestion: true, - questionType: resumeData.question.question.question_type, - questionId: questionId, - options: resumeData.question.options, - optionsLanguage: resumeData.question.question.options_language || 'pl', - sessionId: resumeData.session_id, - topicId: resumeData.topic_id, - questionIndex: resumeData.question_index, - totalQuestions: resumeData.total_questions, - }; - - return [...prev, questionMsg]; - }); - - if (resumeData.question.question.question_type === 'production') { - setTimeout(() => { - inputRef.current?.focus(); - }, 300); - } - } - }) - .catch(() => {}); - }, []); - - // 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE — - // дебаунсим сохранение истории на сервер (500мс), чтобы не долбить - // бэк при каждом новом сообщении. - useEffect(() => { - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); - } catch (e) { - // ignore - } - if (messages.length === 0) return; - if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); - historySaveTimeoutRef.current = setTimeout(() => { - saveTeacherHistory(messages).catch(() => {}); - }, 500); - return () => { - if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); - }; - }, [messages]); - const extractPolishText = (text: string): string => { const lines = text.split('\n'); - const polishLines: string[] = []; - for (const line of lines) { if (!line.trim()) continue; - if (line.includes('🇵🇱')) { - const polish = line.split('🇵🇱')[1]?.trim(); - if (polish) polishLines.push(polish); + const polish = line.split('🇵🇱')[1]?.split('→')[0]?.trim(); + if (polish) return polish; } - else if (line.includes('→')) { + if (line.includes('→')) { const polish = line.split('→')[0]?.trim(); - if (polish) polishLines.push(polish); + if (polish) return polish; } } - - if (polishLines.length > 0) { - return polishLines[0]; - } - return ''; }; - const playText = async (text: string, msgId: number) => { - const polishText = extractPolishText(text); - if (!polishText) return; - + // ============ АУДИО ============ + const stopAudio = () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } - // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем предыдущий URL if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; @@ -306,20 +152,25 @@ const TeacherChatPage: React.FC = () => { if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } + }; + const playText = async (text: string, msgId: number) => { + const polishText = extractPolishText(text); + if (!polishText) return; + + stopAudio(); setIsPlaying(msgId); try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); - audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke + audioUrlRef.current = audioUrl; const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { setIsPlaying(null); - // 🔧 ФИКС (23.09.2026): освобождаем URL после воспроизведения if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; @@ -349,19 +200,7 @@ const TeacherChatPage: React.FC = () => { } if (!polishText) return; - if (audioRef.current) { - audioRef.current.pause(); - audioRef.current = null; - } - // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS - if (audioUrlRef.current) { - try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } - audioUrlRef.current = null; - } - if ('speechSynthesis' in window) { - window.speechSynthesis.cancel(); - } - + stopAudio(); setPlayingExampleLine(index); try { @@ -391,47 +230,130 @@ const TeacherChatPage: React.FC = () => { } }; - const scrollToBottom = useCallback(() => { - messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + // ============ ВОССТАНОВЛЕНИЕ ============ + useEffect(() => { + // 1. Загружаем историю из localStorage + try { + const saved = localStorage.getItem(STORAGE_KEY); + if (saved) { + const parsed = JSON.parse(saved); + if (Array.isArray(parsed) && parsed.length > 0) { + setMessages(parsed); + const maxId = Math.max(...parsed.map((m: TeacherMessage) => m.id)); + idRef.current = maxId + 1; + + // Восстанавливаем текущий экран + const lastQuestion = [...parsed].reverse().find((m: TeacherMessage) => m.isQuestion); + const lastMsg = parsed[parsed.length - 1]; + + if (lastMsg?.isCompleted) { + setScreen({ kind: 'completed', correct: 0, total: 0 }); + } else if (lastQuestion) { + setCurrentQuestionId(lastQuestion.questionId || ''); + setSessionId(lastQuestion.sessionId || null); + setCurrentLessonId(lastQuestion.lessonId || ''); + setCurrentTopicId(lastQuestion.topicId || ''); + setCurrentTopicName(lastQuestion.topicName || ''); + setScreen({ kind: 'lesson' }); + } + } + } + } catch (e) { + // ignore + } + + // 2. Запрашиваем resume с сервера + teacherResume() + .then((resumeData) => { + if (resumeData.has_active_session && resumeData.question) { + setSessionId(resumeData.session_id || null); + setCurrentTopicId(resumeData.topic_id || ''); + setCurrentLevel((resumeData as any).level_code || 'A1'); + + const questionId = resumeData.question.question.question_id; + + setMessages(prev => { + const existingQuestion = [...prev].reverse().find(m => m.isQuestion); + if (existingQuestion) { + setCurrentQuestionId(existingQuestion.questionId || questionId); + setScreen({ kind: 'lesson' }); + return prev; + } + + setCurrentQuestionId(questionId); + setScreen({ kind: 'lesson' }); + + const questionMsg: TeacherMessage = { + id: idRef.current++, + type: 'bot', + text: getLocalized(resumeData.question.question, 'prompt'), + isQuestion: true, + questionType: resumeData.question.question.question_type, + questionId: questionId, + options: resumeData.question.options, + optionsLanguage: resumeData.question.question.options_language || 'pl', + sessionId: resumeData.session_id, + topicId: resumeData.topic_id, + questionIndex: resumeData.question_index, + totalQuestions: resumeData.total_questions, + }; + + return [...prev, questionMsg]; + }); + } + }) + .catch(() => {}); }, []); + // ============ СОХРАНЕНИЕ ============ useEffect(() => { - scrollToBottom(); - }, [messages, isLoading, scrollToBottom]); - - useEffect(() => { - if (isStarted) { - setTimeout(() => { - inputRef.current?.focus(); - }, 300); + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); + } catch (e) { + // ignore } - }, [isStarted]); + if (messages.length === 0) return; + if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); + historySaveTimeoutRef.current = setTimeout(() => { + saveTeacherHistory(messages).catch(() => {}); + }, 500); + return () => { + if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); + }; + }, [messages]); + // ============ ФОКУС ============ + useEffect(() => { + if (screen.kind === 'lesson') { + const lastQuestion = [...messages].reverse().find(m => m.isQuestion); + if (lastQuestion?.questionType === 'production') { + setTimeout(() => inputRef.current?.focus(), 300); + } + } + }, [screen.kind, messages]); + + // ============ ФОКУС ============ useEffect(() => { return () => { - if (audioRef.current) { - audioRef.current.pause(); - audioRef.current = null; - } - // 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем URL при размонтировании - if (audioUrlRef.current) { - try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } - audioUrlRef.current = null; - } - // 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP + stopAudio(); if (toastTimeoutRef.current) { clearTimeout(toastTimeoutRef.current); toastTimeoutRef.current = null; } - if ('speechSynthesis' in window) { - window.speechSynthesis.cancel(); - } }; }, []); + // ============ СКРОЛЛ НАВЕРХ ПРИ СМЕНЕ ЭКРАНА ============ + useEffect(() => { + if (contentRef.current) { + contentRef.current.scrollTop = 0; + } + }, [screen.kind, currentQuestionId]); + + // ============ HANDLERS ============ const handleClearChat = () => { setMessages([]); - setIsStarted(false); + setScreen({ kind: 'start' }); setSessionId(null); setCurrentQuestionId(''); setCurrentLessonId(''); @@ -443,13 +365,11 @@ const TeacherChatPage: React.FC = () => { setShowMenuModal(false); }; - // 🔧 НОВОЕ: при закрытии «Печати» возвращаемся в меню учителя (☰) const handleCloseTyping = () => { setShowTyping(false); setShowMenuModal(true); }; - // 🔧 НОВОЕ: при закрытии «Произношения» возвращаемся в меню учителя (☰) const handleClosePronunciation = () => { setShowPronunciation(false); setShowMenuModal(true); @@ -471,8 +391,10 @@ const TeacherChatPage: React.FC = () => { if (data.lesson_id) setCurrentLessonId(data.lesson_id); if (data.topic_id) setCurrentTopicId(data.topic_id); if (data.topic_name) setCurrentTopicName(data.topic_name); + if ((data as any).level_code) setCurrentLevel((data as any).level_code); if (data.question) { + // Сохраняем сообщение-объяснение (без вопроса) const lessonCardMsg: TeacherMessage = { id: idRef.current++, type: 'bot', @@ -482,10 +404,8 @@ const TeacherChatPage: React.FC = () => { hasPolishText: hasPolishContent(data.text), isLessonCard: true, }; - setMessages(prev => [...prev, lessonCardMsg]); - - await new Promise(resolve => setTimeout(resolve, 400)); + // Сохраняем сообщение-вопрос const questionMsg: TeacherMessage = { id: idRef.current++, type: 'bot', @@ -503,10 +423,11 @@ const TeacherChatPage: React.FC = () => { totalQuestions: data.total_questions, }; + setMessages(prev => [...prev, lessonCardMsg, questionMsg]); setCurrentQuestionId(data.question.question.question_id); - setMessages(prev => [...prev, questionMsg]); - setIsStarted(true); + setScreen({ kind: 'lesson' }); } else { + // Нет вопроса — урок завершён или тест const botMessage: TeacherMessage = { id: idRef.current++, type: 'bot', @@ -514,11 +435,17 @@ const TeacherChatPage: React.FC = () => { topicId: data.topic_id, topicName: data.topic_name, hasPolishText: hasPolishContent(data.text), + isCompleted: data.message_type === 'completed', }; setMessages(prev => [...prev, botMessage]); + + if (data.message_type === 'completed') { + setScreen({ kind: 'completed', correct: 0, total: 0 }); + } } } catch (e) { console.error('Error starting teacher:', e); + showToast(t('teacherAIError') || 'Ошибка'); } finally { setIsLoading(false); } @@ -530,22 +457,12 @@ const TeacherChatPage: React.FC = () => { const timeTaken = Date.now() - startTimeRef.current; startTimeRef.current = Date.now(); - const userMessage: TeacherMessage = { - id: idRef.current++, - type: 'user', - text: answer, - }; - - setMessages(prev => [...prev, userMessage]); - setInputValue(''); setIsLoading(true); try { const data = await teacherAnswer(sessionId, currentQuestionId, answer, timeTaken); let correctAnswerText = data.correct_answer || ''; - let wrongAnswerText = answer; - let explanationText = data.explanation || data.wrong_because || ''; if (!correctAnswerText) { const currentQuestion = messages.find(m => m.isQuestion && m.questionId === currentQuestionId); @@ -557,26 +474,7 @@ const TeacherChatPage: React.FC = () => { } } - const currentQuestion = messages.find(m => m.isQuestion && m.questionId === currentQuestionId); - if (currentQuestion && currentQuestion.options) { - const selectedOption = currentQuestion.options.find(o => o.option_key === answer); - if (selectedOption) { - if (currentQuestion.optionsLanguage === 'user') { - wrongAnswerText = getLocalized(selectedOption, 'text'); - } else { - wrongAnswerText = selectedOption.text_pl; - } - } - } - - if (!data.is_correct) { - setExplanationData({ - wrongAnswer: wrongAnswerText, - correctAnswer: correctAnswerText, - explanation: explanationText || '', - }); - } - + // Сохраняем reaction-сообщение const reactionMessage: TeacherMessage = { id: idRef.current++, type: 'bot', @@ -587,45 +485,31 @@ const TeacherChatPage: React.FC = () => { ], hasPolishText: false, }; - setMessages(prev => [...prev, reactionMessage]); + // Если сессия завершена if (data.session_completed) { - if (data.session_stats && data.session_type === 'teacher_test') { - const stats = data.session_stats; - const percent = stats.total > 0 ? Math.round((stats.correct_count / stats.total) * 100) : 0; + const stats = data.session_stats || { total: 0, correct_count: 0 }; - const testCompletedMessage: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: `${t('teacherTestCompleted')} ${stats.correct_count}/${stats.total} (${percent}%)`, - }; - setMessages(prev => [...prev, testCompletedMessage]); + const completedMessage: TeacherMessage = { + id: idRef.current++, + type: 'system', + text: t('teacherCompleted') || 'Урок завершён!', + isCompleted: true, + }; + setMessages(prev => [...prev, completedMessage]); - await new Promise(resolve => setTimeout(resolve, 300)); + setScreen({ + kind: 'completed', + correct: stats.correct_count, + total: stats.total, + }); + setIsLoading(false); + return; + } - const lessonCompletedMessage: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: t('teacherCompleted'), - commands: ['/examples', '/practice'], - isCompleted: true, - }; - setMessages(prev => [...prev, lessonCompletedMessage]); - } else { - const completedMessage: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: t('teacherCompleted'), - isCompleted: true, - }; - setMessages(prev => [...prev, completedMessage]); - } - - setIsStarted(false); - setSessionId(null); - setCurrentQuestionId(''); - } else if (data.question) { + // Если есть следующий вопрос + if (data.question) { const nextQuestionMessage: TeacherMessage = { id: idRef.current++, type: 'bot', @@ -638,72 +522,31 @@ const TeacherChatPage: React.FC = () => { questionIndex: data.question_index, totalQuestions: data.question.total_questions, }; - - setCurrentQuestionId(data.question.question.question_id); setMessages(prev => [...prev, nextQuestionMessage]); - - if (data.question.question.question_type === 'production') { - setTimeout(() => { - inputRef.current?.focus(); - }, 300); - } + setCurrentQuestionId(data.question.question.question_id); } + + // Показываем экран "after-answer" — с реакцией и кнопкой "Следующий вопрос" + setScreen({ kind: 'after-answer' }); } catch (e) { console.error('Error answering:', e); + showToast(t('teacherAIError') || 'Ошибка'); } finally { setIsLoading(false); } }; - const handleFreeMessage = async (text: string) => { - if (!text.trim() || isLoading) return; + // Переход к следующему вопросу (после ответа) + const handleNextQuestion = () => { + // Ищем последний вопрос в messages (последний добавленный) + const lastQuestion = [...messages].reverse().find(m => m.isQuestion); - const userMessage: TeacherMessage = { - id: idRef.current++, - type: 'user', - text: text, - }; - - setMessages(prev => [...prev, userMessage]); - setInputValue(''); - setIsLoading(true); - - try { - const data = await teacherFreeMessage(text, currentLessonId, currentTopicId, currentTopicName); - - if (data.limit_exceeded && data.message) { - const msg: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: data.message, - }; - setMessages(prev => [...prev, msg]); - } else if (data.response) { - const msg: TeacherMessage = { - id: idRef.current++, - type: 'bot', - text: data.response, - hasPolishText: hasPolishContent(data.response), - }; - setMessages(prev => [...prev, msg]); - } else { - const msg: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: t('teacherAIError'), - }; - setMessages(prev => [...prev, msg]); - } - } catch (e) { - console.error('Error sending free message:', e); - const msg: TeacherMessage = { - id: idRef.current++, - type: 'system', - text: t('teacherAIError'), - }; - setMessages(prev => [...prev, msg]); - } finally { - setIsLoading(false); + if (lastQuestion) { + setCurrentQuestionId(lastQuestion.questionId || ''); + setScreen({ kind: 'lesson' }); + } else { + // Нет вопроса — урок завершён + setScreen({ kind: 'completed', correct: 0, total: 0 }); } }; @@ -721,11 +564,11 @@ const TeacherChatPage: React.FC = () => { } else if (data.response) { setExamplesText(data.response); } else { - setExamplesError(t('testNoExamples')); + setExamplesError(t('testNoExamples') || 'Примеры недоступны'); } } catch (e) { console.error('Error loading examples:', e); - setExamplesError(t('teacherAIError')); + setExamplesError(t('teacherAIError') || 'Ошибка'); } finally { setIsLoadingExamples(false); } @@ -738,8 +581,7 @@ const TeacherChatPage: React.FC = () => { try { const analytics = await getLearningAnalytics(); if (!analytics.has_practice_available) { - // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() - showToast(t('testPracticeNoWeak')); + showToast(t('testPracticeNoWeak') || 'Нет слабых навыков'); setIsStartingPractice(false); return; } @@ -754,37 +596,16 @@ const TeacherChatPage: React.FC = () => { }, }); } else { - // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() - showToast(data.message || t('testPracticeNoWeak')); + showToast(data.message || t('testPracticeNoWeak') || 'Нет слабых навыков'); setIsStartingPractice(false); } } catch (e) { console.error('Error starting practice:', e); - // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() - showToast(t('teacherAIError')); + showToast(t('teacherAIError') || 'Ошибка'); setIsStartingPractice(false); } }; - const handleCommand = async (command: string) => { - if (isLoading) return; - - if (command === '/examples') { - await handleLoadExamples(); - return; - } - - if (command === '/practice') { - await handleStartPractice(); - return; - } - - if (command === '/show-answer') { - setShowExplanationModal(true); - return; - } - }; - const handleOptionClick = (option: any) => { handleAnswer(option.option_key); }; @@ -792,12 +613,7 @@ const TeacherChatPage: React.FC = () => { const handleSubmitAnswer = () => { const text = inputValue.trim(); if (!text) return; - - if (isFreeQuestion(text)) { - handleFreeMessage(text); - } else { - handleAnswer(text); - } + handleAnswer(text); }; const handleKeyDown = (e: React.KeyboardEvent) => { @@ -807,61 +623,37 @@ const TeacherChatPage: React.FC = () => { } }; - const lastMessage = messages.length > 0 ? messages[messages.length - 1] : null; - const isQuestionActive = lastMessage?.isQuestion && !isLoading; - const showContinueButton = messages.length > 0 && !isStarted && !lastMessage?.isCompleted && !lastMessage?.commands; + // ============ COMPUTED ============ + // Текущий вопрос (последний в messages) + const currentQuestion = [...messages].reverse().find(m => m.isQuestion) || null; + // Текущее объяснение (последнее isLessonCard) + const currentLesson = [...messages].reverse().find(m => m.isLessonCard) || null; + + // Последняя реакция (если есть) + const lastReaction = [...messages].reverse().find(m => m.isCorrect !== undefined && !m.isQuestion) || null; + + // ============ RENDER ============ return (
+ {/* Фоновые градиенты */}
- {/* 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — кастомный toast вместо alert() */} - {toastMessage && ( -
- {toastMessage} -
- )} - - {/* Модальное окно правильного ответа */} - {showExplanationModal && explanationData && ( -
{ if (e.target === e.currentTarget) setShowExplanationModal(false); }} - > -
-

- ✅ {t('teacherShowAnswer')} -

- - {explanationData.wrongAnswer && ( -
-
- ❌ {t('teacherWrongAnswer')} -
-
- {explanationData.wrongAnswer} -
-
- )} - - {explanationData.correctAnswer && ( -
-
- ✅ {t('teacherCorrectAnswer')} -
-
- {explanationData.correctAnswer} -
-
- )} - - {explanationData.explanation && ( -
-
- 📖 {t('teacherWhy')} -
-
- {explanationData.explanation} -
-
- )} - - -
+ {/* Toast */} + {toastMessage && ( +
+ {toastMessage}
)} - {/* Модалка с примерами */} + {/* Модалка примеров */} {showExamplesModal && (
{ >
-

- 💡 {t('testExamplesTitle')} +

+ 💡 {t('testExamplesTitle') || 'Примеры'}

{isLoadingExamples ? ( -
- {t('loading')} +
+ {t('loading') || 'Загрузка...'}
) : examplesError ? ( -
+
⚠️ {examplesError}
) : ( @@ -1032,32 +724,15 @@ const TeacherChatPage: React.FC = () => { onClick={() => playExampleLine(line, idx)} style={{ padding: '12px 14px', - background: playingExampleLine === idx - ? 'rgba(79,169,232,0.18)' - : 'rgba(79,169,232,0.08)', - borderRadius: radius.md, - fontSize: '14px', - lineHeight: '1.6', - color: textColor, - cursor: 'pointer', - border: playingExampleLine === idx - ? '1px solid rgba(79,169,232,0.5)' - : '1px solid transparent', - transition: 'all 0.2s ease', - display: 'flex', - alignItems: 'center', - gap: '10px', + background: playingExampleLine === idx ? 'rgba(79,169,232,0.18)' : 'rgba(79,169,232,0.08)', + borderRadius: radius.md, fontSize: '14px', lineHeight: '1.6', + color: textColor, cursor: 'pointer', + border: playingExampleLine === idx ? '1px solid rgba(79,169,232,0.5)' : '1px solid transparent', + display: 'flex', alignItems: 'center', gap: '10px', }} - onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }} - onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > {line} - + 🔊
@@ -1066,18 +741,12 @@ const TeacherChatPage: React.FC = () => { )} @@ -1085,7 +754,7 @@ const TeacherChatPage: React.FC = () => {
)} - {/* Меню учителя */} + {/* Модалки */} setShowMenuModal(false)} @@ -1095,83 +764,71 @@ const TeacherChatPage: React.FC = () => { onOpenPronunciation={() => setShowPronunciation(true)} /> - {/* 🔧 НОВОЕ: модалка «Печать» (открывается из меню учителя) */} - + + - {/* 🔧 НОВОЕ: модалка «Произношение» (открывается из меню учителя) */} - + {/* ============ ОСНОВНОЙ КОНТЕНТ ============ */} +
-
- - {/* Заголовок */} + {/* ЗАГОЛОВОК */}
-
- 🎓 -
-

- {t('teacher')} -

+ + {screen.kind === 'lesson' || screen.kind === 'after-answer' ? ( +
+ + {currentLevel} + + {currentQuestion?.questionIndex !== undefined && currentQuestion?.totalQuestions !== undefined && ( + + {currentQuestion.questionIndex + 1}/{currentQuestion.totalQuestions} + + )} + + {currentTopicName || currentLesson?.topicName || t('lessons') || 'Уроки'} + +
+ ) : ( +

+ 📚 {t('lessons') || 'Уроки'} +

+ )} + + {messages.length > 0 && (
- {/* Сообщения */} -
- {messages.length === 0 && !isStarted && ( -
+ {/* КОНТЕНТ */} +
+ + {/* ЭКРАН START */} + {screen.kind === 'start' && ( +
🎓

- {t('teacherWelcome')} + {t('teacherWelcome') || 'Добро пожаловать!'}

)} - {showContinueButton && ( -
+ {/* ЭКРАН LESSON — один урок = одна страница */} + {screen.kind === 'lesson' && ( + <> + {/* Заголовок страницы */} +
+
+ {currentLevel} · {t('level') || 'Уровень'} +
+ {(currentTopicName || currentLesson?.topicName) && ( +
+ {t('topic') || 'Тема'}: {currentTopicName || currentLesson?.topicName} +
+ )} +
+ {currentLesson && ( +
+ {currentLesson.text.split('\n')[0]} +
+ )} +
+ + {/* Объяснение + примеры (из lessonCard) */} + {currentLesson && ( +
+
+ 📖 + + {t('teacherExplanation') || 'Объяснение'} + +
+
+ {currentLesson.text} +
+ {currentLesson.hasPolishText && ( + + )} +
+ )} + + {/* Задание (текущий вопрос) */} + {currentQuestion && ( +
+
+
+ ✏️ + + {t('teacherTask') || 'Задание'} + +
+ {currentQuestion.questionIndex !== undefined && currentQuestion.totalQuestions !== undefined && ( + + {currentQuestion.questionIndex + 1} / {currentQuestion.totalQuestions} + + )} +
+ +
+ {currentQuestion.text} +
+ + {/* Варианты ответа (recognition) */} + {currentQuestion.questionType === 'recognition' && currentQuestion.options && ( +
+ {currentQuestion.options.map((option) => ( + + ))} +
+ )} + + {/* Ввод (production) */} + {currentQuestion.questionType === 'production' && ( +
+ setInputValue(e.target.value)} + onKeyDown={handleKeyDown} + placeholder={t('teacherPlaceholder') || 'Введите ответ'} + disabled={isLoading} + style={{ + flex: 1, padding: '12px 16px', borderRadius: radius.md, + border: `1px solid ${teacherColor}30`, + background: 'rgba(255,255,255,0.8)', + color: textColor, fontSize: '15px', + fontFamily: fonts.main, outline: 'none', + }} + /> + +
+ )} +
+ )} + + )} + + {/* ЭКРАН AFTER-ANSWER — реакция + кнопка "Следующий вопрос" */} + {screen.kind === 'after-answer' && ( +
+ {/* Реакция */} + {lastReaction && ( +
+
+ {lastReaction.isCorrect ? '✅' : '❌'} +
+
+ {lastReaction.text} +
+ {lastReaction.commands?.includes('/show-answer') && ( + + )} +
+ )} + + {/* Кнопка "Следующий вопрос" */} + +
+ )} + + {/* ЭКРАН COMPLETED */} + {screen.kind === 'completed' && ( +
+
🎉
+

+ {t('teacherLessonCompleted') || 'Урок завершён!'} +

+ {screen.total > 0 && ( +

+ {screen.correct} / {screen.total} ({Math.round((screen.correct / screen.total) * 100)}%) +

+ )} + + + + +
)} - {messages.map((msg) => ( -
-
- {msg.text} -
- - {msg.type === 'bot' && !msg.isQuestion && msg.hasPolishText && ( - - )} - - {msg.isQuestion && msg.options && msg.options.length > 0 && ( -
- {msg.options.map((option) => ( - - ))} -
- )} - - {msg.commands && msg.commands.length > 0 && ( -
- {msg.commands.map((cmd) => { - if (cmd === '/show-answer') { - return ( - - ); - } - if (cmd === '/examples') { - return ( - - ); - } - if (cmd === '/practice') { - return ( - - ); - } - return null; - })} -
- )} - - {msg.isCompleted && ( - - )} -
- ))} - - {isLoading && ( -
- {[0, 1, 2].map((i) => ( -
- ))} -
- )} - -
- - {isQuestionActive && ( -
- setInputValue(e.target.value)} - onKeyDown={handleKeyDown} - placeholder={t('teacherPlaceholder')} - disabled={isLoading} - style={{ - flex: 1, - padding: '12px 16px', - borderRadius: radius.md, - border: `1px solid ${teacherColor}30`, - background: 'rgba(255,255,255,0.8)', - color: textColor, - fontSize: '14px', - fontFamily: fonts.main, - outline: 'none', - transition: 'all 0.2s ease', - }} - onFocus={(e) => { - e.currentTarget.style.borderColor = teacherColor; - e.currentTarget.style.boxShadow = `0 0 0 3px ${teacherColor}15`; - }} - onBlur={(e) => { - e.currentTarget.style.borderColor = `${teacherColor}30`; - e.currentTarget.style.boxShadow = 'none'; - }} - /> - -
- )}
);