From ea409765783d814db6d06614a42478ec37a6ae17 Mon Sep 17 00:00:00 2001 From: Drobysh Date: Sun, 4 Oct 2026 15:16:30 +0300 Subject: [PATCH] =?UTF-8?q?feat(lesson):=20UX-=D1=80=D0=B5=D0=B4=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D0=B9=D0=BD=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0=20?= =?UTF-8?q?=E2=80=94=20=D0=BF=D1=80=D0=BE=D0=BC=D0=B5=D0=B6=D1=83=D1=82?= =?UTF-8?q?=D0=BE=D1=87=D0=BD=D1=8B=D0=B9=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD?= =?UTF-8?q?,=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=20=D0=BE=D1=88=D0=B8?= =?UTF-8?q?=D0=B1=D0=BE=D0=BA,=20scrollIntoView?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - translations: 16 ключей lesson* × 4 языка - LessonViewPage: retryMode + retryQuestions, промежуточный экран, «Повторить ошибки» только для ошибочных заданий, scrollIntoView к блоку вопроса вместо прыжка вверх - App.tsx: GLOBAL_SCROLL_BREAKS_LESSON_NAV — не скроллим вверх на /lessons/* --- src/App.tsx | 6 + src/i18n/translations.ts | 68 +++ src/pages/LessonViewPage.tsx | 925 +++++++++++++++-------------------- 3 files changed, 477 insertions(+), 522 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 1595f82..d834dd3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -207,7 +207,13 @@ function AppContent() { } }, [showDashboard, isAdmin, isAdminResolved]); + // 🔧 ФИКС (04.10.2026): GLOBAL_SCROLL_BREAKS_LESSON_NAV — + // не скроллим вверх, если мы внутри урока (смена вопроса). + // Оставляем глобальный сброс только при реальной смене route. useEffect(() => { + // Пропускаем, если мы на странице урока — там свой scrollIntoView. + if (location.pathname.includes('/lessons/')) return; + window.scrollTo(0, 0); document.documentElement.scrollTop = 0; document.body.scrollTop = 0; diff --git a/src/i18n/translations.ts b/src/i18n/translations.ts index df1eeda..3f10f93 100644 --- a/src/i18n/translations.ts +++ b/src/i18n/translations.ts @@ -234,6 +234,23 @@ export const translations: Record> = { feedAdminErrorPublish: "Nie udało się opublikować", feedAdminErrorDelete: "Nie udało się usunąć", feedAdminSuccess: "Gotowe!", + // 🔧 НОВОЕ (04.10.2026): lesson UX keys — промежуточный экран, повтор ошибок + lessonCorrect: "Poprawnie!", + lessonNoWorry: "Nic się nie stało!", + lessonReadAgain: "Przejrzyj lekcję i spróbuj ponownie.", + lessonRetry: "Powtórz", + lessonRetryWrong: "Powtórz błędy", + lessonRetryMode: "Powtórka", + lessonFinish: "Zakończ", + lessonCheck: "Sprawdź", + lessonIntermediateTitle: "Zadania ukończone!", + lessonCorrectCount: "poprawnych odpowiedzi", + lessonShowCorrect: "Poprawna odpowiedź:", + lessonTryAgain: "Już 3 próby!", + lessonNextTopic: "Następny temat", + lessonChooseAnswer: "Wybierz odpowiedź", + lessonCompleted: "Lekcja ukończona!", + lessonRepeat: "Warto powtórzyć", }, ru: { menu: "Меню", @@ -470,6 +487,23 @@ export const translations: Record> = { feedAdminErrorPublish: "Не удалось опубликовать", feedAdminErrorDelete: "Не удалось удалить", feedAdminSuccess: "Готово!", + // 🔧 НОВОЕ (04.10.2026): lesson UX keys + lessonCorrect: "Правильно!", + lessonNoWorry: "Ничего страшного!", + lessonReadAgain: "Посмотри урок ещё раз и попробуй снова.", + lessonRetry: "Повторить", + lessonRetryWrong: "Повторить ошибки", + lessonRetryMode: "Повтор", + lessonFinish: "Завершить", + lessonCheck: "Проверить", + lessonIntermediateTitle: "Задания пройдены!", + lessonCorrectCount: "правильных ответов", + lessonShowCorrect: "Правильный ответ:", + lessonTryAgain: "Уже 3 попытки!", + lessonNextTopic: "Следующая тема", + lessonChooseAnswer: "Выбери ответ", + lessonCompleted: "Урок завершён!", + lessonRepeat: "Стоит повторить", }, uk: { menu: "Меню", @@ -706,6 +740,23 @@ export const translations: Record> = { feedAdminErrorPublish: "Не вдалося опублікувати", feedAdminErrorDelete: "Не вдалося видалити", feedAdminSuccess: "Готово!", + // 🔧 НОВОЕ (04.10.2026): lesson UX keys + lessonCorrect: "Правильно!", + lessonNoWorry: "Нічого страшного!", + lessonReadAgain: "Переглянь урок ще раз і спробуй знову.", + lessonRetry: "Повторити", + lessonRetryWrong: "Повторити помилки", + lessonRetryMode: "Повтор", + lessonFinish: "Завершити", + lessonCheck: "Перевірити", + lessonIntermediateTitle: "Завдання виконано!", + lessonCorrectCount: "правильних відповідей", + lessonShowCorrect: "Правильна відповідь:", + lessonTryAgain: "Вже 3 спроби!", + lessonNextTopic: "Наступна тема", + lessonChooseAnswer: "Вибери відповідь", + lessonCompleted: "Урок завершено!", + lessonRepeat: "Варто повторити", }, en: { menu: "Menu", @@ -942,6 +993,23 @@ export const translations: Record> = { feedAdminErrorPublish: "Failed to publish", feedAdminErrorDelete: "Failed to delete", feedAdminSuccess: "Done!", + // 🔧 НОВОЕ (04.10.2026): lesson UX keys + lessonCorrect: "Correct!", + lessonNoWorry: "No worries!", + lessonReadAgain: "Review the lesson and try again.", + lessonRetry: "Retry", + lessonRetryWrong: "Retry mistakes", + lessonRetryMode: "Retry", + lessonFinish: "Finish", + lessonCheck: "Check", + lessonIntermediateTitle: "Tasks completed!", + lessonCorrectCount: "correct answers", + lessonShowCorrect: "Correct answer:", + lessonTryAgain: "3 attempts already!", + lessonNextTopic: "Next topic", + lessonChooseAnswer: "Choose an answer", + lessonCompleted: "Lesson completed!", + lessonRepeat: "Worth repeating", }, }; diff --git a/src/pages/LessonViewPage.tsx b/src/pages/LessonViewPage.tsx index 36d34b4..002da94 100644 --- a/src/pages/LessonViewPage.tsx +++ b/src/pages/LessonViewPage.tsx @@ -26,6 +26,7 @@ interface Question { question_type: string; skill_tag: string; difficulty: number; + options_language?: string; }; options: QuestionOption[]; } @@ -62,12 +63,17 @@ interface ReportData { 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 } // неправильно - | { kind: 'retrying' }; // нажал «Повторить урок», читает заново + | { 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(); @@ -83,13 +89,20 @@ const LessonViewPage: React.FC = () => { const [sessionId, setSessionId] = useState(null); const [isCompleting, setIsCompleting] = useState(false); const startTimeRef = useRef(Date.now()); - const topRef = useRef(null); - // 🔧 НОВОЕ (02.10.2026): новое состояние ответа + отчёт + // 🔧 НОВОЕ (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'; @@ -121,7 +134,20 @@ const LessonViewPage: React.FC = () => { } }, [lessonId, topicId]); - // 🔧 НОВОЕ (02.10.2026): сохраняем ответ с is_retry + // 🔧 НОВОЕ (04.10.2026): при смене вопроса скроллим к блоку вопроса, + // а не в начало страницы. + useEffect(() => { + if (questionBlockRef.current && !showIntermediate) { + // requestAnimationFrame — даём React отрендерить новый контент + requestAnimationFrame(() => { + questionBlockRef.current?.scrollIntoView({ + behavior: 'smooth', + block: 'center', + }); + }); + } + }, [currentQuestionIndex, retryMode, showIntermediate]); + const saveAnswer = async ( questionId: string, answer: string, @@ -143,10 +169,17 @@ const LessonViewPage: React.FC = () => { questionId, answer, timeTaken, - true, // is_final_answer - false, // hint_used - isRetry, // 🔧 НОВОЕ + 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); @@ -154,55 +187,14 @@ const LessonViewPage: React.FC = () => { } }; - // 🔧 НОВОЕ (02.10.2026): выбор варианта — теперь с новой логикой const handleAnswerSelect = async (questionId: string, optionKey: string) => { if (saving) return; haptic.selection(); setSaving(true); - - // Оптимистично показываем выбранный вариант setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey })); - const isRetry = answerState.kind === 'retrying'; - const res = await saveAnswer(questionId, optionKey, isRetry); - - 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); - }; - - // 🔧 НОВОЕ (02.10.2026): ввод текста — сохраняем через blur - 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 isRetry = answerState.kind === 'retrying'; - const res = await saveAnswer(questionId, textInputValue.trim(), isRetry); + const res = await saveAnswer(questionId, optionKey, retryMode); if (!res) { setSaving(false); @@ -225,55 +217,110 @@ const LessonViewPage: React.FC = () => { setSaving(false); }; - // 🔧 НОВОЕ (02.10.2026): «Повторить урок» — скролл наверх, - // разблокируем ответы, показываем объяснение + примеры - const handleRetry = () => { + 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(); - setAnswerState({ kind: 'retrying' }); - setSelectedAnswers(prev => { - const copy = { ...prev }; - if (lesson && lesson.questions[currentQuestionIndex]) { - delete copy[lesson.questions[currentQuestionIndex].question.question_id]; - } - return copy; + 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(''); - // Скролл наверх - topRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }); + setAnswerState({ kind: 'unanswered' }); + setShowIntermediate(false); startTimeRef.current = Date.now(); }; - // 🔧 НОВОЕ (02.10.2026): «Следующий вопрос» (пропустить ошибку) - const handleNext = async () => { + // 🔧 НОВОЕ (04.10.2026): «Далее» — без скролла вверх. На последнем + // вопросе показываем промежуточный экран. + const handleNext = () => { haptic.light(); - if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) { + 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(); - topRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }); } else { - // Последний вопрос → завершаем урок, получаем отчёт 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); + 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) { @@ -284,32 +331,24 @@ const LessonViewPage: React.FC = () => { } }; - // ============ ЭКРАН ОТЧЁТА ============ + // ============ ЭКРАН ФИНАЛЬНОГО ОТЧЁТА ============ if (report) { const percent = report.percent; const emoji = percent >= 90 ? '🎉' : percent >= 75 ? '💪' : percent >= 60 ? '👍' : '📚'; return (
{emoji}
@@ -318,127 +357,74 @@ const LessonViewPage: React.FC = () => {
- {t('lessonCompleted') || 'Урок завершён!'} + {t('lessonCompleted')}
- {/* Круг с процентом */}
{percent}%
-
- {report.weak_skills.length === 0 ? '✨' : ''} -
- {/* Сообщение */} -

