Build a typing speed test: random paragraph, live WPM and ac
Test your typing speed with live WPM, accuracy, mistake highlighting and a results chart
Build a typing speed test: random paragraph, live WPM and accuracy, highlight correct and wrong letters, 60-second timer, results screen with a WPM chart, best score saved.Build this with Ergo →
Live result
Open full screen ↗How Ergo built it
Ergo made a plan first, then worked through it step by step:
- Plan UI and typing-test logic
- Create index.html with test and results screens
- Style polished dark UI in style.css
- Implement typing engine, timer, live stats in script.js
- Add WPM chart and localStorage best score
- Verify files and interactions
Ergo's answer
I'll build a complete single-page typing test with a random paragraph, per-letter feedback, live stats, a 60-second timer, a canvas results chart, and persistent best scores.
The layout and styling are ready. I’m now wiring the typing engine, precise timer, live metrics, results modal, chart, and saved best score.
The core test and results flow is implemented. I’m checking the full files now for interaction bugs, timer accuracy, chart rendering, and keyboard/mobile behavior before finalizing.
I found and fixed a few edge cases: the chart now scales correctly on narrow screens, the hidden “new best” badge cannot be overridden by CSS, and keyboard activation of buttons no longer gets swallowed. I’m adding touch-keyboard support and doing the final verification.
Final checks are clean. I’m making two last robustness tweaks: preventing duplicate input on mobile keyboards and keeping the time-progress bar consistent when a paragraph is completed early.
One last consistency fix: accuracy now reflects all keystrokes, so the displayed mistake count and accuracy percentage always agree—even after corrections.
Built TypeRush, a polished typing speed test with:
- 12 random paragraphs with no immediate repeats
- Live WPM, accuracy, character count, and 60-second countdown
- Per-letter highlighting — green for correct, red for mistakes, plus a blinking cursor
- Results screen with final WPM, accuracy, mistakes, consistency, and a canvas WPM chart
- Persistent best score using
localStorage, with a “New personal best” badge - Backspace corrections, restart, new-text controls, sound toggle, keyboard shortcuts, and mobile support
Open index.html in the preview and click the paragraph to begin. The timer starts on your first letter. Press Esc to restart, or use the results screen to retry or load new text.
Files
index.html143 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeRush — 60 Second Typing Test</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="app-shell">
<header class="topbar">
<a class="brand" href="#" id="brandLink" aria-label="TypeRush home">
<span class="brand-mark">T</span>
<span>Type<span class="brand-accent">Rush</span></span>
</a>
<div class="header-actions">
<div class="best-pill" title="Your best score">
<span class="best-icon">🏆</span>
<span>Best</span>
<strong id="bestWpm">0</strong>
<span class="best-unit">WPM</span>
</div>
<button class="icon-button" id="soundToggle" type="button" aria-label="Toggle sound" title="Toggle sound">🔊</button>
</div>
</header>
<main>
<section class="hero">
<p class="eyebrow">60 SECOND CHALLENGE</p>
<h1>How fast do your fingers fly?</h1>
<p class="subtitle">Type the paragraph below. The clock starts on your first keystroke.</p>
</section>
<section class="stats-grid" aria-label="Live typing statistics">
<article class="stat-card stat-primary">
<span class="stat-label">Speed</span>
<div class="stat-value"><span id="wpm">0</span><small>WPM</small></div>
</article>
<article class="stat-card">
<span class="stat-label">Accuracy</span>
<div class="stat-value"><span id="accuracy">100</span><small>%</small></div>
</article>
<article class="stat-card">
<span class="stat-label">Time left</span>
<div class="stat-value"><span id="timer">60</span><small>s</small></div>
</article>
<article class="stat-card">
<span class="stat-label">Characters</span>
<div class="stat-value"><span id="charCount">0</span><small id="charTotal">/ 0</small></div>
</article>
</section>
<section class="test-card" id="testCard">
<div class="progress-track" aria-hidden="true">
<div class="progress-fill" id="progressFill"></div>
</div>
<div class="test-toolbar">
<div class="status-wrap">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Click the text or press any key to start</span>
</div>
<span class="difficulty" id="paragraphLabel">Paragraph 1</span>
</div>
<div class="typing-area" id="typingArea" tabindex="0" role="textbox" aria-label="Typing test paragraph" aria-describedby="typingHelp">
<div class="paragraph" id="paragraph"></div>
<textarea id="typeInput" class="type-input" rows="1" tabindex="-1" aria-hidden="true" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false"></textarea>
<div class="focus-overlay" id="focusOverlay">
<span class="focus-icon">⌨</span>
<strong>Click here to focus</strong>
<span>Start typing when you're ready</span>
</div>
</div>
<p class="sr-only" id="typingHelp">Type the displayed paragraph. Correct letters turn green, mistakes turn red. The test lasts 60 seconds.</p>
<div class="test-footer">
<div class="legend">
<span><i class="legend-swatch correct"></i>Correct</span>
<span><i class="legend-swatch incorrect"></i>Mistake</span>
<span class="shortcut"><kbd>Esc</kbd> to restart</span>
</div>
<div class="test-actions">
<button class="button button-ghost" id="newParagraphBtn" type="button">New text</button>
<button class="button button-secondary" id="restartBtn" type="button">↻ Restart</button>
</div>
</div>
</section>
<section class="tips-grid" aria-label="Typing tips">
<article><span>01</span><div><strong>Find your rhythm</strong><p>Steady typing beats short bursts of speed.</p></div></article>
<article><span>02</span><div><strong>Eyes on the text</strong><p>Look ahead instead of at your keyboard.</p></div></article>
<article><span>03</span><div><strong>Accuracy first</strong><p>Speed follows naturally once mistakes drop.</p></div></article>
</section>
</main>
<footer>Built for focus. No sign-up, no distractions.</footer>
</div>
<section class="results-screen" id="resultsScreen" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="resultsTitle">
<div class="results-card">
<button class="close-results" id="closeResultsBtn" type="button" aria-label="Close results">×</button>
<div class="results-heading">
<p class="eyebrow" id="resultsEyebrow">TIME'S UP</p>
<h2 id="resultsTitle">Nice run!</h2>
<p id="resultsMessage">Here's how you did.</p>
<div class="new-best" id="newBestBadge" hidden>★ New personal best!</div>
</div>
<div class="results-hero">
<div class="result-wpm">
<span id="finalWpm">0</span>
<small>WPM</small>
</div>
<div class="result-mini-grid">
<div><strong id="finalAccuracy">0%</strong><span>Accuracy</span></div>
<div><strong id="finalChars">0</strong><span>Correct chars</span></div>
<div><strong id="finalErrors">0</strong><span>Mistakes</span></div>
<div><strong id="finalConsistency">0%</strong><span>Consistency</span></div>
</div>
</div>
<div class="chart-section">
<div class="chart-heading">
<h3>Your speed over time</h3>
<span>Words per minute</span>
</div>
<div class="chart-wrap">
<canvas id="wpmChart" aria-label="Words per minute chart"></canvas>
<div class="chart-empty" id="chartEmpty" hidden>Not enough data to chart this run.</div>
</div>
</div>
<div class="results-actions">
<button class="button button-secondary" id="resultsNewTextBtn" type="button">Try new text</button>
<button class="button button-primary" id="resultsRetryBtn" type="button">↻ Test again</button>
</div>
</div>
</section>
<script src="./script.js"></script>
</body>
</html>style.css818 lines
:root {
--bg: #080b14;
--surface: rgba(18, 23, 39, 0.82);
--surface-solid: #121727;
--surface-raised: #181f33;
--border: rgba(148, 163, 184, 0.14);
--text: #edf2ff;
--muted: #8994ac;
--accent: #8b5cf6;
--accent-2: #6366f1;
--green: #34d399;
--green-bg: rgba(52, 211, 153, 0.13);
--red: #fb7185;
--red-bg: rgba(251, 113, 133, 0.18);
--yellow: #fbbf24;
--radius: 20px;
--shadow: 0 24px 80px rgba(0, 0, 0, 0.42);
}
* {
box-sizing: border-box;
}
[hidden] {
display: none !important;
}
html {
color-scheme: dark;
scroll-behavior: smooth;
}
body {
margin: 0;
min-height: 100vh;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
background:
radial-gradient(circle at 12% -10%, rgba(99, 102, 241, 0.2), transparent 35rem),
radial-gradient(circle at 95% 10%, rgba(139, 92, 246, 0.13), transparent 30rem),
var(--bg);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
button, a {
-webkit-tap-highlight-color: transparent;
}
button {
font: inherit;
}
button:focus-visible, a:focus-visible, [tabindex]:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 4px;
}
.app-shell {
width: min(1080px, calc(100% - 40px));
margin: 0 auto;
}
.topbar {
min-height: 84px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.brand {
display: inline-flex;
align-items: center;
gap: 11px;
color: var(--text);
text-decoration: none;
font-size: 21px;
font-weight: 800;
letter-spacing: -0.5px;
}
.brand-mark {
display: grid;
place-items: center;
width: 35px;
height: 35px;
border-radius: 11px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
box-shadow: 0 8px 24px rgba(139, 92, 246, 0.35);
font-size: 18px;
}
.brand-accent {
color: #a78bfa;
}
.header-actions {
display: flex;
align-items: center;
gap: 10px;
}
.best-pill {
display: flex;
align-items: center;
gap: 7px;
padding: 8px 13px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(18, 23, 39, 0.72);
color: var(--muted);
font-size: 13px;
}
.best-pill strong {
color: var(--text);
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.best-icon {
font-size: 14px;
}
.best-unit {
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
}
.icon-button {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface);
cursor: pointer;
font-size: 15px;
transition: border-color 160ms ease, transform 160ms ease;
}
.icon-button:hover {
border-color: rgba(167, 139, 250, 0.5);
transform: translateY(-1px);
}
.hero {
padding: 40px 0 28px;
text-align: center;
}
.eyebrow {
margin: 0 0 10px;
color: #a78bfa;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.19em;
}
.hero h1 {
margin: 0;
font-size: clamp(32px, 5vw, 52px);
line-height: 1.08;
letter-spacing: -0.045em;
}
.subtitle {
margin: 15px auto 0;
color: var(--muted);
font-size: 15px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 14px;
}
.stat-card {
padding: 18px 20px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--surface);
backdrop-filter: blur(16px);
}
.stat-primary {
background: linear-gradient(135deg, rgba(139, 92, 246, 0.19), rgba(99, 102, 241, 0.08));
border-color: rgba(139, 92, 246, 0.3);
}
.stat-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-value {
display: flex;
align-items: baseline;
gap: 7px;
font-size: 31px;
line-height: 1.2;
font-weight: 750;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.stat-value small {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0;
}
.stat-primary .stat-value {
color: #c4b5fd;
}
.test-card {
position: relative;
overflow: hidden;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
transition: border-color 200ms ease, box-shadow 200ms ease;
}
.test-card.is-active {
border-color: rgba(139, 92, 246, 0.44);
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.42), 0 0 0 4px rgba(139, 92, 246, 0.05);
}
.progress-track {
height: 3px;
background: rgba(148, 163, 184, 0.08);
}
.progress-fill {
width: 100%;
height: 100%;
transform-origin: left;
background: linear-gradient(90deg, var(--accent), #c084fc);
transition: transform 180ms linear;
}
.test-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 16px 24px;
border-bottom: 1px solid var(--border);
color: var(--muted);
font-size: 12px;
}
.status-wrap {
display: flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: #64748b;
}
.status-dot.running {
background: var(--green);
box-shadow: 0 0 0 4px rgba(52, 211, 153, 0.12);
animation: pulse 1.8s infinite;
}
.status-dot.finished {
background: var(--yellow);
}
.status-dot.finished + span {
cursor: pointer;
text-decoration: underline;
text-decoration-color: rgba(137, 148, 172, 0.35);
text-underline-offset: 3px;
}
@keyframes pulse {
50% { opacity: 0.45; }
}
.difficulty {
white-space: nowrap;
color: #b7c0d4;
}
.typing-area {
position: relative;
min-height: 270px;
padding: 32px 34px;
cursor: text;
}
.paragraph {
position: relative;
color: #59657c;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
font-size: clamp(18px, 2.25vw, 23px);
font-weight: 500;
line-height: 1.95;
letter-spacing: 0.015em;
overflow-wrap: anywhere;
user-select: none;
}
.char {
position: relative;
border-radius: 4px;
transition: color 70ms ease, background-color 70ms ease;
}
.char.correct {
color: #d1fae5;
background: var(--green-bg);
}
.char.incorrect {
color: #fecdd3;
background: var(--red-bg);
text-decoration: underline;
text-decoration-color: var(--red);
text-underline-offset: 5px;
}
.char.current {
color: #f8fafc;
}
.char.current::before {
content: "";
position: absolute;
left: -1px;
top: 13%;
width: 2px;
height: 74%;
border-radius: 3px;
background: #a78bfa;
animation: blink 1s step-end infinite;
}
@keyframes blink {
50% { opacity: 0; }
}
.type-input {
position: absolute;
left: 12px;
bottom: 8px;
width: 2px;
height: 2px;
padding: 0;
border: 0;
opacity: 0;
pointer-events: none;
resize: none;
}
.focus-overlay {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
background: rgba(8, 11, 20, 0.7);
backdrop-filter: blur(5px);
opacity: 0;
visibility: hidden;
transition: opacity 180ms ease, visibility 180ms ease;
cursor: pointer;
}
.typing-area:not(.is-focused) .focus-overlay.visible {
opacity: 1;
visibility: visible;
}
.focus-icon {
margin-bottom: 4px;
font-size: 27px;
}
.focus-overlay strong {
font-size: 16px;
}
.focus-overlay span:last-child {
color: var(--muted);
font-size: 13px;
}
.test-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 16px 22px;
border-top: 1px solid var(--border);
}
.legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
color: var(--muted);
font-size: 11px;
}
.legend > span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 10px;
height: 10px;
border-radius: 3px;
}
.legend-swatch.correct {
background: var(--green-bg);
border: 1px solid rgba(52, 211, 153, 0.45);
}
.legend-swatch.incorrect {
background: var(--red-bg);
border: 1px solid rgba(251, 113, 133, 0.45);
}
.shortcut {
margin-left: 4px;
}
kbd {
padding: 2px 5px;
border: 1px solid rgba(148, 163, 184, 0.24);
border-bottom-width: 2px;
border-radius: 5px;
background: rgba(148, 163, 184, 0.07);
color: #c4cddb;
font: inherit;
font-size: 10px;
}
.test-actions, .results-actions {
display: flex;
gap: 8px;
}
.button {
min-height: 40px;
padding: 9px 16px;
border: 1px solid transparent;
border-radius: 11px;
cursor: pointer;
font-weight: 700;
font-size: 12px;
transition: transform 150ms ease, background 150ms ease, border-color 150ms ease, box-shadow 150ms ease;
}
.button:hover {
transform: translateY(-1px);
}
.button:active {
transform: translateY(0);
}
.button-primary {
color: white;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
box-shadow: 0 8px 22px rgba(99, 102, 241, 0.24);
}
.button-primary:hover {
box-shadow: 0 10px 28px rgba(99, 102, 241, 0.36);
}
.button-secondary {
color: var(--text);
border-color: var(--border);
background: var(--surface-raised);
}
.button-secondary:hover {
border-color: rgba(167, 139, 250, 0.45);
}
.button-ghost {
color: var(--muted);
background: transparent;
}
.button-ghost:hover {
color: var(--text);
background: rgba(148, 163, 184, 0.06);
}
.tips-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
padding: 26px 4px 40px;
}
.tips-grid article {
display: flex;
gap: 12px;
}
.tips-grid article > span {
color: #6d5ca8;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 11px;
padding-top: 3px;
}
.tips-grid strong {
font-size: 12px;
}
.tips-grid p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.6;
}
footer {
padding: 20px 0 30px;
border-top: 1px solid var(--border);
color: #59657c;
text-align: center;
font-size: 11px;
}
.results-screen {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
padding: 24px;
overflow-y: auto;
background: rgba(4, 6, 12, 0.84);
backdrop-filter: blur(12px);
opacity: 0;
visibility: hidden;
transition: opacity 220ms ease, visibility 220ms ease;
}
.results-screen.open {
opacity: 1;
visibility: visible;
}
.results-card {
position: relative;
width: min(720px, 100%);
max-height: calc(100vh - 48px);
overflow-y: auto;
padding: 34px;
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 24px;
background:
radial-gradient(circle at 50% 0%, rgba(139, 92, 246, 0.13), transparent 24rem),
var(--surface-solid);
box-shadow: 0 32px 100px rgba(0, 0, 0, 0.6);
transform: translateY(14px) scale(0.985);
transition: transform 240ms ease;
}
.results-screen.open .results-card {
transform: translateY(0) scale(1);
}
.close-results {
position: absolute;
top: 16px;
right: 16px;
width: 34px;
height: 34px;
border: 1px solid var(--border);
border-radius: 10px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 22px;
line-height: 1;
}
.close-results:hover {
color: var(--text);
background: rgba(148, 163, 184, 0.07);
}
.results-heading {
text-align: center;
}
.results-heading h2 {
margin: 0;
font-size: 30px;
letter-spacing: -0.035em;
}
.results-heading > p:not(.eyebrow) {
margin: 7px 0 0;
color: var(--muted);
font-size: 13px;
}
.new-best {
display: inline-block;
margin-top: 12px;
padding: 6px 12px;
border: 1px solid rgba(251, 191, 36, 0.28);
border-radius: 999px;
color: #fde68a;
background: rgba(251, 191, 36, 0.1);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.03em;
}
.results-hero {
display: grid;
grid-template-columns: 0.85fr 1.5fr;
align-items: center;
gap: 24px;
margin: 28px 0;
padding: 24px;
border: 1px solid var(--border);
border-radius: 18px;
background: rgba(8, 11, 20, 0.36);
}
.result-wpm {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border-right: 1px solid var(--border);
}
.result-wpm > span {
background: linear-gradient(135deg, #ede9fe, #a78bfa);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
font-size: 70px;
line-height: 1;
font-weight: 800;
letter-spacing: -0.07em;
font-variant-numeric: tabular-nums;
}
.result-wpm small {
margin-top: 7px;
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
}
.result-mini-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
.result-mini-grid div {
display: flex;
flex-direction: column;
gap: 2px;
}
.result-mini-grid strong {
font-size: 23px;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.result-mini-grid span {
color: var(--muted);
font-size: 11px;
}
.chart-section {
padding: 4px 2px 0;
}
.chart-heading {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 14px;
}
.chart-heading h3 {
margin: 0;
font-size: 13px;
}
.chart-heading span {
color: var(--muted);
font-size: 10px;
}
.chart-wrap {
position: relative;
height: 190px;
}
#wpmChart {
display: block;
width: 100%;
height: 100%;
}
.chart-empty {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--muted);
font-size: 12px;
}
.results-actions {
justify-content: center;
margin-top: 26px;
}
.results-actions .button {
min-width: 140px;
min-height: 44px;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 720px) {
.app-shell { width: min(100% - 24px, 1080px); }
.topbar { min-height: 70px; }
.hero { padding: 28px 0 22px; }
.hero h1 { font-size: 34px; }
.subtitle { max-width: 330px; font-size: 13px; }
.stats-grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
.stat-card { padding: 13px 15px; }
.stat-value { font-size: 26px; }
.typing-area { min-height: 320px; padding: 24px 20px; }
.paragraph { font-size: 18px; line-height: 1.9; }
.test-toolbar { padding: 13px 17px; }
.test-footer { align-items: stretch; flex-direction: column; padding: 14px 17px; }
.test-actions { justify-content: flex-end; }
.shortcut { display: none; }
.tips-grid { grid-template-columns: 1fr; gap: 16px; }
.results-screen { padding: 12px; }
.results-card { padding: 28px 20px; max-height: calc(100vh - 24px); }
.results-hero { grid-template-columns: 1fr; gap: 22px; padding: 20px; }
.result-wpm { padding-bottom: 20px; border-right: 0; border-bottom: 1px solid var(--border); }
.result-wpm > span { font-size: 62px; }
.result-mini-grid { text-align: center; }
.chart-wrap { height: 160px; }
}
@media (max-width: 420px) {
.best-pill > span:not(.best-icon):not(.best-unit) { display: none; }
.best-pill { gap: 5px; }
.brand { font-size: 19px; }
.test-actions .button { padding-inline: 12px; }
.results-actions { flex-direction: column-reverse; }
.results-actions .button { width: 100%; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
scroll-behavior: auto !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}script.js621 lines
(() => {
"use strict";
const TEST_DURATION = 60;
const STORAGE_KEY = "typerush-best-v1";
const paragraphs = [
"The morning train slipped quietly through the valley, carrying sleepy travelers past fields painted gold by the rising sun. A conductor moved from carriage to carriage, greeting familiar faces and checking tickets with a practiced smile. Outside the window, small villages appeared and vanished in seconds, each one holding stories that the passengers would never know. For a brief moment, everyone on board shared the same direction, the same gentle rhythm, and the same peaceful suspension between where they had been and where they were going.",
"A good cup of coffee can turn an ordinary morning into a small ceremony. The sound of water heating, the rich smell of fresh grounds, and the first careful sip all invite us to slow down before the day gathers speed. Some people guard their recipe like a treasured secret, while others happily experiment with new beans and brewing methods. However you make it, the ritual offers a comforting reminder that simple pleasures are often the ones we remember most.",
"Deep in the forest, a narrow path curved around mossy stones and towering pine trees. Sunlight filtered through the branches in scattered beams, illuminating tiny insects that danced above the ferns. Every few steps revealed another detail: a bright mushroom beside a rotting log, a bird calling from an unseen perch, or the delicate pattern of a spider web stretched between two twigs. Walking there felt less like exercise and more like entering a living world that had been patiently waiting to be noticed.",
"Learning a new skill rarely follows a straight line. At first, every movement feels awkward and every mistake seems enormous, but small improvements quietly gather beneath the surface. Then one day, a task that once demanded complete concentration becomes almost effortless. The secret is not a sudden burst of talent but the willingness to return again and again. Progress grows in the unglamorous moments when nobody is watching and the only reward is knowing that you tried.",
"The little bookshop on the corner had no flashy signs or towering displays, yet people traveled across the city to visit it. Its shelves were crowded with secondhand novels, forgotten travel guides, and poetry collections whose spines had faded in the sun. The owner seemed to know exactly where everything belonged, even when the stacks appeared completely chaotic. Visitors often arrived searching for one title and left an hour later with three unexpected discoveries tucked beneath their arms.",
"Rain tapped against the windows as the city settled into evening. Streetlights shimmered on the wet pavement, and umbrellas bobbed along the sidewalks like a slow-moving river. Inside the apartment, a pot of soup simmered on the stove while music played softly from another room. There was nowhere else to be and nothing urgent demanding attention. It was the kind of quiet night that rarely appears on a calendar but somehow becomes one of the brightest memories of the season.",
"Scientists studying the ocean continue to discover creatures that challenge our understanding of life. Some thrive near volcanic vents where sunlight never reaches, while others drift through the midnight zone with bodies that glow like lanterns. Every expedition returns with new questions about adaptation, survival, and the connections between species. The deeper researchers look, the clearer it becomes that Earth still holds countless mysteries, and that curiosity is one of the most powerful tools we have for exploring them.",
"The recipe had been written on a stained index card in my grandmother's careful handwriting. There were no precise measurements, only instructions like add enough flour and bake until it smells right. Somehow, those vague directions produced the same warm, comforting result every single time. Years later, I finally understood that the card was never meant to stand alone. It carried the memory of her hands, her kitchen, and the patient way she taught by simply letting me watch.",
"A city becomes easier to love when you explore it on foot. Without the hurry of traffic or the barrier of a windshield, unexpected details begin to appear: painted tiles above a doorway, the scent of bread drifting from a bakery, or a tiny garden hidden behind an iron gate. The streets stop being routes between obligations and become places worth experiencing. Even a familiar neighborhood can feel new when you give yourself permission to wander without checking the time.",
"At the edge of the desert, the night sky seemed impossibly crowded with stars. Away from the glow of towns and highways, the darkness revealed colors and patterns that usually went unnoticed. A cool wind moved across the sand, erasing the footprints left behind by the group. Nobody spoke for several minutes. There are moments when language feels too small, and the best response is simply to stand beneath the immense sky and pay attention.",
"The old bicycle needed new brakes, a little oil, and a thorough cleaning, but its frame was still solid. With an afternoon of patient work, it was ready for the road again. The first ride felt wonderfully familiar, even after years in the garage. Wheels hummed against the pavement, the handlebars responded to the lightest touch, and the world moved past at exactly the right speed. Sometimes restoration is not about making something look new; it is about rediscovering why you loved it.",
"Every great project begins as a rough collection of ideas that do not quite fit together. Sketches cover the table, notes pile up, and the final shape remains frustratingly unclear. Then a small decision creates a path forward, followed by another and another. Creativity often looks like inspiration from the outside, but from within it feels more like patient problem solving. The magic appears when persistence gives a promising idea enough time to reveal itself."
];
const $ = (id) => document.getElementById(id);
const elements = {
bestWpm: $("bestWpm"),
soundToggle: $("soundToggle"),
brandLink: $("brandLink"),
wpm: $("wpm"),
accuracy: $("accuracy"),
timer: $("timer"),
charCount: $("charCount"),
charTotal: $("charTotal"),
paragraph: $("paragraph"),
paragraphLabel: $("paragraphLabel"),
typeInput: $("typeInput"),
typingArea: $("typingArea"),
focusOverlay: $("focusOverlay"),
testCard: $("testCard"),
statusText: $("statusText"),
statusDot: $("statusDot"),
progressFill: $("progressFill"),
newParagraphBtn: $("newParagraphBtn"),
restartBtn: $("restartBtn"),
resultsScreen: $("resultsScreen"),
resultsEyebrow: $("resultsEyebrow"),
resultsTitle: $("resultsTitle"),
resultsMessage: $("resultsMessage"),
newBestBadge: $("newBestBadge"),
finalWpm: $("finalWpm"),
finalAccuracy: $("finalAccuracy"),
finalChars: $("finalChars"),
finalErrors: $("finalErrors"),
finalConsistency: $("finalConsistency"),
wpmChart: $("wpmChart"),
chartEmpty: $("chartEmpty"),
closeResultsBtn: $("closeResultsBtn"),
resultsNewTextBtn: $("resultsNewTextBtn"),
resultsRetryBtn: $("resultsRetryBtn")
};
let paragraphIndex = -1;
let charSpans = [];
let typed = [];
let totalKeystrokes = 0;
let totalErrors = 0;
let running = false;
let finished = false;
let focused = false;
let startTime = 0;
let elapsedSeconds = 0;
let animationFrame = 0;
let samples = [];
let lastSampleSecond = 0;
let soundEnabled = true;
let audioContext = null;
let best = loadBest();
function loadBest() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
return saved && Number.isFinite(saved.wpm) ? saved : { wpm: 0, accuracy: 0 };
} catch (error) {
return { wpm: 0, accuracy: 0 };
}
}
function saveBest(result) {
best = result;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(result));
} catch (error) {
// The test still works when storage is unavailable.
}
renderBest();
}
function renderBest() {
elements.bestWpm.textContent = Math.round(best.wpm || 0);
}
function randomParagraphIndex() {
if (paragraphs.length < 2) return 0;
let next;
do {
next = Math.floor(Math.random() * paragraphs.length);
} while (next === paragraphIndex);
return next;
}
function selectParagraph(index = randomParagraphIndex()) {
paragraphIndex = index;
const text = paragraphs[paragraphIndex];
elements.paragraph.textContent = "";
const fragment = document.createDocumentFragment();
charSpans = Array.from(text).map((character) => {
const span = document.createElement("span");
span.className = "char";
span.textContent = character;
fragment.appendChild(span);
return span;
});
elements.paragraph.appendChild(fragment);
elements.paragraphLabel.textContent = `Paragraph ${paragraphIndex + 1} · ${text.length} characters`;
elements.charTotal.textContent = `/ ${text.length}`;
if (charSpans[0]) charSpans[0].classList.add("current");
}
function resetTest({ newParagraph = false } = {}) {
cancelAnimationFrame(animationFrame);
running = false;
finished = false;
typed = [];
totalKeystrokes = 0;
totalErrors = 0;
elapsedSeconds = 0;
samples = [];
lastSampleSecond = 0;
startTime = 0;
if (newParagraph) selectParagraph();
else {
charSpans.forEach((span, index) => {
span.className = index === 0 ? "char current" : "char";
});
}
elements.wpm.textContent = "0";
elements.accuracy.textContent = "100";
elements.timer.textContent = String(TEST_DURATION);
elements.charCount.textContent = "0";
elements.progressFill.style.transform = "scaleX(1)";
elements.testCard.classList.remove("is-active");
elements.statusDot.className = "status-dot";
elements.statusText.textContent = focused
? "Start typing — the clock begins on your first letter"
: "Click the text or press any key to start";
elements.focusOverlay.classList.toggle("visible", !focused);
closeResults();
}
function startTest() {
if (running || finished) return;
running = true;
startTime = performance.now();
elements.testCard.classList.add("is-active");
elements.statusDot.className = "status-dot running";
elements.statusText.textContent = "Test in progress — keep going!";
animationFrame = requestAnimationFrame(updateTimer);
}
function updateTimer(now) {
if (!running) return;
elapsedSeconds = Math.min(TEST_DURATION, (now - startTime) / 1000);
const remaining = Math.max(0, TEST_DURATION - elapsedSeconds);
const shownSecond = Math.ceil(remaining);
if (elements.timer.textContent !== String(shownSecond)) {
elements.timer.textContent = String(shownSecond);
}
elements.progressFill.style.transform = `scaleX(${remaining / TEST_DURATION})`;
const wholeSecond = Math.floor(elapsedSeconds);
if (wholeSecond > lastSampleSecond && wholeSecond <= TEST_DURATION) {
recordSample(wholeSecond);
lastSampleSecond = wholeSecond;
}
updateLiveStats();
if (elapsedSeconds >= TEST_DURATION) {
finishTest("time");
return;
}
animationFrame = requestAnimationFrame(updateTimer);
}
function correctCount() {
let count = 0;
for (let i = 0; i < typed.length; i += 1) {
if (typed[i] === charSpans[i].textContent) count += 1;
}
return count;
}
function calculateWpm(seconds = elapsedSeconds) {
if (seconds <= 0) return 0;
return Math.max(0, Math.round((correctCount() / 5) / (seconds / 60)));
}
function calculateAccuracy() {
if (totalKeystrokes === 0) return 100;
return Math.max(0, Math.min(100, Math.round(((totalKeystrokes - totalErrors) / totalKeystrokes) * 100)));
}
function updateLiveStats() {
elements.wpm.textContent = String(calculateWpm());
elements.accuracy.textContent = String(calculateAccuracy());
elements.charCount.textContent = String(typed.length);
}
function recordSample(second) {
samples.push({ second, wpm: calculateWpm(second) });
}
function handleCharacter(character) {
if (finished) return;
if (!running) startTest();
if (typed.length >= charSpans.length) return;
const index = typed.length;
const expected = charSpans[index].textContent;
typed.push(character);
totalKeystrokes += 1;
charSpans[index].classList.remove("current");
if (character === expected) {
charSpans[index].classList.add("correct");
playTone(520, 0.025, 0.012);
} else {
charSpans[index].classList.add("incorrect");
totalErrors += 1;
playTone(150, 0.045, 0.018);
}
if (charSpans[index + 1]) charSpans[index + 1].classList.add("current");
updateLiveStats();
if (typed.length === charSpans.length) {
finishTest("complete");
}
}
function handleBackspace() {
if (finished || !running || typed.length === 0) return;
const index = typed.length - 1;
typed.pop();
if (charSpans[index + 1]) charSpans[index + 1].classList.remove("current");
charSpans[index].classList.remove("correct", "incorrect");
charSpans[index].classList.add("current");
updateLiveStats();
}
function finishTest(reason) {
if (finished) return;
running = false;
finished = true;
cancelAnimationFrame(animationFrame);
if (reason === "complete" && elapsedSeconds < TEST_DURATION) {
elapsedSeconds = Math.max(0.1, (performance.now() - startTime) / 1000);
} else {
elapsedSeconds = TEST_DURATION;
}
if (samples.length === 0 || samples[samples.length - 1].second < Math.floor(elapsedSeconds)) {
recordSample(Math.max(1, Math.round(elapsedSeconds)));
}
const finalWpm = calculateWpm(elapsedSeconds);
const finalAccuracy = calculateAccuracy();
const correct = correctCount();
const consistency = calculateConsistency();
const isNewBest = finalWpm > (best.wpm || 0) && totalKeystrokes > 0;
if (isNewBest) saveBest({ wpm: finalWpm, accuracy: finalAccuracy });
elements.testCard.classList.remove("is-active");
elements.statusDot.className = "status-dot finished";
elements.statusText.textContent = reason === "complete" ? "Paragraph complete!" : "Time's up!";
elements.timer.textContent = reason === "complete" ? String(Math.max(0, Math.ceil(TEST_DURATION - elapsedSeconds))) : "0";
elements.progressFill.style.transform = `scaleX(${reason === "complete" ? Math.max(0, (TEST_DURATION - elapsedSeconds) / TEST_DURATION) : 0})`;
charSpans.forEach((span) => span.classList.remove("current"));
updateLiveStats();
showResults({ wpm: finalWpm, accuracy: finalAccuracy, correct, errors: totalErrors, consistency, isNewBest, reason });
}
function calculateConsistency() {
if (samples.length < 2) return samples.length ? 100 : 0;
const values = samples.map((sample) => sample.wpm);
const average = values.reduce((sum, value) => sum + value, 0) / values.length;
if (average <= 0) return 0;
const variance = values.reduce((sum, value) => sum + ((value - average) ** 2), 0) / values.length;
const variation = Math.sqrt(variance) / average;
return Math.max(0, Math.min(100, Math.round(100 - variation * 100)));
}
function showResults(result) {
elements.finalWpm.textContent = String(result.wpm);
elements.finalAccuracy.textContent = `${result.accuracy}%`;
elements.finalChars.textContent = String(result.correct);
elements.finalErrors.textContent = String(result.errors);
elements.finalConsistency.textContent = `${result.consistency}%`;
elements.newBestBadge.hidden = !result.isNewBest;
elements.resultsEyebrow.textContent = result.reason === "complete" ? "PARAGRAPH COMPLETE" : "TIME'S UP";
let title = "Good start!";
let message = "Every test makes you a little sharper.";
if (result.wpm >= 80) {
title = "Absolutely flying!";
message = "That's serious keyboard speed. Can you beat it?";
} else if (result.wpm >= 55) {
title = "Impressive run!";
message = "You're faster than most everyday typists.";
} else if (result.wpm >= 35) {
title = "Nice rhythm!";
message = "A solid result — keep the momentum going.";
} else if (result.wpm > 0) {
title = "Warming up!";
message = "Focus on accuracy first; speed will follow.";
}
elements.resultsTitle.textContent = title;
elements.resultsMessage.textContent = message;
elements.resultsScreen.classList.add("open");
elements.resultsScreen.setAttribute("aria-hidden", "false");
elements.resultsRetryBtn.focus({ preventScroll: true });
requestAnimationFrame(drawChart);
}
function closeResults() {
const wasOpen = elements.resultsScreen.classList.contains("open");
elements.resultsScreen.classList.remove("open");
elements.resultsScreen.setAttribute("aria-hidden", "true");
if (wasOpen && document.activeElement && elements.resultsScreen.contains(document.activeElement)) {
elements.typingArea.focus({ preventScroll: true });
}
}
function reopenResults() {
if (!finished) return;
elements.resultsScreen.classList.add("open");
elements.resultsScreen.setAttribute("aria-hidden", "false");
requestAnimationFrame(drawChart);
}
function setFocus(value) {
focused = value;
elements.typingArea.classList.toggle("is-focused", value);
elements.focusOverlay.classList.toggle("visible", !value);
if (value && !running && !finished) {
elements.statusText.textContent = "Start typing — the clock begins on your first letter";
}
}
function playTone(frequency, duration, volume) {
if (!soundEnabled) return;
try {
audioContext = audioContext || new (window.AudioContext || window.webkitAudioContext)();
if (audioContext.state === "suspended") audioContext.resume();
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.type = "sine";
oscillator.frequency.value = frequency;
gain.gain.setValueAtTime(volume, audioContext.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, audioContext.currentTime + duration);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + duration);
} catch (error) {
soundEnabled = false;
}
}
function drawChart() {
const canvas = elements.wpmChart;
if (!canvas || !elements.resultsScreen.classList.contains("open")) return;
const bounds = canvas.getBoundingClientRect();
const ratio = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, bounds.width);
const height = Math.max(1, bounds.height);
canvas.width = Math.round(width * ratio);
canvas.height = Math.round(height * ratio);
const context = canvas.getContext("2d");
context.scale(ratio, ratio);
context.clearRect(0, 0, width, height);
const hasData = samples.length > 0 && samples.some((sample) => sample.wpm > 0);
elements.chartEmpty.hidden = hasData;
if (!hasData) return;
const padding = { top: 12, right: 12, bottom: 25, left: 32 };
const chartWidth = width - padding.left - padding.right;
const chartHeight = height - padding.top - padding.bottom;
const maxWpm = Math.max(20, ...samples.map((sample) => sample.wpm));
const yMax = Math.ceil(maxWpm / 20) * 20;
const xMax = Math.max(TEST_DURATION, samples[samples.length - 1].second);
const x = (second) => padding.left + (second / xMax) * chartWidth;
const y = (wpm) => padding.top + chartHeight - (wpm / yMax) * chartHeight;
context.font = "10px system-ui, sans-serif";
context.textAlign = "right";
context.textBaseline = "middle";
for (let tick = 0; tick <= 4; tick += 1) {
const value = (yMax / 4) * tick;
const yPos = y(value);
context.strokeStyle = "rgba(148, 163, 184, 0.10)";
context.lineWidth = 1;
context.beginPath();
context.moveTo(padding.left, yPos);
context.lineTo(width - padding.right, yPos);
context.stroke();
context.fillStyle = "rgba(137, 148, 172, 0.75)";
context.fillText(String(Math.round(value)), padding.left - 8, yPos);
}
context.textAlign = "center";
context.textBaseline = "top";
[0, 15, 30, 45, 60].forEach((second) => {
if (second > xMax) return;
context.fillStyle = "rgba(137, 148, 172, 0.7)";
context.fillText(`${second}s`, x(second), height - padding.bottom + 9);
});
const points = [{ second: 0, wpm: 0 }, ...samples];
const gradient = context.createLinearGradient(0, padding.top, 0, height - padding.bottom);
gradient.addColorStop(0, "rgba(139, 92, 246, 0.34)");
gradient.addColorStop(1, "rgba(139, 92, 246, 0.01)");
context.beginPath();
context.moveTo(x(points[0].second), y(0));
points.forEach((point) => context.lineTo(x(point.second), y(point.wpm)));
context.lineTo(x(points[points.length - 1].second), y(0));
context.closePath();
context.fillStyle = gradient;
context.fill();
context.beginPath();
points.forEach((point, index) => {
if (index === 0) context.moveTo(x(point.second), y(point.wpm));
else context.lineTo(x(point.second), y(point.wpm));
});
context.strokeStyle = "#a78bfa";
context.lineWidth = 2.5;
context.lineJoin = "round";
context.lineCap = "round";
context.stroke();
const last = samples[samples.length - 1];
context.beginPath();
context.arc(x(last.second), y(last.wpm), 4, 0, Math.PI * 2);
context.fillStyle = "#c4b5fd";
context.fill();
context.strokeStyle = "#6d28d9";
context.lineWidth = 2;
context.stroke();
}
elements.typingArea.addEventListener("click", () => {
elements.typingArea.focus({ preventScroll: true });
setFocus(true);
focusMobileInput();
});
elements.typingArea.addEventListener("focus", () => setFocus(true));
elements.typingArea.addEventListener("blur", () => setFocus(false));
elements.focusOverlay.addEventListener("click", (event) => {
event.stopPropagation();
elements.typingArea.focus({ preventScroll: true });
focusMobileInput();
});
function focusMobileInput() {
if (!window.matchMedia("(pointer: coarse)").matches || finished) return;
try {
elements.typeInput.focus({ preventScroll: true });
} catch (error) {
elements.typeInput.focus();
}
}
elements.typeInput.addEventListener("focus", () => setFocus(true));
elements.typeInput.addEventListener("blur", () => {
if (document.activeElement !== elements.typingArea) setFocus(false);
});
let suppressMobileInput = false;
elements.typeInput.addEventListener("beforeinput", (event) => {
if (finished) return;
if (event.inputType === "insertText" && event.data) {
event.preventDefault();
suppressMobileInput = true;
setTimeout(() => { suppressMobileInput = false; }, 0);
Array.from(event.data).forEach(handleCharacter);
} else if (event.inputType === "deleteContentBackward") {
event.preventDefault();
suppressMobileInput = true;
setTimeout(() => { suppressMobileInput = false; }, 0);
handleBackspace();
}
});
elements.typeInput.addEventListener("input", (event) => {
const value = elements.typeInput.value;
elements.typeInput.value = "";
if (suppressMobileInput) return;
if (event.inputType === "deleteContentBackward") {
handleBackspace();
} else if (value) {
Array.from(value).forEach(handleCharacter);
}
});
elements.typeInput.addEventListener("paste", (event) => event.preventDefault());
document.addEventListener("keydown", (event) => {
const resultsOpen = elements.resultsScreen.classList.contains("open");
if (resultsOpen) {
if (event.key === "Escape") {
closeResults();
} else if (event.key === "Tab") {
const focusable = [elements.closeResultsBtn, elements.resultsNewTextBtn, elements.resultsRetryBtn];
const currentIndex = focusable.indexOf(document.activeElement);
event.preventDefault();
const direction = event.shiftKey ? -1 : 1;
const nextIndex = (currentIndex + direction + focusable.length) % focusable.length;
focusable[nextIndex].focus();
}
return;
}
if (document.activeElement === elements.restartBtn || document.activeElement === elements.newParagraphBtn || document.activeElement === elements.soundToggle) {
if (event.key === "Enter" || event.key === " ") return;
}
if (event.key === "Escape") {
resetTest();
return;
}
if (finished) return;
// Text entered through the mobile helper is handled by beforeinput.
if (event.target === elements.typeInput) return;
if (event.key === "Backspace") {
event.preventDefault();
handleBackspace();
return;
}
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault();
if (!focused) {
elements.typingArea.focus();
setFocus(true);
}
handleCharacter(event.key);
}
});
elements.restartBtn.addEventListener("click", () => {
resetTest();
elements.typingArea.focus();
});
elements.newParagraphBtn.addEventListener("click", () => {
resetTest({ newParagraph: true });
elements.typingArea.focus();
});
elements.resultsRetryBtn.addEventListener("click", () => {
resetTest();
elements.typingArea.focus();
});
elements.resultsNewTextBtn.addEventListener("click", () => {
resetTest({ newParagraph: true });
elements.typingArea.focus();
});
elements.closeResultsBtn.addEventListener("click", closeResults);
elements.statusText.addEventListener("click", reopenResults);
elements.resultsScreen.addEventListener("click", (event) => {
if (event.target === elements.resultsScreen) closeResults();
});
elements.brandLink.addEventListener("click", (event) => {
event.preventDefault();
resetTest({ newParagraph: true });
window.scrollTo({ top: 0, behavior: "smooth" });
});
elements.soundToggle.addEventListener("click", () => {
soundEnabled = !soundEnabled;
elements.soundToggle.textContent = soundEnabled ? "🔊" : "🔇";
elements.soundToggle.setAttribute("aria-label", soundEnabled ? "Mute sound" : "Enable sound");
elements.soundToggle.title = soundEnabled ? "Mute sound" : "Enable sound";
if (soundEnabled) playTone(600, 0.04, 0.015);
});
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(drawChart, 100);
});
renderBest();
selectParagraph();
resetTest();
})();