🌊 Волна 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:
+44
-14
@@ -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 { BrowserRouter, Routes, Route, useNavigate, useLocation } from 'react-router-dom';
|
||||||
import { LanguageProvider, useLanguage } from './i18n/LanguageContext';
|
import { LanguageProvider, useLanguage } from './i18n/LanguageContext';
|
||||||
import LanguageSelectPage from './pages/LanguageSelectPage';
|
import LanguageSelectPage from './pages/LanguageSelectPage';
|
||||||
@@ -26,12 +26,17 @@ function AppContent() {
|
|||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { setLang } = useLanguage();
|
const { setLang } = useLanguage();
|
||||||
const [showDashboard, setShowDashboard] = useState(false);
|
const [showDashboard, setShowDashboard] = useState(false);
|
||||||
const [isAdmin, setIsAdmin] = useState(() => {
|
// 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — isAdmin только из сервера.
|
||||||
// Начальное значение из localStorage, чтобы не мигало при загрузке
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
return localStorage.getItem('filwords_is_admin') === '1';
|
// 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — ref-флаг,
|
||||||
});
|
// чтобы регистрация не вызывалась дважды в StrictMode.
|
||||||
|
const registerAttemptedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — очищаем старый ключ,
|
||||||
|
// который мог быть подделан в предыдущих версиях.
|
||||||
|
localStorage.removeItem('filwords_is_admin');
|
||||||
|
|
||||||
const tg = window.Telegram?.WebApp;
|
const tg = window.Telegram?.WebApp;
|
||||||
if (tg) {
|
if (tg) {
|
||||||
tg.ready();
|
tg.ready();
|
||||||
@@ -42,22 +47,42 @@ function AppContent() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🔧 ФИКС (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();
|
const userId = getUserId();
|
||||||
if (userId) {
|
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()
|
registerUser()
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
trackDailyLogin().catch(() => {});
|
trackDailyLogin().catch(() => {});
|
||||||
|
|
||||||
// 🔧 ИСПРАВЛЕНО: получаем is_admin с бэка, а не из хардкода
|
// 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — не пишем в localStorage.
|
||||||
if (typeof data.is_admin === 'boolean') {
|
if (typeof data.is_admin === 'boolean') {
|
||||||
setIsAdmin(data.is_admin);
|
setIsAdmin(data.is_admin);
|
||||||
localStorage.setItem('filwords_is_admin', data.is_admin ? '1' : '0');
|
|
||||||
} else {
|
} else {
|
||||||
// Fallback: если бэк по какой-то причине не вернул флаг — спрашиваем отдельно
|
|
||||||
getIsAdmin()
|
getIsAdmin()
|
||||||
.then((adminData) => {
|
.then((adminData) => {
|
||||||
setIsAdmin(adminData.is_admin);
|
setIsAdmin(adminData.is_admin);
|
||||||
localStorage.setItem('filwords_is_admin', adminData.is_admin ? '1' : '0');
|
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -65,15 +90,20 @@ function AppContent() {
|
|||||||
const langFromStorage = localStorage.getItem('filwords_lang');
|
const langFromStorage = localStorage.getItem('filwords_lang');
|
||||||
|
|
||||||
if (!langFromStorage) {
|
if (!langFromStorage) {
|
||||||
// Первый визит — показываем выбор языка
|
|
||||||
navigate('/language');
|
navigate('/language');
|
||||||
} else if (data.app_language && data.app_language !== langFromStorage) {
|
} else if (data.app_language && data.app_language !== langFromStorage) {
|
||||||
// Синхронизируем язык с сервером
|
|
||||||
setLang(data.app_language);
|
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 — открывает модалку дашборда
|
// 🔧 Слушаем событие "open-dashboard" из MenuPage — открывает модалку дашборда
|
||||||
|
|||||||
+21
@@ -2,6 +2,11 @@ import { getInitData } from './telegram';
|
|||||||
|
|
||||||
const API_BASE = 'https://api.filwordspl.com';
|
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 fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
||||||
const initData = getInitData();
|
const initData = getInitData();
|
||||||
|
|
||||||
@@ -11,8 +16,14 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
|||||||
// Формат "tma <initData>" — стандарт Telegram Mini Apps.
|
// Формат "tma <initData>" — стандарт Telegram Mini Apps.
|
||||||
const url = `${API_BASE}${endpoint}`;
|
const url = `${API_BASE}${endpoint}`;
|
||||||
|
|
||||||
|
// 🔧 ФИКС (23.09.2026): FETCH_NO_TIMEOUT — AbortController с таймаутом.
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||||
|
|
||||||
|
try {
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
|
signal: controller.signal,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `tma ${initData}`,
|
'Authorization': `tma ${initData}`,
|
||||||
@@ -27,6 +38,9 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
|
|||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
return data;
|
return data;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ============ Пользователь ============
|
// ============ Пользователь ============
|
||||||
@@ -180,8 +194,13 @@ export const getTTS = (text: string, voice: string = 'female'): Promise<Blob> =>
|
|||||||
// Заодно: voice теперь кодируется через encodeURIComponent (TTS_VOICE_NOT_ENCODED).
|
// Заодно: voice теперь кодируется через encodeURIComponent (TTS_VOICE_NOT_ENCODED).
|
||||||
const url = `${API_BASE}/tts?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}`;
|
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, {
|
return fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
|
signal: controller.signal,
|
||||||
headers: {
|
headers: {
|
||||||
'Authorization': `tma ${initData}`,
|
'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}`);
|
throw new Error(`API Error: ${res.status} - ${errorText}`);
|
||||||
}
|
}
|
||||||
return res.blob();
|
return res.blob();
|
||||||
|
}).finally(() => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -114,6 +114,17 @@ const AdminDashboardModal: React.FC<AdminDashboardModalProps> = ({ isOpen, onClo
|
|||||||
}
|
}
|
||||||
}, [isOpen, loadData]);
|
}, [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 => {
|
const formatDate = (isoStr: string): string => {
|
||||||
try {
|
try {
|
||||||
const date = new Date(isoStr);
|
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 [error, setError] = useState<string | null>(null);
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
const isMountedRef = useRef(true);
|
const isMountedRef = useRef(true);
|
||||||
|
// 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change — счётчик запросов,
|
||||||
|
// чтобы старый ответ не перезаписал новый при быстрой смене секции.
|
||||||
|
const requestIdRef = useRef(0);
|
||||||
|
|
||||||
// 🔧 Шаг 6: состояния админ-режима
|
// 🔧 Шаг 6: состояния админ-режима
|
||||||
const [showComposer, setShowComposer] = useState(false);
|
const [showComposer, setShowComposer] = useState(false);
|
||||||
@@ -79,19 +82,23 @@ const FeedModal: React.FC<FeedModalProps> = ({ isOpen, onClose, section, isAdmin
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
|
// 🔧 ФИКС (23.09.2026): feed_modal_race_on_section_change
|
||||||
|
const currentRequestId = ++requestIdRef.current;
|
||||||
|
|
||||||
getFeedSection(section, language)
|
getFeedSection(section, language)
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (!isMountedRef.current) return;
|
// 🔧 Игнорируем устаревшие ответы
|
||||||
|
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
|
||||||
setPosts(data.posts || []);
|
setPosts(data.posts || []);
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
if (!isMountedRef.current) return;
|
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
|
||||||
console.error('Failed to load feed:', e);
|
console.error('Failed to load feed:', e);
|
||||||
setError('Failed to load feed');
|
setError('Failed to load feed');
|
||||||
setPosts([]);
|
setPosts([]);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (!isMountedRef.current) return;
|
if (!isMountedRef.current || currentRequestId !== requestIdRef.current) return;
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
});
|
});
|
||||||
}, [section, language]);
|
}, [section, language]);
|
||||||
|
|||||||
@@ -255,11 +255,13 @@ const SupportChatModal: React.FC<SupportChatModalProps> = ({ isOpen, onClose, is
|
|||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
// 🔧 ИСПРАВЛЕНО: определяем "от кого" сообщение через isAdmin проп, а не через хардкод
|
// 🔧 ФИКС (23.09.2026): support_userid_nan — раньше при userId=null
|
||||||
// Если я админ: мои сообщения — те, где sender_id === userId. Остальные — от пользователя.
|
// Number(null)=0 и сравнение давало неверный результат, все пузыри
|
||||||
// Если я пользователь: мои сообщения — те, где sender_id === userId. Остальные — от админа.
|
// рисовались как входящие. Теперь строковое сравнение + проверка null.
|
||||||
// В обоих случаях "свои" = sender_id === userId. Меняется только логика цвета.
|
const isMessageFromMe = (senderId: number) => {
|
||||||
const isMessageFromMe = (senderId: number) => senderId === Number(userId);
|
if (userId === null || userId === undefined) return false;
|
||||||
|
return String(senderId) === String(userId);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -148,6 +148,9 @@ const TeacherMenuModal: React.FC<TeacherMenuModalProps> = ({
|
|||||||
setSelectedLetter(null);
|
setSelectedLetter(null);
|
||||||
setSelectedRule(null);
|
setSelectedRule(null);
|
||||||
setSelectedCheatSheet(null);
|
setSelectedCheatSheet(null);
|
||||||
|
// 🔧 ФИКС (23.09.2026): teacher_menu_tracked_once — сбрасываем ref,
|
||||||
|
// чтобы при следующем открытии меню снова трекалось.
|
||||||
|
menuTrackedRef.current = false;
|
||||||
onClose();
|
onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user