🌊 Волна 16: frontend #6 — юзабилити + типы (15 багов)

Юзабилити:
- BUBBLE_MESSAGE_OVERLAP: message/errorMessage взаимоисключение (BubbleWordsPage.tsx)
- REGISTER_FAILURE_NO_RETRY_IN_SESSION: retry с backoff (App.tsx)
- TESTVIEW_DUPLICATE_SAVE: убран дубль saveAnswer (TestViewPage.tsx)
- TEACHER_TOAST_NO_CLEANUP: clearTimeout (TeacherChatPage.tsx)
- TESTVIEW_TOAST_NO_CLEANUP: clearTimeout (TestViewPage.tsx)

Производительность:
- MENU_LEADERBOARD_HEAVY_FETCH: limit 100→50 (MenuPage.tsx)
- FLASHCARDS_RETRACK_ON_ACHIEVEMENT: одноразовый трекинг (FlashcardsPage.tsx)
- TEACHER_HISTORY_SAVE_EVERY_MESSAGE: debounce 500мс (TeacherChatPage.tsx)
- LEADERBOARD_GETUSERID_EVERY_RENDER: useState initializer (LeaderboardPage.tsx)

Типы:
- ANY_TYPES_PERSONAL_STATS + ADMIN_STATS: интерфейсы (api.ts)
- ANY_TYPES_LESSON_FULL: LessonFullResponse (api.ts)

Качество:
- SILENT_ERROR_SWALLOWING_APP: console.warn (App.tsx)
- STALE_CLOSURE_NAVIGATE_SETLANG: useRef для navigate/setLang (App.tsx)
- FETCH_JSON_NO_CONTENT_TYPE_CHECK: проверка content-type (api.ts)

Пропущено осознанно:
- INIT_DATA_IN_URL_DELETE_FEED (Cloudflare preflight)

