Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
817 lines (728 loc) · 29.6 KB
/
Copy pathindex.html
File metadata and controls
817 lines (728 loc) · 29.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TypeTest</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #323437;
--sub: #646669;
--text: #d1d0c5;
--accent: #e2b714;
--error: #ca4754;
--correct: #d1d0c5;
--caret: #e2b714;
}
body {
background: var(--bg);
color: var(--sub);
font-family: 'Roboto Mono', 'Courier New', monospace;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
user-select: none;
}
/* ── Header ── */
header {
width: 100%;
max-width: 960px;
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 2.2rem;
flex-wrap: wrap;
gap: 1rem;
}
.logo {
font-size: 1.5rem;
font-weight: 700;
color: var(--accent);
letter-spacing: 2px;
}
.logo span { color: var(--text); }
/* ── Language switcher ── */
.lang-switcher {
display: flex;
gap: 0;
border: 1px solid var(--sub);
border-radius: 8px;
overflow: hidden;
}
.lang-btn {
background: transparent;
border: none;
color: var(--sub);
font-family: inherit;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 1px;
padding: 0.35rem 1rem;
cursor: pointer;
text-transform: uppercase;
transition: background 0.18s, color 0.18s;
border-radius: 0;
}
.lang-btn:first-child {
border-right: 1px solid var(--sub);
}
.lang-btn.active {
background: var(--accent);
color: var(--bg);
}
.lang-btn:not(.active):hover {
background: rgba(100,102,105,0.25);
color: var(--text);
}
/* ── Stats bar ── */
.stats-bar {
display: flex;
gap: 2rem;
align-items: baseline;
}
.stat {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
}
.stat-label {
font-size: 0.6rem;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--sub);
}
.stat-value {
font-size: 1.35rem;
font-weight: 700;
color: var(--accent);
min-width: 2.5ch;
text-align: center;
}
.stat-value.pb {
color: var(--text);
font-size: 0.95rem;
}
#timer {
font-size: 2.1rem;
font-weight: 700;
color: var(--accent);
min-width: 2.5ch;
text-align: left;
transition: color 0.3s;
}
#timer.urgent { color: var(--error); }
/* ── Sub-header row (lang + center) ── */
.toolbar {
width: 100%;
max-width: 960px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 1.4rem;
}
/* ── Test area ── */
.test-wrapper {
width: 100%;
max-width: 960px;
position: relative;
}
#words-container {
font-size: 1.5rem;
line-height: 2.5rem;
color: var(--sub);
position: relative;
height: calc(2.5rem * 3);
overflow: hidden;
cursor: text;
outline: none;
-webkit-tap-highlight-color: transparent;
}
#words {
position: absolute;
top: 0;
left: 0;
transition: top 0.15s ease;
width: 100%;
}
.word {
display: inline-flex;
margin: 0 0.4rem 0 0;
position: relative;
}
.word.error-word::after {
content: '';
position: absolute;
bottom: 2px;
left: 0; right: 0;
height: 2px;
background: var(--error);
border-radius: 1px;
}
.letter { position: relative; }
.letter.correct { color: var(--correct); }
.letter.incorrect { color: var(--error); }
.letter.extra { color: var(--error); opacity: 0.8; }
/* ── Caret ── */
#caret {
position: absolute;
width: 2px;
height: 1.6rem;
background: var(--caret);
border-radius: 1px;
top: 0; left: 0;
pointer-events: none;
transition: left 0.06s ease, top 0.1s ease;
animation: blink 1.1s step-start infinite;
box-shadow: 0 0 6px var(--caret);
}
#caret.typing { animation: none; opacity: 1; }
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
#hidden-input {
position: absolute;
opacity: 0; pointer-events: none;
width: 1px; height: 1px;
top: 0; left: 0;
}
/* ── Result screen ── */
#result-screen {
display: none;
flex-direction: column;
align-items: center;
gap: 1.5rem;
text-align: center;
animation: fadeIn 0.4s ease;
}
#result-screen.visible { display: flex; }
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.result-title {
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 3px;
color: var(--sub);
}
.result-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2rem 3.5rem;
}
.result-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.result-label {
font-size: 0.6rem;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--sub);
}
.result-val {
font-size: 3rem;
font-weight: 700;
color: var(--accent);
line-height: 1;
}
.result-val.secondary {
font-size: 2rem;
color: var(--text);
}
.pb-badge {
font-size: 0.75rem;
color: var(--accent);
letter-spacing: 1px;
text-transform: uppercase;
background: rgba(226,183,20,0.12);
padding: 3px 10px;
border-radius: 5px;
}
/* ── Buttons ── */
.btn-row {
display: flex;
gap: 1rem;
margin-top: 0.5rem;
}
button {
background: transparent;
border: 1px solid var(--sub);
color: var(--sub);
font-family: inherit;
font-size: 0.82rem;
padding: 0.45rem 1.3rem;
border-radius: 6px;
cursor: pointer;
letter-spacing: 1px;
text-transform: uppercase;
transition: background 0.18s, color 0.18s, border-color 0.18s;
}
button:hover { background: var(--sub); color: var(--bg); }
button.primary { border-color: var(--accent); color: var(--accent); }
button.primary:hover { background: var(--accent); color: var(--bg); }
.hint {
margin-top: 1.2rem;
font-size: 0.68rem;
color: var(--sub);
opacity: 0.45;
letter-spacing: 1px;
text-align: center;
}
@media (max-width: 640px) {
#words-container { font-size: 1.1rem; line-height: 2rem; height: calc(2rem * 3); }
.result-val { font-size: 2.2rem; }
.result-grid { gap: 1.5rem 2rem; }
header { justify-content: center; }
}
</style>
</head>
<body>
<header>
<div class="logo">type<span>test</span></div>
<!-- Language switcher -->
<div class="lang-switcher">
<button class="lang-btn active" id="btn-en">EN</button>
<button class="lang-btn" id="btn-ru">RU</button>
</div>
<!-- Live stats -->
<div class="stats-bar">
<div class="stat">
<span class="stat-label">timer</span>
<span class="stat-value" id="timer">30</span>
</div>
<div class="stat">
<span class="stat-label">wpm</span>
<span class="stat-value" id="live-wpm">–</span>
</div>
<div class="stat">
<span class="stat-label">pb</span>
<span class="stat-value pb" id="pb-display">–</span>
</div>
</div>
</header>
<!-- ── Test area ── -->
<div class="test-wrapper" id="test-area">
<div id="words-container" tabindex="0">
<div id="words"></div>
<div id="caret"></div>
</div>
<input id="hidden-input" type="text"
autocomplete="off" autocorrect="off"
autocapitalize="off" spellcheck="false" />
<div class="btn-row" style="margin-top:1.2rem; justify-content:center;">
<button class="primary" id="restart-btn">↺ Restart</button>
</div>
<p class="hint">press <strong>Tab</strong> to restart</p>
</div>
<!-- ── Result screen ── -->
<div id="result-screen">
<div class="result-title" id="res-title">results</div>
<div class="result-grid">
<div class="result-item">
<span class="result-label">wpm</span>
<span class="result-val" id="res-wpm">0</span>
</div>
<div class="result-item">
<span class="result-label">accuracy</span>
<span class="result-val secondary" id="res-acc">0%</span>
</div>
<div class="result-item">
<span class="result-label">correct</span>
<span class="result-val secondary" id="res-correct">0</span>
</div>
<div class="result-item">
<span class="result-label">incorrect</span>
<span class="result-val secondary" id="res-incorrect">0</span>
</div>
<div class="result-item">
<span class="result-label">time</span>
<span class="result-val secondary">30s</span>
</div>
<div class="result-item">
<span class="result-label">personal best</span>
<span class="result-val secondary" id="res-pb">–</span>
</div>
</div>
<div id="pb-badge" class="pb-badge" style="display:none;">🏆 New Personal Best!</div>
<div class="btn-row">
<button class="primary" id="result-restart-btn">↺ Try Again</button>
</div>
<p class="hint">press <strong>Tab</strong> to restart</p>
</div>
<script>
(function () {
'use strict';
/* ═══════════════════════════════════════════════
WORD POOLS
═══════════════════════════════════════════════ */
const WORDS_EN = [
// common function words
'the','be','to','of','and','a','in','that','have','it','for','not','on','with',
'he','as','you','do','at','this','but','his','by','from','they','we','say','her',
'she','or','an','will','my','one','all','would','there','their','what','so','up',
'out','if','about','who','get','which','go','me','when','make','can','like','time',
'no','just','him','know','take','people','into','year','your','good','some','could',
'them','see','other','than','then','now','look','only','come','its','over','think',
'also','back','after','use','two','how','our','work','first','well','way','even',
'new','want','because','any','these','give','day','most','us','great','between',
'need','large','often','hand','high','place','hold','turn','move','live','where',
'much','before','line','right','mean','old','same','tell','follow','came','show',
'around','form','small','set','put','end','does','another','home','read','number',
'off','always','try','kind','again','change','away','animal','house','point','page',
'letter','mother','answer','found','study','still','learn','should','world','near',
'build','self','earth','father','keep','tree','never','start','city','grow','carry',
'state','once','book','hear','stop','without','second','late','miss','idea','body',
'music','color','stand','sun','question','fish','area','mark','dog','horse','birds',
'problem','complete','room','knew','since','ever','piece','told','usually','didn',
'friends','easy','heard','order','red','door','sure','become','top','ship','across',
'today','during','short','better','best','however','low','hours','black','products',
'happened','whole','measure','remember','early','waves','reached','listen','wind',
'rock','space','covered','fast','several','hold','himself','toward','five','step',
'morning','passed','vowel','true','hundred','against','pattern','numeral','table',
'north','slowly','money','map','farm','pulled','draw','voice','power','town','fine',
'drive','led','buy','age','effect','yes','hot','ball','stood','wave','drop','heart',
'ring','am','third','shall','held','hair','describe','cook','floor','either','result',
'burn','hill','safe','catch','present','horse','check','game','shape','equate','miss',
'brought','heat','snow','tire','bring','yes','distant','fill','east','paint','language',
'among','grand','ball','yet','wave','drop','heart','ring'
];
const WORDS_RU = [
// самые частотные слова русского языка
'и','в','не','он','на','я','что','тот','быть','с',
'а','весь','это','как','она','по','но','они','к','из',
'у','же','вы','за','бы','по','только','ее','мне','было',
'вот','от','меня','еще','нет','о','из','ему','теперь','когда',
'даже','ну','вдруг','ли','если','уже','или','ни','быть','один',
'почти','моё','тем','чтобы','нее','кажется','сейчас','было','потом','этого',
'надо','ней','нас','про','всего','них','какой','когда','уже','всю',
'между','видеть','идти','думать','знать','первый','всё','такой','где','же',
'можно','после','тут','при','хотя','должен','каждый','дело','сам','раз',
'чуть','более','хотеть','время','год','рука','говорить','два','нет','сказать',
'место','понять','потому','конечно','жизнь','потому','давать','день','слово',
'свой','знать','стать','самый','перед','тоже','под','дать','человек','добрый',
'большой','белый','старый','высокий','новый','любить','жить','работать','ходить',
'видеть','слышать','стоять','писать','читать','помнить','сказать','делать','спать',
'ехать','идти','бежать','лететь','плыть','строить','купить','продать','найти',
'взять','поднять','опустить','открыть','закрыть','начать','кончить','помочь',
'понять','узнать','решить','думать','верить','любить','жалеть','бояться',
'радоваться','улыбаться','плакать','смеяться','говорить','молчать','кричать',
'просить','ждать','отвечать','спрашивать','объяснять','рассказывать','учить',
'забыть','вспомнить','хотеть','мочь','знать','уметь','успеть','стараться',
'город','дом','дорога','лес','поле','река','море','гора','небо','земля',
'солнце','луна','звезда','вода','огонь','ветер','снег','дождь','цветок',
'дерево','книга','стол','стул','окно','дверь','школа','работа','семья',
'друг','мать','отец','сын','дочь','брат','сестра','дед','бабушка','ребёнок',
'время','день','ночь','утро','вечер','год','месяц','неделя','час','минута',
'хлеб','вода','чай','молоко','мясо','рыба','яблоко','тарелка','ложка','нож',
'красивый','умный','добрый','злой','быстрый','медленный','тихий','громкий',
'далёкий','близкий','лёгкий','тяжёлый','холодный','тёплый','мягкий','твёрдый',
'интересный','скучный','весёлый','грустный','свободный','занятый','важный','нужный',
'русский','великий','простой','сложный','общий','разный','последний','следующий',
'добро','зло','правда','ложь','любовь','дружба','надежда','вера','мир','война',
'счастье','горе','радость','страх','сила','слабость','красота','мудрость','свобода'
];
/* ═══════════════════════════════════════════════
CONFIG
═══════════════════════════════════════════════ */
const TEST_DURATION = 30;
const WORD_COUNT = 60;
/* ═══════════════════════════════════════════════
STATE
═══════════════════════════════════════════════ */
let currentLang = 'en';
let words = [];
let wordEls = [];
let letterEls = [];
let wordIndex = 0;
let letterIndex = 0;
let totalTyped = 0;
let correctChars = 0;
let incorrectChars = 0;
let wrongWordFlags = [];
let extraLetters = [];
let timerInterval = null;
let timeLeft = TEST_DURATION;
let started = false;
let finished = false;
let lastCaretRow = 0;
/* ═══════════════════════════════════════════════
DOM REFS
═══════════════════════════════════════════════ */
const wordsDiv = document.getElementById('words');
const wordsCont = document.getElementById('words-container');
const caretEl = document.getElementById('caret');
const hiddenInput = document.getElementById('hidden-input');
const timerEl = document.getElementById('timer');
const liveWpmEl = document.getElementById('live-wpm');
const pbDisplayEl = document.getElementById('pb-display');
const testArea = document.getElementById('test-area');
const resultScreen = document.getElementById('result-screen');
const resWpmEl = document.getElementById('res-wpm');
const resAccEl = document.getElementById('res-acc');
const resCorrectEl = document.getElementById('res-correct');
const resIncorrectEl = document.getElementById('res-incorrect');
const resPbEl = document.getElementById('res-pb');
const pbBadgeEl = document.getElementById('pb-badge');
const btnEn = document.getElementById('btn-en');
const btnRu = document.getElementById('btn-ru');
/* ═══════════════════════════════════════════════
PERSONAL BEST (per-language)
═══════════════════════════════════════════════ */
function pbKey () { return 'typetest_pb_' + currentLang; }
function getPB () { return parseInt(localStorage.getItem(pbKey()) || '0', 10); }
function savePB (v) { localStorage.setItem(pbKey(), String(v)); }
function updatePbDisplay () {
const pb = getPB();
pbDisplayEl.textContent = pb ? pb + ' wpm' : '–';
}
/* ═══════════════════════════════════════════════
LANGUAGE SWITCH
═══════════════════════════════════════════════ */
function setLang (lang) {
currentLang = lang;
btnEn.classList.toggle('active', lang === 'en');
btnRu.classList.toggle('active', lang === 'ru');
// For Russian, switch to a system monospace that handles Cyrillic well
wordsCont.style.fontFamily = lang === 'ru'
? "'Courier New', 'DejaVu Sans Mono', monospace"
: "'Roboto Mono', 'Courier New', monospace";
resetTest();
}
btnEn.addEventListener('click', () => setLang('en'));
btnRu.addEventListener('click', () => setLang('ru'));
/* ═══════════════════════════════════════════════
BUILD WORD LIST & DOM
═══════════════════════════════════════════════ */
function pickWords () {
const pool = currentLang === 'ru' ? WORDS_RU : WORDS_EN;
const result = [];
for (let i = 0; i < WORD_COUNT; i++) {
result.push(pool[Math.floor(Math.random() * pool.length)]);
}
return result;
}
function buildDOM () {
wordsDiv.innerHTML = '';
wordEls = [];
letterEls = [];
extraLetters = [];
wrongWordFlags = [];
words.forEach((word, wi) => {
const wordEl = document.createElement('span');
wordEl.className = 'word';
const letters = [];
for (const ch of word) {
const lEl = document.createElement('span');
lEl.className = 'letter';
lEl.textContent = ch;
wordEl.appendChild(lEl);
letters.push(lEl);
}
wordsDiv.appendChild(wordEl);
wordEls.push(wordEl);
letterEls.push(letters);
extraLetters.push([]);
wrongWordFlags.push(false);
if (wi < WORD_COUNT - 1) {
const sp = document.createElement('span');
sp.className = 'word-space';
sp.textContent = ' ';
wordsDiv.appendChild(sp);
}
});
}
/* ═══════════════════════════════════════════════
CARET
═══════════════════════════════════════════════ */
function moveCaret () {
const letters = letterEls[wordIndex];
const extras = extraLetters[wordIndex];
const contRect = wordsCont.getBoundingClientRect();
let ref, side;
if (extras.length > 0) {
ref = extras[extras.length - 1];
side = 'right';
} else if (letterIndex < letters.length) {
ref = letters[letterIndex];
side = 'left';
} else if (letters.length > 0) {
ref = letters[letters.length - 1];
side = 'right';
} else return;
const r = ref.getBoundingClientRect();
caretEl.style.left = (r[side] - contRect.left) + 'px';
caretEl.style.top = (r.top - contRect.top + (r.height - caretEl.offsetHeight) / 2) + 'px';
scrollIfNeeded();
}
function scrollIfNeeded () {
const caretTop = parseFloat(caretEl.style.top) || 0;
const lineH = parseFloat(getComputedStyle(wordsCont).lineHeight) || 40;
const currentRow = Math.round(caretTop / lineH);
if (currentRow > 1 && currentRow !== lastCaretRow) {
wordsDiv.style.top = (parseFloat(wordsDiv.style.top || '0') - lineH) + 'px';
lastCaretRow = currentRow;
}
}
/* ═══════════════════════════════════════════════
TIMER
═══════════════════════════════════════════════ */
function startTimer () {
if (started) return;
started = true;
timerInterval = setInterval(() => {
timeLeft--;
timerEl.textContent = timeLeft;
if (timeLeft <= 10) timerEl.classList.add('urgent');
const elapsed = TEST_DURATION - timeLeft;
if (elapsed > 0) liveWpmEl.textContent = Math.round((correctChars / 5) / (elapsed / 60));
if (timeLeft <= 0) endTest();
}, 1000);
}
/* ═══════════════════════════════════════════════
INPUT
═══════════════════════════════════════════════ */
function handleKey (e) {
if (finished) return;
const key = e.key;
if (key === 'Tab') { e.preventDefault(); resetTest(); return; }
if (!started && key.length === 1) startTimer();
caretEl.classList.add('typing');
clearTimeout(caretEl._bt);
caretEl._bt = setTimeout(() => caretEl.classList.remove('typing'), 1000);
if (key === 'Backspace') handleBackspace();
else if (key === ' ') handleSpace();
else if (key.length === 1) handleChar(key);
moveCaret();
}
function handleChar (ch) {
const letters = letterEls[wordIndex];
const extras = extraLetters[wordIndex];
totalTyped++;
if (letterIndex < letters.length) {
const ok = ch === words[wordIndex][letterIndex];
letters[letterIndex].className = 'letter ' + (ok ? 'correct' : 'incorrect');
if (ok) correctChars++; else { incorrectChars++; wrongWordFlags[wordIndex] = true; }
letterIndex++;
} else {
const s = document.createElement('span');
s.className = 'letter extra';
s.textContent = ch;
wordEls[wordIndex].appendChild(s);
extras.push(s);
incorrectChars++;
wrongWordFlags[wordIndex] = true;
}
}
function handleBackspace () {
const letters = letterEls[wordIndex];
const extras = extraLetters[wordIndex];
if (extras.length > 0) {
extras.pop().remove();
incorrectChars = Math.max(0, incorrectChars - 1);
} else if (letterIndex > 0) {
letterIndex--;
letters[letterIndex].className = 'letter';
incorrectChars = Math.max(0, incorrectChars - 1);
} else if (wordIndex > 0) {
wordIndex--;
letterIndex = words[wordIndex].length;
recalcWrongFlag(wordIndex);
}
}
function recalcWrongFlag (wi) {
const wrong = letterEls[wi].some(l => l.classList.contains('incorrect'))
|| extraLetters[wi].length > 0;
wrongWordFlags[wi] = wrong;
wordEls[wi].classList.toggle('error-word', wrong);
}
function handleSpace () {
if (letterIndex === 0) return;
const letters = letterEls[wordIndex];
for (let i = letterIndex; i < letters.length; i++) {
if (!letters[i].classList.contains('correct') && !letters[i].classList.contains('incorrect')) {
letters[i].classList.add('incorrect');
wrongWordFlags[wordIndex] = true;
incorrectChars++;
}
}
wordEls[wordIndex].classList.toggle('error-word', wrongWordFlags[wordIndex]);
correctChars++;
wordIndex++;
letterIndex = 0;
if (wordIndex >= WORD_COUNT) endTest();
}
/* ═══════════════════════════════════════════════
END TEST
═══════════════════════════════════════════════ */
function endTest () {
clearInterval(timerInterval);
finished = true;
hiddenInput.blur();
const wpm = Math.round((correctChars / 5) / (TEST_DURATION / 60));
const total = correctChars + incorrectChars;
const acc = total > 0 ? Math.round((correctChars / total) * 100) : 100;
const pb = getPB();
const newPB = wpm > pb;
if (newPB) savePB(wpm);
testArea.style.display = 'none';
resultScreen.classList.add('visible');
resWpmEl.textContent = wpm;
resAccEl.textContent = acc + '%';
resCorrectEl.textContent = correctChars;
resIncorrectEl.textContent = incorrectChars;
resPbEl.textContent = (newPB ? wpm : getPB()) + ' wpm';
pbBadgeEl.style.display = newPB ? 'inline-block' : 'none';
updatePbDisplay();
}
/* ═══════════════════════════════════════════════
RESET
═══════════════════════════════════════════════ */
function resetTest () {
clearInterval(timerInterval);
finished = started = false;
timeLeft = TEST_DURATION;
wordIndex = letterIndex = totalTyped = correctChars = incorrectChars = lastCaretRow = 0;
timerEl.textContent = TEST_DURATION;
timerEl.classList.remove('urgent');
liveWpmEl.textContent = '–';
wordsDiv.style.top = '0';
words = pickWords();
buildDOM();
moveCaret();
resultScreen.classList.remove('visible');
testArea.style.display = '';
hiddenInput.value = '';
hiddenInput.focus();
wordsCont.focus();
updatePbDisplay();
}
/* ═══════════════════════════════════════════════
EVENT LISTENERS
═══════════════════════════════════════════════ */
wordsCont.addEventListener('click', () => hiddenInput.focus());
hiddenInput.addEventListener('keydown', handleKey);
wordsCont.addEventListener('keydown', e => {
if (e.key === 'Tab') { e.preventDefault(); resetTest(); return; }
hiddenInput.focus();
});
document.addEventListener('keydown', e => {
if (e.key === 'Tab') { e.preventDefault(); resetTest(); }
});
document.getElementById('restart-btn').addEventListener('click', resetTest);
document.getElementById('result-restart-btn').addEventListener('click', resetTest);
/* ── Init ── */
resetTest();
requestAnimationFrame(() => requestAnimationFrame(moveCaret));
})();
</script>
</body>
</html>