-
Notifications
You must be signed in to change notification settings - Fork 1
/
textmix.js
1270 lines (983 loc) · 43.2 KB
/
textmix.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
const urlParams = new URLSearchParams(window.location.search); //get everything after the ?
var needToLoadSaved = urlParams.get('loadsavedtext');
var saveCode = urlParams.get('savecode'); //(null if there's no saveCode specified)
var researchMode = urlParams.get('researchmode');
if (researchMode == 'true') { researchMode = true } //convert string to boolean
else {researchMode = false};
var scraperMode = urlParams.get('scrapermode');
if (scraperMode == 'true') { //convert string to boolean
scraperMode = true;
} else {scraperMode = false;}
var level = urlParams.get('level'); //which level JSON file to save the scraped text in
var mobile = false;
if (window.innerWidth<800) {
mobile = true;
}
//display or hide the language setting for wikipedia and the box to paste text if these settings are selected:
function languagePopup(yes) {
var opacity;
var clickable;
if (yes) {
opacity = '100%';
clickable = "auto";
getSettings();
if (mobile) {
document.getElementById('language-settings').style.display = "block";
}
} else {
opacity = '50%';
clickable = "none";
if (mobile) {
document.getElementById('language-settings').style.display = "none"; //hide it completely if mobile
}
};
document.getElementById('language-settings').style.opacity = opacity;
document.getElementById('language-settings').style.pointerEvents = clickable;
}
function pastePopup(yes) {
var display;
if (yes) {
display = 'block';
getSettings();
} else {
display = 'none';
};
document.getElementById('paste-div').style.display = display;
if (scraperMode) { document.getElementById('title-div').style.display = display };
}
function challengesPopup(yes, textFile) {
var display;
if (yes) {
display = 'block';
if (!studentMode) {
getSettings();
if (needToLoadPresetText) {
loadAllLevels = true; //load studentmode texts from ALL levels
var levels = "beg hi_beg int hi_int adv".split(" ");
for (i=0; i<levels.length; i++) {
var fileName = "studentmode_texts/" + levels[i]+".json"
loadPresetTexts(fileName)
}
needToLoadPresetText = false;
}
}
else { loadPresetTexts(textFile) }; //studentmode, so just load one level of texts
document.getElementById('start-button').style.display = "none";
document.getElementById('quickstart-button').style.display = "none";
document.getElementById('save-button').style.display = "none";
}
else {
display = 'none';
loadPresetTexts(textFile);
document.getElementById('start-button').style.display = "inline-block";
if (!mobile){document.getElementById('quickstart-button').style.display = "inline-block"};
document.getElementById('save-button').style.display = "inline-block";
};
document.getElementById('challenges-container').style.display = display;
}
function disappear(thing) {
thing.style.display = "none";
}
var studentMode = false;
var time;
var timer = document.getElementById('timer');
var score = 0;
var count = 0;
var rawText;
var listOfSentences = [];
var rand;
var rainbowMode = false;
var wordsArray = [];
var wordChunksArray = [];
var jumbledSentence = [];
var sentenceString = '';
var answerBox = document.getElementById('answerbox');
var answerSentence = document.getElementById('answersentence');
var answer;
var previousSentences = document.getElementById("previous-sentences-div");
var wordsToUndo =[];
var undoHistory =[];
var indexOfBlank;
var wordsEntered = 0; //number of words that have been clicked so far
var strikes = 3;
var wordChunkSize = 5;
var clozeSentence = [];
var clozeWords = [];
var randomMode = false;
var readingMode = false; //mode to keep sentences on the screen after they've been completed
var articleList = ['a','an','the'];
var prepList = ['in','at','on','for','of','with','out','to','from'];
var grammarList = [];
var clickedDivs = [];
var undoCount = 0;
var skip = false;
var dataSource;
var searchTerm;
var language = "simple";
var learningMode;
var foundArticle = false;
var progress = 0;
var progressBoxOuter = document.getElementById('progress-box-outer');
var progressBoxInner = document.getElementById('progress-box-inner');
var windowWidth = window.innerWidth;
var imageDiv;
var imageContainer;
var imageVisible = false;
var finishedSentences = 0;
var needToCheckRadios = true;
var needToLoadPresetText = true; //not loaded yet
var loadAllLevels = false; //for Teacher Mode, load the studentmode texts from ALL levels
var winScreen;
var reviewScreen;
var youWon;
var tryAgain;
var saved;
var existingData;
var presetTexts = [];
var printingWorksheet = false;
var targetWords;
var levelName;
var levelNames = {'beg': 'Beginner', 'hi_beg': 'High-Beginner', 'int': 'Intermediate', 'hi_int': 'High-Intermediate', 'adv': 'Advanced'}
var newTitle;
//for research mode:
var correctSentences = [];
var failedSentences = [];
var username;
// (no game over or strikes in research mode)
var loadScreen;
var undoButton = document.getElementById("undo-button");
var skipButton = document.getElementById("skip-button");
var quitButton = document.getElementById("quit-button");
var statusBar = document.getElementById("status-bar");
var saveScreen = document.getElementById("save-screen");
//set up stuff:
undoButton.addEventListener("click", undo);
skipButton.addEventListener("click", ready);
quitButton.addEventListener("click", resetApp);
if (researchMode) {
var txt = "Save & Quit";
quitButton.innerHTML = txt;
document.getElementById("main-menu-button").innerHTML = txt;
};
document.getElementById("main-menu-button").addEventListener("click", resetApp);
document.getElementById("try-again-button").addEventListener("click", function() {
tryAgain = true;
resetApp();
});
document.getElementById("back").addEventListener("click", goToStartScreen);
document.getElementById('start-button').addEventListener("click", runApp);
document.getElementById('quickstart-button').addEventListener("click", function() {
needToCheckRadios = false;
document.getElementById('search-term').value = "tea";
runApp();
});
document.getElementById('save-button').addEventListener("click", saveAndShare);
document.getElementById("skip-button").style.display = "none";
statusBar.style.display = "none";
loadTxtFile("100commonwords.txt"); //load the grammarList
//Setup scraper mode:
var textFile;
if (!scraperMode) {textFile = 'public_saved_texts.json'} //usual main JSON file
else { scraperModeSetup() };
function scraperModeSetup() {
textFile = 'studentmode_texts/' + level + '.json'; // beg.json, hi_beg.json, etc.
levelName = levelNames[level];
setTeacherStudent(false);
disappear(document.getElementById('quickstart-button'));
disappear(document.getElementById('start-button'));
document.getElementById('save-button').innerHTML = 'Add text';
document.getElementById('paste-div').style.display = 'block';
pastePopup(true);
document.getElementById('radio-paste').checked = 'checked';
dataSource = 'paste';
}
//Set up start screen:
function goToStartScreen() {
$('.settings-box').css("display","none");
$('.startscreen-box').css("display","block");
document.querySelector('footer').style.visibility = "visible";
disappear(document.getElementById('start-button'));
disappear(document.getElementById('quickstart-button'));
disappear(document.getElementById('save-button'));
disappear(document.getElementById('back'));
}
if (!scraperMode) { goToStartScreen() };
if (researchMode) {
disappear(document.getElementById('settings-area'));
document.getElementById('start-text').innerHTML += "Please choose a text to start:"
username = prompt("Please enter your username:");
setTeacherStudent(true); //skip the teacher/student select screen
}
function setTeacherStudent(student) {
//STUDENT MODE IS LIKE "CAMPAIGN MODE" - everything (except level and learning mode) is preset and ready to go
if (student) {
studentMode = true;
level = 'int';
dataSource = "preset text";
if (researchMode) {challengesPopup(true, 'studentmode_texts/researchtexts.json')}
else {challengesPopup(true, 'studentmode_texts/int.json')}; //start with this set of challenges
if (!researchMode) {document.getElementById('studentmode-level-settings').style.display = "block"};
if (!researchMode) {document.getElementById('learning-mode-settings').style.display = "block" }; //researchMode is only for sentence jumble activities (no cloze)
}
else {
$('#settings-screen').css("display","block");
$('.settings-box').css("display","block");
disappear(document.getElementById('studentmode-level-settings'));
disappear(document.getElementById('paste-div'));
disappear(document.getElementById('title-div'));
disappear(document.getElementById('challenges-container'));
document.getElementById('start-button').style.display = "inline-block";
if (!mobile){document.getElementById('quickstart-button').style.display = "inline-block"};
document.getElementById('save-button').style.display = "inline-block";
};
//Once the user has chosen either student or teacher mode:
$('.startscreen-box').css("display","none");
disappear(saveScreen);
disappear(document.getElementById('select-teacher-student'));
document.querySelector('footer').style.visibility = "hidden";
if (!researchMode) {document.getElementById("back").style.display = "block" };
}
//create popup explanations:
function createPopupExplanations(thingToHoverOver, textToPopup) {
thingToHoverOver.addEventListener("mouseover", function() {
document.getElementById('popup-explanation').style.visibility = "visible";
document.getElementById('popup-explanation').innerHTML = textToPopup;
});
thingToHoverOver.addEventListener("mouseout", function() {
document.getElementById('popup-explanation').style.visibility = "hidden";
})
}
if (!scraperMode) {
createPopupExplanations(document.getElementById('start-button'), "Start the game with the above settings.");
createPopupExplanations(document.getElementById('quickstart-button'), "Start the game with a random text and default settings.");
createPopupExplanations(document.getElementById('save-button'), "Create a game with the above settings and get a unique URL to share with students.");
createPopupExplanations(document.getElementById('wordchunk-settings'), "Choose how each sentence is split. '1' means a traditional word jumble where each word must be unscrambled.");
createPopupExplanations(document.getElementById('game-mode-settings'), "Preset sentences randomly or in order. In 'reading mode', completed sentences stay on the screen so you can ready the next sentence in context.");
createPopupExplanations(document.getElementById('learning-mode-settings'), "Choose what kind of practice the activity should provide.");
createPopupExplanations(document.getElementById('text-source-settings'), "Select the source of text. If 'Wikipedia', also select language and search term.");
createPopupExplanations(document.getElementById('language-settings'), "(For Wikipedia text) Choose the language and search term to get an article exerpt. Case sensitive - must capitalize proper nouns!");
createPopupExplanations(document.getElementById('studentmode-button'), "Practice your English with fun sentence scramble and fill-in-the-blank games!");
createPopupExplanations(document.getElementById('teachermode-button'), "Create a customized cloze or sentence scramble activity for your students. Choose the text, format, and more.");
}
//set up challenges
function loadPresetTexts(jsonFileName) {
readOrWriteData(null, 'get all texts', null, null, null, jsonFileName); //This will set up presetTexts array
}
function makePresetTextDivs() { //This function gets run by readOrWriteData after presetTexts have been loaded
// if (needToLoadPresetText) { // if not yet loaded
var challengesContainer = document.getElementById('challenges-container');
//first clear the challenges-container:
if (!loadAllLevels) {
while (challengesContainer.firstChild) {
challengesContainer.removeChild(challengesContainer.firstChild);
}
}
//make the preset text (challenge) divs:
for (i=0; i<presetTexts.length; i++) {
var challengeDiv = document.createElement('div');
challengeDiv.setAttribute("class", "challenge");
challengeDiv.setAttribute("id", "challenge-"+i);
challengesContainer.appendChild(challengeDiv);
var title;
if (researchMode) { title = existingData.listOfTexts[i].title }
else { title = existingData[i].title}
challengeDiv.innerHTML = "<b>"+title+"</b>" + "<br><br>( "+presetTexts[i].length+" sentences )";
// Add the level to each challenge div, if loading all levels:
if (loadAllLevels) {challengeDiv.innerHTML += "<br>" + existingData[i].level} ;
};
//Once all the divs have been made, add the event listeners (must do this separately so it doesn't keep looping the creation of event listeners over just the variable challengeDiv):
for (i=0; i<presetTexts.length; i++) {
document.getElementById("challenge-"+i).addEventListener("click", function() {
var index = parseInt(this.id.substr(10)); //get the number of the challenge div (same as i, but can't use i here because i is part of this FOR loop, which can't be seen by the function later on)
if (!researchMode) {
rawText = presetTexts[index].join(". ")
listOfSentences = presetTexts[index];
}
else { // research texts aren't split into sentences yet
rawText = presetTexts[index];
listOfSentences = splitText(presetTexts[index]);
}
runApp();
});
}
if (studentMode && !researchMode) { showAttribution() };
};
// if (!studentMode) {needToLoadPresetText = false;} //prevent it from loading again if this radio button is unclicked and then clicked again
//}
// CHECK IF SAVECODE IS SPECIFIED --------------------------
function loadSavedText() {
//If loading from saved URL, ignore all the setup stuff below; just load the text and readOrWriteData() will handle the rest
if(needToLoadSaved == 'yes') {
dataSource = "load";
learningMode = 'jumble';
needToCheckRadios = false;
statusBar.style.display = "inline-block";
//load up the text:
readOrWriteData(saveCode, 'read one text', null, null, null, textFile); //this sets existingData. saveCode tells which array in the array of arrays in the JSON file. This array will be set as listOfSentences.
console.log("Loaded text from JSON file.");
} else{
console.log("Didn't load text; settings must be chosen.");
};
}
loadSavedText();
// ----------------------------------------------------
//Set up the "save & share" option:
//pass parameters through the URL like this: ?name=brendon&hair=brown
function saveAndShare() { //save the text you chose and spit out a URL to share with others
saved = true; //Let's it know that it's been saved, so savedScreen can be removed later
saveCode = randomColor().split("#")[1]; //get random string without the #
var urlToShare = location.protocol + '//' + location.host + location.pathname + "?loadsavedtext=yes" + "&savecode=" + saveCode;
var urlField = document.getElementById('saved-url-field');
urlField.value = urlToShare;
$('#settings-screen').css('display','none');
$('#save-screen').css('display','block');
urlField.onclick = function() {
this.select();
document.execCommand('copy');
var p = document.createElement('p');
p.innerHTML = "<h2>Copied to clipboard</h2>";
saveScreen.appendChild(p);
}
getSettings();
function writeWikiText() { //after wikiSearch is complete, run this as callback function.
rawText = document.getElementById("hidden-text-div").textContent;
listOfSentences = splitText(document.getElementById("hidden-text-div").textContent);
readOrWriteData(saveCode, "write", randomMode, wordChunkSize, listOfSentences, textFile);
}
if(dataSource == "wikipedia"){
searchTerm = document.getElementById('search-term').value;
wikiSearch(searchTerm, language, "hidden-text-div", writeWikiText);
}
else {
getText(); //run everything except getOneSentence() and makeDivs(). This will set up listOfSentences.
//finally, write the listOfSentences array to JSON file: saveCode tells which array in the array of arrays in the JSON file. This array will be set as listOfSentences.
readOrWriteData(saveCode, "write", randomMode, wordChunkSize, listOfSentences, textFile);
};
document.getElementById('play-now').addEventListener("click", function() {
window.location.href = urlToShare; // go to the link just created
});
}
function printWorksheet() {
printingWorksheet = true;
var worksheetData;
if (learningMode == 'jumble') {worksheetData = "<h3>Name: _______________________</h3><h3><b>Directions: </b>Reorder the words to make a sentence.</h3>"}
else {worksheetData = "<h3>Name: _______________________</h3><h3><b>Directions: </b>Write the correct word in each blank.</h3>"};
for (j=0; j<listOfSentences.length; j++) {
prepareSentence(); // this sets up jumbledSentence!
//for jumble mode:
if (learningMode == 'jumble') {
var wordChunk;
var item ='';
var wordBank = '';
for(i=0; i<jumbledSentence.length; i++) {
wordChunk = jumbledSentence[i].join(" ");
item += wordChunk + " / ";
};
worksheetData += (j+1) + ". " + item + "<br><br>________________________________________________________<br><br>";
}
//for cloze mode:
else {
item = clozeSentence.join(" ");
if (jumbledSentence != undefined) { //as long as there are articles in the sentence
for(i=0; i<jumbledSentence.length; i++) {
wordBank += jumbledSentence[i] + " ";
}
}
worksheetData += (j+1) + ". " + item + "<br><br>" + wordBank + "<br><br>";
}
count ++ ; // loop through listOfSentences
}
var newWindow = window.open();
newWindow.document.write(worksheetData);
}
function goToLoadScreen() {
loadScreen = createScreen("<br><br><br><h2>Are you ready?</h2><br><br>");
loadScreen.id = "load-screen";
document.body.appendChild(loadScreen);
var loadStartButton = document.createElement('div');
loadStartButton.className = "launcher-button";
loadStartButton.innerHTML = "START";
loadStartButton.addEventListener("click", function() {
disappear(document.getElementById("settings-screen"));
$("#load-screen").fadeOut(500, function () {
disappear(document.getElementById("load-screen"));
});
setInterval(incrementTime, 1000);
});
loadScreen.appendChild(loadStartButton);
}
function getSettings() {
//check the radio button settings:
if(needToCheckRadios) {
if (studentMode) {
checkRadio('studentmode-level')
checkRadio('learning');
}
else {
checkRadio('randomize');
checkRadio('wordchunk-size');
checkRadio('datasource');
checkRadio('language');
checkRadio('learning');
}
};
if(document.getElementById("timer-checkbox").checked == false || studentMode) {
timer.style.display = "none";
}
}
//set game settings based on radio buttons:
//set the corresponding setting variable
//this is 'DRY' CODING RIGHT HERE!!!
//can easily add new radio game settings here!
function checkRadio(radioName) {
var choices = document.getElementsByName(radioName);
for (i=0; i<choices.length; i++) {
if (choices[i].checked == true) { //if radio button selected
if(radioName == "randomize") {
if (choices[i].value == 'yes') {
randomMode = true;
}
else if (choices[i].value == 'no') {
randomMode = false;
}
else { //if reading mode is checked
readingMode = true;
}
}
else if (radioName == "wordchunk-size") {
wordChunkSize = parseInt(choices[i].value); //radio btn values can only be strings
}
else if (radioName == "studentmode-level") {
randomMode = false;
wordChunkSize = 4;
level = choices[i].value;
if (researchMode && level == 'int') {
challengesPopup(true, 'studentmode_texts/researchtexts.json')
}
else { challengesPopup(true, 'studentmode_texts/' + level + '.json') };
}
else if (radioName == "datasource") {
dataSource = choices[i].value;
if (dataSource == 'words') {
document.getElementById('paste-input').placeholder="Enter a list of target vocabulary words, separated by commas. Sentences will be generated based on these words."
}
if (dataSource == 'paste') {
document.getElementById('paste-input').placeholder="Paste some text! About a paragraph or so is good. A whole article is good for a challenge!"
}
}
else if (radioName == "learning") {
learningMode = choices[i].value;
if (choices[i].value != 'jumble') {
wordChunkSize = 1; //if articles or prepositions, set the word group size to 1
}
}
else {
language = choices[i].value;
};
} ;
};
};
function runApp() {
searchTerm = document.getElementById('search-term').value;
if (dataSource=='wikipedia' && searchTerm == ''){
alert('Please enter a search term!');
return;
}
if (needToLoadSaved == "yes") { //if ready() and getText() have already been run via make_text_file.js
goToLoadScreen()
}
else { //need to get text via getText() below
$("#settings-screen").fadeOut(500, function () {
disappear(document.getElementById("settings-screen"));
});
if (timer.style.display != "none" || researchMode) { //as long as the timer is turned on, or secretly time them in researchMode
setInterval(incrementTime, 1000);
};
statusBar.style.display = "inline-block";
getText();
}
}
function splitText(text) { //splits into sentences
sentences = text.split(/(?<!Mr|Mrs|Dr|Prof)\.\s|\."\s|\?\s/); //regex negative lookbehind
return sentences;
}
function cleanSentence(sentence) {
try { //if there aren't any periods or newlines to replace, this prevents an error
if (finishedSentences == listOfSentences.length - 1) { //if the last sentence is coming up
sentence = sentence.replace(".",""); //remove any period at the end of the sentence (if it's the last sentence, this period won't have been removed by split('.'))
}
sentence = sentence.replace(".\n",".");
sentence = sentence.replace( /[\r\n]+/gm, ""); //replace all carriage returns, etc.
} catch{}; //Note: double spaces after period are already removed via cleanText() in wikipedia_fetcher.js
return sentence;
}
function getOneSentence() {
if(dataSource == "wikipedia" && needToLoadSaved != "yes"){ //a.k.a. if we still need to send a request to wikipedia API
//hidden-text-div is where wikiSearch put the text
listOfSentences = splitText(document.getElementById("hidden-text-div").textContent);
};
//if source is not wikipedia, listOfSentences was already set by getText()
if(randomMode) {
rand = Math.floor(Math.random() * listOfSentences.length);
sentenceString = listOfSentences[rand];
} else {
sentenceString = listOfSentences[count];
};
cleanSentence(sentenceString);
return sentenceString;
}
function prepareSentence() { //what to do with the sentence once it done been got!
try{
wordChunksArray = getOneSentence().split(' ');
} catch{};
wordsArray = wordChunksArray; //get the list of words before they're chunked, for setting font size on mobile later
if (learningMode!= 'jumble') { makeClozeSentence() } //if cloze mode
else { //if normal word jumble (jumble) learning mode
console.log('Run as normal word jumble, no need to make cloze sentence.');
wordChunksArray = chunkArray(wordChunksArray, wordChunkSize); // Split up into word groups/chunks. This is an array of arrays (chunks of words) in CORRECT ORDER. Each array has a number of words equal to wordChunkSize.
jumbledSentence = shuffle(wordChunksArray); //mix up the arrays within the array
}
};
function makeClozeSentence() {
foundArticle = false;
wordChunksArray[wordChunksArray.length-1] += '.'; //add period to last word
if (!printingWorksheet && count < listOfSentences.length-2) { //as long as there are still 2 sentences left to get
count++; //get 2 sentences instead of 1 (better for articles, prepositions, etc)
finishedSentences++;
wordChunksArray = wordChunksArray.concat(getOneSentence().split(' '));
wordChunksArray[wordChunksArray.length-1] += '.';
};
clozeSentence = []; //reset it after completing a sentence
clozeWords = [];
for (i=0; i<wordChunksArray.length; i++) {
if (learningMode=='articles' && articleList.includes(wordChunksArray[i]) || learningMode=='prepositions' && prepList.includes(wordChunksArray[i]) || learningMode=='grammar' && grammarList.includes(wordChunksArray[i])) { //if the word is an article/preposition
clozeWords.push(wordChunksArray[i]); //these will be the word divs to click
clozeSentence.push("_____"); //add a blank to the new clozeSentence array
//this will be the sentence with blanks, added to the answerbox later
foundArticle = true;
} else{ //if not an article
clozeSentence.push(wordChunksArray[i]) //add the word to the new clozeSentence array
}
}
jumbledSentence = shuffle(clozeWords);
}
//must wait until Ajax is done getting Wikipedia text to run the following:
//(it's the callback function of wikiSearch)
function ready() {
if (skip) {
count++;
// do these things no matter which learning mode:
skipButton.style.display = "none";
undoButton.style.display = "inline-block"; //put back undo button (was removed by addSkipButton())
wordsEntered ++;
checkAnswer();
skip = false;
};
prepareSentence();
makeDivs();
}
function loadTxtFile(filename) {
//If loading from a txt file on computer
var req = new XMLHttpRequest();
req.open("GET", filename, true);
req.send();
var list;
req.onreadystatechange = function() {
if(this.readyState==4 && this.status==200) {
console.log('Loaded ' + filename);
grammarList = this.responseText.split(' ');
};
};
}
function getText() {
getSettings();
switch(dataSource) {
case "preset text":
//Do nothing - listOfSentences was already set up via loadPresetTexts()
ready();
break;
case "news":
newsSearch(ready);
break;
case "words":
wordChunkSize = 2;
targetWords = document.getElementById('paste-input').value.replace(/\s/g, "").split(',');
for (i=0; i<targetWords.length; i++) {
targetWords[i] = " " + targetWords[i] + " "; //surround the word by spaces
}
getExampleSentences(targetWords, ready);
break;
case "wikipedia":
var searchTerm = document.getElementById('search-term').value;
wikiSearch(searchTerm, language, "hidden-text-div", ready);
break;
case "paste":
rawText = document.getElementById('paste-input').value.replace(/. /g, ". "); //remove double spaces
listOfSentences = splitText(rawText);
if (scraperMode) {newTitle = document.getElementById('title-input').value}
ready();
break;
default: //if user chose to use the preset string of sentences
rawText = preMadeList;
listOfSentences = splitText(preMadeList);
ready();
};
};
/*JAPANESE VERSION (DOESN'T WORK):
listOfSentences = document.getElementById("hidden-text-div").textContent.split("。");
//split again by Japanese comma
for (i=0; i<listOfSentences.length; i++) {
var furtherSplit = listOfSentences[i].split("、");
listOfSentences.splice(i); //take out original sentence
for (w=0; w<furtherSplit.length; w++) {
listOfSentences.push(furtherSplit[w]); //add back in newly split sentences
};
};
}; */
function undo() {
if (undoCount>0) {
answerSentence.innerHTML = undoHistory[undoCount-1]; // undo by returning to the last answerSentence
undoHistory.splice(undoHistory.length-1, 1); //remove the last entry from undoHistory
clickedDivs.splice(clickedDivs.length-1, 1); //erase the undone word(s) from clickedDivs
document.getElementById(wordsToUndo[wordsToUndo.length-1]).style.visibility = "visible"; //bring the last clicked word div back (its ID will be the last item in the wordsToUndo array)
wordsToUndo.splice(wordsToUndo.length-1, 1); //delete the undone word from wordsToUndo array
wordsEntered --;
undoCount --;
console.log("undoCount = " + undoCount) ;
} else {console.log("Nothing to undo.")};
}
function addSkipButton() {
skipButton.style.display = "inline-block"
undoButton.style.display = "none";
skip = true;
}
function makeDivs() {
if (!researchMode) { time = 60 }
else {time = 0};
//reset stuff:
answerBox.style.backgroundColor = 'white';
answerSentence.style.backgroundColor = 'white';
answerSentence.style.color = '#4286f4';
undoHistory = [];
if(wordChunksArray.length>1) { //no need for undo button if only one word-div to click
undoButton.style.display = "inline-block";
}
undoCount = 0;
clickedDivs = [];
//for mobile, make font smaller if many words
if(mobile && wordsArray.length > 20) {
answerBox.style.fontSize = "26px";
} else if(mobile && wordsArray.length > 30) {
answerBox.style.fontSize = "20px";
} else {
answerBox.style.fontSize = "32px";
};
if (imageVisible) {
answerBox.removeChild(imageContainer);
imageVisible = false;
};
if (readingMode) { //move the just-completed sentence to Previous Sentences before deleting answerSentence.innerHTML
previousSentences.style.display = "block";
previousSentences.innerHTML += " " + answerSentence.innerHTML;
};
answerSentence.innerHTML = '';
$('.word-div').remove(); //clear all the word divs from the last round (also could do w/o JQuery)
// If the sentence has no articles/prepositions/grammar words, create skip button (cloze modes only):
if(learningMode != 'jumble' && !foundArticle) { addSkipButton() };
wordsEntered = 0;
// Display the cloze sentence:
if (learningMode != 'jumble') { // If cloze mode
for(i=0; i<clozeSentence.length; i++) { //clozeSentence is an array - must loop through to put each word in answer box as a string (or else it will show up with commas if set to innerHTML)
answerSentence.innerHTML += clozeSentence[i] + ' ';
};
answerSentence.innerHTML = answerSentence.innerHTML.slice(0,answerSentence.innerHTML.length-1);//remove space at end
}
var wordChunkString = '';
var noOfChars; //for counting the letters in a word div, to shrink font size if needed
//create the word divs:
for(i=0; i<jumbledSentence.length; i++) {
var div = document.createElement('div');
var wordChunk = jumbledSentence[i]; //if cloze mode, then jumbledSentence is actually word bank to fill in blanks. Instead of making divs from the words IN the sentence, only use the words REMOVED from the sentence (Articles, prepositions, etc.)
//Find how many characters long the wordchunk is (not how many words)
wordChunkString = '';
for (c=0; c<wordChunk.length; c++) { wordChunkString += wordChunk[c] };
noOfChars = wordChunkString.length;
//Shrink font size on mobile if many word divs OR many letters in a particular div
if(mobile && learningMode=='jumble' && jumbledSentence.length > 5 || noOfChars > 22) {
div.setAttribute('class','word-div small-word-div');
} else {
div.setAttribute('class', 'word-div');
};
div.setAttribute('id', 'word-' + i);
for (j=0; j<wordChunk.length; j++) {
if (learningMode == 'jumble') {
div.innerHTML += wordChunk[j] + " "; //add spaces between groups of words (not needed in cloze mode)
} else {
div.innerHTML += wordChunk[j];
}
};
div.addEventListener('click', clickedWord);
document.getElementById('word-div-container').appendChild(div);
};
};
function clickedWord() { //When you click a word/words
answerSentence = document.getElementById('answersentence'); //get the current status of the answer
wordsToUndo.push(this.id);
undoHistory.push(answerSentence.innerHTML); // save the sentence BEFORE blank is filled
undoCount ++;
console.log("undoCount = " + undoCount) ;
clickedDivs.push(this.innerHTML); //puts the clicked word(s) into an array
if (learningMode != 'jumble') { //if cloze mode:
answerSentence.innerHTML = answerSentence.innerHTML.replace('_____', this.innerHTML); //replace the FIRST blank with the clicked word
}
else { //if normal word jumble (jumble) mode:
answerSentence.innerHTML += clickedDivs[undoCount-1]; //add the word(s) to answerSentence
}
// do these things no matter which learning mode:
if (mobile && jumbledSentence.length>7) { //on mobile, make words reposition to fit after disappearing
$(this).css('display', 'none');
} else {
$(this).css('visibility', 'hidden');
}
wordsEntered ++;
if(wordsEntered == jumbledSentence.length) { //if all the words in the senetence have been entered
checkAnswer();
}
};
function checkAnswer() {
answer = answerSentence.textContent; //must use innerText, not innerHTML because   characters sometimes come up in wikipedia - innerText just renders them as normal spaces
// IF CORRECT (cloze modes do not add an extra space at the end)
if(answer == sentenceString + ' ' || answer == wordChunksArray.join(" ") && learningMode!='jumble' || skip==true) { //if you're skipping this last sentence, automatically win, don't even check for correctness
correctAnswer();
}
else { wrongAnswer() };
};
function correctAnswer() {
if (!skip) {
answerSentence.innerHTML = answer.substr(answer[0],answer.length-1) + '.'; //add period to the end. Skip will have already added one.
}
//Inrease score:
if (!researchMode) {score += wordChunksArray.length * time}
else {score += wordChunksArray.length * 100};
finishedSentences ++;
correctSentences.push(answer);
document.getElementById('score-box').innerHTML = "Score: " + score;
//Record if research mode:
if (researchMode) { recordForResearch(username, sentenceString, null, time) };
//Increase progress meter:
var totalSentences = listOfSentences.length;
progress = Math.floor(100*(finishedSentences / totalSentences));
document.getElementById('progress-box-outer').innerHTML = "Progress: " + progress + "% <div id='progress-box-inner'></div>";
var width = document.getElementById('progress-box-outer').offsetWidth;
document.getElementById('progress-box-inner').style.width = (progress/100)*width + "px";
if (progress == 100) { // all sentences are finished - YOU WIN!
win();
return; //stop reading this block of code (stuff below is for if you've not yet won the game)
};