Kexin-251202's picture
update user/admin, update data import options
9def1ee verified
Raw History Blame
6.56 kB
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;