Spaces:
Sleeping
Sleeping
File size: 8,344 Bytes
8bbb872 | 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | import React, { useState, useEffect } from 'react';
function FocusPage({ videoManager, sessionResult, setSessionResult, isActive, displayVideoRef }) {
const [currentFrame, setCurrentFrame] = useState(30);
const [timelineEvents, setTimelineEvents] = useState([]);
const videoRef = displayVideoRef;
// 辅助函数:格式化时间
const formatDuration = (seconds) => {
// 如果是 0,直接显示 0s (或者你可以保留原来的 0m 0s)
if (seconds === 0) return "0s";
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}m ${secs}s`;
};
useEffect(() => {
if (!videoManager) return;
// 设置回调函数来更新时间轴
const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;
videoManager.callbacks.onStatusUpdate = (isFocused) => {
setTimelineEvents(prev => {
const newEvents = [...prev, { isFocused, timestamp: Date.now() }];
if (newEvents.length > 60) newEvents.shift();
return newEvents;
});
// 调用原始回调(如果有)
if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);
};
// 清理函数:不再自动停止session,只清理回调
return () => {
if (videoManager) {
videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;
}
};
}, [videoManager]);
const handleStart = async () => {
try {
if (videoManager) {
setSessionResult(null); // 开始时清除结果层
setTimelineEvents([]);
console.log('🎬 Initializing camera...');
await videoManager.initCamera(videoRef.current);
console.log('✅ Camera initialized');
console.log('🚀 Starting streaming...');
await videoManager.startStreaming();
console.log('✅ Streaming started successfully');
}
} catch (err) {
console.error('❌ Start error:', err);
let errorMessage = "Failed to start: ";
if (err.name === 'NotAllowedError') {
errorMessage += "Camera permission denied. Please allow camera access.";
} else if (err.name === 'NotFoundError') {
errorMessage += "No camera found. Please connect a camera.";
} else if (err.name === 'NotReadableError') {
errorMessage += "Camera is already in use by another application.";
} else if (err.message && err.message.includes('HTTPS')) {
errorMessage += "Camera requires HTTPS. Please use a secure connection.";
} else {
errorMessage += err.message || "Unknown error occurred.";
}
alert(errorMessage + "\n\nCheck browser console for details.");
}
};
const handleStop = () => {
if (videoManager) {
videoManager.stopStreaming();
}
};
const handlePiP = async () => {
try {
const sourceVideoEl = videoRef.current;
if (!sourceVideoEl) {
alert('Video not ready. Please click Start first.');
return;
}
if (document.pictureInPictureElement) {
await document.exitPictureInPicture();
return;
}
sourceVideoEl.disablePictureInPicture = false;
if (typeof sourceVideoEl.webkitSetPresentationMode === 'function') {
sourceVideoEl.play().catch(() => {});
sourceVideoEl.webkitSetPresentationMode('picture-in-picture');
return;
}
if (!document.pictureInPictureEnabled || typeof sourceVideoEl.requestPictureInPicture !== 'function') {
alert('Picture-in-Picture is not supported in this browser.');
return;
}
const pipPromise = sourceVideoEl.requestPictureInPicture();
sourceVideoEl.play().catch(() => {});
await pipPromise;
} catch (err) {
console.error('PiP error:', err);
alert('Failed to enter Picture-in-Picture.');
}
};
// 浮窗功能
const handleFloatingWindow = () => {
handlePiP();
};
// ==========================================
// 新增功能:预览按钮的处理函数
// ==========================================
const handlePreview = () => {
// 强制设置一个 0 分 0 秒的假数据,触发 overlay 显示
setSessionResult({
duration_seconds: 0,
focus_score: 0
});
};
const handleCloseOverlay = () => {
setSessionResult(null);
};
// ==========================================
const handleFrameChange = (val) => {
setCurrentFrame(val);
if (videoManager) {
videoManager.setFrameRate(val);
}
};
const pageStyle = isActive
? undefined
: {
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden',
opacity: 0,
pointerEvents: 'none'
};
return (
<main id="page-b" className="page" style={pageStyle}>
{/* 1. Camera / Display Area */}
<section id="display-area" style={{ position: 'relative', overflow: 'hidden' }}>
<video
ref={videoRef}
muted
playsInline
autoPlay
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
/>
{/* 结果覆盖层 */}
{sessionResult && (
<div className="session-result-overlay">
<h3>Session Complete!</h3>
<div className="result-item">
<span className="label">Duration:</span>
<span className="value">{formatDuration(sessionResult.duration_seconds)}</span>
</div>
<div className="result-item">
<span className="label">Focus Score:</span>
<span className="value">{(sessionResult.focus_score * 100).toFixed(1)}%</span>
</div>
{/* 新增:加一个小按钮方便关闭预览 */}
<button
onClick={handleCloseOverlay}
style={{
marginTop: '20px',
padding: '8px 20px',
background: 'transparent',
border: '1px solid white',
color: 'white',
borderRadius: '20px',
cursor: 'pointer'
}}
>
Close
</button>
</div>
)}
</section>
{/* 2. Timeline Area */}
<section id="timeline-area">
<div className="timeline-label">Timeline</div>
<div id="timeline-visuals">
{timelineEvents.map((event, index) => (
<div
key={index}
className="timeline-block"
style={{
backgroundColor: event.isFocused ? '#00FF00' : '#FF0000',
width: '10px',
height: '20px',
display: 'inline-block',
marginRight: '2px',
borderRadius: '2px'
}}
title={event.isFocused ? 'Focused' : 'Distracted'}
/>
))}
</div>
<div id="timeline-line"></div>
</section>
{/* 3. Control Buttons */}
<section id="control-panel">
<button id="btn-cam-start" className="action-btn green" onClick={handleStart}>Start</button>
<button id="btn-floating" className="action-btn yellow" onClick={handleFloatingWindow}>Floating Window</button>
{/* 修改:把 Models 按钮暂时改成 Preview 按钮,或者加在它后面 */}
<button
id="btn-preview"
className="action-btn"
style={{ backgroundColor: '#6c5ce7' }} // 紫色按钮以示区别
onClick={handlePreview}
>
Preview Result
</button>
<button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>Stop</button>
</section>
{/* 4. Frame Control */}
<section id="frame-control">
<label htmlFor="frame-slider">Frame</label>
<input
type="range"
id="frame-slider"
min="1"
max="60"
value={currentFrame}
onChange={(e) => handleFrameChange(e.target.value)}
/>
<input
type="number"
id="frame-input"
value={currentFrame}
onChange={(e) => handleFrameChange(e.target.value)}
/>
</section>
</main>
);
}
export default FocusPage;
|