forked from guillaumebrunerie/reversetreeenhancer
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDuolingoTreeEnhancer.user.js
1566 lines (1417 loc) · 52.6 KB
/
DuolingoTreeEnhancer.user.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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Duolingo Tree Enhancer
// @namespace https://github.com/camiloaa/duolingotreeenhancer
// @version 1.4.5
// @description Enhance Duolingo by customizing difficulty and providing extra functionality. Based on Guillaume Brunerie's ReverseTreeEnhancer
// @author Camilo Arboleda
// @match https://www.duolingo.com/*
// @match https://preview.duolingo.com/*
// @icon https://raw.githubusercontent.com/camiloaa/duolingotreeenhancer/master/duolingo.png
// @require https://github.com/camiloaa/GM_config/raw/master/gm_config.js
// @downloadURL https://github.com/camiloaa/duolingotreeenhancer/raw/master/DuolingoTreeEnhancer.user.js
// @updateURL https://github.com/camiloaa/duolingotreeenhancer/raw/master/DuolingoTreeEnhancer.user.js
// @grant none
// ==/UserScript==
//debug('DuolingoTreeEnhancer');
const K_PLUGIN_NAME = "DuolingoTreeEnhancer";
const K_CHALLENGE_JUDGE_QUESTION = "_3-JBe";
const K_SPEAKER_BUTTON = "_1KXUd _1I13x _2kfEr _1nlVc _2fOC9 UCrz7 t5wFJ _3a8EI _1ZuR6"
const K_CONFIG_BUTTON = " _3HHNB _2A7uO _2gwtT _1nlVc _2fOC9 t5wFJ _3dtSu _25Cnc _3yAjN _3Ev3S _1figt";
const K_SPEAKER_ICON_STYLE = "text-align:center; margin-top:-7px; margin-left:-8px";
const duo_languages = JSON.parse(
'{"gu":"Gujarati","ga":"Irish","gn":"Guarani (Jopará)","'
+ 'gl":"Galician","la":"Latin","tt":"Tatar","tr":"Turkish",'
+ '"lv":"Latvian","tl":"Tagalog","th":"Thai","te":"Telugu",'
+ '"ta":"Tamil","yi":"Yiddish","dk":"Dothraki","de":"German",'
+ '"db":"Dutch (Belgium)","da":"Danish","uz":"Uzbek",'
+ '"el":"Greek","eo":"Esperanto","en":"English",'
+ '"zc":"Chinese (Cantonese)","eu":"Basque","et":"Estonian",'
+ '"ep":"English (Pirate)","es":"Spanish","zs":"Chinese",'
+ '"ru":"Russian","ro":"Romanian","be":"Belarusian",'
+ '"bg":"Bulgarian","ms":"Malay","bn":"Bengali",'
+ '"ja":"Japanese","or":"Oriya","xl":"Lolcat","ca":"Catalan",'
+ '"xe":"Emoji","xz":"Zombie","cy":"Welsh","cs":"Czech",'
+ '"pt":"Portuguese","lt":"Lithuanian","pa":"Punjabi (Gurmukhi)",'
+ '"pl":"Polish","hy":"Armenian","hr":"Croatian",'
+ '"hv":"High Valyrian","ht":"Haitian Creole","hu":"Hungarian",'
+ '"hi":"Hindi","he":"Hebrew","mb":"Malay (Brunei)",'
+ '"mm":"Malay (Malaysia)","ml":"Malayalam","mn":"Mongolian",'
+ '"mk":"Macedonian","ur":"Urdu","kk":"Kazakh","uk":"Ukrainian",'
+ '"mr":"Marathi","my":"Burmese","dn":"Dutch","af":"Afrikaans",'
+ '"vi":"Vietnamese","is":"Icelandic","it":"Italian",'
+ '"kn":"Kannada","zt":"Chinese (Traditional)","as":"Assamese",'
+ '"ar":"Arabic","zu":"Zulu","az":"Azeri","id":"Indonesian",'
+ '"nn":"Norwegian (Nynorsk)","no":"Norwegian",'
+ '"nb":"Norwegian (Bokmål)","ne":"Nepali","fr":"French",'
+ '"fa":"Farsi","fi":"Finnish","fo":"Faroese","ka":"Georgian",'
+ '"ss":"Swedish (Sweden)","sq":"Albanian","ko":"Korean",'
+ '"sv":"Swedish","km":"Khmer","kl":"Klingon","sk":"Slovak",'
+ '"sn":"Sindarin","sl":"Slovenian","ky":"Kyrgyz",'
+ '"sf":"Swedish (Finland)","sw":"Swahili","zh":"Chinese"}');
var activeClass = "";
var duoState = JSON.parse(localStorage.getItem('duo.state'));
var targetLang = duoState.user.learningLanguage;
var sourceLang = duoState.user.fromLanguage;
/* --------------------------------------
* Prototypes Section
* --------------------------------------*/
/* Restore console */
var _i = document.createElement('iframe');
_i.style.display = 'none';
document.body.appendChild(_i);
console_alt = _i.contentWindow.console;
function debug(objectToLog) {
console_alt.debug("[" + K_PLUGIN_NAME + "]: %o", objectToLog);
}
function info(objectToLog) {
console_alt.info("[" + K_PLUGIN_NAME + "]: %o", objectToLog);
}
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
Element.prototype.parentN = function (n) {
if (parseInt(n) <= 0) {
return this;
}
return this.parentElement.parentN(n - 1);
}
String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
/* --------------------------------------
* UI-elements Section
* --------------------------------------*/
function getFirstElementByDataTestValue(data_test) {
return document.querySelector("[data-test='" + data_test + "']");
}
function getFirstMatchingElementByDataTestValue(data_test) {
return document.querySelector("*[data-test*='" + data_test + "']");
}
function getElementsByDataTestValue(data_test) {
return document.querySelectorAll("[data-test='" + data_test + "']");
}
function getMatchingElementsByDataTestValue(data_test) {
return document.querySelectorAll("[data-test*='" + data_test + "']");
}
function getDuoTree() {
return getFirstElementByDataTestValue("skill-tree");
}
function getChallenge() {
return getFirstMatchingElementByDataTestValue("challenge");
}
function getChallengeHeader() {
return getFirstElementByDataTestValue("challenge-header");
}
function getTranslatePrompt() {
const first_token = getHintSentence()
return first_token.parentNode;
}
function getHintSentence() {
const first_token = getHintToken()
return first_token.parentNode;
}
function getHintToken() {
return getFirstElementByDataTestValue("hint-token");
}
function getFormPrompt() {
return getFirstElementByDataTestValue("challenge-form-prompt");
}
function getInputBoxes() {
return getElementsByDataTestValue("challenge-text-input");
}
function getCardChoices() {
return getElementsByDataTestValue("challenge-choice-card-input");
}
function getChoiceBox() {
return getFirstElementByDataTestValue("challenge-choice").parentNode;
}
function getChoices() {
return getElementsByDataTestValue("challenge-choice");
}
function getChoicesText() {
return getElementsByDataTestValue("challenge-judge-text");
}
function getChoosenAnser() {
const choices = Array.prototype.slice.call(getChoices());
const answers = Array.prototype.slice.call(getChoicesText());
for (var i = 0; i < choices.length; i++) {
if (choices[i].attributes["aria-checked"].value == "true") {
return answers[i];
}
}
}
function getFirstTapToken() {
var first_token = getFirstElementByDataTestValue("challenge-tap-token");
return first_token;
}
function getTappedAnswer() {
const first_token = getFirstTapToken();
const parent_token = first_token.parentN(3);
if (parent_token.hasAttribute("dir")) {
return parent_token;
}
return parent_token.parentElement;
}
function getAnswerFooter() {
return getFirstMatchingElementByDataTestValue("blame")
}
function getFirstAnswerInFooter() {
answers = getAnswerFooter().getElementsByTagName("h2");
if (answers.length > 0) {
return answers[0].nextSibling;
}
return null;
}
function getLastAnswerInFooter() {
answers = getAnswerFooter().getElementsByTagName("h2");
if (answers.length > 0) {
return answers[answers.length - 1].nextSibling;
}
return null;
}
/* Turns a stylesheet (as a string) into a style element */
function toStyleElem(css) {
var style = document.createElement('style');
style.className = "enhancer-stylesheet";
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
return style;
}
function addCSSHiding(css) {
//debug("addCSSHiding: " + css);
var style = toStyleElem(css);
document.head.appendChild(style);
}
/* Stylesheet for the hiding text */
// HARDCODED CLASSNAME HERE -> Hide orange new words
css_style_hide_text = `{parent} {child}:not(:hover){
background-color: #def0a5;
color: #def0a5;
transition: .2s;
flex-basis:100%
}
{child}:hover {
transition: .5s;
flex-basis:100%
}
{child} span[data-test="hint-token"] {
color: #3c3c3c;
}
{child} ._1bkpY:not(:hover) {
color: inherit;
}
`;
css_style_hide_pic = `{parent} {child}:not(:hover){
transition: .2s;
opacity: 0;
}
{child}:hover {
transition: .5s;
opacity: 1;
}`;
function revealElements() {
var styles = document.getElementsByClassName("enhancer-stylesheet");
for (var i = styles.length - 1; i >= 0; i--) {
styles[i].parentNode.removeChild(styles[i]);
}
}
function hideElements(elements, css) {
// elements can be an array or an HTMLCollection
// better use the old safe for cycle
//debug("hideElements");
//debug(elements);
// Make the style dependent on parent. Important for multiple selection
const parent_class = elements[0].parentElement.classList[0];
const child_class = ["enhancer-hide-class", parent_class].filter(Boolean).join("-");
const parent_style = (parent_class) ? "." + parent_class : "";
const child_style = "."+child_class;
addCSSHiding(css.formatUnicorn({parent:parent_style, child: child_style}));
elements.forEach(element => {
element.classList.add(child_class);
if (element.parentElement.firstChild != element) {
element.parentElement.style = "display:flex;";
}
});
//debug("hidden elements: " + elements.length);
}
function hideTextElements(elements) {
//debug("hideTextElements");
hideElements(elements, css_style_hide_text);
}
function hidePicElements(elements) {
//debug("hidePicElements");
hideElements(elements, css_style_hide_pic);
}
/* Put an element inside a flexbox */
function putInFlexbox(element, id = "enhancer-flexbox") {
// Put everything inside a flexbox
//debug("putInFlexbox");
//debug(element);
if (element.id == id) {
//debug("Found myself!");
return element;
}
if (element.parentNode.id == id) {
//debug("Found my parent!");
return element.parentNode;
}
var flexbox = document.createElement("div");
flexbox.style = "display: flex";
//debug(element.parentNode);
element.parentNode.insertBefore(flexbox, element);
flexbox.appendChild(element);
flexbox.id = id;
element.style = "width:100%";
return flexbox;
}
/* Audio functions and variables*/
var global_counter = 0;
// Play an audio element.
function playURL(url, speaker_button) {
debug("Playing URL " + url);
const audio_id = "audio-userscript-cm-" + (++global_counter % 10);
let audio = document.createElement('audio');
audio.classList.add("enhancer-audio-class");
audio.setAttribute("id", audio_id);
audio.setAttribute("autoplay", "true");
var source = document.createElement('source');
source.setAttribute("type", "audio/mpeg");
source.setAttribute("src", url);
audio.appendChild(source);
var div = document.getElementById("empty-play-button-cm");
if (div != null) {
var play_button = document.createElement('div');
play_button.style = K_SPEAKER_ICON_STYLE;
play_button.appendChild(audio);
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "28");
svg.setAttribute("height", "32");
svg.setAttribute("version", "1.1");
var ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
ellipse.setAttribute("cx", "17");
ellipse.setAttribute("cy", "17");
ellipse.setAttribute("rx", "10");
ellipse.setAttribute("ry", "10");
ellipse.style = "fill:none;stroke:#1cb0f6;stroke-width:5;stroke-linecap:round";
svg.appendChild(ellipse);
play_button.appendChild(svg);
div.addEventListener('click',function(){audio.play();});
div.removeAttribute("id"); // Make it anonymous
div.appendChild(play_button);
} else {
// Not sure what to do with it
// speaker_button.insertBefore(audio, document.body);
}
audio.load();
}
// play OS TTS
function playTTS(url, lang, speaker_button) {
//debug("Web Speech in "+lang);
let synth = window.speechSynthesis;
let voices = window.speechSynthesis.getVoices();
let voiceSelect;
for (let i = 0; i < voices.length; i++) {
if(voices[i].lang.includes(lang)) {
voiceSelect = i;
}
}
let utter = new SpeechSynthesisUtterance(url);
utter.voice = voices[voiceSelect];
var div = document.getElementById("empty-play-button-cm");
if (div != null) {
var play_button = document.createElement('div');
play_button.style = K_SPEAKER_ICON_STYLE;
// play_button.appendChild(audio);
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "28");
svg.setAttribute("height", "32");
svg.setAttribute("version", "1.1");
var ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
ellipse.setAttribute("cx", "17");
ellipse.setAttribute("cy", "17");
ellipse.setAttribute("rx", "10");
ellipse.setAttribute("ry", "10");
ellipse.style = "fill:none;stroke:#1cb0f6;stroke-width:5;stroke-linecap:round";
svg.appendChild(ellipse);
play_button.appendChild(svg);
div.addEventListener('click',function(){synth.speak(utter);});
div.removeAttribute("id"); // Make it anonymous
div.appendChild(play_button);
} else {
// speaker_button.insertBefore(audio, document.body);
}
synth.speak(utter);
}
// Play a sentence using the first available TTS
function playSound(sentence, lang, speaker_button) {
var url = "";
for (i = 0; i < sayFuncOrder.length; i++) {
try {
//debug("playSound loop " + sayFuncOrder[i]);
if (sayFunc[sayFuncOrder[i]](sentence, lang, speaker_button)) {
break;
}
} catch (err) {
// Do nothing, I don't care
}
}
}
// Google TTS Functions
// ====================
//
function googleTTSLang(target) {
if (target == "dn") {
return "nl";
}
if (target == "zs") {
return "zh";
}
return target;
}
function osttsSay(sentence, lang, speaker_button) {
playTTS(sentence, lang, speaker_button);
return true;
}
function googleSay(sentence, lang, speaker_button) {
// Create Google TTS in a way that it doesn't get tired that quickly.
var gRand = function() {
return Math.floor(Math.random() * 1000000) + '|'
+ Math.floor(Math.random() * 1000000)
};
url = "https://translate.google.com/translate_tts?ie=UTF-8&tl="
+ googleTTSLang(lang) + "&total=1&textlen=" + sentence.length
+ "&q=" + encodeURIComponent(sentence)
+ "&client=tw-ob"+ "&tk=" + gRand();
playURL(url, speaker_button);
return true;
}
// Yandex TTS Functions
// ====================
//
function yandexTTSLang(target) {
switch (target) {
case 'ar': return 'ar_AE';
case 'ca': return 'ca_ES';
case 'cs': return 'cs_CZ';
case 'da': return 'da_DK';
case 'de': return 'de_DE';
case 'el': return 'el_GR';
case 'en': return 'en_GB';
case 'es': return 'es_ES';
case 'fi': return 'fi_FI';
case 'fr': return 'fr_FR';
case 'it': return 'it_IT';
case 'dn': return 'nl_NL';
case 'no': return 'no_NO';
case 'pl': return 'pl_PL';
case 'pt': return 'pt_PT';
case 'ru': return 'ru_RU';
case 'se': return 'sv_SE';
case 'tr': return 'tr_TR';
}
return lang;
};
function yandexSay(sentence, lang, speaker_button) {
var sayLang = yandexTTSLang(lang);
//debug("Yandex " + sayLang);
if (sayLang != undefined) {
url = 'http://tts.voicetech.yandex.net/tts?text='
+ encodeURIComponent(sentence) + '&lang=' + sayLang
+ '&format=mp3&quality=hi';
playURL(url, speaker_button);
return true;
}
return false;
};
// Baidu TTS Functions
// ====================
// Duolingo to Baidu language codes
function baiduTTSLang(lang) {
switch (lang) {
case 'zs': return 'zh'; // Chinese
}
return lang;
};
function baiduSay(sentence, lang, speaker_button) {
var sayLang = baiduTTSLang(lang);
//debug("Baidu " + sayLang + " " + lang);
if (sayLang != undefined) {
url = 'http://tts.baidu.com/text2audio?text='
+ encodeURIComponent(sentence) + '&lan=' + sayLang
+ '&ie=UTF-8';
playURL(url, speaker_button);
return true;
}
return false;
}
// List of supported TTS providers
var sayFunc = new Array();
sayFunc['baidu'] = baiduSay;
sayFunc['google'] = googleSay;
sayFunc['yandex'] = yandexSay;
sayFunc['ostts'] = osttsSay;
var sayFuncOrder = [ 'ostts', 'baidu', 'yandex', 'google', ];
function insertNodeAfter(node, after) {
if (after.nextSibling != null) {
//debug("New play button after!");
after.parentNode.insertBefore(node, after.nextSibling);
} else {
//debug("New play button end!");
after.parentNode.appendChild(node);
}
}
function insertNodeBefore(node, before) {
//debug("New button before!");
before.parentNode.insertBefore(node, before);
}
// Say a sentence
function say(itemToSay, lang, node, css) {
var sentence = itemToSay.type == "textarea" ? itemToSay.textContent : itemToSay.innerText;;
sentence = sentence.replace(/•/g, "");
sentence = sentence.replace(/\.\./g, ".");
sentence = sentence.replace(/\n/g," ");
info("Saying '" + sentence + "'");
var div = document.createElement('button');
div.className = K_SPEAKER_BUTTON + " enhancer-media-button";
div.id = "empty-play-button-cm";
try {
div.style = css;
} catch (err) {
// Do nothing, really
}
if (typeof (lang) != 'undefined') {
if (typeof (node) != 'undefined') {
putInFlexbox(node);
insertNodeBefore(div, node);
} else {
putInFlexbox(itemToSay);
insertNodeBefore(div, itemToSay);
}
playSound(sentence, lang, div);
} else {
// Do nothing, really
}
}
function keyUpHandler(e) {
if (e.altKey && e.ctrlKey && (e.keyCode == 75)) {
const audio_elements = document.getElementsByClassName("enhancer-media-button");
//debug(audio_elements)
if (audio_elements.length < 1) {
return;
}
const audio = audio_elements[++global_counter % audio_elements.length];
//debug(audio);
audio.click();
} else if (e.altKey && e.ctrlKey && (e.keyCode == 72)) {
revealElements();
} else {
}
}
document.addEventListener('keyup', keyUpHandler, false);
/* Functions acting on the various types of exercices */
/* Translation from target language (eg. Polish) */
function challengeTranslate(challenge) {
//debug("challengeTranslate");
var question_box = getTranslatePrompt();
var answerbox = challenge.getElementsByTagName("textarea");
var input_area = answerbox[0];
var question_hint = getHintSentence();
const speaker_button = question_box.getElementsByTagName("button");
const has_button = speaker_button.length != 0;
const has_enhancer_button = has_button ? /enhancer-media-button/.test(speaker_button[0].className) : false;
if (input_area !== undefined) {
lang = input_area.getAttribute("lang");
if (isCheckSpell()) {
input_area.setAttribute("spellcheck", "true");
}
} else {
//debug("Tapped exercise "+has_button+" "+has_enhancer_button);
input_area = getTappedAnswer();
if (!has_button || has_enhancer_button) {
// Not sure how to figure out which language it is.
// Most likely it is a source to target challenge,
// since target to source should have a sound icon already,
// but it is still just a guess
lang = targetLang;
} else {
lang = sourceLang;
}
//debug("Probably translating to: " + lang);
}
if (lang == targetLang) {
question = sourceLang;
answer = targetLang;
} else {
question = targetLang;
answer = sourceLang;
}
//debug("challengeTranslate from "+question+" to "+answer);
if (/answer/.test(activeClass)) {
//debug("We have an answer");
input_area.disabled = false;
revealElements();
// Read the answer aloud if necessary
if (/answer-correct/.test(activeClass)) { // Answer is right
var grade = getFirstAnswerInFooter();
if (grade == null) {
//debug("perfect answer!")
grade = input_area;
}
if (isSayText(answer)) {
say(grade, answer, input_area);
}
} else {
sayAnswersInFooter(input_area, answer);
}
} else {
//debug("Should we read the question?");
if (isHideText(question)) {
hideTextElements([question_hint]);
}
//debug(question_hint);
// Read the question aloud if no TTS is available
if (isSayText(question)) {
// We know there is not TTS because there is no play button
if (!has_button) {
//debug("Read the question aloud");
say(question_hint, question);
} else {
//debug("just log the question");
say(question_hint); // No lang
}
}
}
}
/* Speak question */
function challengeSpeak(challenge) {
if (/answer/.test(activeClass)) {
revealElements();
} else {
var question_hint = getHintSentence();
if (isHideText(targetLang)) {
hideTextElements([question_hint]);
}
if (isSayText(targetLang)) {
say(question_hint);
}
}
}
/* Multiple-choice translation question */
function challengeJudge(challenge) {
//debug("challengeJudge");
// HARDCODED CLASSNAME HERE -> ChallengeJudge doesn't have a "data-" hint
var textCell = challenge.getElementsByClassName(K_CHALLENGE_JUDGE_QUESTION)[0];
if (/answer/.test(activeClass)) {
//debug("challengeJudge answer");
revealElements();
if (isSayText(targetLang)) {
var selection_row = getChoiceBox();
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("challengeJudge correct");
grade = getChoosenAnser();
say(grade, targetLang, grade.parentElement);
} else {
//debug("challengeJudge incorrect");
sayAnswersInFooter(selection_row, targetLang);
}
}
} else { // Asking a question
//debug("challengeJudge question");
// Do we want to hide the target language?
if (isHideTranslations()) {
//debug("challengeJudge Hiding target");
const choices = Array.prototype.slice.call(getChoicesText());
hideTextElements(choices);
}
if (isHideText(sourceLang)) {
hideTextElements([textCell]);
}
if (isSayText(sourceLang)) {
//debug("challengeJudge: Sentence to translate");
say(textCell, sourceLang);
}
}
}
/* Type in a missing word */
function challengeComplete(challenge) {
//debug("challengeComplete");
var question_hint = getHintSentence();
var input_boxes = getInputBoxes();
if (isHideText(sourceLang)) {
hideTextElements([question_hint]);
}
//debug("challengeComplete from "+sourceLang+" to "+targetLang);
if (/answer/.test(activeClass)) {
//debug("We have an answer");
revealElements();
if (isSayText(targetLang)) {
// Read the answer aloud if necessary
var grade = getFirstAnswerInFooter();
if (grade == null && input_boxes.length > 0) {
// Make the whole answer a single text
//debug("You were right");
var answer_box = input_boxes[0].parentNode.parentNode;
for (var i = 0; i < input_boxes.length; i++) {
var input_box = input_boxes[i];
var box_to_fix = input_box.parentNode;
//debug(box_to_fix)
var ansText = input_box.value;
box_to_fix.innerHTML = ansText;
}
say(answer_box, targetLang);
} else {
//debug("You made a mistake");
say(grade, targetLang);
}
}
} else {
if (isHideText(sourceLang)) {
hideTextElements([question_hint]);
}
if (isSayText(sourceLang)) {
// challengeComplete is always source->target
say(question_hint, sourceLang); // No lang
}
}
}
/* Tap missing words */
function challengeTapComplete(challenge) {
//debug("challengeTapComplete");
//debug("challengeTapComplete from "+sourceLang+" to "+targetLang);
if (/answer/.test(activeClass)) {
//debug("We have an answer");
revealElements();
if (isSayText(targetLang)) {
// Read the answer aloud if necessary
var grade = getFirstAnswerInFooter();
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("You were right");
var full_sentence = getHintSentence().parentNode;
say(full_sentence, targetLang);
} else {
//debug("You made a mistake");
say(grade, targetLang);
}
}
} else {
// Nothing to do here
}
}
/* Tap missing endings */
function challengeTapCloze(challenge) {
//debug("challengeTapCloze");
//debug("challengeTapCloze from "+sourceLang+" to "+targetLang);
if (/answer/.test(activeClass)) {
//debug("We have an answer");
if (isSayText(targetLang)) {
// Read the answer aloud if necessary
var grade = getFirstAnswerInFooter();
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("You were right");
const full_sentence = getHintSentence().parentNode;
var elements_to_remove = full_sentence.getElementsByClassName("_70ERZ");
//debug(full_sentence);
for (var i = elements_to_remove.length - 1; i >= 0; i--) {
elements_to_remove[i].remove();
}
var token_answer = getFirstTapToken().parentN(4);
//debug(token_answer);
const full_answer = token_answer.innerText.replace(/[\n\r]/g, '');
token_answer.innerHTML = full_answer;
say(full_sentence, targetLang);
} else {
//debug("You made a mistake");
say(grade, targetLang);
}
}
} else {
// Nothing to do here
}
}
/* Type missing endings */
function challengeTypeCloze(challenge) {
//debug("challengeTypeCloze");
//debug("challengeTypeCloze from "+sourceLang+" to "+targetLang);
if (/answer/.test(activeClass)) {
//debug("We have an answer");
if (isSayText(targetLang)) {
// Read the answer aloud if necessary
var grade = getFirstAnswerInFooter();
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("You were right");
var full_sentence = getHintSentence().parentNode;
const input_fields= full_sentence.getElementsByTagName("input");
if (input_fields.length > 0) {
const input_field = input_fields[0];
//debug(input_field);
var word_to_replace = input_field.parentNode;
var word_to_join = word_to_replace.parentNode;
const answer = input_field.value;
word_to_replace.innerHTML = answer;
// Join all word parts without new-line chars
const full_answer = word_to_join.innerText.replace(/[\n\r]/g, '');
word_to_join.innerHTML = full_answer;
}
say(full_sentence, targetLang);
} else {
//debug("You made a mistake");
say(grade, targetLang);
}
}
} else {
// Nothing to do here
}
}
/* Select the correct image */
function challengeSelect(challenge) {
//debug("challengeSelect");
if (/answer/.test(activeClass)) {
revealElements();
} else {
//debug("challengeSelect question");
if (isHidePics()) {
const choices = Array.prototype.slice.call(getCardChoices());
const images = choices.map(choice => choice.nextElementSibling);
hidePicElements(images);
}
const textCell = getChallengeHeader();
if (isHideText(sourceLang)) {
hideTextElements([textCell]);
}
if (isSayText(sourceLang)) {
say(textCell, sourceLang);
}
}
}
/* Type the word corresponding to the images */
function challengeName(challenge) {
//debug("challengeName");
if (/answer/.test(activeClass)) {
revealElements();
} else {
const textCell = getChallengeHeader();
if (isHidePics()) {
const input_boxes = getInputBoxes()
var pic_to_hide = input_boxes[0].parentN(2).firstChild;
hidePicElements([pic_to_hide]);
}
if (isHideText(sourceLang)) {
hideTextElements([textCell]);
}
if (isSayText(sourceLang)) {
say(textCell, sourceLang);
}
}
}
/*
* Choose the missing word in the sentence.
*/
function challengeForm(challenge) {
//debug("challengeForm");
if (/answer/.test(activeClass)) {
if (isSayText(targetLang)) {
var grade = null;
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("challengeForm correct");
grade = getChoosenAnser();
} else {
//debug("challengeForm incorrect");
grade = getFirstAnswerInFooter();
}
//debug(grade);
var ansText = grade.innerText;
//debug(ansText);
var parent_span = getFormPrompt().firstChild;
//debug(parent_span);
parent_span.childNodes.forEach(node => { if (node.className != "") { node.innerHTML = ansText } });
say(parent_span, targetLang);
}
if (isSayText(sourceLang)) {
if (!isSayText(targetLang)) {
sayAnswersInFooter();
} else {
say(getLastAnswerInFooter());
}
}
} else {
//debug("Challenge Form: nothing to read here");
}
}
/*
* Choose the missing word in the sentence.
*/
function challengeGapFill(challenge) {
//debug("challengeGapFill");
if (/answer/.test(activeClass)) {
if (isSayText(targetLang)) {
var grade = null;
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("challengeGapFill correct");
grade = getChoosenAnser();
} else {
//debug("challengeGapFill incorrect");
grade = getFirstAnswerInFooter();
}
var ansText = grade.innerText;
var parent_span = getHintSentence().parentNode;
//debug(parent_span);
parent_span.childNodes.forEach(node => { if (node.className != "") { node.innerHTML = ansText } });
say(parent_span, targetLang);
}
if (isSayText(sourceLang)) {
if (!isSayText(targetLang)) {
sayAnswersInFooter();
} else {
say(getLastAnswerInFooter());
}
}
} else {
//debug("Challenge Form: nothing to read here");
}
}
/*
* Choose the right answer to a dialog in the target language
*/
function challengeDialoge(challenge) {
//debug("challengeDialog");
if (/answer/.test(activeClass)) {
if (isSayText(targetLang)) {
var grade = null;
if (/answer-correct/.test(activeClass)) { // Answer is right
//debug("challengeDialog correct");