nakama/frontend/src/App.jsx

167 lines
4.9 KiB
React
Raw Normal View History

2025-11-04 22:31:04 +00:00
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
2025-11-10 20:13:22 +00:00
import { initTelegramApp } from './utils/telegram'
2025-11-10 21:56:36 +00:00
import { signInWithTelegram, verifyAuth } from './utils/api'
2025-11-03 20:35:01 +00:00
import { initTheme } from './utils/theme'
import Layout from './components/Layout'
import Feed from './pages/Feed'
import Search from './pages/Search'
import Notifications from './pages/Notifications'
import Profile from './pages/Profile'
import UserProfile from './pages/UserProfile'
2025-11-03 22:51:17 +00:00
import CommentsPage from './pages/CommentsPage'
import PostMenuPage from './pages/PostMenuPage'
2025-11-03 20:35:01 +00:00
import './styles/index.css'
2025-11-04 22:31:04 +00:00
function AppContent() {
2025-11-03 20:35:01 +00:00
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
2025-11-04 22:31:04 +00:00
const navigate = useNavigate()
const startParamProcessed = useRef(false) // Флаг для обработки startParam только один раз
2025-11-04 22:41:35 +00:00
const initAppCalled = useRef(false) // Флаг чтобы initApp вызывался только один раз
2025-11-03 20:35:01 +00:00
useEffect(() => {
initTheme()
2025-11-10 21:56:36 +00:00
2025-11-04 22:41:35 +00:00
if (!initAppCalled.current) {
initAppCalled.current = true
initApp()
}
2025-11-03 20:35:01 +00:00
}, [])
2025-11-10 21:56:36 +00:00
const waitForInitData = async () => {
const start = Date.now()
const timeout = 5000
while (Date.now() - start < timeout) {
const tg = window.Telegram?.WebApp
if (tg?.initData && tg.initData.length > 0) {
return tg
}
await new Promise(resolve => setTimeout(resolve, 100))
}
throw new Error('Telegram не передал initData. Откройте приложение в официальном клиенте.')
}
2025-11-03 20:35:01 +00:00
const initApp = async () => {
try {
initTelegramApp()
2025-11-10 21:56:36 +00:00
const tg = await waitForInitData()
tg.disableVerticalSwipes?.()
tg.ready?.()
tg.expand?.()
const userData = await signInWithTelegram(tg.initData)
setUser(userData)
setError(null)
if (!startParamProcessed.current && tg?.startParam?.startsWith('post_')) {
startParamProcessed.current = true
const postId = tg.startParam.replace('post_', '')
setTimeout(() => {
navigate(`/feed?post=${postId}`, { replace: true })
}, 200)
2025-11-04 22:41:35 +00:00
}
2025-11-03 20:35:01 +00:00
} catch (err) {
console.error('Ошибка инициализации:', err)
2025-11-10 21:56:36 +00:00
try {
// Попытаться восстановить сессию по токенам
const userData = await verifyAuth()
setUser(userData)
setError(null)
} catch (verifyError) {
console.error('Не удалось восстановить сессию:', verifyError)
setError(err?.response?.data?.error || err.message || 'Ошибка авторизации')
}
} finally {
2025-11-03 20:35:01 +00:00
setLoading(false)
}
}
if (loading) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
flexDirection: 'column',
gap: '16px'
}}>
<div className="spinner" />
<p style={{ color: 'var(--text-secondary)' }}>Загрузка...</p>
</div>
)
}
if (error) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
flexDirection: 'column',
gap: '16px',
padding: '20px'
}}>
<p style={{ color: 'var(--text-primary)', textAlign: 'center' }}>
Ошибка загрузки приложения
</p>
<p style={{ color: 'var(--text-secondary)', textAlign: 'center' }}>
{error}
</p>
2025-11-04 21:51:05 +00:00
<button
2025-11-10 21:56:36 +00:00
onClick={() => window.location.reload()}
2025-11-04 21:51:05 +00:00
style={{
padding: '12px 24px',
borderRadius: '12px',
background: 'var(--button-accent)',
color: 'white',
border: 'none',
cursor: 'pointer',
fontSize: '16px'
}}
>
Попробовать снова
</button>
2025-11-03 20:35:01 +00:00
</div>
)
}
2025-11-04 21:51:05 +00:00
if (!user) {
return null
}
2025-11-04 22:31:04 +00:00
return (
<Routes>
<Route path="/" element={<Layout user={user} />}>
<Route index element={<Navigate to="/feed" replace />} />
<Route path="feed" element={<Feed user={user} />} />
<Route path="search" element={<Search user={user} />} />
<Route path="notifications" element={<Notifications user={user} />} />
<Route path="profile" element={<Profile user={user} setUser={setUser} />} />
<Route path="user/:id" element={<UserProfile currentUser={user} />} />
<Route path="post/:postId/comments" element={<CommentsPage user={user} />} />
<Route path="post/:postId/menu" element={<PostMenuPage user={user} />} />
</Route>
</Routes>
)
}
function App() {
2025-11-03 20:35:01 +00:00
return (
<BrowserRouter>
2025-11-04 22:31:04 +00:00
<AppContent />
2025-11-03 20:35:01 +00:00
</BrowserRouter>
)
}
export default App