-
Notifications
You must be signed in to change notification settings - Fork 4
/
typingtutor.js
402 lines (370 loc) · 11.9 KB
/
typingtutor.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
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
(function($) {
//there should be 2 input elements - 1 for text and one for textarea
$.fn.typingtutor = function(options) {
//todo: validate input
var settings = $.extend({
speedInterval: 4,
focus: false,
textBackgroundColor: '#ffffff',
showInvalidText: false
}, options);
//todo: make order independent
var text = this[0];
var textarea = this[1];
$(textarea).css('resize', 'none');
$(textarea).attr('onpaste', 'return false;');
$(textarea).attr('oncut', 'return false;');
//hopefully the browser will support HTML5
$(textarea).attr('spellcheck', 'false');
var currentLinePosition = 0;
var lines = $(text).find('p');
var originalTexts = [];
var lineLetters = [];
var totalCharacters = 0;
for (var i = 0; i < lines.length; i++) {
lines[i] = $(lines[i]);
var lineText = $.trim(lines[i].text()).replace(/\t/g, ' ');
totalCharacters += lineText.length;
lines[i][0].innerHTML = '';
originalTexts[i] = lineText;
lineLetters[i] = [];
for (var j = 0; j < lineText.length; j++) {
var letter = $('<span>' + lineText.charAt(j) + '</span>');
lines[i].append(letter);
lineLetters[i][j] = letter;
}
//append a whitespace to the end of each line
var lastLetter = $('<span> </span>');
lineLetters[i][j] = lastLetter;
lines[i].append(lastLetter);
originalTexts[i] += ' ';
}
totalCharacters -= 1; //substracting 1 for the very first hit
$(text).css('font-family', '"Courier New", Courier, monospace');
var textBgColor = '#c9ffe0';
var cursorColor = '#c6dea2';
var errorColor = '#ff6188';
//resulting object
var res = {};
function drawTextBackground(line, position) {
if (lineLetters[line] && lineLetters[line][position]) {
lineLetters[line][position].css('background-color', textBgColor);
}
}
function clearTextBackground(line, position) {
if (lineLetters[line] && lineLetters[line][position]) {
lineLetters[line][position].css('background-color', settings.textBackgroundColor);
}
}
function resetLetterAt(line, position) {
lineLetters[line][position].text(originalTexts[line][position]);
}
function drawCursor(line, position) {
if (lineLetters[line] && lineLetters[line][position]) {
lineLetters[line][position].css('background-color', cursorColor);
//next key callback
nextKeyCallback(line, position-1);
//clear error state
isError = false;
}
}
function increaseErrorCount(){
isError = true;
ec++;
if (eh) {
eh.call(this, ec);
}
if(settings.nextKeyCallback){
settings.nextKeyCallback.call(this, 8);
}
}
function highlightError(line, position, letter) {
if (lineLetters[line] && lineLetters[line][position]) {
if (settings.showInvalidText && $.trim(letter).length > 0) {
lineLetters[line][position].text(letter);
}
lineLetters[line][position].css('background-color', errorColor);
}
clearSpeed();
increaseErrorCount();
res.nextKeys = 8;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function getLines() {
var currentText = textarea.value;
var allLines = currentText.split(/\n/g);
if ($.browser.name === 'msie' && endsWith(currentText, '\n')) {
//todo test for ie > 8
allLines.push('');
}
return allLines;
}
function getLinesCount() {
return getLines().length;
}
function getLastLine() {
var allLines = getLines();
return allLines[allLines.length - 1];
}
//speed interval
var si = settings.speedInterval;
//last correct date
var lcd;
//times
var tms = [];
//speed callback
var scb = settings.speedTrackCallback;
//finish callback
var fcb = settings.finishCallback;
function clearSpeed() {
lcd = null;
tms.length = 0;
}
var millisInMinute = 1000 * 60;
var startTime = null;
//error count
var ec = 0;
//error handler
var eh = settings.errorCallback;
var isError = false;
function nextKeyCallback(currentLinePosition, currentTypingPosition) {
if(settings.nextKeyCallback){
var currentLineText = originalTexts[currentLinePosition];
//next typing position
var ntp = currentTypingPosition + 1;
if(currentLineText.length > ntp) {
if(currentLineText.charAt(ntp) === ' ' && ntp === currentLineText.length - 1) {
//either whitespace or enter are allowed to move to the next line
res.nextKeys = [13, 32];
} else {
res.nextKeys = [currentLineText.charCodeAt(ntp)];
}
settings.nextKeyCallback.call(this, res.nextKeys);
}
}
}
var keyPress = function(e) {
if (!startTime) {
startTime = new Date().getTime();
}
if (e.keyCode === 8 || e.keyCode === 13) {
return;
}
//a letter has been typed
var lastTypedLine = getLastLine();
var currentTypingPosition = lastTypedLine.length;
if (!originalTexts[currentLinePosition]) {
return;
}
if (currentTypingPosition >= originalTexts[currentLinePosition].length - 1) {
//at the end of the line
if (!isError && e.which === 32) {
//trigger enter event
e.preventDefault();
e = new jQuery.Event('keydown');
e.which = e.keyCode = 13;
$(textarea).trigger(e);
$(textarea).val($(textarea).val() + '\n');
//hack for IE: move cursor to the end:
if($.browser.name === 'msie'){
var range = $(textarea)[0].createTextRange();
range.collapse(false);
range.select();
}
return;
}
}
if (currentTypingPosition > originalTexts[currentLinePosition].length - 1) {
increaseErrorCount();
return;
}
if (originalTexts[currentLinePosition].substring(0, currentTypingPosition + 1) === lastTypedLine + String.fromCharCode(e.which)) {
//a correct letter is about to be pressed
isError = false;
drawTextBackground(currentLinePosition, currentTypingPosition);
drawCursor(currentLinePosition, currentTypingPosition + 1);
if (scb) {
//correct date
var cd = new Date().getTime();
if (lcd) {
//recording current time
var t = cd - lcd;
tms.push(t);
if (tms.length === si) {
//calculate average and call speed feedback
var tot = 0;
$.each(tms, function(i, val) {
tot += val;
});
//average speed of typing one character
var avg = tot / (tms.length);
var speed = millisInMinute / avg;
scb.call(this, parseInt(speed));
tms.length = 0;
}
}
lcd = cd;
}
//check if the whole text is typed
//at this point we are sure that the typed symbol was correct
//if we're at the end of last line - fire 'finishedcallback'
if (fcb) {
if (!isError && originalTexts.length - 1 === currentLinePosition && originalTexts[originalTexts.length - 1].length - 2/*substracting last whitespace*/ === currentTypingPosition) {
var time = new Date().getTime() - startTime;
var overallSpeed = (totalCharacters / time) * millisInMinute;
fcb.call(this, parseInt(overallSpeed));
//append last typed char to the textarea before disabling it
$(textarea).val($(textarea).val() + String.fromCharCode(e.which));
$(textarea).attr('disabled', true);
$(textarea).unbind('keypress');
$(textarea).unbind('keydown');
$(textarea).unbind('keyup');
}
}
} else {
highlightError(currentLinePosition, currentTypingPosition, String.fromCharCode(e.which));
}
};
var keyDown = function(e) {
//skip arrow keys
if($.inArray(e.keyCode, [37, 38, 39, 40]) !== -1){
e.preventDefault();
return;
}
//disable home key, allow only shift+home combo
if(e.keyCode === 36 && !e.shiftKey){
e.preventDefault();
return;
}
if (e.keyCode === 8) {
//backspace - unstyle last styled character
var lastLine = getLastLine();
var currentTypingPosition = lastLine.length;
if (currentTypingPosition > 0) {
if (!originalTexts[currentLinePosition]) {
return;
}
if (currentTypingPosition < originalTexts[currentLinePosition].length) {
clearTextBackground(currentLinePosition, currentTypingPosition);
}
if (settings.showInvalidText) {
resetLetterAt(currentLinePosition, currentTypingPosition - 1);
}
if (currentTypingPosition > 1) {
if (currentTypingPosition - 1 < originalTexts[currentLinePosition].length) {
clearTextBackground(currentLinePosition, currentTypingPosition - 1);
if (originalTexts[currentLinePosition].substring(0, currentTypingPosition - 1) === lastLine.substring(0, currentTypingPosition - 1)) {
drawCursor(currentLinePosition, currentTypingPosition - 1);
}
}
} else {
drawCursor(currentLinePosition, 0);
}
} else {
//we may have jumped to a previous line
//Remove cursor from previous line
if (currentLinePosition === 0) {
//we're at the beginning of the first line
return;
}
if(! originalTexts[currentLinePosition]){
return;
}
clearTextBackground(currentLinePosition, 0);
currentLinePosition--;
var currentTypedLine = getLines()[currentLinePosition];
currentTypingPosition = currentTypedLine.length + 1; //adding one for space at the end
if (checkInput(currentTypedLine, currentLinePosition, currentTypingPosition)) {
drawCursor(currentLinePosition, currentTypingPosition - 1);
} else {
highlightError(currentLinePosition, currentTypingPosition - 2, String.fromCharCode(e.which));
}
}
} else if (e.keyCode === 13) {
//enter
//validate current line
var lastLine = getLastLine();
if ($.trim(originalTexts[currentLinePosition]) !== lastLine) {
highlightError(currentLinePosition, lastLine.length, String.fromCharCode(e.which));
e.preventDefault();
return;
} else {
drawTextBackground(currentLinePosition, lastLine.length);
}
currentLinePosition++;
drawCursor(currentLinePosition, 0);
}
};
var keyUp = function(e){
//clear backgrounds of of all characters which are beyond current typing point
var lastLine = getLastLine();
var currentTypingPosition = lastLine.length;
if(currentTypingPosition >= lineLetters[currentLinePosition].length){
return;
}
//adding one for cursor
for(var i = currentTypingPosition + 1; i < lineLetters[currentLinePosition].length; i++){
clearTextBackground(currentLinePosition, i);
}
/**
* If true then CTRL(SHIFT)+BACKSPACE deletion has been performed.
*/
var bulkDeleteWithBackspace = (e.keyCode == 8 && (e.ctrlKey || e.shiftKey));
if ((bulkDeleteWithBackspace || e.keyCode === 46) && checkInput(lastLine, currentLinePosition, currentTypingPosition)) {
drawCursor(currentLinePosition, currentTypingPosition);
}
};
$(textarea).keypress(keyPress);
$(textarea).keydown(keyDown);
$(textarea).keyup(keyUp);
function moveToEnd() {
var text = $(textarea).val();
$(textarea).focus().val('').val(text);
}
$(textarea).mouseup(moveToEnd);
/**
* Checks if last line was correct up to currentTypingPosition
*/
function checkInput(lastLine, currentLinePosition, currentTypingPosition){
return $.trim(originalTexts[currentLinePosition]).substring(0, currentTypingPosition - 1) === $.trim(lastLine).substring(0, currentTypingPosition - 1);
}
if(settings.focus){
$(textarea).focus();
}
drawCursor(0, 0);
res.restart = function(){
$(textarea).unbind('keypress');
$(textarea).unbind('keydown');
$(textarea).unbind('keyup');
//clear backgrounds of all texts
$.each(lineLetters, function(i, line){
$.each(line, function(j, letter){
letter.css('background-color', settings.textBackgroundColor);
});
});
drawCursor(0, 0);
currentLinePosition = 0;
$(textarea).val('').attr('disabled', false);
ec = 0;
if (eh) {
eh.call(this, ec);
}
isError = false;
if (scb) {
scb.call(this, 0);
}
clearSpeed();
startTime = null;
$(textarea).keypress(keyPress);
$(textarea).keydown(keyDown);
$(textarea).keyup(keyUp);
$(textarea).focus();
};
res.focus = function() {
$(textarea).focus();
};
return res;
};
}(jQuery));