Spaces:
Sleeping
Sleeping
File size: 6,562 Bytes
c86c45b 9def1ee c86c45b 9def1ee c86c45b 9def1ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | import React, { useState, useRef, useEffect } from 'react';
import './App.css';
import { VideoManagerLocal } from './utils/VideoManagerLocal';
import Home from './components/Home';
import FocusPageLocal from './components/FocusPageLocal';
import Achievement from './components/Achievement';
import Records from './components/Records';
import Customise from './components/Customise';
import Help from './components/Help';
function App() {
const [activeTab, setActiveTab] = useState('home');
const videoManagerRef = useRef(null);
const [isSessionActive, setIsSessionActive] = useState(false);
const [sessionResult, setSessionResult] = useState(null);
// 新增状态:控制身份和弹窗
const [role, setRole] = useState('user');
const [showWelcomePopup, setShowWelcomePopup] = useState(false);
const handleAutoImport = async () => {
const backup = localStorage.getItem('focus_magic_backup');
if (backup) {
try {
const sessions = JSON.parse(backup);
const response = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(sessions)
});
if (response.ok) {
alert("Auto-recovery successful! Data restored from local cache.");
setShowWelcomePopup(false);
} else {
alert("Auto-recovery failed on server.");
}
} catch (err) {
alert("Error reading cache: " + err.message);
}
} else {
alert("No previous automatic backup found. Please use 'Manual Import' to select your downloaded JSON file.");
}
};
const fileInputRef = useRef(null);
// 刚进网页时的初始化逻辑:先清空,后弹窗
useEffect(() => {
fetch('/api/history', { method: 'DELETE' })
.then(() => {
console.log("History cleared for new user.");
setShowWelcomePopup(true);
})
.catch(err => console.error("Failed to clear history on load", err));
const callbacks = {
onSessionStart: () => {
setIsSessionActive(true);
setSessionResult(null);
},
onSessionEnd: (summary) => {
setIsSessionActive(false);
if (summary) setSessionResult(summary);
}
};
videoManagerRef.current = new VideoManagerLocal(callbacks);
return () => {
if (videoManagerRef.current) videoManagerRef.current.stopStreaming();
};
}, []);
// 手动导入文件的处理逻辑 (借用 Customise 的逻辑)
const handleFileChange = async (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (e) => {
try {
const sessions = JSON.parse(e.target.result);
const response = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(sessions)
});
if (response.ok) {
alert("Import successful! You can check your records now.");
setShowWelcomePopup(false);
} else {
alert("Import failed on server side.");
}
} catch (err) {
alert("Error parsing file: " + err.message);
}
event.target.value = '';
};
reader.readAsText(file);
};
// 点击左上角头像切换 Admin/User
const handleAvatarClick = async () => {
if (role === 'admin') {
if (window.confirm("Switch back to User mode? This will clear current test data.")) {
await fetch('/api/history', { method: 'DELETE' });
setRole('user');
setShowWelcomePopup(true);
}
} else {
const pwd = window.prompt("Enter Admin Password:");
if (pwd === "123") { // 这里是你设定的测试密码
try {
// 1. 先清空当前数据
await fetch('/api/history', { method: 'DELETE' });
// 2. 读取 public 目录下的测试文件
const res = await fetch('/test_data.json');
if (!res.ok) throw new Error("test_data.json not found in public folder");
const testData = await res.json();
// 3. 导入测试数据
const importRes = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testData)
});
if (importRes.ok) {
setRole('admin');
alert("Admin mode activated! Test data loaded successfully.");
}
} catch (error) {
alert("Admin login failed: " + error.message);
}
} else if (pwd !== null) {
alert("Incorrect password!");
}
}
};
return (
<div className="app-container">
{/* 迎宾弹窗 */}
{showWelcomePopup && (
<div className="welcome-modal-overlay">
<div className="welcome-modal">
<h2>Welcome to FocusGuard!</h2>
<p>Would you like to start fresh or import your previous local records?</p>
<div className="welcome-buttons">
<button className="btn-main" onClick={() => setShowWelcomePopup(false)}>New Start</button>
<button className="btn-main" style={{backgroundColor: '#4CAF50'}} onClick={handleAutoImport}>Auto Import</button>
<button className="btn-main yellow" onClick={() => fileInputRef.current.click()}>Manual Import</button>
</div>
{/* 隐藏的上传框 */}
<input type="file" ref={fileInputRef} style={{ display: 'none' }} accept=".json" onChange={handleFileChange} />
</div>
</div>
)}
<nav id="top-menu">
{/* 左上角头像区域 */}
<div className="avatar-container" onClick={handleAvatarClick} title="Click to switch User/Admin">
<div className={`avatar-circle ${role}`}>
{role === 'admin' ? 'A' : 'U'}
</div>
</div>
<button className={`menu-btn ${activeTab === 'focus' ? 'active' : ''}`} onClick={() => setActiveTab('focus')}>
Start Focus {isSessionActive && <span style={{marginLeft: '8px', color: '#00FF00'}}>●</span>}
</button>
<div className="separator"></div>
<button className={`menu-btn ${activeTab === 'achievement' ? 'active' : ''}`} onClick={() => setActiveTab('achievement')}>
My Achievement
</button>
<div className="separator"></div>
<button className={`menu-btn ${activeTab === 'records' ? 'active' : ''}`} onClick={() => setActiveTab('records')}>
My Records
</button>
<div className="separator"></div>
<button className={`menu-btn ${activeTab === 'customise' ? 'active' : ''}`} onClick={() => setActiveTab('customise')}>
Customise
</button>
<div className="separator"></div>
<button className={`menu-btn ${activeTab === 'help' ? 'active' : ''}`} onClick={() => setActiveTab('help')}>
Help
</button>
</nav>
{activeTab === 'home' && <Home setActiveTab={setActiveTab} />}
<FocusPageLocal
videoManager={videoManagerRef.current}
sessionResult={sessionResult}
setSessionResult={setSessionResult}
isActive={activeTab === 'focus'}
/>
{activeTab === 'achievement' && <Achievement />}
{activeTab === 'records' && <Records />}
{activeTab === 'customise' && <Customise />}
{activeTab === 'help' && <Help />}
</div>
);
}
export default App; |