feat(settings): страница настроек + глобальный haptic + toggle вибрации

This commit is contained in:
2026-10-01 12:40:52 +03:00
parent 3854779619
commit 696967d88e
5 changed files with 361 additions and 0 deletions
+5
View File
@@ -20,6 +20,8 @@ import TypingPage from './pages/TypingPage';
import AdminDashboardModal from './components/AdminDashboardModal'; import AdminDashboardModal from './components/AdminDashboardModal';
import LearningPage from './pages/LearningPage'; import LearningPage from './pages/LearningPage';
import LecturesPage from './pages/LecturesPage'; import LecturesPage from './pages/LecturesPage';
import SettingsPage from './pages/SettingsPage';
import { useGlobalHaptic } from './hooks/useGlobalHaptic';
// 🔧 ФИКС (25.09.2026): DEAD_CODE_GET_IS_ADMIN_FALLBACK — // 🔧 ФИКС (25.09.2026): DEAD_CODE_GET_IS_ADMIN_FALLBACK —
// getIsAdmin больше не нужен: registerUser гарантирует is_admin: boolean. // getIsAdmin больше не нужен: registerUser гарантирует is_admin: boolean.
import { registerUser, trackDailyLogin } from './api'; import { registerUser, trackDailyLogin } from './api';
@@ -27,6 +29,8 @@ import { getUserId } from './telegram';
function AppContent() { function AppContent() {
const navigate = useNavigate(); const navigate = useNavigate();
// 🔧 ФИКС (01.10.2026): глобальный haptic на всех кнопках
useGlobalHaptic();
const location = useLocation(); const location = useLocation();
const { setLang } = useLanguage(); const { setLang } = useLanguage();
const [showDashboard, setShowDashboard] = useState(false); const [showDashboard, setShowDashboard] = useState(false);
@@ -248,6 +252,7 @@ function AppContent() {
<Route path="/teacher" element={<TeacherChatPage />} /> <Route path="/teacher" element={<TeacherChatPage />} />
<Route path="/learning" element={<LearningPage />} /> <Route path="/learning" element={<LearningPage />} />
<Route path="/lectures" element={<LecturesPage />} /> <Route path="/lectures" element={<LecturesPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Routes> </Routes>
{/* Дашборд админа — открывается через событие "open-dashboard" из MenuPage */} {/* Дашборд админа — открывается через событие "open-dashboard" из MenuPage */}
+65
View File
@@ -0,0 +1,65 @@
/**
* Haptic — глобальная утилита для тактильного отклика.
*
* Использует Telegram.WebApp.HapticFeedback.
* Проверяет настройку filwords_haptics (localStorage).
* - '0' → выключено
* - отсутствует / '1' → включено (по умолчанию)
*/
const isEnabled = (): boolean => {
if (typeof window === 'undefined') return false;
try {
return localStorage.getItem('filwords_haptics') !== '0';
} catch {
return false;
}
};
// 🔧 ФИКС (01.10.2026): telegram_types_outdated —
// типы WebApp в проекте не знают HapticFeedback.selectionChanged,
// notificationOccurred, isVersionAtLeast. Кастуем к any.
const getHaptic = (): any => {
if (typeof window === 'undefined') return null;
return (window.Telegram as any)?.WebApp?.HapticFeedback || null;
};
export const haptic = {
light: () => {
if (!isEnabled()) return;
getHaptic()?.impactOccurred('light');
},
medium: () => {
if (!isEnabled()) return;
getHaptic()?.impactOccurred('medium');
},
heavy: () => {
if (!isEnabled()) return;
getHaptic()?.impactOccurred('heavy');
},
selection: () => {
if (!isEnabled()) return;
getHaptic()?.selectionChanged();
},
success: () => {
if (!isEnabled()) return;
getHaptic()?.notificationOccurred('success');
},
warning: () => {
if (!isEnabled()) return;
getHaptic()?.notificationOccurred('warning');
},
error: () => {
if (!isEnabled()) return;
getHaptic()?.notificationOccurred('error');
},
/** Проверка, включена ли вибрация сейчас */
isEnabled,
/** Проверка, поддерживается ли Haptic в этом Telegram */
isSupported: () => {
if (typeof window === 'undefined') return false;
return !!(window.Telegram as any)?.WebApp?.isVersionAtLeast?.('6.1');
},
};
+35
View File
@@ -0,0 +1,35 @@
import { useEffect } from 'react';
import { haptic } from '../haptic';
/**
* useGlobalHaptic — глобальный перехват touchstart на кнопках.
*
* Работает на всех страницах автоматически.
* Добавляет лёгкую вибрацию на любой <button>, <a>, [role="button"],
* если у элемента нет атрибута data-no-haptic="true".
*
* Особые события (success/error/selection) — точечно в играх.
*/
export const useGlobalHaptic = () => {
useEffect(() => {
const handleTouch = (e: TouchEvent) => {
const target = e.target as HTMLElement;
if (!target) return;
// Ищем ближайший интерактивный элемент
const interactive = target.closest(
'button, a, [role="button"], [data-haptic]',
) as HTMLElement | null;
if (!interactive) return;
// Если явно отключено — не вибрируем
if (interactive.getAttribute('data-no-haptic') === 'true') return;
haptic.light();
};
document.addEventListener('touchstart', handleTouch, { passive: true });
return () => document.removeEventListener('touchstart', handleTouch);
}, []);
};
+9
View File
@@ -60,6 +60,7 @@ const MenuPage: React.FC = () => {
leaderboard: '#E8B93F', leaderboard: '#E8B93F',
teacher: '#8B5CF6', teacher: '#8B5CF6',
support: '#FF6B6B', support: '#FF6B6B',
settings: '#6B7280', // 🔧 НОВОЕ (01.10.2026): серый для настроек
dashboard: '#E8B93F', dashboard: '#E8B93F',
}; };
@@ -890,6 +891,14 @@ const MenuPage: React.FC = () => {
)} )}
</button> </button>
{/* 🔧 НОВОЕ (01.10.2026): Кнопка Настройки — между Поддержкой и Дашбордом */}
<button
onClick={() => navigate('/settings')}
style={getButtonStyle('settings')}
>
<span>⚙️</span> {t('settings')}
</button>
{/* Кнопка Дашборд — только для админов */} {/* Кнопка Дашборд — только для админов */}
{isAdmin && ( {isAdmin && (
<button {...dashboardHandlers} style={getButtonStyle('dashboard')}> <button {...dashboardHandlers} style={getButtonStyle('dashboard')}>
+247
View File
@@ -0,0 +1,247 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { haptic } from '../haptic';
/**
* SettingsPage — настройки приложения.
* Пока: вибрация. Потом: звук, тема, о приложении.
*/
const SettingsPage: React.FC = () => {
const navigate = useNavigate();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { language } = useLanguage();
// 🔧 ФИКС (01.10.2026): hapticSetting — читаем из localStorage.
// '0' = выключено, всё остальное (включая отсутствие) = включено.
const [hapticsEnabled, setHapticsEnabled] = useState<boolean>(() => {
if (typeof window === 'undefined') return true;
try {
return localStorage.getItem('filwords_haptics') !== '0';
} catch {
return true;
}
});
const brandColor = '#2ECC71';
const buttonGradient = 'linear-gradient(135deg, #7A3AFF 0%, #A86BFF 100%)';
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const bgColor = '#F4F5F7';
const cardBg = 'rgba(255,255,255,0.55)';
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: cardBg,
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
border: '1px solid rgba(255,255,255,0.7)',
boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)',
...extra,
});
const toggleHaptics = () => {
const newValue = !hapticsEnabled;
setHapticsEnabled(newValue);
try {
localStorage.setItem('filwords_haptics', newValue ? '1' : '0');
} catch {}
// Вибрируем при включении (обратная связь)
if (newValue) {
// haptic.light() уже проверяет настройку — будет вибрировать,
// потому что localStorage уже обновлён
setTimeout(() => haptic.light(), 50);
}
};
// Локализация
const labels = {
title: {
pl: '⚙️ Ustawienia',
ru: '⚙️ Настройки',
uk: '⚙️ Налаштування',
en: '⚙️ Settings',
},
haptics: {
pl: 'Wibracje',
ru: 'Вибрация',
uk: 'Вібрація',
en: 'Vibration',
},
hapticsDesc: {
pl: 'Dotykowy odzew przy kliknięciach i grze',
ru: 'Тактильный отклик при кликах и в игре',
uk: 'Тактильний відгук при кліках та у грі',
en: 'Haptic feedback on clicks and in games',
},
enabled: {
pl: 'Włączone',
ru: 'Включено',
uk: 'Увімкнено',
en: 'Enabled',
},
disabled: {
pl: 'Wyłączone',
ru: 'Выключено',
uk: 'Вимкнено',
en: 'Disabled',
},
about: {
pl: 'O aplikacji',
ru: 'О приложении',
uk: 'Про додаток',
en: 'About',
},
version: {
pl: 'Wersja',
ru: 'Версия',
uk: 'Версія',
en: 'Version',
},
back: {
pl: '← Wstecz',
ru: '← Назад',
uk: '← Назад',
en: '← Back',
},
};
const tr = (key: keyof typeof labels) => labels[key][language as keyof typeof labels[typeof key]] || labels[key].en;
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '16px',
position: 'relative',
overflow: 'hidden',
}}>
{/* Фоновое свечение */}
<div style={{
position: 'fixed', top: '-80px', left: '-60px',
width: '260px', height: '260px', borderRadius: '50%',
background: '#7A3AFF', opacity: 0.2, filter: 'blur(90px)',
pointerEvents: 'none', zIndex: 0,
}} />
<div style={{ position: 'relative', zIndex: 1, maxWidth: '600px', margin: '0 auto' }}>
{/* Шапка */}
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
marginBottom: '20px',
}}>
<button
onClick={() => navigate('/menu')}
style={{
padding: '10px 16px',
borderRadius: radius.md,
border: 'none',
background: buttonGradient,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: '0 4px 14px rgba(122, 58, 255, 0.4)',
}}
>
{tr('back')}
</button>
</div>
{/* Заголовок */}
<h1 style={{
fontSize: '28px', fontWeight: 800, margin: 0,
marginBottom: '20px', color: textColor,
}}>
{tr('title')}
</h1>
{/* Карточка вибрации */}
<div style={{
...glass({ padding: '16px', borderRadius: radius.lg }),
marginBottom: '12px',
}}>
<div
onClick={toggleHaptics}
style={{
display: 'flex', alignItems: 'center', gap: '16px',
cursor: 'pointer',
}}
>
<div style={{ fontSize: '32px' }}>📳</div>
<div style={{ flex: 1 }}>
<div style={{
fontSize: '16px', fontWeight: 700, color: textColor,
marginBottom: '4px',
}}>
{tr('haptics')}
</div>
<div style={{ fontSize: '12px', color: subColor }}>
{tr('hapticsDesc')}
</div>
</div>
{/* Toggle switch */}
<div style={{
width: '52px',
height: '30px',
borderRadius: '15px',
background: hapticsEnabled ? brandColor : '#D1D5DB',
position: 'relative',
transition: 'background 0.2s ease',
flexShrink: 0,
}}>
<div style={{
position: 'absolute',
top: '3px',
left: hapticsEnabled ? '25px' : '3px',
width: '24px',
height: '24px',
borderRadius: '50%',
background: '#FFFFFF',
boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
transition: 'left 0.2s ease',
}} />
</div>
</div>
<div style={{
marginTop: '10px',
fontSize: '12px',
color: hapticsEnabled ? brandColor : subColor,
fontWeight: 600,
}}>
{hapticsEnabled ? '✓ ' + tr('enabled') : '✕ ' + tr('disabled')}
</div>
</div>
{/* О приложении */}
<div style={{
...glass({ padding: '16px', borderRadius: radius.lg }),
marginBottom: '12px',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
<div style={{ fontSize: '32px' }}>ℹ️</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: '16px', fontWeight: 700, color: textColor, marginBottom: '4px' }}>
{tr('about')}
</div>
<div style={{ fontSize: '12px', color: subColor }}>
Filwords PL · {tr('version')} 3.8.0
</div>
</div>
</div>
</div>
<div style={{ textAlign: 'center', marginTop: '24px', color: '#9CA3AF', fontSize: '12px' }}>
Filwords PL © 2026
</div>
</div>
</div>
);
};
export default SettingsPage;