-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
263 lines (229 loc) · 9.38 KB
/
app.js
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
const textElement = document.getElementById("quoteDisplay");
const inputElement = document.getElementById("textInput");
const timerElement = document.getElementById("timer");
const wpmElement = document.getElementById("wpm");
const titleElement = document.getElementById("headerTitle");
const minLengthElement = document.getElementById("minLengthInput");
const maxLengthElement = document.getElementById("maxLengthInput");
const languagesList = document.getElementById("langaugePicker");
const stripPunctuationElement = document.getElementById("stripPunctuation");
// Populate languageList with countries from countries.js
for (let langID in countries) {
let isSelected;
if (langID == "en-GB") {
// Sets default
isSelected = "selected";
//*Bad practise to use "isSelected" for non-bool var, but it makes the inner HTML insert easier to understand
}
languagesList.insertAdjacentHTML(
"beforeend",
`<option value="${langID}" ${isSelected}>${countries[langID]}</option>`
);
}
function getTranslatedText(text, language) {
if (language.length == 0) {
return "Invalid Language Selection 😥";
}
let output = fetch(
`https://api.mymemory.translated.net/get?q=${text}&langpair=en|${language}&[email protected]`
)
.then((response) => response.json())
.then((data) => data?.responseData?.translatedText);
return output;
}
async function fetchText(minLength, maxLength) {
return fetch(
`https://api.quotable.io/random?maxLength=${maxLength}&minLength=${minLength}`
)
.then((response) => response.json())
.then((fetchedData) => [fetchedData.content, fetchedData.author]);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////// TIMER TIMER TIMER TIMER TIMER TIMER TIMER TIMER TIMER TIMER /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function startTimer() {
timerElement.innerText = 0;
startTime = new Date();
let interval = setInterval(() => {
timerElement.innerText = checkTime();
if (testCompleted) {
// Stop timer when test is done
clearInterval(interval);
}
if (!timerStarted) {
// If the timer has been reset
clearInterval(interval); // Stop the timer
timerElement.innerText = 0; // Reset timer to 0
}
}, 50);
}
let startTime;
function checkTime() {
return (Math.floor(new Date() - startTime) / 1000).toFixed(2); // Math.floor to avoid decimal in ms to seconds conversion
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////// WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM WPM ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// To avoid WPM being displayed at >1000 in the first 0.2 seconds, we can make a delay utility function
// stackoverflow.com/a/47480429
// this function allows us to delay wpm being displayed until it's a reasonable number.
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
var startWpm = async () => {
wpmElement.innerText = 0;
await delay(2000); // Start the timer after 1000ms
let interval = setInterval(() => {
wpmElement.innerText = checkWpm();
if (testCompleted) {
clearInterval(interval);
}
}, 50);
};
function checkWpm() {
if (!timerStarted) {
// For getting new text
return 0;
}
return ((inputElement.value.split(" ").length / checkTime()) * 60).toFixed(0);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DONT SET THIS TO "KEYDOWN"
inputElement.addEventListener("input", (input) => {
// Start timer if it's not already been started
if (!timerStarted) {
timerStarted = true;
startTimer();
wpmStarted = true;
startWpm();
}
let textArray = textElement.querySelectorAll("span"); // Array of all spans (characters we parsed from string)
let inputArray = inputElement.value.split("");
let inputMatchesText = true; // if this ever gets set to false alone the way, it never gets set back to true
textArray.forEach((charSpan, index) => {
let inputtedChar = inputArray[index];
if (inputtedChar == null) {
charSpan.classList.remove("correct");
charSpan.classList.remove("typo");
if (charSpan.innerText == "█") {
charSpan.innerText = " ";
}
inputMatchesText = false;
} else if (inputtedChar == charSpan.innerText) {
if (charSpan.innerText == "█") {
charSpan.innerText = " ";
}
charSpan.classList.add("correct");
charSpan.classList.remove("typo");
} else if (inputtedChar != charSpan.innerText) {
if (charSpan.innerText == " ") {
charSpan.innerText = "█";
}
charSpan.classList.add("typo");
charSpan.classList.remove("correct");
inputMatchesText = false;
}
});
if (inputMatchesText) {
if (testCompleted == false) {
new Audio("complete.mp3").play();
}
testCompleted = true;
console.log(
`WPM: ${(inputElement.value.split(" ").length / checkTime()) * 60}`
);
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Prevents it from being promise call
async function drawText(minLength, maxLength, selectedLanguage) {
let textToType = await fetchText(minLength, maxLength);
titleElement.innerText = "Quote by " + textToType[1]; // textToType[1] = Author
// If not english, translate
if (
selectedLanguage != "en-GB" ||
selectedLanguage != "" ||
selectedLanguage != null
) {
textToType[0] = await getTranslatedText(textToType[0], selectedLanguage);
}
if (stripPunctuationElement.checked) {
textToType[0] = textToType[0].replace(/[^\p{L}\p{N}\s]/gu, "");
}
textElement.innerText = ""; // This must be here or else the size of the window changes on reset
try {
textToType[0].split("").forEach((char) => {
let charSpan = document.createElement("span");
charSpan.innerText = char;
textElement.appendChild(charSpan);
});
} catch (error) {
testCompleted = true; // Prevents completion sound from playing
console.log(
`Error 1: during API fetch, either the API failed to translate or the selected language is unsupported.\n ${error}`
);
textElement.innerText =
"Error occured while translating 😅 If the error persists, the translator might not support this language.";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function checkParams(minLengthString, maxLengthString) {
let minLength = Number(minLengthString);
let maxLength = Number(maxLengthString);
if (minLength > maxLength) {
alert("The minimum length cannot be greater than the maximum length!");
return false;
} else if (minLength < 20) {
alert(
"Invalid minimum length - the minimum length cannot be less than 20 characters!"
);
return false;
} else if (minLength > 350) {
alert(
"Invalid minimum length - the minimum length cannot be greater than 350 characters!"
);
return false;
} else if (isNaN(minLength)) {
alert("Invalid minimum length - Please only use numbers!");
return false;
} else if (isNaN(maxLength)) {
alert("Invalid maximum length - Please only use numbers!");
return false;
}
return true;
}
function startNew() {
// Reset all values...
// TODO: Fix WPM still being displayed when enter is pressed
inputElement.value = "";
wpmElement.value = "";
timerStarted = false;
testCompleted = false;
wpmStarted = false;
// Get length choices
let minLength = minLengthElement.value;
let maxLength = maxLengthElement.value;
if (minLength.length == 0) {
minLength = 50;
}
if (maxLength.length == 0) {
maxLength = 100;
}
// Language choice
selectedLanguage = languagesList.value;
console.log(`Selected language: ${selectedLanguage}`);
if (checkParams(minLength, maxLength)) {
// TODO: Maybe make a check for parameters like min: 348, 349, which returns nothing
drawText(minLength, maxLength, selectedLanguage);
timerElement.innerText = "0.00";
}
}
// Check for "Enter" hotkey for resetting test
document.addEventListener("keypress", (input) => {
if (input.key == "Enter") {
startNew();
}
});
startNew();