From fa9b678255cab6820afbc70e328f72dc7a677a4a Mon Sep 17 00:00:00 2001 From: Drobysh Date: Wed, 23 Sep 2026 17:27:22 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=8A=20=D0=92=D0=BE=D0=BB=D0=BD=D0=B0?= =?UTF-8?q?=205:=20frontend=20=D1=8E=D0=B7=D0=B0=D0=B1=D0=B8=D0=BB=D0=B8?= =?UTF-8?q?=D1=82=D0=B8=20(8=20=D0=B1=D0=B0=D0=B3=D0=BE=D0=B2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - teacher_menu_tracked_once: сброс menuTrackedRef в handleClose (TeacherMenuModal.tsx) - support_userid_nan: String() сравнение + проверка null (SupportChatModal.tsx) - admin_dashboard_no_escape: Escape через keydown (AdminDashboardModal.tsx) - feed_modal_race_on_section_change: requestIdRef для защиты от race (FeedModal.tsx) - SILENT_REGISTER_FAILURE: логирование + сброс ref (App.tsx) - USER_ID_NULL_NO_RETRY: retry с backoff до 5 раз (App.tsx) - STRICTMODE_DOUBLE_REGISTER: registerAttemptedRef (App.tsx) - FETCH_NO_TIMEOUT: AbortController 15с в fetchAPI и getTTS (api.ts) - ADMIN_FLAG_FROM_LOCALSTORAGE: isAdmin только из сервера (App.tsx, бонус) setState_inside_updater_side_effect (useAchievements.ts) — уже был исправлен. Аудит: Issue #3, frontend 8/34 задач --- src/App.tsx | 66 +++++++++++++++++++------- src/api.ts | 49 +++++++++++++------ src/components/AdminDashboardModal.tsx | 11 +++++ src/components/FeedModal.tsx | 13 +++-- src/components/SupportChatModal.tsx | 12 +++-- src/components/TeacherMenuModal.tsx | 3 ++ 6 files changed, 114 insertions(+), 40 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 55e2bed..be76cac 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState, useRef } from 'react'; import { BrowserRouter, Routes, Route, useNavigate, useLocation } from 'react-router-dom'; import { LanguageProvider, useLanguage } from './i18n/LanguageContext'; import LanguageSelectPage from './pages/LanguageSelectPage'; @@ -26,12 +26,17 @@ function AppContent() { const location = useLocation(); const { setLang } = useLanguage(); const [showDashboard, setShowDashboard] = useState(false); - const [isAdmin, setIsAdmin] = useState(() => { - // Начальное значение из localStorage, чтобы не мигало при загрузке - return localStorage.getItem('filwords_is_admin') === '1'; - }); + // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — isAdmin только из сервера. + const [isAdmin, setIsAdmin] = useState(false); + // 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — ref-флаг, + // чтобы регистрация не вызывалась дважды в StrictMode. + const registerAttemptedRef = useRef(false); useEffect(() => { + // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — очищаем старый ключ, + // который мог быть подделан в предыдущих версиях. + localStorage.removeItem('filwords_is_admin'); + const tg = window.Telegram?.WebApp; if (tg) { tg.ready(); @@ -42,38 +47,63 @@ function AppContent() { } } - const userId = getUserId(); - if (userId) { + // 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — защита от двойного вызова + // в React StrictMode (dev). В prod useEffect вызывается один раз, но ref + // не помешает. + if (registerAttemptedRef.current) return; + + // 🔧 ФИКС (23.09.2026): USER_ID_NULL_NO_RETRY — если userId ещё не готов, + // повторяем попытку с backoff (до 5 раз, интервал растёт). + let retries = 0; + const MAX_RETRIES = 5; + + const tryRegister = () => { + const userId = getUserId(); + if (!userId) { + retries++; + if (retries < MAX_RETRIES) { + setTimeout(tryRegister, 300 * retries); + return; + } + // После MAX_RETRIES сдаёмся + console.error('registerUser: userId not available after retries'); + return; + } + + registerAttemptedRef.current = true; + registerUser() .then((data) => { trackDailyLogin().catch(() => {}); - - // 🔧 ИСПРАВЛЕНО: получаем is_admin с бэка, а не из хардкода + + // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — не пишем в localStorage. if (typeof data.is_admin === 'boolean') { setIsAdmin(data.is_admin); - localStorage.setItem('filwords_is_admin', data.is_admin ? '1' : '0'); } else { - // Fallback: если бэк по какой-то причине не вернул флаг — спрашиваем отдельно getIsAdmin() .then((adminData) => { setIsAdmin(adminData.is_admin); - localStorage.setItem('filwords_is_admin', adminData.is_admin ? '1' : '0'); }) .catch(() => {}); } - + const langFromStorage = localStorage.getItem('filwords_lang'); - + if (!langFromStorage) { - // Первый визит — показываем выбор языка navigate('/language'); } else if (data.app_language && data.app_language !== langFromStorage) { - // Синхронизируем язык с сервером setLang(data.app_language); } }) - .catch(() => {}); - } + .catch((err) => { + // 🔧 ФИКС (23.09.2026): SILENT_REGISTER_FAILURE — логируем ошибку, + // сбрасываем ref, чтобы можно было повторить при следующем визите. + console.error('registerUser failed:', err); + registerAttemptedRef.current = false; + }); + }; + + tryRegister(); }, []); // 🔧 Слушаем событие "open-dashboard" из MenuPage — открывает модалку дашборда diff --git a/src/api.ts b/src/api.ts index 5155d4d..0eff084 100644 --- a/src/api.ts +++ b/src/api.ts @@ -2,6 +2,11 @@ import { getInitData } from './telegram'; const API_BASE = 'https://api.filwordspl.com'; +// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — таймаут 15с на все запросы. +// Раньше при зависшем соединении (типично для Telegram WebView на слабой сети) +// запрос висел бесконечно, UI оставался в состоянии загрузки. +const FETCH_TIMEOUT_MS = 15000; + const fetchAPI = async (endpoint: string, options: RequestInit = {}) => { const initData = getInitData(); @@ -11,22 +16,31 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => { // Формат "tma " — стандарт Telegram Mini Apps. const url = `${API_BASE}${endpoint}`; - const res = await fetch(url, { - ...options, - headers: { - 'Content-Type': 'application/json', - 'Authorization': `tma ${initData}`, - ...options.headers, - }, - }); + // 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — AbortController с таймаутом. + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); - if (!res.ok) { - const errorText = await res.text(); - throw new Error(`API Error: ${res.status} - ${errorText}`); + try { + const res = await fetch(url, { + ...options, + signal: controller.signal, + headers: { + 'Content-Type': 'application/json', + 'Authorization': `tma ${initData}`, + ...options.headers, + }, + }); + + if (!res.ok) { + const errorText = await res.text(); + throw new Error(`API Error: ${res.status} - ${errorText}`); + } + + const data = await res.json(); + return data; + } finally { + clearTimeout(timeoutId); } - - const data = await res.json(); - return data; }; // ============ Пользователь ============ @@ -180,8 +194,13 @@ export const getTTS = (text: string, voice: string = 'female'): Promise => // Заодно: voice теперь кодируется через encodeURIComponent (TTS_VOICE_NOT_ENCODED). const url = `${API_BASE}/tts?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}`; + // 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — таймаут на TTS. + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + return fetch(url, { method: 'GET', + signal: controller.signal, headers: { 'Authorization': `tma ${initData}`, }, @@ -191,6 +210,8 @@ export const getTTS = (text: string, voice: string = 'female'): Promise => throw new Error(`API Error: ${res.status} - ${errorText}`); } return res.blob(); + }).finally(() => { + clearTimeout(timeoutId); }); }; diff --git a/src/components/AdminDashboardModal.tsx b/src/components/AdminDashboardModal.tsx index f0ac18f..c3ed32d 100644 --- a/src/components/AdminDashboardModal.tsx +++ b/src/components/AdminDashboardModal.tsx @@ -114,6 +114,17 @@ const AdminDashboardModal: React.FC = ({ isOpen, onClo } }, [isOpen, loadData]); + // 🔧 ФИКС (23.09.2026): admin_dashboard_no_escape — добавлен обработчик Escape. + // Раньше админ-панель закрывалась только кликом на крестик. + useEffect(() => { + if (!isOpen) return; + const handleKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') onClose(); + }; + window.addEventListener('keydown', handleKey); + return () => window.removeEventListener('keydown', handleKey); + }, [isOpen, onClose]); + const formatDate = (isoStr: string): string => { try { const date = new Date(isoStr); diff --git a/src/components/FeedModal.tsx b/src/components/FeedModal.tsx index 5990e15..969535f 100644 --- a/src/components/FeedModal.tsx +++ b/src/components/FeedModal.tsx @@ -44,6 +44,9 @@ const FeedModal: React.FC = ({ isOpen, onClose, section, isAdmin const [error, setError] = useState(null); const scrollRef = useRef(null); const isMountedRef = useRef(true); + // 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change — счётчик запросов, + // чтобы старый ответ не перезаписал новый при быстрой смене секции. + const requestIdRef = useRef(0); // 🔧 Шаг 6: состояния админ-режима const [showComposer, setShowComposer] = useState(false); @@ -79,19 +82,23 @@ const FeedModal: React.FC = ({ isOpen, onClose, section, isAdmin setLoading(true); setError(null); + // 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change + const currentRequestId = ++requestIdRef.current; + getFeedSection(section, language) .then((data) => { - if (!isMountedRef.current) return; + // 🔧 Игнорируем устаревшие ответы + if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; setPosts(data.posts || []); }) .catch((e) => { - if (!isMountedRef.current) return; + if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; console.error('Failed to load feed:', e); setError('Failed to load feed'); setPosts([]); }) .finally(() => { - if (!isMountedRef.current) return; + if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return; setLoading(false); }); }, [section, language]); diff --git a/src/components/SupportChatModal.tsx b/src/components/SupportChatModal.tsx index a4e432c..e695f67 100644 --- a/src/components/SupportChatModal.tsx +++ b/src/components/SupportChatModal.tsx @@ -255,11 +255,13 @@ const SupportChatModal: React.FC = ({ isOpen, onClose, is if (!isOpen) return null; - // 🔧 ИСПРАВЛЕНО: определяем "от кого" сообщение через isAdmin проп, а не через хардкод - // Если я админ: мои сообщения — те, где sender_id === userId. Остальные — от пользователя. - // Если я пользователь: мои сообщения — те, где sender_id === userId. Остальные — от админа. - // В обоих случаях "свои" = sender_id === userId. Меняется только логика цвета. - const isMessageFromMe = (senderId: number) => senderId === Number(userId); + // 🔧 ФИКС (23.09.2026): support_userid_nan — раньше при userId=null + // Number(null)=0 и сравнение давало неверный результат, все пузыри + // рисовались как входящие. Теперь строковое сравнение + проверка null. + const isMessageFromMe = (senderId: number) => { + if (userId === null || userId === undefined) return false; + return String(senderId) === String(userId); + }; return (
= ({ setSelectedLetter(null); setSelectedRule(null); setSelectedCheatSheet(null); + // 🔧 ФИКС (23.09.2026): teacher_menu_tracked_once — сбрасываем ref, + // чтобы при следующем открытии меню снова трекалось. + menuTrackedRef.current = false; onClose(); };