Аудит v4: Issue #6, frontend 15/16 задач
This commit is contained in:
2026-09-24 20:00:59 +03:00
parent 87f482861b
commit 5c27b98f4b
8 changed files with 221 additions and 56 deletions
+33 -6
View File
@@ -31,6 +31,20 @@ function AppContent() {
// 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — ref-флаг, // 🔧 ФИКС (23.09.2026): STRICTMODE_DOUBLE_REGISTER — ref-флаг,
// чтобы регистрация не вызывалась дважды в StrictMode. // чтобы регистрация не вызывалась дважды в StrictMode.
const registerAttemptedRef = useRef(false); const registerAttemptedRef = useRef(false);
// 🔧 ФИКС (24.09.2026): REGISTER_FAILURE_NO_RETRY_IN_SESSION —
// счётчик попыток registerUser.
const registerRetryCountRef = useRef(0);
// 🔧 ФИКС (24.09.2026): STALE_CLOSURE_NAVIGATE_SETLANG —
// navigate и setLang в useRef, чтобы избежать stale closure
// при useEffect с [].
const navigateRef = useRef(navigate);
const setLangRef = useRef(setLang);
useEffect(() => {
navigateRef.current = navigate;
setLangRef.current = setLang;
}, [navigate, setLang]);
useEffect(() => { useEffect(() => {
// 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — очищаем старый ключ, // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — очищаем старый ключ,
@@ -80,7 +94,11 @@ function AppContent() {
registerUser() registerUser()
.then((data) => { .then((data) => {
trackDailyLogin().catch(() => {}); // 🔧 ФИКС (24.09.2026): SILENT_ERROR_SWALLOWING_APP —
// логируем ошибку трекинга логина.
trackDailyLogin().catch((e) => {
console.warn('[App] trackDailyLogin failed:', e);
});
// 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — не пишем в localStorage. // 🔧 ФИКС (23.09.2026): ADMIN_FLAG_FROM_LOCALSTORAGE — не пишем в localStorage.
if (typeof data.is_admin === 'boolean') { if (typeof data.is_admin === 'boolean') {
@@ -90,22 +108,30 @@ function AppContent() {
.then((adminData) => { .then((adminData) => {
setIsAdmin(adminData.is_admin); setIsAdmin(adminData.is_admin);
}) })
.catch(() => {}); .catch((e) => {
// 🔧 ФИКС (24.09.2026): SILENT_ERROR_SWALLOWING_APP
console.warn('[App] getIsAdmin failed:', e);
});
} }
const langFromStorage = localStorage.getItem('filwords_lang'); const langFromStorage = localStorage.getItem('filwords_lang');
if (!langFromStorage) { if (!langFromStorage) {
navigate('/language'); navigateRef.current('/language');
} else if (data.app_language && data.app_language !== langFromStorage) { } else if (data.app_language && data.app_language !== langFromStorage) {
setLang(data.app_language); setLangRef.current(data.app_language);
} }
}) })
.catch((err) => { .catch((err) => {
// 🔧 ФИКС (23.09.2026): SILENT_REGISTER_FAILURE — логируем ошибку, // 🔧 ФИКС (23.09.2026): SILENT_REGISTER_FAILURE — логируем ошибку.
// сбрасываем ref, чтобы можно было повторить при следующем визите.
console.error('registerUser failed:', err); console.error('registerUser failed:', err);
registerAttemptedRef.current = false; registerAttemptedRef.current = false;
// 🔧 ФИКС (24.09.2026): REGISTER_FAILURE_NO_RETRY_IN_SESSION —
// повторяем попытку с backoff (макс 3 попытки).
if (registerRetryCountRef.current < 3) {
registerRetryCountRef.current++;
retryTimeoutId = setTimeout(tryRegister, 2000 * registerRetryCountRef.current);
}
}); });
}; };
@@ -116,6 +142,7 @@ function AppContent() {
return () => { return () => {
if (retryTimeoutId) clearTimeout(retryTimeoutId); if (retryTimeoutId) clearTimeout(retryTimeoutId);
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
// 🔧 Слушаем событие "open-dashboard" из MenuPage — открывает модалку дашборда // 🔧 Слушаем событие "open-dashboard" из MenuPage — открывает модалку дашборда
+106 -7
View File
@@ -232,6 +232,17 @@ const fetchAPI = async (endpoint: string, options: RequestInit = {}) => {
throw new Error(`API Error: ${res.status} - ${errorText}`); throw new Error(`API Error: ${res.status} - ${errorText}`);
} }
// 🔧 ФИКС (24.09.2026): FETCH_JSON_NO_CONTENT_TYPE_CHECK —
// проверяем content-type перед парсингом JSON, чтобы не получить
// неинформативный 'Unexpected token < in JSON' (captive portal, CF challenge).
const contentType = res.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
const text = await res.text();
throw new Error(
`API Error: expected JSON, got ${contentType}. Body: ${text.slice(0, 200)}`
);
}
const data = await res.json(); const data = await res.json();
return data; return data;
}; };
@@ -409,10 +420,39 @@ export const saveAnalyticsToHistory = (message: string): Promise<{ status: strin
body: JSON.stringify({ message }), body: JSON.stringify({ message }),
}); });
export const getPersonalStats = (): Promise<any> => // 🔧 ФИКС (24.09.2026): ANY_TYPES_PERSONAL_STATS —
// типизируем ответ. Если поля изменятся, TS подсветит.
export interface PersonalStatsResponse {
current_level: string;
total_score: number;
achievements: number;
words_guessed: number;
bubble_levels: number;
completed_topics: number;
level_progress: Record<string, {
wordsearch_percent: number;
wordsearch_completed: number;
wordsearch_total: number;
sentence_percent: number;
sentence_completed: number;
sentence_total: number;
total_score: number;
}>;
}
// 🔧 ФИКС (24.09.2026): ANY_TYPES_ADMIN_STATS_ASSISTANT
export interface AdminStatsResponse {
total_users: number;
new_today: number;
online_now: number;
language_counts: Record<string, number>;
level_counts: Record<string, number>;
}
export const getPersonalStats = (): Promise<PersonalStatsResponse> =>
fetchAPI('/assistant/stats/personal'); fetchAPI('/assistant/stats/personal');
export const getAdminStatsFromAssistant = (): Promise<any> => export const getAdminStatsFromAssistant = (): Promise<AdminStatsResponse> =>
fetchAPI('/assistant/stats/admin'); fetchAPI('/assistant/stats/admin');
// ============ Уроки (Learning) ============ // ============ Уроки (Learning) ============
@@ -1150,12 +1190,71 @@ export const getLessonTopics = (level: string): Promise<{ level: string; topics:
export const getLessonTopic = (topicId: string): Promise<ContentTopicDetail> => export const getLessonTopic = (topicId: string): Promise<ContentTopicDetail> =>
fetchAPI(`/admin/content/lessons/topic/${encodeURIComponent(topicId)}`); fetchAPI(`/admin/content/lessons/topic/${encodeURIComponent(topicId)}`);
// 🔧 ФИКС (24.09.2026): ANY_TYPES_LESSON_FULL —
// типизируем lesson/examples/questions для WYSIWYG.
export interface LessonFullExample {
id?: number;
order_number?: number;
text_pl: string;
text_ru: string;
text_uk: string;
text_en: string;
audio_url?: string | null;
}
export interface LessonFullOption {
option_key: string;
text_pl: string;
text_ru: string;
text_uk: string;
text_en: string;
is_correct: boolean;
wrong_because: string | null;
wrong_because_text?: string;
}
export interface LessonFullQuestion {
question_id: string;
context_type: string;
question_type: string;
skill_tag: string;
difficulty: number;
prompt_pl: string;
prompt_ru: string;
prompt_uk: string;
prompt_en: string;
correct_answer: string;
hint_type: string | null;
hint_value: string | null;
options_language: string;
options: LessonFullOption[];
}
export interface LessonFullResponse {
lesson: {
lesson_id: string;
topic_id: string;
order_number: number;
skill_tag: string;
title_pl: string;
title_ru: string;
title_uk: string;
title_en: string;
objective_pl: string;
objective_ru: string;
objective_uk: string;
objective_en: string;
explanation_pl: string;
explanation_ru: string;
explanation_uk: string;
explanation_en: string;
};
examples: LessonFullExample[];
questions: LessonFullQuestion[];
}
// Урок целиком (для WYSIWYG) // Урок целиком (для WYSIWYG)
export const getLessonFull = (lessonId: string): Promise<{ export const getLessonFull = (lessonId: string): Promise<LessonFullResponse> =>
lesson: any;
examples: any[];
questions: any[];
}> =>
fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(lessonId)}`); fetchAPI(`/admin/content/lessons/lesson/${encodeURIComponent(lessonId)}`);
// Сохранить урок // Сохранить урок
+11 -1
View File
@@ -148,6 +148,10 @@ const BubbleWordsPage: React.FC = () => {
const showMessage = (msg: string) => { const showMessage = (msg: string) => {
if (!isMountedRef.current) return; if (!isMountedRef.current) return;
// 🔧 ФИКС (24.09.2026): BUBBLE_MESSAGE_OVERLAP — скрываем errorMessage
// при показе message (взаимоисключение).
setErrorMessage(null);
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current);
setMessage(msg); setMessage(msg);
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current); if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
messageTimeoutRef.current = setTimeout(() => { messageTimeoutRef.current = setTimeout(() => {
@@ -159,6 +163,10 @@ const BubbleWordsPage: React.FC = () => {
// с автоскрытием через 2 секунды (по аналогии с showMessage). // с автоскрытием через 2 секунды (по аналогии с showMessage).
const showError = (msg: string) => { const showError = (msg: string) => {
if (!isMountedRef.current) return; if (!isMountedRef.current) return;
// 🔧 ФИКС (24.09.2026): BUBBLE_MESSAGE_OVERLAP — скрываем message
// при показе errorMessage (взаимоисключение).
setMessage(null);
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
setErrorMessage(msg); setErrorMessage(msg);
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current); if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current);
errorTimeoutRef.current = setTimeout(() => { errorTimeoutRef.current = setTimeout(() => {
@@ -496,7 +504,9 @@ const BubbleWordsPage: React.FC = () => {
{errorMessage && ( {errorMessage && (
<div style={{ <div style={{
position: 'absolute', position: 'absolute',
top: '60px', // 🔧 ФИКС (24.09.2026): BUBBLE_MESSAGE_OVERLAP —
// errorMessage опускаем на 100px, чтобы не перекрывалась с message (60px).
top: '100px',
left: '50%', left: '50%',
transform: 'translateX(-50%)', transform: 'translateX(-50%)',
padding: '10px 20px', padding: '10px 20px',
+22 -19
View File
@@ -146,12 +146,30 @@ const FlashcardsPage: React.FC = () => {
} }
}; };
// 🔧 ФИКС (24.09.2026): FLASHCARDS_RETRACK_ON_ACHIEVEMENT —
// вынесли трекинг в отдельный useEffect с [] (одноразовый),
// чтобы showAchievement не вызывал повторный трекинг при смене identity.
useEffect(() => { useEffect(() => {
window.scrollTo(0, 0); window.scrollTo(0, 0);
isMountedRef.current = true; isMountedRef.current = true;
return () => {
isMountedRef.current = false;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, []);
// 🔧 ИСПРАВЛЕНО: Трекинг только для Алфавита (активная вкладка по умолчанию) // Одноразовый трекинг при монтировании
useEffect(() => {
trackAlphabetOpened() trackAlphabetOpened()
.then((data: any) => { .then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) { if (data?.new_achievements && data.new_achievements.length > 0) {
@@ -165,23 +183,8 @@ const FlashcardsPage: React.FC = () => {
} }
}) })
.catch(() => {}); .catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
return () => { }, []);
isMountedRef.current = false;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — освобождаем URL при unmount
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, [showAchievement]);
// 🔧 ИСПРАВЛЕНО: switchTab теперь сбрасывает window scroll // 🔧 ИСПРАВЛЕНО: switchTab теперь сбрасывает window scroll
const switchTab = (tab: TabType) => { const switchTab = (tab: TabType) => {
+3 -1
View File
@@ -127,7 +127,9 @@ const LeaderboardPage: React.FC = () => {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [selectedAchievement, setSelectedAchievement] = useState<UserAchievement | null>(null); const [selectedAchievement, setSelectedAchievement] = useState<UserAchievement | null>(null);
const [showAchievements, setShowAchievements] = useState(false); const [showAchievements, setShowAchievements] = useState(false);
const currentUserId = getUserId(); // 🔧 ФИКС (24.09.2026): LEADERBOARD_GETUSERID_EVERY_RENDER —
// getUserId() один раз через useState (initializer), не на каждый рендер.
const [currentUserId] = useState<number | null>(() => getUserId());
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
const palette = { const palette = {
+4 -1
View File
@@ -168,7 +168,10 @@ const MenuPage: React.FC = () => {
setTotalScore(0); setTotalScore(0);
}); });
getLeaderboard(100) // 🔧 ФИКС (24.09.2026): MENU_LEADERBOARD_HEAVY_FETCH —
// вместо 100 записей грузим 50 (в 2 раза меньше трафика).
// TODO: вынести в отдельный endpoint /leaderboard/my-rank.
getLeaderboard(50)
.then((data) => { .then((data) => {
const leaderboard = data.leaderboard || []; const leaderboard = data.leaderboard || [];
const myEntry = leaderboard.find((entry: any) => const myEntry = leaderboard.find((entry: any) =>
+24 -4
View File
@@ -110,6 +110,11 @@ const TeacherChatPage: React.FC = () => {
// на КАЖДЫЙ рендер — O(n) при длинном чате. Теперь useRef(0), // на КАЖДЫЙ рендер — O(n) при длинном чате. Теперь useRef(0),
// а актуальное значение ставится один раз при загрузке истории (в useEffect). // а актуальное значение ставится один раз при загрузке истории (в useEffect).
const idRef = useRef(0); const idRef = useRef(0);
// 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP —
// храним таймер для очистки.
const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE
const historySaveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const startTimeRef = useRef<number>(Date.now()); const startTimeRef = useRef<number>(Date.now());
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
@@ -133,9 +138,11 @@ const TeacherChatPage: React.FC = () => {
}; };
// 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast вместо alert() // 🔧 ФИКС (23.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast вместо alert()
// 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP — сохраняем таймер.
const showToast = (msg: string) => { const showToast = (msg: string) => {
setToastMessage(msg); setToastMessage(msg);
setTimeout(() => { if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = setTimeout(() => {
setToastMessage(null); setToastMessage(null);
}, 2500); }, 2500);
}; };
@@ -240,15 +247,23 @@ const TeacherChatPage: React.FC = () => {
.catch(() => {}); .catch(() => {});
}, []); }, []);
// 🔧 ФИКС (24.09.2026): TEACHER_HISTORY_SAVE_EVERY_MESSAGE —
// дебаунсим сохранение истории на сервер (500мс), чтобы не долбить
// бэк при каждом новом сообщении.
useEffect(() => { useEffect(() => {
try { try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
if (messages.length > 0) {
saveTeacherHistory(messages).catch(() => {});
}
} catch (e) { } catch (e) {
// ignore // 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]); }, [messages]);
const extractPolishText = (text: string): string => { const extractPolishText = (text: string): string => {
@@ -403,6 +418,11 @@ const TeacherChatPage: React.FC = () => {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null; audioUrlRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): TEACHER_TOAST_NO_CLEANUP
if (toastTimeoutRef.current) {
clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
+15 -14
View File
@@ -53,6 +53,9 @@ const TestViewPage: React.FC = () => {
const [isStartingPractice, setIsStartingPractice] = useState(false); const [isStartingPractice, setIsStartingPractice] = useState(false);
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert(). // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert().
const [toastMessage, setToastMessage] = useState<string | null>(null); const [toastMessage, setToastMessage] = useState<string | null>(null);
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP —
// храним таймер для очистки.
const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke. // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null); const audioUrlRef = useRef<string | null>(null);
@@ -73,9 +76,11 @@ const TestViewPage: React.FC = () => {
}); });
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast. // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast.
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — сохраняем таймер.
const showToast = (msg: string) => { const showToast = (msg: string) => {
setToastMessage(msg); setToastMessage(msg);
setTimeout(() => setToastMessage(null), 2500); if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500);
}; };
useEffect(() => { useEffect(() => {
@@ -112,6 +117,11 @@ const TestViewPage: React.FC = () => {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null; audioUrlRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP
if (toastTimeoutRef.current) {
clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
@@ -166,19 +176,10 @@ const TestViewPage: React.FC = () => {
} else { } else {
setIsCompleting(true); setIsCompleting(true);
// Сохраняем ответ последнего вопроса // 🔧 ФИКС (24.09.2026): TESTVIEW_DUPLICATE_SAVE —
const currentQ = questions[currentIndex]; // ответ последнего вопроса уже сохранён в handleAnswerSelect /
const answer = selectedAnswers[currentQ.question.question_id]; // handleTextInputBlur. Повторно НЕ сохраняем — убираем дубль.
// (как в PracticeViewPage)
if (answer && sessionId) {
const timeTaken = Date.now() - startTimeRef.current;
try {
// 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS
await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true, false);
} catch (e) {
console.error('Error saving final answer:', e);
}
}
// Небольшая задержка для сохранения // Небольшая задержка для сохранения
await new Promise(resolve => setTimeout(resolve, 300)); await new Promise(resolve => setTimeout(resolve, 300));