+

{report.message}

- {/* Слабые навыки */} {report.weak_skills.length > 0 && (
- 💡 {t('lessonRepeat') || 'Стоит повторить'} + 💡 {t('lessonRepeat')}
{report.weak_skills.map((w, i) => (
• {w.name} - - {w.errors} {w.errors === 1 ? 'ошибка' : w.errors < 5 ? 'ошибки' : 'ошибок'} - + {w.errors}
))}
)} - {/* Кнопки */}
{report.next_topic && ( )}
@@ -450,14 +436,9 @@ const LessonViewPage: React.FC = () => { if (loading) { return (
{t('loading')}
@@ -466,155 +447,152 @@ const LessonViewPage: React.FC = () => { if (!lesson) return null; - const currentQuestion = lesson.questions[currentQuestionIndex]; - const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1; - const isProduction = currentQuestion?.question.question_type === 'production'; + // ============ ПРОМЕЖУТОЧНЫЙ ЭКРАН ============ + 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; - const optionsLanguage = (currentQuestion?.question as any)?.options_language; + 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'; - const isRetrying = answerState.kind === 'retrying'; + + // Показывать объяснение только на первом вопросе И не в retry-режиме. + const showExplanation = currentQuestionIndex === 0 && !retryMode; return ( -
+
- -
- {/* Модалка с правильным ответом (3-я ошибка) */} + {/* Модалка «3 попытки» — показываем правильный ответ */} {answerState.kind === 'wrong' && answerState.showCorrect && answerState.correctAnswer && ( -
+
💪

- {t('lessonTryAgain') || 'Уже 3 попытки!'} + {t('lessonTryAgain')}

- {t('lessonShowCorrect') || 'Правильный ответ:'} + {t('lessonShowCorrect')}

{answerState.correctAnswer}
-

- {t('lessonReadExplanation') || 'Повтори урок внимательнее — там есть объяснение.'} -

-
- - -
+
)} {/* Заголовок */} -
+
- {/* Счётчик */} + {/* Счётчик задания */}
- {t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length} + {t('testQuestion')} {currentQuestionIndex + 1} / {questionsList.length} + {retryMode && ( + + 🔄 {t('lessonRetryMode')} + + )}
- {/* Объяснение + примеры (на первом вопросе ИЛИ при повторе) */} - {(currentQuestionIndex === 0 || isRetrying) && ( + {/* Объяснение + примеры — ТОЛЬКО на первом вопросе и НЕ в retry */} + {showExplanation && (
- {isRetrying && ( -
- 📖 {t('lessonReadCarefully') || 'Прочитай внимательно:'} -
- )}

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

@@ -663,232 +633,143 @@ const LessonViewPage: React.FC = () => {
)} - {/* Вопрос */} - {currentQuestion && ( -
-

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

+ {/* Блок вопроса — 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', - transition: 'all 0.2s ease', - }} - /> -
- ) : ( -
- {currentQuestion.options.map((option) => { - const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key; - const disabled = (isAnswered && !isRetrying) || saving; + {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 ( - - ); - })} -
- )} -
- )} + return ( + + ); + })} +
+ )} +
- {/* Обратная связь после ответа */} + {/* Обратная связь */} {answerState.kind === 'correct' && (
- ✅ {t('lessonCorrect') || 'Правильно!'} + ✅ {t('lessonCorrect')}
)} {answerState.kind === 'wrong' && !answerState.showCorrect && (
- 💪 {t('lessonNoWorry') || 'Ничего страшного!'} + 💪 {t('lessonNoWorry')}
- {t('lessonReadAgain') || 'Посмотри урок ещё раз и попробуй снова.'} + {t('lessonReadAgain')}
)} {/* Кнопки навигации */} - {!isRetrying && ( -
- {currentQuestionIndex > 0 && ( - - )} +
+ {currentQuestionIndex > 0 && ( + + )} - {answerState.kind === 'unanswered' && ( - - )} + {answerState.kind === 'unanswered' && ( + + )} - {answerState.kind === 'correct' && ( - - )} - - {answerState.kind === 'wrong' && !answerState.showCorrect && ( - <> - - - - )} -
- )} + {isAnswered && ( + + )} +
);