-
Notifications
You must be signed in to change notification settings - Fork 0
/
contentScript.js
512 lines (436 loc) · 18.3 KB
/
contentScript.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
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
$(function() {
//---------Constants------
const STATES = {
LEARNING: 'learning',
PROFICIENCY: 'proficiency/afficiency',
OTHER: 'other'
}
Object.freeze(STATES);
const calcFixScriptId = "calcFixScript";
const startFixScriptId = "startFixScript";
var nextFixScriptId = "nextFixScript";
//Initialize default state to non exercise
var state = STATES.OTHER;
var calcFixApplied = false;
//-------End Constants---------
//-------Class Variables------
var quickSubmitEnabled = false;
/**
* Listener for quickSubmitEnabled and future UI variables
*
* Changes the quickSubmitEnabled variable according to its checked status in popup.html
*/
chrome.storage.onChanged.addListener(function (changes, namespace) {
quickSubmitEnabled = changes['quickSubmitEnabled'].newValue;
})
$(document).keypress(handleQuickSubmitKeypress);
//--------------------
//Give an id to the root div, needed to observe mutations to the DOM
$('div.layout-column').attr('id', 'rootDiv');
// Select the node that will be observed for mutations
var targetNode = document.getElementById('rootDiv');
// Options for the observer (which mutations to observe)
var config = { childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
//Check for learning session by looking for the id of the divs that
//house each checkmark icon
if ($('#item\\.sequence_id').length > 0) {
if (state !== STATES.LEARNING) {
state = STATES.LEARNING;
clearVals();
}
//Apply calculator fix if it hasn't been applied yet
if (!calcFixApplied && !$("[ng-show='calculator&&calculator.grade==6']").hasClass('ng-hide')) {
let newScript = document.createElement('script');
newScript.setAttribute("id", calcFixScriptId);
//Remove "function() {" from the beginning of scriptFunction and the ending "}" from the end of scriptFunction
//so that it can be properly used in <script> tags
let code = calcFixScriptFunction.toString();
let startIndex = code.indexOf("{") + 1;
let endIndex = code.lastIndexOf("}");
code = code.substring(startIndex, endIndex);
newScript.innerHTML = code;
//Append to DOM
document.body.appendChild(newScript);
calcFixApplied = true;
}
}
//Otherwise, check for proficiency/afficiency by looking for proficiency/afficiency timer
else if ($('#proficiencyTimer').length > 0 ||
$('#aficiencyTimer').length > 0) {
if (state !== STATES.PROFICIENCY) {
clearVals();
state = STATES.PROFICIENCY;
}
//reset calc fix for start screen for proficiency/afficiency
if ( $('[ng-show="showStartButton"]').length > 0 && !$('[ng-show="showStartButton"]').hasClass('ng-hide')) {
clearVals();
}
//If a calculator appears in this proficiency session and the fix hasn't been applied yet,
//apply it
if (!calcFixApplied && !$("[ng-show='calculator&&calculator.grade==6']").hasClass('ng-hide')) {
let newScript = document.createElement('script');
newScript.setAttribute("id", calcFixScriptId);
//Remove "function() {" from the beginning of scriptFunction and the ending "}" from the end of scriptFunction
//so that it can be properly used in <script> tags
let code = calcFixScriptFunction.toString();
let startIndex = code.indexOf("{") + 1;
let endIndex = code.lastIndexOf("}");
code = code.substring(startIndex, endIndex);
newScript.innerHTML = code;
//Append to DOM
document.body.appendChild(newScript);
calcFixApplied = true;
}
//Otherwise, not in any problem session
}
else {
if (state !== STATES.OTHER) {
clearVals();
state = STATES.OTHER;
}
if ($('[ng-click="go()"]').length > 0) {
//Remove previous if needed
if ($("#" + startFixScriptId).length >= 1) {
$("#" + startFixScriptId).remove();
}
let newScript = document.createElement('script');
newScript.setAttribute("id", startFixScriptId);
//Remove "function() {" from the beginning of scriptFunction and the ending "}" from the end of scriptFunction
//so that it can be properly used in <script> tags
//TODO: this should be a function
let code = startButtonFixFunction.toString();
let startIndex = code.indexOf("{") + 1;
let endIndex = code.lastIndexOf("}");
code = code.substring(startIndex, endIndex);
newScript.innerHTML = code;
newScript.innerHTML = code;
//Append to DOM
document.body.appendChild(newScript);
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
//-----------End init------
//==========Helper Functions===========
/**
* Removes the appended calculator script from the DOM if it has been
* appended to it, then sets calcFixApplied to false.
*/
function clearVals() {
$("#" + calcFixScriptId).remove();
calcFixApplied = false;
}
/**
* Handles the quick submit keypress combination (shift + enter)
*
* If quick submit is not enabled, does nothing
*
* @param {keypress} event A keypress event
*/
function handleQuickSubmitKeypress(event) {
if (!quickSubmitEnabled) {
return;
}
if ((event.shiftKey ) && (event.keyCode == 13 || event.keyCode == 10)) {
//Submit answer button for learning
var submitAnsLearning = $('[ng-show="panelIndex === 2"]').filter('md-card').find('[ng-click="checkAndSubmitBtnLabel === \\\'Next Question\\\' ? nextQuestion():checkAndSubmitBtnLabel === \\\'Next Skill\\\' ? nextSkill():checkAndSubmitAnswer()"]');
//Submit answer button for proficiency/afficiency
var submitAnsProficiencyAfficiency= $('[ng-click="checkAndSubmitBtnLabel === \\\'Next Question\\\' ?nextQuestion():checkAndSubmitBtnLabel === \\\'Next Skill\\\' ?nextSkill():checkAndSubmitAnswer()"]');
if (submitAnsLearning.length !== 0) {
submitAnsLearning.click();
}
if (submitAnsProficiencyAfficiency.length !== 0) {
submitAnsProficiencyAfficiency.click();
}
}
}
//======End Helper Functions==========
//===========BEGIN INSERTED SCRIPT FUNCTIONS==========
/**
* Code to be inserted into DOM tagged in <script></script>
*
* Attaches an onClick listener to the homepage start button that
* disables action until all assignments have been loaded client side.
*/
var startButtonFixFunction = function() {
var goBtn = angular.element($('[ng-click="go()"]'))
var scope = goBtn.scope();
goBtn.off();
$(goBtn).click(function() {
try {
//Check for to make sure that assignments are loaded, if not then return
if (scope.regularAssignmentItems == null) {
return;
}
//Otherwise get started with assignment
else {
scope.go();
}
}
//Only possible error here results from assignment items not being loaded
//Do nothing in this case
catch (e) {
return;
}
});
}
//Code to be inserted into DOM tagged in <script></script>
/**
* Contains numerous fixes to the Afficient Academy calculator functions
*/
var calcFixScriptFunction = function() {
//Used for calculator history
var historyId = 0;
calcScreen.value = "";
$("#calcScreen").removeAttr("placeholder");
$("#calcScreen").css({"font-family":'Helvetica'});
//Select the calculator equals sign button
var calcElem = $('#calculator').children()[35];
var calcScope = angular.element(calcElem).scope();
calcScope.histDisable = false;
/**
* Evaluates calculator inputs using math.js
*
* Accounts for rounding errors by limiting precision at 14 digits.
*/
calcScope.calcEval = function() {
//Do nothing if the calc screen input is blank
if (calcScreen.value === "") {
calcScope.calcClear();
return;
}
//Do strange % operation (not modulus) if there is a % in the input
if (-1 !== calcScreen.value.indexOf("%")) {
calcScope.calcPct();
return;
}
var result = "";
try {
result = math.format(math.eval(calcScreen.value), { precision: 14 });
//Do nothing if evaluation results in no change
if (result === calcScreen.value) {
return;
}
historyId++;
$("#history").append("<li class='list-group-item' id='history-" + historyId + "'>" + calcScreen.value + "</li>");
calcScreen.value = result;
$("#history-" + historyId).append(" = " + result);
} catch (e) {
console.log('err is: ', e);
calcScreen.value = "ERROR";
}
};
/**
* Calculates square root of calculator input using math.js
*
* 14 digits of precision
*/
calcScope.calcSqrt = function() {
var intermediaryResult = "";
var sqrtResult = "";
try {
intermediaryResult = math.eval(calcScreen.value);
sqrtResult = math.format(math.sqrt(intermediaryResult), { precision: 14 });
historyId++;
$("#history").append("<li class='list-group-item' id='history-" + historyId + "'>√<span style='text-decoration:overline;'> " + calcScreen.value + " </span></li>");
calcScreen.value = sqrtResult;
$("#history-" + historyId).append(" = " + calcScreen.value);
} catch (e) {
calcScreen.value = "ERROR";
}
}
/**
* Calculates cube root of calculator input using math.js
*
* 14 digits of precision
*/
calcScope.calcCbrt = function() {
var intermediaryResult = "";
var cbrtResult = "";
try {
intermediaryResult = math.eval(calcScreen.value);
cbrtResult = math.format(math.cbrt(intermediaryResult), { precision: 14 });
historyId++;
$("#history").append("<li class='list-group-item' id='history-" + historyId + "'>∛<span style='text-decoration:overline;'> " + calcScreen.value + " </span></li>");
calcScreen.value = cbrtResult;
$("#history-" + historyId).append(" = " + calcScreen.value);
} catch (e) {
calcScreen.value = "ERROR";
}
}
/**
* Squares inputs of calculator using math.js
*
* 14 digits of precision
*/
angular.element(calcElem).scope().calcSquare = function() {
var intermediaryResult = "";
var squaredResult = "";
try {
intermediaryResult = math.eval(calcScreen.value);
squaredResult = math.format(math.pow(intermediaryResult, 2), { precision: 14 });
historyId++;
$("#history").append("<li class='list-group-item' id='history-" + historyId + "'>" + calcScreen.value + "<sup>2</sup></li>");
calcScreen.value = squaredResult;
$("#history-" + historyId).append(" = " + calcScreen.value);
} catch (e) {
calcScreen.value = "ERROR";
}
}
/**
* calcPct requires three inputs:
* Two numbers, which we will call a, b
* One operator (+, -, /, *)
*
* For calcPct to correctly parse an input, the input must be of the form:
* a OPERATOR b %
* Where a and b are numbers, OPERATOR is an operator, and % is the % symbol.
*
* Its output evaluates the following:
* a OPERATOR (ab/100)
*
* Or in words, [a] (plus, minus, times, divided by) [b percent of a]
*
* For example, 100 + 5% means
* 100 + ( (100 * 5) / 100) = 105
*
* Or in words, 100 + (5 percent of 100).
*
*/
angular.element(calcElem).scope().calcPct = function() {
var arr, sym;
//count number of operation symbols, if > 1 return error
var symCount = 0;
for (let i = 0; i < calcScreen.value.length; i++) {
if (calcScreen.value.charAt(i) === '+' || calcScreen.value.charAt(i) === '-' ||
calcScreen.value.charAt(i) === '*' || calcScreen.value.charAt(i) === '/') {
symCount += 1;
}
}
if (symCount > 1) {
calcScreen.value = "ERROR";
return;
}
//split by symbol
if (calcScreen.value.indexOf("+") !== -1) {
arr = calcScreen.value.split("+");
sym = "+";
} else if (calcScreen.value.indexOf("-") !== -1) {
arr = calcScreen.value.split("-");
sym = "-";
} else if (calcScreen.value.indexOf("*") !== -1) {
arr = calcScreen.value.split("*");
sym = "*";
} else if (calcScreen.value.indexOf("/") !== -1) {
arr = calcScreen.value.split("/");
sym = "/";
} else {
calcScreen.value = "ERROR";
}
//remove percent symbol from end of input
arr[1] = arr[1].slice(0, arr[1].length - 1);
var result = math.format(math.eval(arr[0] + sym + arr[1] * (arr[0] / 100)), { precision: 14 });
if (isNaN(result)) {
calcScreen.value = "ERROR";
} else {
historyId++;
$("#history").append("<li class='list-group-item' id='history-" + historyId + "'>" + arr[0] + sym + "(" + arr[1] + "% of " + arr[0] + ")</li>");
calcScreen.value = result;
$("#history-" + historyId).append(" = " + calcScreen.value);
}
}
/**
* Clear the calculator screen
*/
calcScope.calcClear = function() {
calcScreen.value = "";
}
/**
* Clear all inputs and calculator history
*/
calcScope.calcClearAll = function() {
calcScope.calcClear();
$("#history").html("");
historyId = 0;
}
/**
* Clears the calculator if there was an error. Otherwise,
* removes last character of calc input.
*/
calcScope.calcBackspace = function() {
if (calcScreen.value === "ERROR") {
calcScope.calcClear();
} else {
calcScreen.value = calcScreen.value.slice(0, calcScreen.value.length - 1)
}
}
/**
* Prevents nonnumeral inputs for the calculator
*
*/
$("#calcScreen").keydown(function(event) {
var key = event.keyCode;
$('#calcScreen').attr("placeholder","");
//If the screen is error, the only acceptable keys are delete and backspace
if (calcScreen.value === "ERROR" && key !== 46 && key !== 8) {
event.preventDefault;
return;
}
//Clear screen if one of these is pressed
else if (calcScreen.value === "ERROR" && (key === 46 || key === 8)) {
calcScope.calcClear();
return;
}
var shift = event.shiftKey;
if (calcScreen.value === "" && isMathOperatorKey(event, key)) {
calcScreen.value = '0';
}
if (isAlphaOrComma(key)) {
event.preventDefault();
}
//DEL key
if (key === 46) {
calcScope.calcClear();
event.preventDefault();
}
//ENTER key
if (key === 13) {
calcScope.calcEval();
event.preventDefault();
}
});
/**
* Helper function for calcScreen.keyDown
* Detects if key (or key combination) is a math operator
*
* @param {event} Keydown event
* @param {keyCode} keyCode corresponding to event
*/
function isMathOperatorKey(event, key) {
var shift = event.shiftKey;
return 107 == key || // +
109 == key || // subtract
106 == key || // multiply
111 == key || // divide
shift && 54 == key || // ^ (shift and 6)
shift && 56 == key || // * (shift and 8)
shift && 187 == key || // + (shift and equals)
189 == key; // dash symbol
}
/**
* Helper function for calcScreen.keyDown
*
* Detects if key is a letter or comma
* @param {keyCode} keyCode corresponding to event
*/
function isAlphaOrComma(key) {
return key > 64 && key < 96 || key === 188;
}
}
//=====END INSERTED SCRIPT FUNCTIONS============
});