-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.js
460 lines (388 loc) · 14.3 KB
/
write.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
$(document).ready(function() {
//DOM setup
//add Quizlet++ button
$(".TopNavigation-contentRight").prepend(`<div class='TopNavigationItem RightNavigationItem'><button class="AssemblyButtonBase AssemblyIconButton AssemblyIconButton--secondary AssemblyButtonBase--medium quizletplusplusbutton" type="button" style='border-radius:25px;padding:0px 12px;font-family:hurme_no2-webfont;font-kerning: normal;font-size: 14px;font-weight:600;'>Quizlet++</button></div>`);
//add Quizlet++ button
$(".t13kodjj").prepend(`<div class='o1c0xcc3'><button class="AssemblyButtonBase AssemblySecondaryButton AssemblyButtonBase--medium AssemblyButtonBase--padding AssemblyButtonBase--border quizletplusplusbutton" type="button" style="margin-right:16px">Q++</button></div>`);
// remove ad
$(".SiteUpgradeButton").parent().remove()
//add Quizlet++ popup container
$(".ModeLayout-content").append("<div class='quizletpluspluspopupcontainer'></div>");
popup("Quizlet++ has loaded. Click the Quizlet++ button in the top right to activate.");
//ON CLICK OF QUIZLET BUTTON
$(".site").on("click",".quizletplusplusbutton", function() {
console.log("Quizlet++ Button Click");
$(".quizletplusplusbutton").text("Quizlet++ ✔️");
if (!serviceRunning) {
popup("Quizlet++ is now working. Correct answers will be indicated with a dashed border on mouseover. Click away!");
serviceRunning = true;
collectTermData();
checkWriting();
}
});
//COLLECT TERM DATA FROM PAGE (Using HTML because of limitations with chrome extensions and their lack of ability in accessing window objects because they're run in a "secure bullshitty thing")
var termObj;
function collectTermData() {
console.log($("#convenientCode").html());
termObj = JSON.parse($("#convenientCode").html());
}
//CUSTOM POPUP MESSAGE
var nextPopupBoxId = 0;
function popup(text) {
var tempId = nextPopupBoxId;
$(".quizletpluspluspopupcontainer").append("<div id='"+nextPopupBoxId+"' class='quizletpluspluspopup'>"+text+"</div>");
nextPopupBoxId++;
setTimeout(function() {
$(".quizletpluspluspopupcontainer #"+tempId).hide( 200 );
},10000);
}
//FIRE ON FLASHCARD CHANGE
var serviceRunning = false;
$('.WriteViewController').on('DOMSubtreeModified', function(){
if (serviceRunning) {
console.log("flashcard changed. checking element now");
checkFlashcard();
}
else {
console.log("Flashcard change did nothing. Service not running yet.")
}
});
//writing
function checkWriting() {
// get question...
let question = $("div[data-testid='Question Text']");
console.log("question:", question);
// let questionText = question.find(".FormattedText").text();
let questionHTML = question.find(".FormattedText div");
if (questionHTML.length == 0) {
return;
}
// replace <br> with \n
// let questionText = questionHTML[0].innerText;
let questionText = questionHTML.html().replace(/<br>/g, "\n");
// console.log("questionText: " + questionText)
// print questionText as raw text to console
// that means \n will be printed as \n
// and not as a new line
// console.log("questionTexti: " + questionText)
console.log("questionText:", {
"0": questionText
})
let flashCardText = questionText;
//fetch text
// var flashCardText = $(".a5hy006 .FormattedText").text();
// if (flashCardText == "") {
// flashCardText = $(".FixedQuestionLayout-content .FormattedTextWithImage div").text();
// }
console.log(flashCardText);
//check if flashcard content exists in set
//THIS IS WHERE THE SETTINGS CHECK WOULD COME IN HANDY
flashCardAnswer = findOtherBestMatch(flashCardText);
if (flashCardAnswer == null) {
console.log("err");
return;
}
//ALL CLEAR BOYS, THE TERM HAS BEEN FOUND
console.log(flashCardAnswer);
//check if flashcard content actually changed!
if (previousText == flashCardText) {
console.log("duplicate");
//return;
}
else {
currentCharCount = 0;
popup(flashCardText + "::" + flashCardAnswer);
}
previousText = flashCardText;
//send popup
//enable listening
upArrowListen = true;
// add span w/ correct answer to input
//label.AssemblyInput
let parentAppned = $("label.AssemblyInput");
// check if div.correctAnswer already exists
if (parentAppned.find("div.correctAnswer").length > 0) {
return;
}
// else...
let span = $("<div>").attr({
"class": "correctAnswer"
}).append(
$("<span>").text("").addClass("typed"),
$("<span>").text("").addClass("restOf")
)
parentAppned.append(span);
updatePlaceholder();
}
//DETECT CURRENT FLASHCARD INFO
var previousText;
var flashCardAnswer;
function checkFlashcard() {
//check if flashcard is shown, in comparison to a "wrong answer" panel
if ($('.ModeLayout-content').find( ".FormattedText div" ).length == 0) {
console.log("not a flashcard!");
return;
}
//fetch text
var flashCardText = $(".ModeLayout-content .FormattedText div").text();
console.log(flashCardText);
//check if flashcard content actually changed!
if (previousText == flashCardText) {
// console.log("duplicate");
return;
}
previousText = flashCardText;
//check if flashcard content exists in set
//THIS IS WHERE THE SETTINGS CHECK WOULD COME IN HANDY
if (findOther(flashCardText) == null) {
console.log("err");
return;
}
else {
// console.log("all clear");
}
//ALL CLEAR BOYS, THE TERM HAS BEEN FOUND
flashCardAnswer = findOther(flashCardText);
// console.log(flashCardAnswer);
//send popup
popup(flashCardText + "::" + flashCardAnswer);
//start listener for up arrow
upArrowListen = true;
currentCharCount = 0;
}
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
var upArrowListen = false;
var currentCharCount = 0;
let inputContainerSelector = $(".AutoExpandTextarea-textarea");
waitForElm(".AutoExpandTextarea-textarea").then((elm) => {
//DETECT KEYDOWNS
$('.WriteViewController').on("keyup", ".AutoExpandTextarea-textarea", function(e) {
// console.log(e.keyCode);
// console.log(e.key)
//ADDING LETTERS
if ((e.keyCode >= 65 && e.keyCode <= 90) || e.keyCode == 32) {
console.log("watched key press detected:" + e.key);
if (upArrowListen) {
if (flashCardAnswer != null && flashCardAnswer != "") {
console.log("flash card answer: "+flashCardAnswer+".")
currentCharCount += (currentCharCount < flashCardAnswer.length) ? 1 : 0;
console.log(currentCharCount);
$(".AutoExpandTextarea-textarea").val(flashCardAnswer.substr(0,currentCharCount));
e.preventDefault();
}
}
else {
console.log("should not be listening");
}
}
else {
console.log("out of range to listen to")
}
});
$(".WriteViewController").on("keydown", ".AutoExpandTextarea-textarea", function(e) {
//check keypress limit
//PRESSING ENTER
if (e.keyCode == 13 && upArrowListen) {
currentCharCount = 0;
upArrowListen = false;
e.preventDefault();
$(this).blur();
$(".WriteViewController .TypeTheAnswerField-actions button").focus();
$(".WriteViewController .TypeTheAnswerField-actions button").click();
}
else if (flashCardAnswer != undefined && flashCardAnswer.length > 1 && currentCharCount >= flashCardAnswer.length && upArrowListen) {
e.preventDefault();
console.log("you've typed it all. stop man");
//and just to be sure?
$(".AutoExpandTextarea-textarea").val(flashCardAnswer);
}
else {
return;
}
});
//
//SEPARATE ON KEYUP FOR BACKSPACES
$(".LearnModeMain").on("keyup", "#user-answer", function(e) {
//REMOVING LETTERS
if (e.keyCode == 8) {
console.log("backspace detected");
currentCharCount = $(".AutoExpandTextarea-textarea").val().length;
}
});
// wait for ui
// new
$(inputContainerSelector).on("input", function(e) {
if (!upArrowListen) {
return;
}
let currInputText = $(inputSelector).val();
// edit answer
let newFlashcardAnswer = flashCardAnswer.replace(/\n/g, " ");
flashCardAnswer = newFlashcardAnswer;
if (flashCardAnswer.strip() == "") { // don't stop user from typing if glitched!
return;
}
print("new flashcard answer: " + flashCardAnswer +".")
// console.log("input detected");
// console.log("typed: " + currInputText);
// console.log("change from last: " + (currInputText.length - prevInputText.length));
let totLength = flashCardAnswer.length;
let typedLength = currInputText.length;
if (typedLength > totLength) {
console.log("too long");
$(inputSelector).val(flashCardAnswer);
selectAnswer();
return;
}
if (currInputText == flashCardAnswer) {
// console.log("correct");
upArrowListen = false;
$(inputSelector).val(flashCardAnswer);
// focus on "answer" button.
selectAnswer();
return;
}
if (currInputText == flashCardAnswer.substr(0, typedLength)) {
// console.log("correct so far");
updatePlaceholder();
return;
}
// typed wrong. intercept and replace
console.log("wrong");
$(inputSelector).val(flashCardAnswer.substr(0, typedLength));
updatePlaceholder();
prevInputText = currInputText;
});
});
//FIND ID FROM TEXT IN QUIZLET ARRAY
//text = string, textordefinition = "word" or "definiton"
function findOther(text) {
var index = termObj.findIndex(obj=> obj.def==text);
if (index == -1) {
var index = termObj.findIndex(obj=> obj.term==text);
if (index == -1) {
console.log("could not find matching text in set!");
return null;
}
else {
return termObj[index].def;
}
}
else {
return termObj[index].term;
}
}
function levenshtein(a, b) {
return similarity(a, b);
}
function similarity(s1, s2) {
var longer = s1;
var shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
var longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
function editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
var costs = new Array();
for (var i = 0; i <= s1.length; i++) {
var lastValue = i;
for (var j = 0; j <= s2.length; j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
// new
function findOtherBestMatch(text) {
let closestThreshold = 0.5;
function findClosest(text, list) {
var closest = list[0];
var closestIndex = 0;
var closestDist = levenshtein(text, closest);
let outObj = {};
for (var i = 1; i < list.length; i++) {
var dist = levenshtein(text, list[i]);
if (dist > closestDist) {
closestDist = dist;
closest = list[i];
closestIndex = i;
}
outObj[i] = {
"d": dist,
"text": list[i]
};
}
console.log(outObj);
console.log("closest: " + closest + " dist: " + closestDist + " index: " + closestIndex)
// threshold met?
if (closestDist < closestThreshold) {
return -1;
}
return closestIndex;
}
// determine if text is a term or definition (only called in writing mode)
let defCheck = $(".StudyModesLayout article section:contains('Definition')");
if (defCheck.length > 0) {
console.log("def check")
// text is a definition
let termList = termObj.map(obj => obj.def);
console.log(termList);
let testClosestIndex = findClosest(text, termList);
if (testClosestIndex == -1) {
return null;
}
else {
return termObj[testClosestIndex].term;
}
}
else {
console.log("term check")
// try as a term
let defList = termObj.map(obj => obj.term);
let testClosestIndex = findClosest(text, defList);
if (testClosestIndex == -1) {
return null;
}
else {
return termObj[testClosestIndex].def;
}
}
}
});