-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
3270 lines (2932 loc) · 97.6 KB
/
main.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
/* * * * * * * * * *
PALMYRA
Copyright (c) 2019 New York University Abu Dhabi
License: MIT BSD-3
THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE U.S. GOVERNMENT OR ANY DEPARTMENTS OR EMPLOYEES THEREOF BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.)
* * * * * * * * * * */
// define a global root variable
// this allows the tree to persists
var root;
var currentTreeIndex = 0;
var treesArray = [];
var numberOfNodesArray = [];
var viewerHeight = 0;
var addNode;
var selectedNodeLink, selectedMorphology;
var nodeDeleted = false;
var rootNodeName = "*";
var enableNodeSelection = true;
// default settings that can be configured
var orientation = "r-to-l";
var listingKey = "text";
var newPOSTag = "NOM";
var newLinkLabel = "---";
var newNodeName = "*";
var editLemma = false;
// keeping tack of the pos tags, relation labels, and features, their values, and their defaults
var posTags = {};
var relLabels = {};
var featureValues = {};
var defaultFeatValues = {};
// lexical features that will be displayed as text fields
var lexicalFeatsList = [];
// variables to keep track of the keystrokes related to the editing of POS tags and relation labels
var pointer = 0;
var lastKeyStroke = "";
var editingControl = "pos";
var lastClickedNodeId = 0;
var focusWindow = "";
var isConlluLocal;
var configRead = false;
var settings = [
["customwidth", 0.25],
["customdepth", 100],
["nodesize", 10],
["xsep", 5],
["ysep", 10],
["currentFont", "standard"],
];
var undo_stack = new Array();
var redo_stack = new Array();
function undo() {
if (undo_stack.length > 1 && redo_stack.length < 10) {
redo_stack.push(undo_stack.pop());
// display tree
sessionStorage.removeItem("treeData");
saveTree();
d3.select("body").select("svg").remove();
getTree(undo_stack[undo_stack.length-1]);
update(root);
selectRoot();
showSelection();
// reset focusWindow
focusWindow = "";
}
}
function redo() {
if (redo_stack.length > 0) {
undo_stack.push(redo_stack.pop());
// display tree
sessionStorage.removeItem("treeData");
saveTree();
d3.select("body").select("svg").remove();
getTree(undo_stack[undo_stack.length-1]);
update(root);
selectRoot();
showSelection();
// reset focusWindow
focusWindow = "";
}
}
// update redo stack and undo stack when a tree is updated
function UndoRedoHelperOnTreeUpdate() {
if (undo_stack.length > 0) {
// limit undo steps to 10
if (undo_stack.length == 10) undo_stack.shift();
cur_version = undo_stack.pop();
undo_stack.push(JSON.parse(JSON.stringify(JSON.decycle(cur_version)))); // push deep copy of current version to stack
undo_stack.push(cur_version); // then push current version to stack for modification
redo_stack = new Array();
}
}
// update redo stack and undo stack when moving to a new tree
function UndoRedoHelperOnMoveToTree(treeIndex) {
undo_stack = new Array(treesArray[treeIndex]);
redo_stack = new Array();
}
function UndoRedoHelperOnTreePageSetUp() {
undo_stack = new Array(treesArray[0]);
}
// TODO: move to keyboardShortcuts.js
window.addEventListener('keydown', function(event) {
if ((event.metaKey || event.ctrlKey) && !event.shiftKey && (event.key === 'z' || event.key === 'Z')) undo();
if ((event.metaKey || event.ctrlKey) && event.shiftKey && ( event.key === 'z' || event.key === 'Z')) redo();
});
// if custom setting not saved, initialize with default
for (var k = 0; k < settings.length; k++) {
if (!localStorage[settings[k][0]]) {
localStorage[settings[k][0]] = settings[k][1];
}
}
// the main display function
var main = function () {
// in case extra toolbar windows are showing, hide them
view([$("#download"), $("#linktext"), $("#listing")], hideComponents);
findStorage();
$(".upload").show();
populateConfigFileSelector();
};
function hideComponents(ComponentsList) {
for (let component of ComponentsList) {
component.hide();
}
}
function view(ComponentsList, callback) {
callback(ComponentsList);
}
window.onbeforeunload = function () {
var message = "Do you want to leave this page?";
return message;
};
var findStorage = function () {
var check = "check";
try {
localStorage.setItem(check, check);
localStorage.removeItem(check);
return true;
} catch (e) {
alert("Your browser does not support Palmyra.");
}
};
// wait to call 'main' until the page has finished loading
$(document).ready(main);
$("[id='upload1']").hide();
$(window).resize(function () {
sessionStorage.removeItem("treeData");
saveTree();
d3.select("body").select("svg").remove();
getTree(treesArray[currentTreeIndex]);
// update(root);
});
// Add listener to textbox when downloading a file. When the enter key is pressed, the file will be downloaded
// TODO: move to keyboardShortcuts.js
var download_form = document.getElementById("filename");
download_form.addEventListener("keydown", function (event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("dwnbtn").click();
/* download_button.click(); */
/* document.querySelector('form').submit(); */
};
});
//Read the config file that is called when using the sentence uploader which will continue to call
//the readSentenceTreeData when the FileReader finishes loading the file.
var readConfigFileForSentence = async function () {
await readConfigFile();
readSentenceTreeData();
};
// converts JSON format tree to CONLL format
var convertJSONToCONLL = function (node) {
if (
typeof node.children === "undefined" &&
typeof node._children === "undefined"
) {
return [];
}
if (node.collapsed === false) {
node.features = "";
for (var featKey in node.feats) {
if (node.features === "") {
if (
featKey !== "_" &&
node.feats[featKey] !== "" &&
node.feats[featKey] !== "undefined"
) {
node.features = featKey + "=" + node.feats[featKey];
}
} else {
if (
featKey !== "_" &&
node.feats[featKey] !== "" &&
node.feats[featKey] !== "undefined"
) {
node.features += "|" + featKey + "=" + node.feats[featKey];
}
}
}
if (node.features === "") {
node.features = "_";
}
var fullArray = [];
if (typeof node.parent !== "undefined" && node.parent.id) {
var pid = (node.parent.id + 1) / 2;
} else pid = (node.pid + 1) / 2;
if (pid == 0.5) pid = 0;
for (var k = 0; k < node.children.length; k++) {
var tempArray = convertJSONToCONLL(node.children[k]);
fullArray = fullArray.concat(tempArray);
}
if (node.id !== 0) {
if (node.lemma === "") {
node.lemma = "_";
}
if (node.pos === "") {
node.pos = "_";
}
if (node.xpos === "") {
node.xpos = "_";
}
if (node.features === "") {
node.features = "_";
}
if (node.deps === "") {
node.deps = "_";
}
if (node.misc === "") {
node.misc = "_";
}
fullArray.push([
(node.id + 1) / 2,
node.name,
node.lemma,
node.pos,
node.xpos,
node.features,
pid,
node.link,
node.deps,
node.misc,
]);
} else {
fullArray.sort(function (a, b) {
return a[0] - b[0];
});
for (var i = 0; i < fullArray.length; i++) {
fullArray[i] = fullArray[i].join("\t");
}
fullArray = fullArray.join("\n");
}
return fullArray;
}
// include hidden nodes
else {
node.features = "";
for (var featKey in node.feats) {
if (node.features === "") {
if (
featKey !== "_" &&
node.feats[featKey] !== "" &&
node.feats[featKey] !== "undefined"
) {
node.features = featKey + "=" + node.feats[featKey];
}
} else {
if (
featKey !== "_" &&
node.feats[featKey] !== "" &&
node.feats[featKey] !== "undefined"
) {
node.features += "|" + featKey + "=" + node.feats[featKey];
}
}
}
if (node.features === "") {
node.features = "_";
}
var fullArray = [];
if (typeof node.parent !== "undefined" && node.parent.id) {
var pid = (node.parent.id + 1) / 2;
} else pid = (node.pid + 1) / 2;
if (pid == 0.5) pid = 0;
node.name = node.name.slice(2, -2);
for (var k = 0; k < node._children.length; k++) {
var tempArray = convertJSONToCONLL(node._children[k]);
fullArray = fullArray.concat(tempArray);
}
if (node.id !== 0) {
if (node.lemma === "") {
node.lemma = "_";
}
if (node.pos === "") {
node.pos = "_";
}
if (node.xpos === "") {
node.xpos = "_";
}
if (node.features === "") {
node.features = "_";
}
if (node.deps === "") {
node.deps = "_";
}
if (node.misc === "") {
node.misc = "_";
}
fullArray.push([
(node.id + 1) / 2,
node.name,
node.lemma,
node.pos,
node.xpos,
node.features,
pid,
node.link,
node.deps,
node.misc,
]);
} else {
fullArray.sort(function (a, b) {
return a[0] - b[0];
});
for (var i = 0; i < fullArray.length; i++) {
fullArray[i] = fullArray[i].join("\t");
}
fullArray = fullArray.join("\n");
}
return fullArray;
}
};
var outputToCONLLFormat = function (inputJSON) {
var inputArray = [];
var rootNodeIndex = 0;
var rootNode = new Object();
rootNode.name = "root";
rootNode.id = 0;
rootNode.children = [];
rootNode.collapsed = false;
for (var i = 0; i < inputArray.length; i++) {
var pid = inputArray[i].pid - 1;
if (pid == -2) {
inputArray[i].pid = 0;
rootNode.children.push(inputArray[i]);
} else {
if (typeof inputArray[pid].children == "undefined") {
inputArray[pid].children = [];
}
inputArray[pid].children.push(inputArray[i]);
}
}
return rootNode;
};
//read the conllu file and generate the json tree objects
var convertToJSON = function (inputData) {
var inputArray = [];
numberOfNodesArray = [];
var newTree = [];
newTree.meta = {};
var sentenceText = "";
if (inputData !== "") {
var lines = inputData.split("\n");
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim().length == 0) {
if (newTree.length > 0) {
newTree.meta["treeTokens"] = sentenceText.trim();
inputArray.push(newTree);
numberOfNodesArray.push(newTree.length / 2);
newTree = [];
newTree.meta = {};
sentenceText = "";
}
continue;
}
//the read meta data of the tree
//store the original sentence to be displayed in the listings
if (lines[i].trim().startsWith("#")) {
lineToks = lines[i].trim().split(" ");
//index 0 = '#'
key = lineToks[1];
//index 2 = '='
value = lineToks.slice(3, lineToks.length).join(" ");
newTree.meta[key] = value;
continue;
}
if (lines[i].trim().match(/^\d+-\d+\s/)) {
continue;
}
var singleLine = lines[i].split("\t");
var treeNode = new Object();
var projectedNode = new Object();
treeNode.id = parseInt(singleLine[0]) * 2 - 1;
treeNode.name = singleLine[1];
treeNode.lemma = singleLine[2];
treeNode.pos = singleLine[3];
treeNode.xpos = singleLine[4];
treeNode.feats = {};
if (singleLine[5] == "_") {
treeNode.feats["_"] = "_";
} else {
var featToks = singleLine[5].split("|");
for (var j = 0; j < featToks.length; j++) {
var featKey = featToks[j].split("=")[0];
var featValue = featToks[j].split("=")[1];
treeNode.feats[featKey] = featValue;
}
}
treeNode.pid = parseInt(singleLine[6]) * 2 - 1;
treeNode.link = singleLine[7];
treeNode.deps = singleLine[8];
treeNode.misc = singleLine[9];
treeNode.duplicate = false;
treeNode.collapsed = false;
sentenceText += treeNode.name + " ";
newTree.push(treeNode);
projectedNode.id = parseInt(singleLine[0]) * 2;
projectedNode.name = treeNode.name;
projectedNode.pos = singleLine[3];
//the parent of the projected node is the original node itself
projectedNode.pid = parseInt(singleLine[0]) * 2 - 1;
projectedNode.link = "";
projectedNode.duplicate = true;
projectedNode.collapsed = false;
newTree.push(projectedNode);
}
}
if (newTree.length > 0) {
inputArray.push(newTree);
numberOfNodesArray.push(newTree.length / 2);
newTree = [];
newTree.meta = {};
sentenceText = "";
}
//connect the nodes to their proper parents (i.e. create the tree)
for (var i = 0; i < inputArray.length; i++) {
newTree = inputArray[i];
var rootNode = new Object();
rootNode.name = rootNodeName;
rootNode.id = 0;
rootNode.collapsed = false;
rootNode.children = [];
rootNode.meta = inputArray[i].meta;
for (var j = 0; j < newTree.length; j++) {
var pid = newTree[j].pid - 1;
if (pid == -2) {
newTree[j].pid = 0;
rootNode.children.push(newTree[j]);
} else {
if (typeof newTree[pid].children == "undefined") {
newTree[pid].children = [];
}
newTree[pid].children.push(newTree[j]);
}
}
inputArray[i] = rootNode;
}
return inputArray;
};
function isValidExtension(original_filename) {
if (!original_filename.endsWith(".conllu") && !original_filename.endsWith(".conllx")) {
alert(
"File does not end with the .conllu/conllx extension, please upload a ConllU/X file."
);
return false;
}
return true;
}
function addFilenameToHtmlElements(original_filename) {
// // display filename on page and when downloading files
// document.getElementById("conlluFileName").innerHTML = original_filename;
filenameIdx = 0 // the index of the filename in the parent div is always 0 (1 is the tree number)
filenameParent = document.getElementById("conlluFileNameDiv");
const span = renderFilenameInReadMode(original_filename, filenameParent, filenameIdx);
filenameParent.replaceChild(span, filenameParent.children[0]);
}
function LocalFileInputChecker() {
let x = document.getElementById("inputFile");
let textArea = document.getElementById("treedata2").value // upload text counts as local
if ((("files" in x) && (x.files.length == 0) && !textArea)) {
alert(
"Please select a ConllU/X file, or enter sentences in the text area below."
);
return null;
};
isConlluLocal = true;
return x.files[0];
}
function RemoteFileInputChecker() {
// check if there is a picked file
// return the File object
if (!document.getElementById("picked_filename").innerHTML) {
alert(
"Please select a ConllU/X file, or use use the Upload button in the sentence uploader section."
);
}
isConlluLocal = false;
return pickedFile;
}
async function setupTreePage(FileInputChecker) {
let file = FileInputChecker();
if (!file) return;
if (!isValidExtension(file.name)) {return;}
addFilenameToHtmlElements(file.name);
await readConfigFile();
parseConllFile(file);
$("#auth_logout_btns").remove()
}
var parseConllFile = function (file) {
// set up function that is triggered when file is read
var reader = new FileReader();
reader.onload = function (e) {
treesArray = convertToJSON(reader.result);
currentTreeIndex = 0;
UndoRedoHelperOnTreePageSetUp();
// hide upload window
view([$(".upload")], hideComponents);
try {
getTree(treesArray[0]);
} catch (e) {
// alert user if error occurs
console.log(e)
alert("File upload error!");
}
};
reader.readAsText(file);
};
var readSentenceTreeData = function () {
var original = $("#treedata2").val();
if (original !== "") {
var treeDataArray = [];
var inputTextArray = original.split("\n").filter(function (entry) {
return entry.trim() != "";
});
for (var i = 0; i < inputTextArray.length; i++) {
var singleLine = inputTextArray[i].split(" ").filter(function (entry) {
return entry.trim() != "";
});
for (var j = 0; j < singleLine.length; j++) {
treeDataArray.push(
[
j + 1,
singleLine[j],
"_",
newPOSTag,
"_",
"_",
0,
newLinkLabel,
"_",
"_",
].join("\t")
);
}
treeDataArray.push("\n");
}
try {
// try to store tree data and display tree
treesArray = convertToJSON(treeDataArray.join("\n"));
getTree(treesArray[0]);
view([$(".upload"), $('#auth_logout_btns')], hideComponents);
UndoRedoHelperOnTreePageSetUp();
} catch (e) {
// alert user if error occurs
alert("Text upload error!");
throw(e);
}
} else {
view([$(".upload"), $('#auth_logout_btns')], hideComponents)
addNewTree();
}
return treesArray;
};
var setSentenceTreeData = function () {
addFilenameToHtmlElements('Untitled.conllx');
setupTreePage(LocalFileInputChecker);
// console.log("sadfakl")
// console.log($("#auth_logout_btns").hide())
//we conly call the readConfigFileForSentence here to insure that the configuration file is
//completely read before moving on to the rest of the funcion. The actual reading of the sentence
//data happens in the readSentenceTreeData function which gets called in the readConfigFileForSentence
//function in the .onload part of the FileReader.
readConfigFileForSentence();
};
// helper function
// reset the tree data (to an empty string) and reload the window
var clearTree = function () {
if (window.confirm("Do you really want to leave?")) {
sessionStorage.removeItem("treeData");
window.location.reload();
}
};
// add a new tree at the end
var addNewTree = function () {
hideAllWindows();
sessionStorage.removeItem("treeData");
saveTree();
var rootNode = new Object();
rootNode.name = rootNodeName;
rootNode.id = 0;
rootNode.collapsed = false;
rootNode.children = [];
rootNode.meta = {};
rootNode.meta["treeTokens"] = "";
rootNode.lemma = "";
rootNode.pos = "";
rootNode.xpos = "";
rootNode.feats = {};
rootNode.deps = "";
rootNode.misc = "";
currentTreeIndex = treesArray.length;
d3.select("body").select("svg").remove();
treesArray.push(rootNode);
numberOfNodesArray.push(0);
getTree(treesArray[currentTreeIndex]);
update(root);
UndoRedoHelperOnMoveToTree(currentTreeIndex);
//$('.morphologyMerge').show();
};
// delete the current tree
var deleteCurrentTree = function () {
//We only allow deletion with confirmation when there are more than one tree.
//A future solution should be to delete the last tree and insert and empty.
//We do not allow no trees.
hideAllWindows();
if (treesArray.length > 1) {
// if there are more than one tree in the file
if (window.confirm("Do you want to delete this tree?")) {
//Check with user
d3.select("body").select("svg").remove();
treesArray.splice(currentTreeIndex, 1);
numberOfNodesArray.splice(currentTreeIndex, 1);
if (currentTreeIndex > 0) {
currentTreeIndex = currentTreeIndex - 1;
}
getTree(treesArray[currentTreeIndex]);
update(root);
UndoRedoHelperOnMoveToTree(currentTreeIndex);
}
} else {
//if there is only one tree
alert(
"Sorry! You cannot delete the last tree. Add a new tree first, then delete this tree."
);
// TODO
// addNewTree();
// deleteCurrentTree();
}
};
function moveToTreeHelper(treeIndex) {
if (treeIndex != currentTreeIndex) {
UndoRedoHelperOnMoveToTree(treeIndex);
}
sessionStorage.removeItem("treeData");
saveTree();
currentTreeIndex = treeIndex;
d3.select("body").select("svg").remove();
getTree(treesArray[currentTreeIndex]);
update(root);
selectRoot();
showSelection();
}
// move to the first tree
function firstTree() {
hideAllWindows();
if (currentTreeIndex != 0) {
moveToTreeHelper(0);
}
}
// move to the last tree
function lastTree() {
hideAllWindows();
if (currentTreeIndex != treesArray.length - 1) {
moveToTreeHelper(treesArray.length-1);
}
}
// move to the next tree
function nextTree() {
hideAllWindows();
if (currentTreeIndex < treesArray.length - 1) {
moveToTreeHelper(currentTreeIndex+1);
}
}
// move to the prev tree
function prevTree() {
hideAllWindows();
if (currentTreeIndex > 0) {
moveToTreeHelper(currentTreeIndex-1);
}
}
// go to the input tree number
function goToTree() {
hideAllWindows();
if (
currentTreeIndex !==
document.getElementById("treeNumberInput").value - 1
) {
//check that the entered value is not less than 1 or more than the number of trees
if (
document.getElementById("treeNumberInput").value > 0 &&
document.getElementById("treeNumberInput").value <= treesArray.length
) {
moveToTreeHelper(document.getElementById("treeNumberInput").value - 1);
}
}
}
// toggle between English and Arabic
var directionToggle = function () {
hideAllWindows();
if (orientation == "r-to-l") {
orientation = "l-to-r";
} else {
orientation = "r-to-l";
}
sessionStorage.removeItem("treeData");
saveTree();
d3.select("body").select("svg").remove();
getTree(treesArray[currentTreeIndex]);
update(root);
};
function editByKeyboard(linkType, textValue) {
UndoRedoHelperOnTreeUpdate();
d3.select(`text#${linkType}` + selectedNodeLink.id).text(textValue);
if(linkType == "nodePOS") {
selectedNodeLink.pos = textValue;
} else if(linkType === "linkLabel") {
selectedNodeLink.link = textValue;
}
}
// edit the relation labels through keystrokes
function editLabel(labelText) {
editByKeyboard('linkLabel', labelText)
};
function editByButton(inputSource, linkType) {
if (selectedNodeLink) {
UndoRedoHelperOnTreeUpdate();
const textValue = inputSource.currentTarget.value;
// d3.select("text#linkLabel" + selectedNodeLink.id).text(labelText);
// selectedNodeLink.link = labelText;
d3.select(`text#${linkType}` + selectedNodeLink.id).text(textValue);
if(linkType == "nodePOS") {
selectedNodeLink.pos = textValue;
} else if(linkType === "linkLabel") {
selectedNodeLink.link = textValue;
}
showSelection();
}
}
// edit the relation labels through button clicks
function editLabelByButton(inputSource) {
editByButton(inputSource, 'linkLabel')
};
// edit the POS tags through keystrokes
function editPOS(posText) {
editByKeyboard('nodePOS', posText)
};
// edit the POS tags through button clicks
function editPOSByButton(inputSource) {
editByButton(inputSource, 'nodePOS');
};
// Morhology Handling
// reset the morphology changes
var cancelMorphology = function () {
hideAllWindows();
};
// reset the morphology changes
var saveMorphology = function () {
UndoRedoHelperOnTreeUpdate();
var morphologyArray = document
.getElementById("morphologyName")
.value.split(" ");
var morphologyText = morphologyArray.shift();
while (morphologyText.length < 1 && morphologyArray.length > 0) {
morphologyText = morphologyArray.shift();
}
if (morphologyText.length < 1) {
morphologyText = newNodeName;
}
d3.select("text#nodeLabel" + selectedMorphology.parent.id).text(
morphologyText
);
d3.select("text#morphology" + selectedMorphology.id).text(morphologyText);
selectedMorphology.name = morphologyText;
selectedMorphology.parent.name = morphologyText;
if (editLemma === true) {
selectedMorphology.parent.lemma = document.getElementById("lemma").value;
}
for (var i = 0; i < lexicalFeatsList.length; i++) {
selectedMorphology.parent.feats[lexicalFeatsList] = document.getElementById(
lexicalFeatsList[i]
).value;
}
while (morphologyArray.length > 0) {
morphologyText = morphologyArray.pop();
if (morphologyText.length > 0)
addNode(selectedMorphology, "right", morphologyText);
}
var morphologyFeatures = document
.getElementById("morphoFeats")
.getElementsByClassName("morphoFeat");
for (var i = 0; i < morphologyFeatures.length; i++) {
feature = document
.getElementById("morphoFeats")
.getElementsByClassName("morphoFeat")[i].id;
selectedIndex = document
.getElementById("morphoFeats")
.getElementsByClassName("morphoFeat")
[i].getElementsByClassName("inputArray")[0].selectedIndex;
if (selectedIndex != -1) {
featureDisplay = document
.getElementById("morphoFeats")
.getElementsByClassName("morphoFeat")[i]
.getElementsByClassName("inputArray")[0].options[selectedIndex].value;
featureValue = "";
for (var j = 0; j < featureValues[feature].length; j++) {
if (featureValues[feature][j]["display"] === featureDisplay) {
featureValue = featureValues[feature][j]["value"];
}
}
// if a valid feature was selected, update node feature
if (featureValue !== "u") {
selectedMorphology.parent.feats[feature] = featureValue;
} else { // if unspecified was selected, remove feature from node
delete selectedMorphology.parent.feats[feature]
}
}
}
hideAllWindows();
update(root);
};
// this is a recursive function that goes through the tree and uncollapses all the nodes that need to be collapsed.
var uncollapseAllNodes = function (currentTree) {
if (!currentTree.duplicate && currentTree.children !== undefined) {
for (var i = 0; i < currentTree.children.length; i++) {
if (currentTree.children[i].collapsed) {
toggleChildrenOut(currentTree.children[i]);
}
uncollapseAllNodes(currentTree.children[i]);
}
}
};
// this is a replica of the toggleChildren function that we needed to be outside of the getTree function
// to be called from uncollapseAllNodes
function toggleChildrenOut(d) {
if (d.collapsed == true) {
d.children.forEach(function (childNode) {
childNode.name = childNode.name.slice(2, -2);
});
d.children = d._children;
d._children = null;
d.name = d.name.slice(2, -2);
d.collapsed = false;
} else {
d._children = d.children;
d.children = null;
d.name = "<<" + d.name + ">>";
d._children.forEach(function (childNode) {
if (childNode.duplicate == true) {
d.children = [];
childNode.name = "<<" + childNode.name + ">>";
d.children.push(childNode);
}
});
d.collapsed = true;
}
update(d);
}
var selectRoot = function () {
if (selectedNodeLink === undefined) {
selectedNodeLink = root;
// nodeSingleClick(root);
showSelection();