-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4531 lines (4148 loc) · 125 KB
/
script.js
File metadata and controls
4531 lines (4148 loc) · 125 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Firebase Configuration
const firebaseConfig = {
apiKey: "AIzaSyBUM8QweWGD3t0ksNs_nf8u-uhxFMZDrc8",
authDomain: "typemaster-ai.firebaseapp.com",
databaseURL: "https://typemaster-ai-default-rtdb.firebaseio.com",
projectId: "typemaster-ai",
storageBucket: "typemaster-ai.firebasestorage.app",
messagingSenderId: "836500969709",
appId: "1:836500969709:web:fb913fe69c4aba8695d4e4",
measurementId: "G-MZPN6ETQL7",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();
// DOM Elements
const elements = {
// Mode buttons
modeButtons: document.querySelectorAll(".game-mode-btn"),
modeSettings: document.querySelectorAll(".mode-settings"),
// Settings
timeSelect: document.getElementById("time-select"),
customTimeGroup: document.getElementById("custom-time-group"),
customTime: document.getElementById("custom-time"),
difficultySelect: document.getElementById("difficulty-select"),
languageSelect: document.getElementById("language-select"),
punctuationToggle: document.getElementById("punctuation-toggle"),
soundSelect: document.getElementById("sound-select"),
volumeControl: document.getElementById("volume-control"),
volumeValue: document.getElementById("volume-value"),
// Survival settings
survivalType: document.getElementById("survival-type"),
maxMistakesGroup: document.getElementById("max-mistakes-group"),
maxMistakes: document.getElementById("max-mistakes"),
survivalTimeGroup: document.getElementById("survival-time-group"),
survivalTime: document.getElementById("survival-time"),
survivalDifficulty: document.getElementById("survival-difficulty"),
survivalLanguage: document.getElementById("survival-language"),
// Practice settings
practiceFocus: document.getElementById("practice-focus"),
// Prediction settings
predictionDifficulty: document.getElementById("prediction-difficulty"),
// Numbers settings
numbersLength: document.getElementById("numbers-length"),
numbersType: document.getElementById("numbers-type"),
// Test area
wordsContainer: document.getElementById("words-container"),
typingInput: document.getElementById("typing-input"),
timer: document.getElementById("timer"),
startBtn: document.getElementById("start-btn"),
resetBtn: document.getElementById("reset-btn"),
// Stats
wpm: document.getElementById("wpm"),
accuracy: document.getElementById("accuracy"),
correctWords: document.getElementById("correct-words"),
incorrectWords: document.getElementById("incorrect-words"),
timeRemaining: document.getElementById("time-remaining"),
keystrokes: document.getElementById("keystrokes"),
// Analysis
analysisContent: document.getElementById("analysis-content"),
heatmapKeys: document.getElementById("heatmap-keys"),
errorBreakdown: document.getElementById("error-breakdown"),
// Modals
authModal: document.getElementById("auth-modal"),
resultsModal: document.getElementById("results-modal"),
privacyModal: document.getElementById("privacy-modal"),
termsModal: document.getElementById("terms-modal"),
tutorialModal: document.getElementById("tutorial-modal"),
notificationModal: document.getElementById("notification-modal"),
// Auth
loginBtn: document.getElementById("login-btn"),
logoutBtn: document.getElementById("logout-btn"),
userStatus: document.getElementById("user-status"),
userAvatar: document.getElementById("user-avatar"),
userNameDisplay: document.getElementById("user-name-display"),
// Forms
formTabs: document.querySelectorAll(".form-tab"),
loginForm: document.getElementById("login-form"),
signupForm: document.getElementById("signup-form"),
loginEmail: document.getElementById("login-email"),
loginPassword: document.getElementById("login-password"),
signupEmail: document.getElementById("signup-email"),
signupUsername: document.getElementById("signup-username"),
signupPassword: document.getElementById("signup-password"),
loginSubmit: document.getElementById("login-submit"),
signupSubmit: document.getElementById("signup-submit"),
googleLogin: document.getElementById("google-login"),
googleSignup: document.getElementById("google-signup"),
authError: document.getElementById("auth-error"),
// Results
resultWpm: document.getElementById("result-wpm"),
resultAccuracy: document.getElementById("result-accuracy"),
resultCorrect: document.getElementById("result-correct"),
resultIncorrect: document.getElementById("result-incorrect"),
resultKeystrokes: document.getElementById("result-keystrokes"),
resultTime: document.getElementById("result-time"),
resultsAchievements: document.getElementById("results-achievements"),
resultsShare: document.getElementById("results-share"),
resultsRetry: document.getElementById("results-retry"),
// Theme
themeOptions: document.querySelectorAll(".theme-option"),
fontOptions: document.querySelectorAll(".font-option"),
// Links
privacyLink: document.getElementById("privacy-link"),
termsLink: document.getElementById("terms-link"),
helpBtn: document.getElementById("help-btn"),
// Close buttons
closeAuth: document.getElementById("close-auth"),
closeResults: document.getElementById("close-results"),
closePrivacy: document.getElementById("close-privacy"),
closeTerms: document.getElementById("close-terms"),
closeTutorial: document.getElementById("close-tutorial"),
closeNotification: document.getElementById("close-notification"),
closeHelp: document.getElementById("close-help"),
// Modals
helpModal: document.getElementById("help-modal"),
// Notification
notificationMessage: document.getElementById("notification-message"),
// New Features
profileContainer: document.getElementById("profile-container"),
profileAvatar: document.getElementById("profile-avatar"),
profileStats: document.getElementById("profile-stats"),
achievementsContainer: document.getElementById("achievements-container"),
leaderboardContainer: document.getElementById("leaderboard-container"),
leaderboardContent: document.getElementById("leaderboard-content"),
aiSuggestions: document.getElementById("ai-suggestions"),
curriculumLevels: document.getElementById("curriculum-levels"),
keyboard: document.getElementById("keyboard"),
};
// Game State
const state = {
currentMode: "timed",
isRunning: false,
isPaused: false,
startTime: null,
timerInterval: null,
words: [],
currentWordIndex: 0,
currentCharIndex: 0,
correctWords: 0,
incorrectWords: 0,
totalKeystrokes: 0,
correctKeystrokes: 0,
errors: {},
heatmap: {},
user: null,
userData: null,
testHistory: [],
achievements: [],
leaderboard: [],
curriculum: [],
currentLesson: null,
soundEnabled: true,
soundType: "mechanical", // Default to mechanical sound
soundVolume: 0.7, // Default volume at 70%
currentTheme: "light",
currentFont: "default",
};
// Initialize the application
async function init() {
setupEventListeners();
generateKeyboard();
loadUserPreferences();
checkAuthState();
showTutorial();
loadCurriculum();
loadAchievements();
generateHeatmap();
// Generate initial words on page load
generateWords();
updateWordHighlighting();
// Initialize ML models for enhanced functionality
updateMLStatus("loading");
await initializeMLModels();
// Initialize charts with empty data
initializeCharts();
}
// Set up event listeners
function setupEventListeners() {
// Mode selection
elements.modeButtons.forEach((button) => {
button.addEventListener("click", () => switchMode(button.dataset.mode));
});
// Settings changes
elements.timeSelect.addEventListener("change", handleTimeSelectChange);
elements.customTime.addEventListener("input", updateTimerDisplay);
elements.survivalType.addEventListener("change", handleSurvivalTypeChange);
elements.themeOptions.forEach((option) => {
option.addEventListener("click", () => changeTheme(option.dataset.theme));
});
elements.fontOptions.forEach((option) => {
option.addEventListener("click", () => changeFont(option.dataset.font));
});
// Test controls
elements.startBtn.addEventListener("click", startTest);
elements.resetBtn.addEventListener("click", resetTest);
elements.typingInput.addEventListener("input", handleTypingInput);
elements.typingInput.addEventListener("keydown", handleKeyDown);
elements.typingInput.addEventListener("focus", handleInputFocus);
elements.typingInput.addEventListener("blur", handleInputBlur);
// Auth
elements.loginBtn.addEventListener("click", showAuthModal);
elements.logoutBtn.addEventListener("click", handleLogout);
elements.formTabs.forEach((tab) => {
tab.addEventListener("click", () => switchAuthTab(tab.dataset.tab));
});
elements.loginSubmit.addEventListener("click", handleLogin);
elements.signupSubmit.addEventListener("click", handleSignup);
elements.googleLogin.addEventListener("click", handleGoogleLogin);
elements.googleSignup.addEventListener("click", handleGoogleSignup);
elements.signupPassword.addEventListener("input", validatePassword);
// Toggle keyboard visibility
const toggleKeyboardBtn = document.getElementById("toggle-keyboard");
const keyboardContainer = document.querySelector(".keyboard-container");
if (toggleKeyboardBtn && keyboardContainer) {
toggleKeyboardBtn.addEventListener("click", () => {
keyboardContainer.classList.toggle("collapsed");
const isCollapsed = keyboardContainer.classList.contains("collapsed");
toggleKeyboardBtn.innerHTML = `<i class="fas fa-keyboard"></i> <span>${
isCollapsed ? "Show" : "Hide"
} Keyboard</span>`;
});
}
// Results actions
elements.resultsShare.addEventListener("click", shareResults);
elements.resultsRetry.addEventListener("click", retryTest);
// Close buttons
elements.helpBtn.addEventListener("click", () =>
showModal(elements.helpModal)
);
elements.closeAuth.addEventListener("click", () =>
hideModal(elements.authModal)
);
elements.closeResults.addEventListener("click", () => {
hideModal(elements.resultsModal);
elements.typingInput.disabled = false;
});
elements.closePrivacy.addEventListener("click", () =>
hideModal(elements.privacyModal)
);
elements.closeTerms.addEventListener("click", () =>
hideModal(elements.termsModal)
);
elements.closeTutorial.addEventListener("click", () =>
hideModal(elements.tutorialModal)
);
elements.closeNotification.addEventListener("click", () =>
hideModal(elements.notificationModal)
);
elements.closeHelp.addEventListener("click", () =>
hideModal(elements.helpModal)
);
document
.getElementById("accept-help")
.addEventListener("click", () => hideModal(elements.helpModal));
// Keyboard events
document.addEventListener("keydown", handleGlobalKeyDown);
// Sound settings
elements.soundSelect.addEventListener("change", (e) => {
state.soundType = e.target.value;
if (state.soundType === "none") {
state.soundEnabled = false;
} else {
state.soundEnabled = true;
}
// Play a test sound when changing sound type
if (state.soundEnabled) {
playKeySound();
}
});
// Volume control
elements.volumeControl.addEventListener("input", (e) => {
state.soundVolume = e.target.value / 100;
elements.volumeValue.textContent = e.target.value + "%";
// Play a test sound when adjusting volume
if (state.soundEnabled) {
playKeySound();
}
});
}
// Generate on-screen keyboard
function generateKeyboard() {
const keyboardLayout = [
["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="],
["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]"],
["a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'"],
["z", "x", "c", "v", "b", "n", "m", ",", ".", "/"],
["Space", "Backspace"],
];
elements.keyboard.innerHTML = "";
keyboardLayout.forEach((row) => {
const rowElement = document.createElement("div");
rowElement.className = "keyboard-row";
row.forEach((key) => {
const keyElement = document.createElement("div");
keyElement.className = "keyboard-key";
keyElement.textContent = key === "Space" ? "Space" : key;
keyElement.dataset.key = key === "Space" ? " " : key;
if (key === "Space") {
keyElement.style.minWidth = "300px";
} else if (key === "Backspace") {
keyElement.style.minWidth = "100px";
}
keyElement.addEventListener("click", () =>
handleVirtualKeyPress(key === "Space" ? " " : key)
);
rowElement.appendChild(keyElement);
});
elements.keyboard.appendChild(rowElement);
});
}
// Handle virtual keyboard key press
function handleVirtualKeyPress(key) {
const input = elements.typingInput;
const cursorPosition = input.selectionStart;
if (key === "Backspace") {
if (cursorPosition > 0) {
const newValue =
input.value.substring(0, cursorPosition - 1) +
input.value.substring(cursorPosition);
input.value = newValue;
input.setSelectionRange(cursorPosition - 1, cursorPosition - 1);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
} else if (key === "Enter") {
// In typing tests, Enter typically submits the current word
if (input.value.includes(" ")) {
// If there's already a space, treat as space
input.value += " ";
} else {
// Otherwise, submit the current word
input.value += " ";
}
input.setSelectionRange(input.value.length, input.value.length);
input.dispatchEvent(new Event("input", { bubbles: true }));
} else if (key === " ") {
input.value += " ";
input.setSelectionRange(input.value.length, input.value.length);
input.dispatchEvent(new Event("input", { bubbles: true }));
} else {
input.value =
input.value.substring(0, cursorPosition) +
key +
input.value.substring(cursorPosition);
input.setSelectionRange(cursorPosition + 1, cursorPosition + 1);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
input.focus();
playKeySound();
}
// Switch between game modes
function switchMode(mode) {
state.currentMode = mode;
// Update active mode button
elements.modeButtons.forEach((button) => {
button.classList.toggle("active", button.dataset.mode === mode);
});
// Show/hide mode settings
elements.modeSettings.forEach((settings) => {
settings.classList.toggle("active", settings.id === `${mode}-settings`);
});
// Update start button text based on mode
if (mode === "curriculum") {
elements.startBtn.textContent = "Start Lesson";
} else if (mode === "practice") {
elements.startBtn.textContent = "Start Practice";
} else if (mode === "prediction") {
elements.startBtn.textContent = "Start Challenge";
} else if (mode === "numbers") {
elements.startBtn.textContent = "Start Numbers Test";
} else {
elements.startBtn.textContent = "Start Typing Test";
}
// Reset test when switching modes
resetTest();
}
// Handle time selection change
function handleTimeSelectChange() {
if (elements.timeSelect.value === "custom") {
elements.customTimeGroup.style.display = "block";
} else {
elements.customTimeGroup.style.display = "none";
updateTimerDisplay();
}
}
// Handle survival type change
function handleSurvivalTypeChange() {
if (elements.survivalType.value === "mistakes") {
elements.maxMistakesGroup.style.display = "block";
elements.survivalTimeGroup.style.display = "none";
} else {
elements.maxMistakesGroup.style.display = "none";
elements.survivalTimeGroup.style.display = "block";
}
}
// Update timer display based on selected time
function updateTimerDisplay() {
let time;
if (elements.timeSelect.value === "custom") {
time = parseInt(elements.customTime.value) || 60;
} else {
time = parseInt(elements.timeSelect.value);
}
elements.timer.textContent = time;
elements.timeRemaining.textContent = time;
}
// Start the typing test
function startTest() {
if (state.isRunning) return;
state.isRunning = true;
state.isPaused = false;
state.startTime = new Date();
state.currentWordIndex = 0;
state.currentCharIndex = 0;
state.correctWords = 0;
state.incorrectWords = 0;
state.totalKeystrokes = 0;
state.correctKeystrokes = 0;
state.errors = {};
state.heatmap = {};
// Generate words based on mode
if (state.currentMode === "numbers") {
generateNumbers();
} else if (state.currentMode === "prediction") {
generatePredictionText();
} else if (state.currentMode === "practice") {
generatePracticeText();
} else if (state.currentMode === "curriculum") {
startCurriculumLesson();
} else {
generateWords();
}
// Focus input
elements.typingInput.focus();
elements.typingInput.value = "";
// Start timer based on mode
if (state.currentMode === "survival") {
if (elements.survivalType.value === "time") {
const minutes = parseInt(elements.survivalTime.value) || 5;
startTimer(minutes * 60);
} else {
// Mistakes-based survival doesn't have a time limit
elements.timer.textContent = "∞";
elements.timeRemaining.textContent = "∞";
}
} else if (state.currentMode === "timed") {
let time;
if (elements.timeSelect.value === "custom") {
time = parseInt(elements.customTime.value) || 60;
} else {
time = parseInt(elements.timeSelect.value);
}
startTimer(time);
} else {
// Other modes (practice, prediction, numbers) use timed mode by default
startTimer(60);
}
// Update UI
elements.startBtn.disabled = true;
elements.resetBtn.disabled = false;
updateStats();
}
// Reset the typing test
function resetTest() {
state.isRunning = false;
state.isPaused = false;
clearInterval(state.timerInterval);
elements.typingInput.value = "";
elements.typingInput.disabled = false;
elements.startBtn.disabled = false;
elements.resetBtn.disabled = true;
// Reset timer display
updateTimerDisplay();
// Regenerate words instead of clearing
if (state.currentMode === "numbers") {
generateNumbers();
} else if (state.currentMode === "prediction") {
generatePredictionText();
} else if (state.currentMode === "practice") {
generatePracticeText();
} else if (state.currentMode === "curriculum") {
// For curriculum, show the current lesson or first lesson
if (state.currentLesson) {
loadCurriculumLesson(state.currentLesson);
}
} else {
generateWords();
}
updateWordHighlighting();
// Reset stats
updateStats();
}
// Handle typing input
function handleTypingInput(e) {
// Auto-start test if not running
if (!state.isRunning && !state.isPaused) {
startTest();
return;
}
if (!state.isRunning || state.isPaused) return;
const input = e.target;
const value = input.value;
state.totalKeystrokes++;
// Play key sound if enabled
playKeySound();
// Update heatmap
if (value.length > 0) {
const lastChar = value[value.length - 1];
if (!state.heatmap[lastChar]) {
state.heatmap[lastChar] = 0;
}
state.heatmap[lastChar]++;
updateHeatmapDisplay();
}
if (state.currentMode === "numbers") {
handleNumbersInput(value);
} else {
handleWordsInput(value);
}
updateStats();
}
// Handle input for words mode
function handleWordsInput(value) {
const currentWord = state.words[state.currentWordIndex];
const wordElement = elements.wordsContainer.children[state.currentWordIndex];
// Check if space was pressed (word completed)
if (value.endsWith(" ")) {
// Check if word was typed correctly
const typedWord = value.trim();
if (typedWord === currentWord) {
state.correctWords++;
wordElement.classList.add("correct");
state.correctKeystrokes += currentWord.length;
} else {
state.incorrectWords++;
wordElement.classList.add("incorrect");
// Track errors
const errorKey = `${currentWord}->${typedWord}`;
if (!state.errors[errorKey]) {
state.errors[errorKey] = 0;
}
state.errors[errorKey]++;
}
// Move to next word
state.currentWordIndex++;
state.currentCharIndex = 0;
// Clear input
elements.typingInput.value = "";
// Update word highlighting
updateWordHighlighting();
// Check if user is about to run out of words (5th last word)
const wordsRemaining = state.words.length - state.currentWordIndex;
if (
wordsRemaining === 5 &&
(state.currentMode === "survival" || state.currentMode === "timed")
) {
// Generate 15 more words
const newWords = [];
const difficulty = elements.difficultySelect.value;
const language = elements.languageSelect.value;
const punctuation = elements.punctuationToggle.value === "enabled";
for (let i = 0; i < 15; i++) {
let word = getRandomWord(difficulty, language);
if (punctuation && Math.random() < 0.1) {
word = addPunctuation(word);
}
newWords.push(word);
state.words.push(word);
// Create word element
const wordElement = document.createElement("div");
wordElement.className = "word";
wordElement.textContent = word;
elements.wordsContainer.appendChild(wordElement);
}
}
// Check survival mode mistakes
if (
state.currentMode === "survival" &&
elements.survivalType.value === "mistakes"
) {
const maxMistakes = parseInt(elements.maxMistakes.value) || 5;
if (state.incorrectWords >= maxMistakes) {
endTest();
return;
}
}
// Check if test is complete
if (state.currentWordIndex >= state.words.length) {
if (
state.currentMode === "survival" ||
state.currentMode === "timed" ||
state.currentMode === "practice" ||
state.currentMode === "prediction"
) {
// Generate more words until timer runs out
generateMoreWords();
} else {
endTest();
}
}
} else {
// Update character highlighting for current word
updateCharacterHighlighting(value);
}
}
// Handle input for numbers mode
function handleNumbersInput(value) {
const targetNumber = state.words[0]; // In numbers mode, we only have one "word" (the number sequence)
const numberElement = elements.wordsContainer.children[0];
// Update character highlighting
updateNumberHighlighting(value);
// Check if number sequence is completed
if (value === targetNumber) {
state.correctWords++;
state.correctKeystrokes += targetNumber.length;
endTest();
} else if (value.length >= targetNumber.length) {
// If input length matches target but content doesn't, it's incorrect
state.incorrectWords++;
endTest();
}
}
// Update character highlighting for current word
function updateCharacterHighlighting(inputValue) {
const currentWord = state.words[state.currentWordIndex];
const wordElement = elements.wordsContainer.children[state.currentWordIndex];
// Clear previous highlighting
wordElement.innerHTML = "";
// Track correct keystrokes for this update
let correctInThisWord = 0;
// Add each character with appropriate class
for (let i = 0; i < currentWord.length; i++) {
const charSpan = document.createElement("span");
charSpan.textContent = currentWord[i];
if (i < inputValue.length) {
if (currentWord[i] === inputValue[i]) {
charSpan.className = "correct";
correctInThisWord++;
} else {
charSpan.className = "incorrect";
}
}
wordElement.appendChild(charSpan);
}
// Update correct keystrokes (only count once per character)
state.correctKeystrokes = state.correctWords * 5 + correctInThisWord; // Approximate
// Highlight current word
elements.wordsContainer.querySelectorAll(".word").forEach((word, index) => {
word.classList.toggle("current", index === state.currentWordIndex);
});
}
// Update number highlighting for numbers mode
function updateNumberHighlighting(inputValue) {
const targetNumber = state.words[0];
const numberElement = elements.wordsContainer.children[0];
// Clear previous highlighting
numberElement.innerHTML = "";
// Add each digit with appropriate class
for (let i = 0; i < targetNumber.length; i++) {
const digitSpan = document.createElement("span");
digitSpan.textContent = targetNumber[i];
if (i < inputValue.length) {
if (targetNumber[i] === inputValue[i]) {
digitSpan.className = "correct";
} else {
digitSpan.className = "incorrect";
}
}
numberElement.appendChild(digitSpan);
}
}
// Update word highlighting
function updateWordHighlighting() {
elements.wordsContainer.querySelectorAll(".word").forEach((word, index) => {
word.classList.toggle("current", index === state.currentWordIndex);
});
}
// Handle key down events
function handleKeyDown(e) {
// Prevent default for tab key to avoid losing focus
if (e.key === "Tab") {
e.preventDefault();
}
// Play key sound
playKeySound();
// Highlight virtual keyboard key
highlightVirtualKey(e.key);
}
// Handle global key down events
function handleGlobalKeyDown(e) {
// Start/Restart test with Tab key
if (e.key === "Tab" && !isModalOpen()) {
e.preventDefault();
if (state.isRunning) {
resetTest();
setTimeout(() => startTest(), 100);
} else {
startTest();
}
}
// Stop test with Escape key (not restart)
if (e.key === "Escape" && state.isRunning) {
resetTest();
}
}
// Handle input focus
function handleInputFocus() {
if (state.isRunning && !state.isPaused) {
elements.typingInput.placeholder = "";
}
}
// Handle input blur
function handleInputBlur() {
if (state.isRunning && !state.isPaused) {
elements.typingInput.placeholder = "Click here to continue typing...";
}
}
// Highlight virtual keyboard key
function highlightVirtualKey(key) {
const keyElement = elements.keyboard.querySelector(`[data-key="${key}"]`);
if (keyElement) {
keyElement.classList.add("active");
setTimeout(() => {
keyElement.classList.remove("active");
}, 100);
}
}
// Initialize Audio Context
function initAudioContext() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
return audioContext;
}
// Play key sound
function playKeySound() {
if (!state.soundEnabled || state.soundType === "none") return;
try {
const ctx = initAudioContext();
switch (state.soundType) {
case "mechanical":
playMechanicalSound(ctx);
break;
case "typewriter":
playTypewriterSound(ctx);
break;
case "asmr":
playASMRSound(ctx);
break;
case "soft":
playSoftSound(ctx);
break;
case "clicky":
playClickySound(ctx);
break;
case "vintage":
playVintageSound(ctx);
break;
case "modern":
playModernSound(ctx);
break;
case "gaming":
playGamingSound(ctx);
break;
default:
playMechanicalSound(ctx);
}
} catch (error) {
console.error("Error playing sound:", error);
}
}
// Mechanical keyboard sound (Cherry MX Blue style)
function playMechanicalSound(ctx) {
const now = ctx.currentTime;
// Create oscillator for the click
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
// Sharp, clicky sound
oscillator.frequency.setValueAtTime(800, now);
oscillator.frequency.exponentialRampToValueAtTime(400, now + 0.01);
gainNode.gain.setValueAtTime(0.3 * state.soundVolume, now);
gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.05);
oscillator.start(now);
oscillator.stop(now + 0.05);
}
// Typewriter sound (vintage mechanical)
function playTypewriterSound(ctx) {
const now = ctx.currentTime;
// Main strike sound
const oscillator1 = ctx.createOscillator();
const gainNode1 = ctx.createGain();
oscillator1.connect(gainNode1);
gainNode1.connect(ctx.destination);
oscillator1.frequency.setValueAtTime(150, now);
oscillator1.frequency.exponentialRampToValueAtTime(50, now + 0.02);
gainNode1.gain.setValueAtTime(0.4 * state.soundVolume, now);
gainNode1.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
oscillator1.start(now);
oscillator1.stop(now + 0.08);
// Metallic resonance
const oscillator2 = ctx.createOscillator();
const gainNode2 = ctx.createGain();
oscillator2.connect(gainNode2);
gainNode2.connect(ctx.destination);
oscillator2.frequency.setValueAtTime(1200, now + 0.005);
oscillator2.frequency.exponentialRampToValueAtTime(800, now + 0.03);
gainNode2.gain.setValueAtTime(0.15 * state.soundVolume, now + 0.005);
gainNode2.gain.exponentialRampToValueAtTime(0.01, now + 0.06);
oscillator2.start(now + 0.005);
oscillator2.stop(now + 0.06);
}
// ASMR soft keyboard sound
function playASMRSound(ctx) {
const now = ctx.currentTime;
// Soft, muffled sound with pink noise
const bufferSize = ctx.sampleRate * 0.1;
const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
const data = buffer.getChannelData(0);
// Generate pink noise (softer than white noise)
let b0 = 0,
b1 = 0,
b2 = 0,
b3 = 0,
b4 = 0,
b5 = 0,
b6 = 0;
for (let i = 0; i < bufferSize; i++) {
const white = Math.random() * 2 - 1;
b0 = 0.99886 * b0 + white * 0.0555179;
b1 = 0.99332 * b1 + white * 0.0750759;
b2 = 0.969 * b2 + white * 0.153852;
b3 = 0.8665 * b3 + white * 0.3104856;
b4 = 0.55 * b4 + white * 0.5329522;
b5 = -0.7616 * b5 - white * 0.016898;
data[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362) * 0.11;
b6 = white * 0.115926;
}
const noise = ctx.createBufferSource();
const gainNode = ctx.createGain();
const filter = ctx.createBiquadFilter();
noise.buffer = buffer;
noise.connect(filter);
filter.connect(gainNode);
gainNode.connect(ctx.destination);
filter.type = "lowpass";
filter.frequency.setValueAtTime(2000, now);
filter.frequency.exponentialRampToValueAtTime(500, now + 0.05);
gainNode.gain.setValueAtTime(0.15 * state.soundVolume, now);
gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
noise.start(now);
noise.stop(now + 0.08);
}
// Soft membrane keyboard sound
function playSoftSound(ctx) {
const now = ctx.currentTime;
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
const filter = ctx.createBiquadFilter();