Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1386 lines (1206 loc) · 42 KB
/
Copy pathscript.js
File metadata and controls
1386 lines (1206 loc) · 42 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
"use strict";
//dom manipulation methods set selectors elements some elemnts to make too
const start = document.querySelector(".start-button");
const reset = document.querySelectorAll(".reset-button");
const passageDisplay = document.querySelector("#passage-display");
const passagePreview = document.querySelector("#passage-preview");
const userInput = document.querySelector("#user-input");
const tryAgain = document.querySelector("#try-button");
const passageArea = document.querySelector("#passage-area");
const difficultySettings = document.querySelectorAll(
".difficulty-settings button",
);
const modeSettings = document.querySelectorAll(".mode-settings button");
console.log(modeSettings)
let totalKeysPressed = 0;
let previousLength = 0;
let timerInterval = null;
const TOTAL_TIME = 60;
const personalBest = document.querySelector("#personal-best");
const hasCompletedBaseline = document.querySelector("#baseline-established");
const PERSONAL_BEST_KEY = "personalBest";
const HAS_COMPLETED_KEY = "hasCompletedBaseline";
// let userInput = null;
const gameState = {
difficulty: "easy",
mode: "timed",
isTestActive: false,
typedText: "",
currentPassage: "", // Added to store the current passage
passages: {
easy: [],
medium: [],
hard: [],
},
timeRemaining: TOTAL_TIME,
timeElapsed: 0,
timerStartTime: null,
timerRunning: false,
passageLines: [],
currentLineIndex: 0,
accuracy: 0, // accuracy as a percentage
totalErrors: 0,
normalizedTarget: "", // Store the normalized target text for strict comparison
normalizedTypedText: "", // Store the normalized user input for comparison
perIndexErrors: [], // Track indices that were ever wrong
};
function shouldReduceMotion() {
return window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
}
function runConfettiBurst() {
if (typeof confetti !== "function") return;
if (shouldReduceMotion()) return;
confetti({
particleCount: 150,
spread: 100,
angle: 90,
});
setTimeout(() => {
confetti({
particleCount: 150,
spread: 100,
angle: 90,
});
}, 300);
}
function resetConfettiSafely() {
if (typeof confetti !== "function") return;
if (shouldReduceMotion()) return;
confetti.reset();
}
difficultySettings.forEach((button) => {
button.addEventListener("click", () => {
// remove active from all
difficultySettings.forEach((d) => d.classList.remove("active"));
// add active to the clicked one
button.classList.add("active");
gameState.difficulty = button.textContent.toLocaleLowerCase();
renderPassagePreview();
console.log("Difficulty", gameState.difficulty);
});
});
modeSettings.forEach((buttons) => {
buttons.addEventListener("click", () => {
// remove active from all
modeSettings.forEach((s) => s.classList.remove("active"));
// add active to the clicked one
buttons.classList.add("active");
gameState.mode = buttons.textContent.includes("Timed")
? "timed"
: "passage";
console.log("Mode", gameState.mode);
console.log(gameState.mode);
});
});
//Add click listener to start button → call a startTest() function
if (start) {
start.addEventListener("click", () => {
startTest();
// passageDisplay.focus();
console.log(start)
console.log(start)
});
}
if (passagePreview) {
passagePreview.addEventListener("click", () => {
startTest();
console.log(startTest())
});
}
const clickText = document.querySelector(".click-text");
if (clickText) {
clickText.addEventListener("click", () => {
startTest();
});
}
if (reset) {
reset.forEach((btn) => {
btn.addEventListener("click", () => {
resetTest();
});
});
}
if (tryAgain) {
tryAgain.addEventListener("click", () => {
resetTest();
});
}
function setActiveStates(...stateNames) {
document
.querySelectorAll(".test-state")
.forEach((s) => s.classList.remove("active"));
stateNames.forEach((name) => {
const el = document.getElementById(name);
if (el) el.classList.add("active");
});
}
setActiveStates("test-setup", "passage-area");
async function renderPassagePreview() {
if (!passagePreview) return;
const passages = await loadData();
const selectedPassage = getRandomSelection(passages, gameState.difficulty);
const previewText = selectedPassage
? normalizeText(selectedPassage)
: "Preview unavailable.";
passagePreview.value = previewText;
passagePreview.classList.add("is-blurred");
}
// when the reset button is clicked, reset the game state and clear the passage display
// function setRemoveActiveStates(...stateNames) {
// document
// .querySelectorAll(".test-state")
// .forEach((s) => s.classList.remove("active"));
// stateNames.forEach((name) => {
// const el = document.getElementById(name);
// if (el) el.classList.add("active");
// });
// }
async function startTest() {
// Clear any existing timer
if (timerInterval) {
clearInterval(timerInterval);
gameState.timerRunning = false;
timerInterval = null;
}
gameState.isTestActive = true;
gameState.typedText = "";
document
.querySelectorAll(".wpm")
.forEach((el) => ((el.textContent = "0"), (el.style.fontSize = "20px")));
// document
// .querySelectorAll(".wpm")
// .forEach((el) => (el.textContent = calculateWpm(gameState.typedText)));
const passages = await loadData();
const selectedPassage = getRandomSelection(passages, gameState.difficulty);
if (!selectedPassage) {
console.error("No passage available for the selected difficulty.");
gameState.currentPassage = "";
} else {
// ✅ NORMALIZE passage when storing it
gameState.currentPassage = normalizeText(selectedPassage);
}
gameState.currentLineIndex = 0;
gameState.passageLines = gameState.currentPassage
? gameState.currentPassage.split("\n")
: [];
if (userInput) {
userInput.value = "";
previousLength = 0;
userInput.focus();
}
if (passageArea) {
passageArea.style.display = "none";
}
passagePreview?.classList.remove("is-blurred");
setActiveStates("test-setup", "test-active", "try-button");
// After setActiveStates("test-setup", "test-active", "try-button"); changes classes/visibility, requestAnimationFrame(...) runs on the next paint frame, when those updates are applied.
// Then this block runs:
requestAnimationFrame(() => {
applyPassageWrapping();
if (passageDisplay) {
passageDisplay.value =
gameState.currentPassage || "No passage available.";
}
gameState.normalizedTarget = gameState.currentPassage
? normalizeForCompare(gameState.currentPassage).toLocaleLowerCase()
: "";
buildVisualFeedback();
});
if (userInput) {
userInput.focus();
}
// Update WPM display in results section
document.querySelectorAll("#personal-best").forEach((el) => {
el.textContent = getPersonalBest();
});
const timeDisplay = document.querySelector(".time");
if (timeDisplay) {
if (gameState.mode === "timed") {
timeDisplay.textContent = "1:00";
} else {
timeDisplay.textContent = "0:00";
}
}
console.log("Test started with passage:", gameState.currentPassage); // ✅ Log normalized
console.log("Passage length:", gameState.currentPassage.length); // ✅ Log length
//Clear your per-index “ever wrong” structure for a brand-new session.
// Store a stable normalized target for this session
// After selecting passage, normalize once for strict
// comparison and save it in session state (separate from display-wrapped text).
// Ensure the stable normalized target is captured after any wrapping/transforming
// Capture a stable normalized target immediately (don't defer to rAF)
// Capture a stable normalized target after wrapping has been applied.
// Use requestAnimationFrame to ensure applyPassageWrapping() (which runs in rAF)
// has finished updating gameState.currentPassage before we normalize it.
// Reset input/session text state
// Clear gameState.typedText and input field.
// Reset line index and related per-line state.
gameState.currentLineIndex = 0;
gameState.typedText = "";
gameState.totalErrors = 0;
gameState.normalizedTypedText = "";
gameState.accuracy = 0;
totalKeysPressed = 0;
gameState.perIndexErrors = [];
buildVisualFeedback();
document
.querySelectorAll(".accuracy")
.forEach((el) => (el.textContent = "100%"));
document
.querySelectorAll(".accuracy")
.forEach((el) => (el.style.color = "var(--neutral-green)"));
resetConfettiSafely();
// Disable difficulty and mode buttons during test
disableAllButtons();
disableMenu();
}
function endTest() {
gameState.isTestActive = false;
gameState.timerRunning = false;
// Clear timer safely
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
// if (userInput) {
// userInput.value = "";
// }
const finalWpm = calculateWpm(gameState.typedText);
const previousBest = getPersonalBest();
// Update WPM display in results section
document.querySelectorAll(".wpm").forEach((el) => {
el.textContent = finalWpm;
});
// Check if this is first test (baseline) or new high score
if (previousBest === 0) {
// First test - Baseline Established
savePersonalBest(finalWpm);
updatePersonalBestHeader();
displayResultMessage(finalWpm, 0);
setActiveStates("baseline-established");
} else if (finalWpm > previousBest) {
// New high score - High Score Smashed
savePersonalBest(finalWpm);
updatePersonalBestHeader();
displayResultMessage(finalWpm, previousBest);
setActiveStates("high-score-smashed");
} else {
// Normal completion
displayResultMessage(finalWpm, previousBest);
setActiveStates("test-results");
}
console.log("Test ended", gameState);
// Snapshot final metrics (same model as live input)
const liveTyped = gameState.typedText;
const liveTarget = gameState.currentPassage;
const liveDenominator = liveTyped.length;
if (gameState.perIndexErrors.length < liveDenominator) {
gameState.perIndexErrors.length = liveDenominator;
}
for (let i = 0; i < liveDenominator; i++) {
const typedChar = liveTyped[i] || "";
const targetChar = liveTarget[i] || "";
if (typedChar !== targetChar) {
gameState.perIndexErrors[i] = true; // never reset to false
}
if (targetChar === " ") {
gameState.perIndexErrors[i] = true;
}
}
const incorrectCount = gameState.perIndexErrors
.slice(0, liveDenominator)
.filter(Boolean).length;
gameState.totalErrors = incorrectCount;
const correctChars = liveDenominator - incorrectCount;
gameState.accuracy =
liveDenominator === 0
? 0
: Math.round((correctChars / liveDenominator) * 100);
// Update final result UI
document.querySelectorAll(".characters").forEach((e) => {
e.textContent = `${correctChars} / ${incorrectCount} `;
});
document.querySelectorAll(".accuracy").forEach((el) => {
el.textContent = `${gameState.accuracy}%`;
});
document.querySelectorAll(".characters").forEach((el) => {
el.innerHTML = `<span class="chars-correct">${correctChars}</span> /
<span class="chars-incorrect">${incorrectCount}</span>`;
});
}
// localStorage.setItem(PERSONAL_BEST_KEY, "0");
function resetTest() {
gameState.isTestActive = false;
gameState.typedText = "";
gameState.timeRemaining = 0;
previousLength = 0;
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
gameState.timerRunning = false;
// gameState.currentLineIndex = 0;
// clear all strict/session state related to typing and errors
gameState.totalErrors = 0;
gameState.accuracy = 0;
gameState.normalizedTypedText = "";
gameState.normalizedTarget = "";
totalKeysPressed = 0;
gameState.perIndexErrors = [];
if (userInput) {
userInput.value = "";
}
calculateWpm(""); // Reset WPM display to 0
gameState.timerStartTime = null;
// gameState.startTime = null;
const timeDisplay = document.querySelector(".time");
if (timeDisplay) {
timeDisplay.textContent = `0:00`;
}
const wpmDisplays = document.querySelectorAll(".wpm");
wpmDisplays.forEach((el) => (el.textContent = "0"));
const accuracyDisplays = document.querySelectorAll(".accuracy");
accuracyDisplays.forEach((el) => {
el.textContent = "100%";
el.style.color = "var(--neutral-green)";
});
const personalBest = getPersonalBest();
document.querySelectorAll("#personal-best").forEach((el) => {
el.textContent = personalBest;
});
if (passageArea) {
passageArea.style.display = "";
}
renderPassagePreview();
setActiveStates("test-setup", "passage-area");
console.log("Test reset", gameState);
document.querySelectorAll(".characters").forEach((e) => {
e.textContent = `0 / 0`;
e.style.color = "var(--neutral-400)";
});
resetConfettiSafely();
const visualFeedback = document.querySelector("#visual-feedback");
if (visualFeedback) {
visualFeedback.innerHTML = "";
}
// Re-enable difficulty and mode buttons
enableAllButtons();
enableMenu();
}
// loadData data.json
async function loadData() {
try {
const response = await fetch("./data.json");
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
return data;
} catch (error) {
console.error("Failed Error fetching data:", error);
return null;
} finally {
console.log("Fetch attempt finished.");
}
}
function getRandomSelection(passages, difficulty) {
if (!passages || !passages[difficulty]) {
console.error("Invalid passages data or difficulty level.");
return null;
}
// Access the correct difficulty area
const difficultyArea = passages[difficulty];
//safety check
if (!difficultyArea || difficultyArea.length === 0) {
return null;
}
// Pick random index
const index = Math.floor(Math.random() * difficultyArea.length);
// Get random passage object
const randomPassage = difficultyArea[index];
// Return passage text
// Handle multiple possible data formats
if (typeof randomPassage === "string") {
return randomPassage; // If it's just a string
}
return randomPassage.text || randomPassage.passage || null; // If it's an object
}
// Timer mode (60 seconds)
function startTimedMode() {
if (gameState.timerRunning) {
console.warn("Timer is already running.");
return; // Prevent multiple timers
}
gameState.timeRemaining = TOTAL_TIME;
gameState.timerRunning = true;
gameState.timerStartTime = Date.now();
// Update UI every 1 second
//clear any existing interval
if (timerInterval) {
clearInterval(timerInterval);
}
//update display immediately
const timeDisplay = document.querySelector(".time");
if (timeDisplay) {
timeDisplay.textContent = `1:00`;
}
timerInterval = setInterval(() => {
// gameState.timeRemaining--;
// Update timer display in HTML
// const timeDisplay = document.querySelector(".time");
const elapsed = Date.now() - gameState.timerStartTime;
const elapsedSeconds = Math.floor(elapsed / 1000);
gameState.timeRemaining = Math.max(0, TOTAL_TIME - elapsedSeconds);
// Convert timeRemaining to minutes and seconds
if (timeDisplay) {
const minutes = Math.max(0, Math.floor(gameState.timeRemaining / 60));
const seconds = Math.max(0, gameState.timeRemaining % 60);
timeDisplay.textContent = `${minutes}:${seconds
.toString()
.padStart(2, "0")}`;
}
// Stop when time runs out
if (gameState.timeRemaining <= 0) {
clearInterval(timerInterval);
gameState.timerRunning = false;
timerInterval = null;
endTest();
}
}, 100);
}
function startPassageMode() {
if (gameState.timerRunning) {
console.warn("Timer is already running.");
return; // Prevent multiple timers
}
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
gameState.timeRemaining = 0;
gameState.timerStartTime = Date.now();
gameState.timerRunning = true;
timerInterval = setInterval(() => {
const elapsed = Date.now() - gameState.timerStartTime;
const elapsedSeconds = Math.floor(elapsed / 1000);
gameState.timeRemaining = elapsedSeconds;
const timeDisplay = document.querySelector(".time");
if (timeDisplay) {
const minutes = Math.floor(elapsedSeconds / 60);
const seconds = elapsedSeconds % 60;
timeDisplay.textContent = `${minutes}:${seconds
.toString()
.padStart(2, "0")}`;
}
}, 1000);
// prevent multiple timers
// if (timerInterval) {
// clearInterval(timerInterval);
// }
}
// Helper function to normalize text (remove extra spaces and tabs)
// general cleanup for stored passage text (keeps words tight).
function normalizeText(text) {
if (typeof text !== "string") return "";
return text.replace(/[ \t]+/g, " ").trim();
}
// compare full passages even if line breaks or multiple spaces differ.
function normalizeForCompare(text) {
if (typeof text !== "string") return "";
return text.replace(/\s+/g, " ").trim();
}
// line‑by‑line comparison while preserving indentation/leading spaces.
function normalizeLine(text) {
if (typeof text !== "string") return "";
return text.replace(/[ \t]+/g, " ").trimEnd();
}
// Compare that width to to decide if it fits.
function getTextareaContentWidth(textarea) {
if (!textarea) return 0;
const styles = window.getComputedStyle(textarea);
const paddingLeft = parseFloat(styles.paddingLeft) || 0;
const paddingRight = parseFloat(styles.paddingRight) || 0;
return textarea.clientWidth - paddingLeft - paddingRight;
}
// applies the textarea font → accurate measurement.
function getTextMeasureContext(textarea) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const styles = window.getComputedStyle(textarea);
ctx.font = [
styles.fontStyle,
styles.fontVariant,
styles.fontWeight,
styles.fontSize,
styles.fontFamily,
].join(" ");
return ctx;
}
// gives actual pixel width of text.
function measureTextWidth(ctx, text) {
if (!ctx) return 0;
return ctx.measureText(text).width;
}
// Use's if a word is too wide.
function breakLongWord(ctx, word, maxWidth) {
const chunks = [];
let current = "";
// iterates e, x, t, r, a, o, r, d, i, n, a, r, y
for (const char of word) {
// candidate = "" + "e" = "e"
const candidate = current + char;
if (measureTextWidth(ctx, candidate) <= maxWidth || current.length === 0) {
// if it fits, add char to current chunk
current = candidate;
} else {
chunks.push(current);
// start new chunk with current char
current = char;
}
}
// push any remaining text in current chunk
if (current.length > 0) {
chunks.push(current);
}
return chunks;
}
function wrapParagraph(ctx, paragraph, maxWidth) {
if (paragraph.length === 0) return [""];
const words = paragraph.split(" ").filter(Boolean);
const lines = [];
let line = "";
words.forEach((word) => {
// candidate = "" + "e" = "e" if line is empty, candidate is just the word, otherwise it's line + space + word
const candidate = line.length ? `${line} ${word}` : word;
// check if adding the word exceeds the max width
if (measureTextWidth(ctx, candidate) <= maxWidth) {
line = candidate;
return;
}
// If the current line has content, push it before starting a new line
if (line.length) {
lines.push(line);
}
// If the word itself is too wide, break it into chunks
if (measureTextWidth(ctx, word) > maxWidth) {
// If the word is too long, break it into chunks
const chunks = breakLongWord(ctx, word, maxWidth);
// Push all chunks except the last one as separate lines
lines.push(...chunks.slice(0, -1));
// Start the new line with the last chunk
line = chunks[chunks.length - 1] || "";
} else {
// Start a new line with the current word if it fits on its own
line = word;
}
});
// Push any remaining line content if it exists or
// if there were no lines at all (to handle empty paragraphs)
if (line.length || lines.length === 0) {
lines.push(line);
}
return lines;
}
// Main function to wrap text for the textarea
function wrapTextToTextarea(text, textarea) {
if (!textarea || typeof text !== "string" || text.length === 0) return text;
const contentWidth = getTextareaContentWidth(textarea);
if (contentWidth <= 0) return text;
const ctx = getTextMeasureContext(textarea);
if (!ctx) return text;
// Split the text into paragraphs and wrap each one separately to preserve line breaks
const paragraphs = text.split("\n");
const wrappedLines = [];
// Wrap each paragraph and add a line break between them
// loop through each paragraph, wrap it, and add the wrapped lines to the result.
// If it's not the last paragraph,
// add an empty line to preserve the original line break.
paragraphs.forEach((paragraph, index) => {
// Wrap the current paragraph and add the wrapped lines to the result
const lines = wrapParagraph(ctx, paragraph, contentWidth);
// Add the wrapped lines to the result array
wrappedLines.push(...lines);
// paragraphs.length = 4
// paragraphs.length - 1 = 3
// Check: 2 < 3 -> true
// paragraphs.length = 3
// paragraphs.length - 1 = 2
// Check: 2 < 2 -> false (this is the last paragraph)
if (index < paragraphs.length - 1) {
// Add an empty line to preserve the original line break between paragraphs
wrappedLines.push("");
}
});
// Join all the wrapped lines into a single string with line breaks and return it
return wrappedLines.join("\n");
}
function applyPassageWrapping() {
if (!passageDisplay || !gameState.currentPassage) {
gameState.passageLines = gameState.currentPassage
? gameState.currentPassage.split("\n")
: [];
console.log(
"passageLines length:",
gameState.passageLines.length,
gameState.passageLines,
);
return;
}
const wrapped = wrapTextToTextarea(gameState.currentPassage, passageDisplay);
gameState.currentPassage = wrapped;
gameState.passageLines = wrapped.split("\n");
}
function moveToNextLine() {
const lines = userInput.value.split("\n");
// Prevent duplicate newlines
// When user types the last character of the current line,
// we want to move to the next line.
if (lines.length - 1 === gameState.currentLineIndex) {
// console.log("Moving to next line");
userInput.value += "\n";
}
// Increment the current line index to move to the next line
gameState.currentLineIndex++;
// Move cursor to end
userInput.selectionStart = userInput.selectionEnd = userInput.value.length;
}
document.addEventListener("DOMContentLoaded", () => {
// ✅ INITIALIZE LOCALSTORAGE ON PAGE LOAD
const storedBest = localStorage.getItem(PERSONAL_BEST_KEY);
if (!storedBest) {
localStorage.setItem(PERSONAL_BEST_KEY, "0");
}
renderPassagePreview();
// ✅ NOW set up the input listener
if (userInput) {
userInput.addEventListener("input", () => {
const currentLength = userInput.value.length;
gameState.typedText = userInput.value;
// Start the timer on the first keystroke if it's not already running
if (
gameState.isTestActive &&
!gameState.timerRunning &&
currentLength > 0
) {
if (gameState.mode === "timed") {
startTimedMode();
} else if (gameState.mode === "passage") {
startPassageMode();
}
}
gameState.normalizedTypedText = normalizeForCompare(
userInput.value,
).toLocaleLowerCase();
// Live scoring uses raw input to preserve line breaks.
const liveTyped = userInput.value;
const liveTarget = gameState.currentPassage;
const liveDenominator = liveTyped.length;
// It resizes the perIndexErrors array to match current typed length.
// Example:
// Before: perIndexErrors = [true, false] (length 2)
// liveDenominator = 5
// After perIndexErrors.length = 5:
// perIndexErrors = [true, false, empty, empty, empty]
if (gameState.perIndexErrors.length < liveDenominator) {
gameState.perIndexErrors.length = liveDenominator;
}
for (let i = 0; i < liveDenominator; i++) {
const typedChar = liveTyped[i] || "";
const targetChar = liveTarget[i] || "";
if (typedChar !== targetChar) {
gameState.perIndexErrors[i] = true; // never reset to false
}
}
buildVisualFeedback();
// It removes whitespace only at the start and end.
if (liveTyped.length > 0 && liveTyped.trim().length === 0) {
// If the user has typed something but it's all whitespace, mark all those indices as errors
for (let i = 0; i < liveDenominator; i++) {
gameState.perIndexErrors[i] = true;
}
}
const incorrectCount = gameState.perIndexErrors
.slice(0, liveDenominator)
.filter(Boolean).length;
gameState.totalErrors = incorrectCount;
const correctChars = liveDenominator - incorrectCount;
gameState.accuracy =
liveDenominator === 0
? 0
: Math.round((correctChars / liveDenominator) * 100);
document.querySelectorAll(".accuracy").forEach((el) => {
el.textContent = `${gameState.accuracy}%`; // Display the calculated accuracy percentage
});
document.querySelectorAll(".characters").forEach((e) => {
e.textContent = `${correctChars} / ${incorrectCount}`;
});
document.querySelectorAll(".wpm").forEach((el) => {
el.textContent = calculateWpm(gameState.typedText);
});
// Sync scroll position between both textareas
// passageDisplay.scrollTop = userInput.scrollTop;
// passageDisplay.scrollLeft = userInput.scrollLeft;
document.querySelector("#visual-feedback").scrollTop =
userInput.scrollTop;
document.querySelector("#visual-feedback").scrollLeft =
userInput.scrollLeft;
if (
gameState.isTestActive &&
currentLength > previousLength &&
(gameState.mode === "timed" || gameState.mode === "passage")
) {
calculateWpm(gameState.typedText);
}
if (currentLength < previousLength) {
// Handle backspace or deletion
// Optionally, you can recalculate WPM here if desired
calculateWpm(gameState.typedText);
}
previousLength = currentLength;
console.log(gameState.typedText);
// Only Normalize user input and passage for comparison
const normalizedTyped = normalizeForCompare(userInput.value);
const normalizedPassage = normalizeForCompare(gameState.currentPassage);
console.log(
`User typed (normalized): "${normalizedTyped}" (${normalizedTyped.length} chars)`,
);
console.log(
`Passage (normalized): "${normalizedPassage}" (${normalizedPassage.length} chars)`,
);
// Compare the normalized texts
if (
normalizedTyped.length >= normalizedPassage.length &&
gameState.isTestActive
) {
endTest();
}
const passageLines = gameState.passageLines;
const typedLines = userInput.value.split("\n");
// ) Determine current line and compare with the corresponding passage line
const currentLine = passageLines[gameState.currentLineIndex] || "";
const typedLine = typedLines[gameState.currentLineIndex] || "";
// Normalize both lines for comparison
const expectedLine = normalizeLine(currentLine);
const typedLineNormalized = normalizeLine(typedLine);
// Auto-advance when the line is fully matched
if (
expectedLine.length > 0 &&
typedLineNormalized.length >= expectedLine.length
) {
const isExactMatch =
typedLineNormalized === expectedLine &&
typedLineNormalized.length === expectedLine.length;
// Normalize current line for comparison
if (typedLine.length > expectedLine.length) {
const overflow = typedLine.slice(expectedLine.length);
typedLines[gameState.currentLineIndex] = currentLine;
if (gameState.currentLineIndex < gameState.passageLines.length - 1) {
const nextIndex = gameState.currentLineIndex + 1;
typedLines[nextIndex] = `${overflow}${typedLines[nextIndex] || ""}`;
}
userInput.value = typedLines.join("\n");
gameState.typedText = userInput.value;
}
}
const hasTab = /\t/.test(typedLine);
const isOnlySpaces = typedLine.length > 0 && /^ +$/.test(typedLine);
const hasLettersOrDigits = /[A-Za-z0-9]/.test(typedLine);
const hasSpace = / /.test(typedLine);
const isMixedTextAndSpaces = hasLettersOrDigits && hasSpace;
const isShorter = typedLine.length < expectedLine.length;
const isExact = typedLine.length === expectedLine.length;
const isLonger = typedLine.length > expectedLine.length;
const isLineLengthReached = typedLine.length === expectedLine.length; // strict
const isLineExact = typedLineNormalized === expectedLine;
const isFullPassageTyped =
gameState.isTestActive && normalizedTyped === normalizedPassage;
const typedAllSpaces =
userInput.value.length > 0 && /^[ ]+$/.test(userInput.value);
const fullLengthMatch =
userInput.value.length === gameState.currentPassage.length;
const finishOrAdvance = ({ allowEndWithoutExact = false } = {}) => {
const isLastLine =
gameState.currentLineIndex >= gameState.passageLines.length - 1;
if (isLastLine) {
if (isFullPassageTyped || allowEndWithoutExact) endTest();
return;
}
moveToNextLine();
};
if (isLineExact) {
finishOrAdvance();
return;
}
if (isOnlySpaces && isLineLengthReached) {
finishOrAdvance({ allowEndWithoutExact: true });
return;
}
if (isMixedTextAndSpaces && isLineLengthReached) {
finishOrAdvance({ allowEndWithoutExact: true });
return;
}
// Keep one strict error metric source
});
}
// Set the first difficulty button as active by default
const firstDifficultyButton = document.querySelector(
".difficulty-settings button",
);
if (firstDifficultyButton) {
firstDifficultyButton.classList.add("active");
gameState.difficulty =
firstDifficultyButton.textContent.toLocaleLowerCase();
}
// Set the first mode button as active by default
const firstModeButton = document.querySelector(".mode-settings button");
if (firstModeButton) {
firstModeButton.classList.add("active");
gameState.mode = firstModeButton.textContent.includes("Timed")
? "timed"
: "passage";
}
});
// Simplified WPM calculation
function calculateWpm(typedText) {
if (typeof typedText !== "string") {
return 0; // Handle non-string input gracefully
}
if (!gameState.timerStartTime) {
return 0; // Timer guard If gameState.timerStartTime is missing, return 0.
}
const elapsedSeconds = Math.floor(
(Date.now() - gameState.timerStartTime) / 1000,
);
if (elapsedSeconds < 1) {
// document.querySelectorAll(".wpm").forEach((el) => {
// el.textContent = "0";
// });