forked from Ammaar-Alam/tigertype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResults.jsx
More file actions
391 lines (363 loc) · 14.4 KB
/
Copy pathResults.jsx
File metadata and controls
391 lines (363 loc) · 14.4 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import { useNavigate } from 'react-router-dom';
import { useRace } from '../context/RaceContext';
import { useAuth } from '../context/AuthContext';
import { useState, useCallback, useEffect } from 'react';
import { useTutorial } from '../context/TutorialContext';
import TutorialAnchor from './TutorialAnchor';
import './Results.css';
import axios from 'axios';
import defaultProfileImage from '../assets/icons/default-profile.svg';
import PropTypes from 'prop-types';
import ProfileModal from './ProfileModal.jsx';
function Results({ onShowLeaderboard }) {
const navigate = useNavigate();
const { raceState, typingState, resetRace, joinPublicRace, playAgain } = useRace();
const { isRunning, endTutorial } = useTutorial();
const { user } = useAuth();
// State for profile modal
const [selectedProfileNetid, setSelectedProfileNetid] = useState(null);
const [showProfileModal, setShowProfileModal] = useState(false);
// State for storing fetched titles for result players
const [resultTitlesMap, setResultTitlesMap] = useState({});
// --- DEBUG LOG ---
useEffect(() => {
// console.log('[Results Component Render] raceState.snippet:', raceState.snippet);
}, [raceState.snippet]);
// --- END DEBUG LOG ---
// Fetch titles for each player in race results
useEffect(() => {
if (raceState.results && raceState.results.length) {
raceState.results.forEach(result => {
const netid = result.netid;
// Sync current user's titles from context
if (netid === user?.netid && user?.titles && resultTitlesMap[netid] !== user.titles) {
setResultTitlesMap(prev => ({ ...prev, [netid]: user.titles }));
}
// Fetch other players' titles
if (netid !== user?.netid && !(netid in resultTitlesMap)) {
axios.get(`/api/user/${netid}/titles`)
.then(res => setResultTitlesMap(prev => ({ ...prev, [netid]: res.data || [] })))
.catch(err => {
console.error(`Error fetching titles for ${netid}:`, err);
setResultTitlesMap(prev => ({ ...prev, [netid]: [] }));
});
}
});
}
}, [raceState.results, user, resultTitlesMap]);
// Handle back button
const handleBack = () => {
if (isRunning) endTutorial();
resetRace();
navigate('/home?refreshUser=true');
};
// Handle avatar click to show profile modal
const handleAvatarClick = (_avatar, netid) => {
setSelectedProfileNetid(netid);
setShowProfileModal(true);
document.body.style.overflow = 'hidden';
};
// Close profile modal
const closeModal = useCallback(() => {
setShowProfileModal(false);
setSelectedProfileNetid(null);
document.body.style.overflow = '';
}, []);
// Add handler to queue another public race
const handleQueueNext = () => {
// Reset local race state before queuing
resetRace();
// Force a new public race queue, ignoring previous lobby code
joinPublicRace(true);
};
// helper to compute a course review URL when DB field is missing
const getCourseUrl = (snippet) => {
if (!snippet) return null;
if (snippet.princeton_course_url) return snippet.princeton_course_url;
const title = snippet.course_name || '';
const m = title.match(/^([A-Z&]+)\s+(\d+[A-Z]?)/);
if (m) {
const query = encodeURIComponent(`${m[1]} ${m[2]}`);
return `https://registrar.princeton.edu/course-offerings?search=${query}`;
}
return null;
};
// Render practice mode results
const renderPracticeResults = () => {
const isTimedMode = Boolean(raceState.snippet?.is_timed_test || raceState.type === 'timed');
// Function to render the main stats block
const renderStatsBlock = (wpm, accuracy, time) => {
const rawWpm = wpm;
const adjustedWpm = rawWpm * (accuracy / 100);
return (
<div className="stats-grid">
{/* Adjusted WPM - hero card */}
<div className="stat-item stat-item-accent stat-item-adjusted">
<div className="stat-label">
<i className="bi bi-lightning"></i>
Adjusted WPM:
</div>
<div className="stat-value highlight">{adjustedWpm?.toFixed(2)}</div>
<div className="stat-meta-row" aria-label="additional result details">
<span className="meta-chip"><i className="bi bi-speedometer"></i> Raw {rawWpm?.toFixed(2)}</span>
</div>
</div>
{/* Row 2: time and accuracy */}
<div className="stat-item">
<div className="stat-label">
<i className="bi bi-clock"></i>
Time Completed:
</div>
<div className="stat-value">{time?.toFixed(2)}s</div>
</div>
<div className="stat-item">
<div className="stat-label">
<i className="bi bi-check-circle"></i>
Accuracy:
</div>
<div className="stat-value">{accuracy?.toFixed(2)}%</div>
</div>
</div>
);
};
// Determine which data source to use
let statsContent;
const resultFromState = raceState.results?.[0];
if (resultFromState) {
statsContent = renderStatsBlock(
resultFromState.wpm,
resultFromState.accuracy,
resultFromState.completion_time
);
} else if (typingState.completed && raceState.startTime) { // Make sure startTime exists
const elapsedSeconds = (Date.now() - raceState.startTime) / 1000;
statsContent = renderStatsBlock(
typingState.wpm,
typingState.accuracy,
elapsedSeconds
);
} else {
statsContent = (
<div className="stats-loading">
<div className="loading-results">
<div className="spinner-border text-orange" role="status">
<span className="visually-hidden">Loading...</span>
</div>
<p>Waiting for results...</p>
</div>
</div>
);
}
const showSnippetInfo = !isTimedMode && raceState.snippet && raceState.snippet.course_name;
const showCourseReview = !isTimedMode && raceState.snippet?.course_name && getCourseUrl(raceState.snippet);
const showMeta = showSnippetInfo || showCourseReview;
return (
<TutorialAnchor anchorId="practice-results">
<div className="practice-results">
<h3>Practice Results</h3>
<div className={`practice-grid${showMeta ? '' : ' single-column'}`}>
<div className="practice-stats">
{statsContent}
</div>
{showMeta && (
<div className="practice-meta">
{showSnippetInfo && (
<div className="snippet-info" role="note" aria-label="Snippet source">
<div className="snippet-label"><i className="bi bi-book"></i> Where is this excerpt from?</div>
<div className="snippet-title">{raceState.snippet.course_name || raceState.snippet.source || 'Unknown Source'}</div>
</div>
)}
{showCourseReview && (
<a
href={getCourseUrl(raceState.snippet)}
className="course-review-btn"
target="_blank"
rel="noopener noreferrer"
>
<i className="bi bi-book"></i>
View Course Review
</a>
)}
</div>
)}
</div>
<div className="practice-actions">
{onShowLeaderboard && (
<TutorialAnchor anchorId="finish-practice">
<button className="leaderboard-shortcut-btn" onClick={onShowLeaderboard}>
<i className="bi bi-trophy"></i> View Leaderboards
</button>
</TutorialAnchor>
)}
<TutorialAnchor anchorId="keyboard-shortcuts">
<div className="keyboard-shortcuts">
<p>Press <kbd>Tab</kbd> for a new excerpt • <kbd>Esc</kbd> to restart</p>
</div>
</TutorialAnchor>
</div>
</div>
</TutorialAnchor>
);
};
// Render multiplayer race results
const renderRaceResults = () => {
if (!raceState.results || raceState.results.length === 0) {
return (
<p>Waiting for results...</p>
);
}
// Get the first place result (winner)
const winner = raceState.results[0];
const otherResults = raceState.results.slice(1);
return (
<>
{/* First place winner with large avatar */}
<div className="winner-showcase">
<div
className="winner-avatar"
onClick={() => handleAvatarClick(winner.avatar_url, winner.netid)}
title="Click to enlarge"
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
handleAvatarClick(winner.avatar_url, winner.netid);
e.preventDefault();
}
}}
>
<img
src={winner.avatar_url || defaultProfileImage}
alt={`${winner.netid}'s avatar`}
onError={(e) => { e.target.onerror = null; e.target.src=defaultProfileImage; }}
/>
</div>
<div className="winner-details">
<div className="winner-header">
<div className="winner-trophy"><i className="bi bi-trophy"></i></div>
<div className="winner-netid">{winner.netid}</div>
</div>
{/* Display titles for winner */}
{(() => {
const titlesList = resultTitlesMap[winner.netid] || [];
const titleToShow = titlesList.find(t => t.is_equipped) || titlesList[0];
return titleToShow ? (
<div className="winner-titles">
<span className="winner-title-badge">{titleToShow.name}</span>
</div>
) : null;
})()}
<div className="winner-stats">
<div className="winner-wpm">{winner.wpm?.toFixed(2) || 0} WPM</div>
<div className="winner-accuracy">{winner.accuracy?.toFixed(2) || 0}% accuracy</div>
<div className="winner-time">{winner.completion_time?.toFixed(2) || 0}s</div>
</div>
</div>
</div>
{/* Other results */}
<div className="results-list">
{otherResults.map((result, index) => (
<div
key={index}
className={`result-item ${result.netid === user?.netid ? 'current-user' : ''}`}
>
<div className="result-rank">#{index + 2}</div>
<div className="result-player">
<div
className="result-avatar"
onClick={() => handleAvatarClick(result.avatar_url, result.netid)}
title="Click to enlarge"
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
handleAvatarClick(result.avatar_url, result.netid);
e.preventDefault();
}
}}
>
<img
src={result.avatar_url || defaultProfileImage}
alt={`${result.netid}'s avatar`}
onError={(e) => { e.target.onerror = null; e.target.src=defaultProfileImage; }}
/>
</div>
<div className="result-text">
<div className="result-netid">{result.netid}</div>
{(() => {
const titlesList = resultTitlesMap[result.netid] || [];
const titleToShow = titlesList.find(t => t.is_equipped) || titlesList[0];
return titleToShow ? (
<div className="result-titles">
<span className="result-title-badge">{titleToShow.name}</span>
</div>
) : null;
})()}
</div>
</div>
<div className="result-stats">
<div className="result-wpm">{result.wpm?.toFixed(2) || 0} WPM</div>
<div className="result-accuracy">{result.accuracy?.toFixed(2) || 0}%</div>
<div className="result-time">{result.completion_time?.toFixed(2) || 0}s</div>
</div>
</div>
))}
</div>
{/* Snippet Source Info */}
{raceState.type !== 'timed' && raceState.snippet && raceState.snippet.course_name && (
<div className="snippet-info" role="note" aria-label="Snippet source">
<div className="snippet-label"><i className="bi bi-book"></i> Where is this excerpt from?</div>
<div className="snippet-title">{raceState.snippet.course_name || raceState.snippet.source || 'Unknown Source'}</div>
</div>
)}
{/* Course Review Button for multiplayer results */}
{raceState.type !== 'timed' && raceState.snippet?.course_name && getCourseUrl(raceState.snippet) && (
<a
href={getCourseUrl(raceState.snippet)}
className="course-review-btn"
target="_blank"
rel="noopener noreferrer"
>
<i className="bi bi-book"></i>
View Course Review
</a>
)}
</>
);
};
return (
<>
<div className="results-container">
<h2>Results</h2>
{raceState.type === 'practice' ? renderPracticeResults() : renderRaceResults()}
{/* Play Again button for private match host */}
{raceState.type === 'private' && raceState.completed && user?.netid === raceState.hostNetId && (
<button className="back-btn" onClick={playAgain}>
Play Again
</button>
)}
{/* Queue Next Race button for quick matches */}
{raceState.type === 'public' && (
<button className="back-btn" onClick={handleQueueNext}>
Queue Another Race
</button>
)}
<button className="back-btn back-to-menu-btn" onClick={handleBack}>
Back to Menu
</button>
</div>
{/* Profile Modal for viewing user profiles */}
{showProfileModal && (
<ProfileModal
isOpen={showProfileModal}
onClose={closeModal}
netid={selectedProfileNetid}
/>
)}
</>
);
}
Results.propTypes = {
onShowLeaderboard: PropTypes.func, // Prop is optional
};
export default Results;