-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
789 lines (676 loc) · 27.2 KB
/
Copy pathscript.js
File metadata and controls
789 lines (676 loc) · 27.2 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Word pool for typing tests
const WORD_POOL = [
'the', 'quick', 'brown', 'fox', 'jumps', 'over', 'lazy', 'dog', 'pack', 'my',
'boxes', 'with', 'five', 'dozen', 'liquor', 'jugs', 'sphinx', 'waltz', 'bad', 'nymph',
'glib', 'jocks', 'quiz', 'physique', 'cwm', 'fjord', 'zygote', 'waxing', 'liquid', 'job',
'typing', 'practice', 'keyboard', 'speed', 'accuracy', 'performance', 'test', 'exercise',
'improvement', 'mastery', 'challenge', 'focus', 'concentration', 'distraction', 'rhythm',
'fluency', 'effortless', 'smooth', 'natural', 'instant', 'response', 'skill', 'ability',
'talent', 'expertise', 'proficiency', 'knowledge', 'experience', 'learning', 'development',
'growth', 'progress', 'advance', 'excel', 'achieve', 'succeed', 'thrive', 'excel',
'platform', 'community', 'users', 'online', 'website', 'application', 'software', 'system',
'interface', 'design', 'feature', 'functionality', 'performance', 'quality', 'standard',
'record', 'achieve', 'beat', 'personal', 'best', 'score', 'result', 'outcome', 'final',
'start', 'begin', 'initiate', 'commence', 'launch', 'activate', 'engage', 'participate',
'join', 'enter', 'compete', 'participate', 'strive', 'pursue', 'chase', 'seek', 'find',
'discover', 'explore', 'journey', 'adventure', 'quest', 'mission', 'goal', 'objective',
'aim', 'target', 'destination', 'path', 'route', 'direction', 'course', 'stream', 'flow',
'wave', 'tide', 'current', 'motion', 'movement', 'action', 'activity', 'work', 'effort',
'labor', 'toil', 'grind', 'hustle', 'dedication', 'commitment', 'passion', 'drive',
'motivation', 'inspiration', 'encouragement', 'support', 'help', 'assist', 'guide',
'mentor', 'teacher', 'trainer', 'coach', 'leader', 'master', 'expert', 'professional'
];
const QUOTES = [
'The only way to do great work is to love what you do.',
'Innovation distinguishes between a leader and a follower.',
'Life is what happens when you are busy making other plans.',
'The future belongs to those who believe in the beauty of their dreams.',
'It is during our darkest moments that we must focus to see the light.',
'Be yourself; everyone else is already taken.',
'The only impossible journey is the one you never begin.',
'Success is not final, failure is not fatal.',
'Believe you can and you are halfway there.',
'The best time to plant a tree was 20 years ago. The second best time is now.'
];
const PUNCTUATION_CHARS = '!@#$%^&*()_+-=[]{}|;:,.<>?/~`';
// Configure Supabase
const SUPABASE_URL = 'https://YOUR_PROJECT_REF.supabase.co';
const SUPABASE_ANON_KEY = 'YOUR_ANON_PUBLIC_KEY';
const supabaseClient = supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// State variables
let currentDuration = 30;
let timeRemaining = 60;
let totalTime = 60;
let isTestActive = false;
let timerInterval = null;
let testStarted = false;
let contentType = 'words';
let testType = 'timed';
let typingStyle = 'highlight';
// Motivational messages
const MOTIVATIONAL_MESSAGES = [
"Great job! Keep it up! 🚀",
"You're doing amazing! 💪",
"Nice typing! Stay focused! 🎯",
"Excellent accuracy! 🔥",
"You're on fire! 🔥",
"Keep that momentum! ⚡",
"Outstanding work! 🌟",
"You're crushing it! 💥",
"Fantastic progress! 📈",
"Keep pushing forward! 💪"
];
let lastMotivationTime = 0;
let words = [];
let currentWordIndex = 0;
let currentCharIndex = 0;
let correctChars = 0;
let incorrectChars = 0;
let totalChars = 0;
let totalErrors = 0;
let typedText = '';
let lastUpdateIndex = -1;
// DOM Elements
const promptText = document.getElementById('promptText');
const wpmDisplay = document.getElementById('wpm');
const accuracyDisplay = document.getElementById('accuracy');
const timerDisplay = document.getElementById('timer');
const keystrokesDisplay = document.getElementById('keystrokes');
const wordCountDisplay = document.getElementById('wordCount');
const resetBtn = document.getElementById('resetBtn');
const themeBtn = document.getElementById('themeBtn');
const wordsTypedDisplay = document.getElementById('wordsTyped');
const totalWordsDisplay = document.getElementById('totalWords');
const progressFill = document.getElementById('progressFill');
const resultModal = document.getElementById('resultModal');
// Auth/dashboard elements
const authPanel = document.getElementById('authPanel');
const loginArea = document.getElementById('loginArea');
const userArea = document.getElementById('userArea');
const userEmail = document.getElementById('userEmail');
const authTitle = document.getElementById('authTitle');
const emailInput = document.getElementById('emailInput');
const passwordInput = document.getElementById('passwordInput');
const signInBtn = document.getElementById('signInBtn');
const signUpBtn = document.getElementById('signUpBtn');
const logoutBtn = document.getElementById('logoutBtn');
const userDashboard = document.getElementById('userDashboard');
const totalSessionsEl = document.getElementById('totalSessions');
const avgWpmEl = document.getElementById('avgWpm');
const bestWpmEl = document.getElementById('bestWpm');
const avgAccuracyEl = document.getElementById('avgAccuracy');
const contributionGraph = document.getElementById('contributionGraph');
const historyList = document.getElementById('historyList');
const modeBtns = document.querySelectorAll('.mode-btn');
const contentTypeSelect = document.getElementById('contentType');
const testTypeSelect = document.getElementById('testType');
const typingStyleSelect = document.getElementById('typingStyle');
const timedModesContainer = document.getElementById('timedModes');
// Initialize
document.addEventListener('DOMContentLoaded', () => {
generateWords();
renderPromptText();
// Initialize timer display
timerDisplay.textContent = testType === 'timed' ? currentDuration : '0';
accuracyDisplay.textContent = '0%';
// Mode buttons
modeBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
if (!isTestActive && !testStarted) {
modeBtns.forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
currentDuration = parseInt(e.target.dataset.duration);
timerDisplay.textContent = currentDuration;
resetTest();
}
});
});
// Content type selector
contentTypeSelect.addEventListener('change', (e) => {
if (!isTestActive && !testStarted) {
contentType = e.target.value;
resetTest();
}
});
// Test type selector
testTypeSelect.addEventListener('change', (e) => {
testType = e.target.value;
// Don't hide timed modes anymore - let users choose all options freely
// timedModesContainer.style.display = testType === 'timed' ? 'flex' : 'none';
resetTest();
});
// Typing style selector
typingStyleSelect.addEventListener('change', (e) => {
typingStyle = e.target.value;
// Preserve light-mode class if it exists
const isLightMode = document.body.classList.contains('light-mode');
document.body.classList.remove('style-highlight', 'style-underline', 'style-fade');
document.body.classList.add(`style-${typingStyle}`);
if (isLightMode) {
document.body.classList.add('light-mode');
}
// Re-render character classes to apply new style
updateCharClasses();
});
// Input focus (avoid stealing focus from dropdown controls)
document.addEventListener('click', (event) => {
if (isTestActive || testStarted) return;
const clickTarget = event.target;
const isInControl = clickTarget.closest('.controls, .selector-group, .test-modes, .control-buttons, #resultModal, .modal-content, .btn, select, option, .logo');
if (!isInControl) {
promptText.focus();
}
});
// Reset button
resetBtn.addEventListener('click', resetTest);
// Theme button
themeBtn.addEventListener('click', toggleTheme);
// Typing input
document.addEventListener('keydown', handleKeydown);
// Prevent paste from starting test
document.addEventListener('paste', (e) => {
e.preventDefault();
// Don't start test on paste
});
// Maintain focus for typing area
document.addEventListener('focusin', (e) => {
// Don't start test on focus events
if (!isTestActive && !testStarted && !e.target.closest('.controls, .selector-group, .test-modes, .control-buttons, #resultModal, .modal-content, .btn, select, option')) {
promptText.focus();
}
});
// Auth actions
signInBtn.addEventListener('click', async () => {
await signIn(emailInput.value.trim(), passwordInput.value);
});
signUpBtn.addEventListener('click', async () => {
await signUp(emailInput.value.trim(), passwordInput.value);
});
logoutBtn.addEventListener('click', async () => {
await signOut();
});
authCheck();
});
async function authCheck() {
const { data: { user } } = await supabaseClient.auth.getUser();
if (user) {
showUserUI(user);
await loadUserData(user);
} else {
showGuestUI();
}
}
function showUserUI(user) {
loginArea.classList.add('hidden');
userArea.classList.remove('hidden');
userEmail.textContent = user.email || 'Unknown';
authTitle.textContent = 'Signed in - progress saved';
userDashboard.classList.remove('hidden');
}
function showGuestUI() {
loginArea.classList.remove('hidden');
userArea.classList.add('hidden');
userEmail.textContent = '';
authTitle.textContent = 'Sign in to save progress';
userDashboard.classList.add('hidden');
}
async function signIn(email, password) {
if (!email || !password) {
alert('Please enter email and password.');
return;
}
const { error } = await supabaseClient.auth.signInWithPassword({ email, password });
if (error) {
alert('Sign in failed: ' + error.message);
return;
}
await authCheck();
}
async function signUp(email, password) {
if (!email || !password) {
alert('Please enter email and password.');
return;
}
const { error } = await supabaseClient.auth.signUp({ email, password });
if (error) {
alert('Sign up failed: ' + error.message);
return;
}
alert('Verification email sent if required. Please confirm and sign in.');
}
async function signOut() {
const { error } = await supabaseClient.auth.signOut();
if (error) {
alert('Sign out failed: ' + error.message);
return;
}
showGuestUI();
}
function getDateKey(d) {
const date = new Date(d);
return date.toISOString().split('T')[0];
}
async function loadUserData(user) {
const { data: sessions, error } = await supabaseClient
.from('typing_sessions')
.select('*')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
.limit(50);
if (error) {
console.error('Failed to load history', error);
return;
}
if (!sessions || sessions.length === 0) {
historyList.innerHTML = '<p>No saved sessions yet.</p>';
totalSessionsEl.textContent = '0';
avgWpmEl.textContent = '0';
bestWpmEl.textContent = '0';
avgAccuracyEl.textContent = '0%';
contributionGraph.innerHTML = '';
return;
}
// Summary metrics
const totalSessions = sessions.length;
const avgWpm = Math.round(sessions.reduce((sum, item) => sum + item.wpm, 0) / totalSessions);
const bestWpm = sessions.reduce((max, item) => Math.max(max, item.wpm), 0);
const avgAccuracy = Math.round(sessions.reduce((sum, item) => sum + item.accuracy, 0) / totalSessions);
totalSessionsEl.textContent = totalSessions;
avgWpmEl.textContent = avgWpm;
bestWpmEl.textContent = bestWpm;
avgAccuracyEl.textContent = `${avgAccuracy}%`;
// Contribution graph 30 days
const today = new Date();
const startDate = new Date(today);
startDate.setDate(today.getDate() - 29);
const counts = {};
sessions.forEach((session) => {
const key = getDateKey(session.created_at || session.createdAt || session.created);
counts[key] = (counts[key] || 0) + 1;
});
contributionGraph.innerHTML = '';
for (let d = new Date(startDate); d <= today; d.setDate(d.getDate() + 1)) {
const key = getDateKey(d);
const value = counts[key] || 0;
const dayEl = document.createElement('div');
dayEl.className = 'contrib-day';
let level = 0;
if (value >= 4) level = 4;
else if (value >= 3) level = 3;
else if (value >= 2) level = 2;
else if (value >= 1) level = 1;
dayEl.dataset.level = level;
dayEl.title = `${key}: ${value} session${value === 1 ? '' : 's'}`;
contributionGraph.appendChild(dayEl);
}
// History list latest 15
historyList.innerHTML = '';
sessions.slice(0, 15).forEach((session) => {
const item = document.createElement('div');
item.className = 'history-item';
const date = new Date(session.created_at || session.createdAt || session.created);
item.innerHTML = `<div>${date.toLocaleDateString()} ${date.toLocaleTimeString()}</div><div class="item-meta">WPM: ${session.wpm} · ACC: ${session.accuracy}% · TIME: ${session.duration}s</div>`;
historyList.appendChild(item);
});
}
async function saveSessionIfLoggedIn(payload) {
const { data: { user } } = await supabaseClient.auth.getUser();
if (!user) return;
const record = {
user_id: user.id,
wpm: payload.wpm,
accuracy: payload.accuracy,
duration: payload.duration,
errors: payload.errors,
correct_chars: payload.correctChars,
incorrect_chars: payload.incorrectChars,
total_chars: payload.totalChars,
created_at: new Date().toISOString()
};
const { error } = await supabaseClient.from('typing_sessions').insert([record]);
if (error) {
console.error('Saving session failed', error);
} else {
await loadUserData(user);
}
}
// Content generators
function generateWords() {
words = [];
const count = contentType === 'quotes' ? 1 : 30;
switch(contentType) {
case 'words':
for (let i = 0; i < count; i++) {
words.push(WORD_POOL[Math.floor(Math.random() * WORD_POOL.length)]);
}
break;
case 'numbers':
for (let i = 0; i < count; i++) {
words.push(Math.floor(Math.random() * 1000).toString());
}
break;
case 'punctuation':
for (let i = 0; i < count; i++) {
const len = Math.floor(Math.random() * 4) + 2;
let word = '';
for (let j = 0; j < len; j++) {
const char = PUNCTUATION_CHARS[Math.floor(Math.random() * PUNCTUATION_CHARS.length)];
// Capitalize letters if they happen to be present
word += char.toUpperCase();
}
words.push(word);
}
break;
case 'quotes':
const quote = QUOTES[Math.floor(Math.random() * QUOTES.length)];
words = quote.split(' ');
break;
case 'mixed':
for (let i = 0; i < count; i++) {
const type = Math.floor(Math.random() * 4); // Changed to 4 for more variety
if (type === 0) {
// Regular lowercase word
words.push(WORD_POOL[Math.floor(Math.random() * WORD_POOL.length)]);
} else if (type === 1) {
// Capitalized word (proper nouns, etc.)
const word = WORD_POOL[Math.floor(Math.random() * WORD_POOL.length)];
words.push(word.charAt(0).toUpperCase() + word.slice(1));
} else if (type === 2) {
// Numbers
words.push(Math.floor(Math.random() * 100).toString());
} else {
// Punctuation (uppercase)
const len = Math.floor(Math.random() * 2) + 1;
let word = '';
for (let j = 0; j < len; j++) {
const char = PUNCTUATION_CHARS[Math.floor(Math.random() * PUNCTUATION_CHARS.length)];
word += char.toUpperCase();
}
words.push(word);
}
}
break;
}
}
function renderPromptText() {
promptText.innerHTML = '';
words.forEach((word, wordIdx) => {
const wordSpan = document.createElement('span');
wordSpan.className = 'word';
// Add characters
word.split('').forEach((char) => {
const charSpan = document.createElement('span');
charSpan.textContent = char;
charSpan.className = 'char';
wordSpan.appendChild(charSpan);
});
// Add space
const spaceSpan = document.createElement('span');
spaceSpan.textContent = ' ';
spaceSpan.className = 'char space';
wordSpan.appendChild(spaceSpan);
promptText.appendChild(wordSpan);
});
totalWordsDisplay.textContent = words.length;
}
function updateCharClasses() {
const allChars = document.querySelectorAll('.char');
const currentLength = typedText.length;
// Only update from the last update point for efficiency
const startIndex = Math.max(0, lastUpdateIndex - 1);
allChars.forEach((charSpan, index) => {
// Skip if we've already updated beyond this point
if (index < startIndex && lastUpdateIndex !== -1) return;
charSpan.classList.remove('correct', 'incorrect', 'current', 'upcoming');
if (index < currentLength) {
// Characters that have been typed
if (typedText[index] === charSpan.textContent) {
charSpan.classList.add('correct');
} else {
charSpan.classList.add('incorrect');
}
} else if (index === currentLength) {
// Current character being typed
charSpan.classList.add('current');
} else {
// Upcoming characters
charSpan.classList.add('upcoming');
}
});
lastUpdateIndex = currentLength;
}
function handleKeydown(e) {
// Prevent default for some keys
if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey)) {
e.preventDefault();
}
// Ignore modifier keys, function keys, and other non-typing keys
if (e.ctrlKey || e.altKey || e.metaKey || e.key.startsWith('F') || e.key === 'Escape' ||
e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight' ||
e.key === 'Home' || e.key === 'End' || e.key === 'PageUp' || e.key === 'PageDown' ||
e.key === 'Insert' || e.key === 'Delete' || e.key === 'CapsLock' || e.key === 'NumLock' ||
e.key === 'ScrollLock' || e.key === 'Pause') {
return;
}
let keyProcessed = false;
if (e.key === 'Backspace') {
if (typedText.length > 0) {
typedText = typedText.slice(0, -1);
keyProcessed = true;
}
} else if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
// Only process single character keys (not shortcuts)
typedText += e.key;
keyProcessed = true;
}
if (!keyProcessed) return;
// Update character classes to reflect changes
updateCharClasses();
// Start test on first valid typing key (not on paste or other events)
if (!testStarted && typedText.length > 0) {
startTest();
}
if (!isTestActive) return;
// For free mode, check if we need more words
if (testType === 'free' && typedText.length > words.join(' ').length - 50) {
generateWords();
renderPromptText();
lastUpdateIndex = -1;
}
// Calculate stats based on typed content
totalChars = typedText.length;
// Calculate accuracy based on correct chars
correctChars = 0;
incorrectChars = 0;
const allChars = document.querySelectorAll('.char');
allChars.forEach((charSpan, index) => {
if (index < typedText.length) {
if (typedText[index] === charSpan.textContent) {
correctChars++;
} else {
incorrectChars++;
}
}
});
totalErrors = incorrectChars;
updateStats();
updateProgress();
// Show motivational message occasionally
showMotivationalMessage();
}
function updateProgress() {
// Count words typed (spaces encountered)
const wordsTyped = typedText.trim().split(/\s+/).filter(word => word.length > 0).length;
wordsTypedDisplay.textContent = wordsTyped;
// For progress bar, use words typed vs total words
const progress = (wordsTyped / words.length) * 100;
progressFill.style.width = Math.min(progress, 100) + '%';
}
function updateStats() {
const timeElapsed = testType === 'timed' ? (totalTime - timeRemaining) : Math.floor((Date.now() - testStartTime) / 1000);
const minutes = timeElapsed / 60;
// WPM calculation
const typedWords = typedText.trim().split(/\s+/).filter(w => w.length > 0).length;
const wpm = minutes > 0 ? Math.round(typedWords / minutes) : 0;
// Accuracy - start at 0 if no characters typed, otherwise calculate based on correct vs total typed
let accuracy = 0;
if (totalChars > 0) {
accuracy = Math.round((correctChars / totalChars) * 100);
}
wpmDisplay.textContent = isNaN(wpm) ? 0 : wpm;
accuracyDisplay.textContent = accuracy + '%';
keystrokesDisplay.textContent = totalChars;
wordCountDisplay.textContent = typedWords;
if (testType === 'timed') {
timerDisplay.textContent = timeRemaining;
} else {
timerDisplay.textContent = timeElapsed;
}
}
let testStartTime = 0;
function startTest() {
testStarted = true;
isTestActive = true;
testStartTime = Date.now();
if (testType === 'timed') {
timeRemaining = currentDuration;
totalTime = currentDuration;
}
totalChars = 0;
correctChars = 0;
incorrectChars = 0;
totalErrors = 0;
lastUpdateIndex = -1;
modeBtns.forEach(btn => btn.disabled = true);
contentTypeSelect.disabled = true;
testTypeSelect.disabled = true;
if (testType === 'timed') {
timerInterval = setInterval(() => {
timeRemaining--;
timerDisplay.textContent = timeRemaining;
if (timeRemaining <= 0) {
endTest();
}
}, 1000);
} else {
// For free mode, update timer display every second
timerInterval = setInterval(() => {
updateStats();
}, 1000);
}
}
async function endTest() {
isTestActive = false;
testStarted = false;
clearInterval(timerInterval);
modeBtns.forEach(btn => btn.disabled = false);
contentTypeSelect.disabled = false;
testTypeSelect.disabled = false;
const timeElapsed = testType === 'timed' ? (totalTime - timeRemaining) : Math.floor((Date.now() - testStartTime) / 1000);
const minutes = timeElapsed / 60;
const typedWords = typedText.split(' ').filter(w => w.length > 0).length;
const finalWpm = minutes > 0 ? Math.round(typedWords / minutes) : 0;
const finalAccuracy = totalChars > 0
? Math.round((correctChars / totalChars) * 100)
: 100;
// Show results
document.getElementById('resultWpm').textContent = isNaN(finalWpm) ? 0 : finalWpm;
document.getElementById('resultAccuracy').textContent = finalAccuracy + '%';
document.getElementById('resultTime').textContent = timeElapsed + 's';
document.getElementById('resultErrors').textContent = totalErrors;
document.getElementById('resultCorrectChars').textContent = correctChars;
document.getElementById('resultIncorrectChars').textContent = incorrectChars;
document.getElementById('resultTotalChars').textContent = totalChars;
resultModal.classList.remove('hidden');
await saveSessionIfLoggedIn({
wpm: isNaN(finalWpm) ? 0 : finalWpm,
accuracy: finalAccuracy,
duration: timeElapsed,
errors: totalErrors,
correctChars: correctChars,
incorrectChars: incorrectChars,
totalChars: totalChars
});
}
function resetTest() {
// Stop any active test
isTestActive = false;
testStarted = false;
clearInterval(timerInterval);
// Reset values
if (testType === 'timed') {
timeRemaining = currentDuration;
totalTime = currentDuration;
}
currentWordIndex = 0;
currentCharIndex = 0;
correctChars = 0;
incorrectChars = 0;
totalChars = 0;
totalErrors = 0;
typedText = '';
lastUpdateIndex = -1;
// Reset UI
timerDisplay.textContent = testType === 'timed' ? currentDuration : '0';
wpmDisplay.textContent = '0';
accuracyDisplay.textContent = '0%';
keystrokesDisplay.textContent = '0';
wordCountDisplay.textContent = '0';
wordsTypedDisplay.textContent = '0';
progressFill.style.width = '0%';
resultModal.classList.add('hidden');
// Regenerate words
generateWords();
renderPromptText();
modeBtns.forEach(btn => btn.disabled = false);
contentTypeSelect.disabled = false;
testTypeSelect.disabled = false;
}
function showMotivationalMessage() {
const now = Date.now();
// Show message every 10-15 seconds during active typing
if (now - lastMotivationTime > (10000 + Math.random() * 5000) && isTestActive) {
const message = MOTIVATIONAL_MESSAGES[Math.floor(Math.random() * MOTIVATIONAL_MESSAGES.length)];
// Create and show notification
const notification = document.createElement('div');
notification.className = 'motivation-notification';
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: linear-gradient(135deg, #a78bfa 0%, #f472b6 100%);
color: white;
padding: 12px 20px;
border-radius: 25px;
font-weight: 600;
font-size: 0.9rem;
box-shadow: 0 8px 24px rgba(167, 139, 250, 0.3);
z-index: 1001;
animation: slideInRight 0.5s ease, fadeOutUp 0.5s ease 3s forwards;
pointer-events: none;
`;
document.body.appendChild(notification);
// Remove after animation
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 3500);
lastMotivationTime = now;
}
}
function toggleTheme() {
document.body.classList.toggle('light-mode');
const isDark = !document.body.classList.contains('light-mode');
themeBtn.textContent = isDark ? '🌙' : '☀️';
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
// Logo click to refresh page
const logoElement = document.querySelector('.logo');
if (logoElement) {
logoElement.addEventListener('click', () => {
location.reload();
});
logoElement.style.cursor = 'pointer';
}