import { createRoot } from 'react-dom/client' import { useCallback, useEffect, useRef, useState } from 'react' import { ConfigProvider, Layout, theme as antdTheme } from 'antd' import zhCN from 'antd/locale/zh_CN' import { ThemeProvider, useColorTheme } from './theme' import { LoginPanel } from './LoginPanel' import { DevicesPage } from './DevicesPage' import { HomePage } from './HomePage' import { api, RequestError, type Account } from './api' import 'antd/dist/reset.css' import './upstream.css' import './selfhost.css' export function navigate(path: string) { if (window.location.pathname !== path) window.history.pushState({}, '', path) window.dispatchEvent(new PopStateEvent('popstate')) } function App() { const { colorTheme } = useColorTheme() const dark = colorTheme === 'dark' const [account, setAccount] = useState() const [error, setError] = useState() const [path, setPath] = useState(() => window.location.pathname) // Keep route state and URL in sync without dispatching popstate: dispatching synchronously makes // React commit the route change separately, so an auth transition can render an intermediate // unauthenticated route and the guard below bounces /app/remote back to /app/login. const justLoggedIn = useRef(false) const go = useCallback((next: string) => { if (window.location.pathname !== next) window.history.pushState({}, '', next) setPath(next) }, []) const signedOut = useCallback(() => { setAccount(null); go('/') }, [go]) useEffect(() => { const onPopState = () => setPath(window.location.pathname) window.addEventListener('popstate', onPopState) return () => window.removeEventListener('popstate', onPopState) }, []) useEffect(() => { api('/auth/me').then(setAccount).catch(err => { if (!(err instanceof RequestError && err.status === 401)) setError(err instanceof Error ? err.message : '无法连接服务。') setAccount(null) }) }, []) // These Ant Design tokens are retained from the upstream App.tsx ConfigProvider. useEffect(() => { if (justLoggedIn.current) { justLoggedIn.current = false; return } if (account === null && path === '/app/remote') go('/app/login') }, [account, path, go]) const login = useCallback((next: Account) => { justLoggedIn.current = true; setAccount(next); go('/app/remote') }, [go]) const content = account === undefined ?
正在检查登录状态…
: path === '/app/remote' && account ? : path === '/app/login' ? : return {content} } createRoot(document.getElementById('root')!).render()