import { useEffect, useRef, PropsWithChildren } from 'react'; import Taro, { useDidShow, useDidHide } from '@tarojs/taro'; import ErrorBoundary from './components/ErrorBoundary'; import { flushEvents } from './services/analytics'; import { useAuthStore } from './stores/auth'; import { useUIStore } from './stores/ui'; import { migrateLegacyStorage } from './utils/secure-storage'; import './app.scss'; function App({ children }: PropsWithChildren>) { const restoreAuth = useAuthStore((s) => s.restore); const restoreUI = useUIStore((s) => s.restore); // useDidShow 在首次 mount 时也会触发,不需要 useEffect 重复调用 useDidShow(() => { migrateLegacyStorage(); restoreAuth(); restoreUI(); }); // 暴露全局 bridge 供 MCP/自动化测试调用(仅 dev 模式) useEffect(() => { if (process.env.NODE_ENV === 'production') return; (globalThis as any).__hms = { restoreAuth: () => { restoreAuth(); return useAuthStore.getState(); }, restoreUI, getAuthState: () => useAuthStore.getState(), }; return () => { delete (globalThis as any).__hms; }; }, []); // Analytics 定时器:仅在页面可见时运行,后台时暂停以节省资源 const analyticsTimerRef = useRef | null>(null); const startAnalyticsTimer = () => { if (analyticsTimerRef.current) return; analyticsTimerRef.current = setInterval(flushEvents, 30000); }; const stopAnalyticsTimer = () => { if (analyticsTimerRef.current) { clearInterval(analyticsTimerRef.current); analyticsTimerRef.current = null; } }; useDidShow(() => { startAnalyticsTimer(); }); useDidHide(() => { stopAnalyticsTimer(); flushEvents(); }); useEffect(() => { return () => { stopAnalyticsTimer(); }; }, []); return {children}; } export default App;