🌊 Волна 5: frontend юзабилити (8 багов)
- 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 задач
This commit is contained in:
+45
-15
@@ -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,22 +47,42 @@ 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(() => {});
|
||||
}
|
||||
@@ -65,15 +90,20 @@ function AppContent() {
|
||||
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 — открывает модалку дашборда
|
||||
|
||||
+35
-14
@@ -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 <initData>" — стандарт 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<Blob> =>
|
||||
// Заодно: 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<Blob> =>
|
||||
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||
}
|
||||
return res.blob();
|
||||
}).finally(() => {
|
||||
clearTimeout(timeoutId);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -114,6 +114,17 @@ const AdminDashboardModal: React.FC<AdminDashboardModalProps> = ({ 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);
|
||||
|
||||
@@ -44,6 +44,9 @@ const FeedModal: React.FC<FeedModalProps> = ({ isOpen, onClose, section, isAdmin
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(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<FeedModalProps> = ({ 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]);
|
||||
|
||||
@@ -255,11 +255,13 @@ const SupportChatModal: React.FC<SupportChatModalProps> = ({ 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 (
|
||||
<div
|
||||
|
||||
@@ -148,6 +148,9 @@ const TeacherMenuModal: React.FC<TeacherMenuModalProps> = ({
|
||||
setSelectedLetter(null);
|
||||
setSelectedRule(null);
|
||||
setSelectedCheatSheet(null);
|
||||
// 🔧 ФИКС (23.09.2026): teacher_menu_tracked_once — сбрасываем ref,
|
||||
// чтобы при следующем открытии меню снова трекалось.
|
||||
menuTrackedRef.current = false;
|
||||
onClose();
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user