-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
338 lines (177 loc) · 7.88 KB
/
script.js
File metadata and controls
338 lines (177 loc) · 7.88 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
const inputText = document.getElementById('TextInput');
const mistakeCounter = document.getElementById('mistakeCounter');
const textElement = document.getElementById('Text');
const timerElement = document.getElementById('timer');
let pointsCounter = document.getElementById('pointsCounterValue');
let num = 0; // Keeps track of the current character being compared
let mistakeNum = 0; // Tracks the number of mistakes
let points = 0; // Initialize points counter
let timeInSeconds = 30; // Set initial timer value in seconds
let remainingTime =0;
let userInputValue ='';
let wrapper = document.getElementById('wrapper');
let timerInterval;
const typedCorrectIndices = new Set();
const PracticeText = [
'The quick brown fox jumps over the lazy dogs.',
'In the bustling heart of the city, people hurriedly walk along the crowded streets, their minds occupied with the tasks of the day, as the vibrant colors of street art on nearby walls capture the attention of passersby.',
'On a quiet evening, as the golden hues of the setting sun paint the sky, a gentle breeze sweeps across the fields, rustling the leaves of the trees and carrying the sweet scent of fresh flowers to those lucky enough to experience the serene beauty of nature.',
'At the corner of the street, a small cafe with cozy lights and the inviting aroma of freshly brewed coffee draws in customers from all walks of life, offering a brief escape from the fast-paced world outside.',
'As the clock strikes midnight, a solitary figure stands at the edge of the vast, silent lake, gazing out over the still waters, contemplating the mysteries of the universe under the watchful gaze of a thousand twinkling stars.'
];
inputText.addEventListener('input', () => {
const userInput = inputText.value; // Get the user's input
const targetText = textElement.innerText; // Get the target text
let resultHTML = ""; // Initialize result HTML
for (let i = 0; i < targetText.length; i++) {
if (i < userInput.length) {
// Compare user input with target text
if (userInput[i] === targetText[i]) {
resultHTML += `<span class="correct">${targetText[i]}</span>`; // Correct character
if (!typedCorrectIndices.has(i)) {
if (userInput[i] !== ' ' && i === userInput.length - 1){
points++; // Increment points only for the first correct typing of this character
pointsCounter.innerHTML = points;
typedCorrectIndices.add(i); // Mark this index as correctly typed
}
}
} else {
resultHTML += `<span class="incorrect">${targetText[i]}</span>`; // Incorrect character
if (userInput[i] !== ' ' && i === userInput.length - 1) {
mistakeNum++; // Increment mistakes only for the current character
mistakeCounter.innerHTML = mistakeNum;
}
}
} else {
// Remaining characters
resultHTML += `<span class="not-typed">${targetText[i]}</span>`;
}
}
// Update the display
textElement.innerHTML = resultHTML;
// Check if the user has completed the sentence
if (userInput === targetText) {
remainingTime = 30 - timeInSeconds;
timeInSeconds = 0;
clearInterval(timerInterval); // Stop the timer
storeTime();
resultBox(); // Show the results box
}
});
document.addEventListener('keydown', (event) => {
if (event.key === ' '){
return;
}
});
// Randomly select a sentence for practice
const randomNumber = Math.floor(Math.random() * PracticeText.length);
textElement.innerText = PracticeText[randomNumber];
// Handle backspace events
inputText.addEventListener('keydown', (event) => {
if (event.key === 'Backspace') {
points--;
if (num > 0) num--;
if (inputText.value[num] !== textElement.innerText[num] && mistakeNum > 0) {
mistakeNum--;
mistakeCounter.innerText = mistakeNum;
}
}
});
const metricValue = document.getElementById('metric-value');
let wpm = (pointsCounter / 5) / 0.5;
const container = document.getElementById('container');
const dashboard = document.getElementById('dashboard');
// Timer function
function startTimer(){
function updateTimer() {
const minutes = Math.floor(timeInSeconds / 60).toString().padStart(2, '0');
const seconds = (timeInSeconds % 60).toString().padStart(2, '0');
timerElement.textContent = `Timer- ${minutes}:${seconds}`;
if (timeInSeconds > 0) {
timeInSeconds--;
} else {
clearInterval(timerInterval); // Stop the timer when it reaches 0
timerElement.textContent = "Time's up!";
// Show the results box
container.style.display="none";
dashboard.style.display="block";
resultBox();
}
}
const timerInterval = setInterval(updateTimer, 1000);
}
let storedTime = ''; // To store remaining time
function storeTime() {
storedTime = remainingTime; // Store the remaining time
console.log("Time stored: ", storedTime); // Log stored time (just for demonstration)
}
// Refresh Button Functionality
function refresh() {
location.reload();
}
const startToType = document.getElementById('startToType');
const clickMe = document.getElementById('ClickMe');
startToType.addEventListener('click',()=>{
wrapper.style.display="flex";
clickMe.style.display="none";
startTimer();
inputText.focus();
console.log("clicked");
});
let timeOptions = document.querySelectorAll('.timeOption');
timeOptions.forEach((timeOption) => {
timeOption.addEventListener('click', () => {
// Remove 'active' class from all options
timeOptions.forEach((option) => option.classList.remove('active'));
// Add 'active' class to the clicked option
timeOption.classList.add('active');
});
});
document.querySelectorAll('.metric, .secondary-metric').forEach(element => {
element.addEventListener('mouseenter', () => {
element.style.transform = 'scale(1.02)';
element.style.transition = 'transform 0.2s ease';
});
element.addEventListener('mouseleave', () => {
element.style.transform = 'scale(1)';
});
});
// // You can add functions here to update the values dynamically
// function updateMetrics(wpm, acc, raw, chars, consistency, time) {
// document.querySelector('.wpm').textContent = wpm;
// document.querySelector('.acc').textContent = acc + '%';
// // Add more updates as needed
// }s
function calculateMetrics() {
const totalTyped = textElement.innerText.replace(/ /g, '').length;
const correctTyped = typedCorrectIndices.size; // Correct characters
const rawWPM = (totalTyped / 5) / (30 / 60); // Based on raw input
const accuracy = ((correctTyped / totalTyped) * 100).toFixed(2) || 0; // Avoid division by zero
const consistency = Math.min((correctTyped / totalTyped) * 100, 100).toFixed(2) || 0;
// Calculate final WPM based on correct words typed
const wpm = (correctTyped / 5) / (30 / 60); // Correct words per minute
console.log(`totalTyped = ${totalTyped}`);
console.log(`Correct typed = ${correctTyped}`);
console.log(`Raw = ${rawWPM}`);
console.log(`Accuracy = ${accuracy}`);
console.log(`Consisteny = ${consistency}`);
console.log(`Wpm = ${wpm}`);
console.log(remainingTime);
// Update dashboard values
document.getElementById('wpm').textContent = Math.round(wpm);
document.getElementById('accuracy').textContent = `${accuracy}%`;
document.getElementById('consistency').textContent = `${consistency}%`;
document.getElementById('raw-wpm').textContent = Math.round(rawWPM);
document.getElementById('characters').textContent = `${correctTyped}/${mistakeNum}`;
if(remainingTime>0){
document.getElementById('time-elapsed').textContent = `${remainingTime}s`;
}else{
document.getElementById('time-elapsed').textContent = `30s`;
}
}
// Call this function when time runs out or the user finishes typing
function resultBox() {
calculateMetrics();
container.style.display = "none"; // Hide typing area
dashboard.style.display = "block"; // Show dashboard
}