-
Notifications
You must be signed in to change notification settings - Fork 0
/
KGObjects.js
1290 lines (1124 loc) · 39.3 KB
/
KGObjects.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
/*
KGObjects.js
prerequisites:
--------------
object.js, gui.js, blocks.js, morphic.js
toc
---
the following list shows the order in which all constructors are
defined. Firt of all you can find the functionalities that have
been added to SpriteMorph, StageMorph and SyntaxElementMorph.
Use this list to locate code in this document:
SpriteMorph
StageMorph
SyntaxElementMorph
Endpoint
WikiDataEndpoint
QueryFunction
Literal
DateElement
Pattern
Subject
LogicOperator
Filter
Query
QueryResult
SearchResult
credits
-------
Vincenzo Offertucci
*/
/*jshint esversion: 6*/
// Global stuff ////////////////////////////////////////////////////////
modules.KGObjects = '2022-September-08';
// Declarations
var Endpoint;
var WikiDataEndpoint;
var QueryFunction;
var Literal;
var DateElement;
var Pattern;
var Subject;
var LogicOperator;
var Filter;
var Query;
var QueryResult;
var SearchResult;
// SpriteMorph ////////////////////////////////////////////////////////
// defining a new custom category
SpriteMorph.prototype.customCategories.set('KGQueries', new Color(153, 0, 0));
const originalAddDefaultScene = Project.prototype.addDefaultScene;
Project.prototype.addDefaultScene = function () {
originalAddDefaultScene.apply(this);
let scena = this.scenes.at(1);
scena.customCategories.set('KGQueries', new Color(153, 0, 0));
};
// defining new blocks
const originalInitBlocks = SpriteMorph.prototype.initBlocks;
SpriteMorph.prototype.initBlocks = function (){
originalInitBlocks();
SpriteMorph.prototype.blocks["subject"] = {
type: 'command',
category: 'KGQueries',
spec: 'subject: %s %c',
defaults: [null, null]
};
SpriteMorph.prototype.blocks["pattern"] = {
type: 'command',
category: 'KGQueries',
spec: 'predicate: %s object: %s',
defaults: [null, null]
};
SpriteMorph.prototype.blocks["filter"] = {
type: 'command',
category: 'KGQueries',
spec: 'filter: %s',
defaults: [null]
};
SpriteMorph.prototype.blocks["queryBlock"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'select distinct %exp %br from %kg %br where %c %br order by %s %ord %br limit %n',
defaults: ['?item', null, null, null, null, 10]
};
SpriteMorph.prototype.blocks["literal"] = {
type: 'reporter',
category: 'KGQueries',
spec: '%s @ %s',
defaults: [null, null]
};
SpriteMorph.prototype.blocks["dateElement"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'date: %s',
defaults: ['AAAA-MM-DD']
};
SpriteMorph.prototype.blocks["showQueryResults"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'show results %var',
defaults: [null]
};
SpriteMorph.prototype.blocks["getColumn"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'get column %n from %var',
defaults: [1, null]
};
SpriteMorph.prototype.blocks["getRow"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'get row %n from %var',
defaults: [1, null]
};
SpriteMorph.prototype.blocks["searchEntity"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'search an entity: %s %br from %kg %br select a language: %s',
defaults: ['something', 'WikiData', 'en']
};
SpriteMorph.prototype.blocks["searchProperty"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'search a property: %s %br from %kg %br select a language: %s',
defaults: ['something', 'WikiData', 'en']
};
SpriteMorph.prototype.blocks["translateQueryBlock"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'translate query block: %s',
defaults: [null]
};
SpriteMorph.prototype.blocks["executeQueryBlock"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'execute query block: %s',
defaults: [null]
};
SpriteMorph.prototype.blocks["languageOf"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'language of: %s is %s',
defaults: [null, 'en']
};
SpriteMorph.prototype.blocks["label"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'rdfs:label',
defaults: []
};
SpriteMorph.prototype.blocks["defineEndpoint"] = {
type: 'reporter',
category: 'KGQueries',
spec: 'define a new endpoint %br name: %s %br url: %s',
defaults: []
};
};
SpriteMorph.prototype.initBlocks();
SpriteMorph.prototype.originalBlockTemplates = SpriteMorph.prototype.blockTemplates;
SpriteMorph.prototype.blockTemplates = function (
category = 'motion',
all = false
){
function block(selector, isGhosted) {
if (StageMorph.prototype.hiddenPrimitives[selector] && !all) {
return null;
}
var newBlock = SpriteMorph.prototype.blockForSelector(selector, true);
newBlock.isTemplate = true;
if (isGhosted) {newBlock.ghost(); }
return newBlock;
}
blocks = this.originalBlockTemplates(category, all);
if (category === 'KGQueries'){
blocks.push('-');
blocks.push(block('queryBlock'));
blocks.push(block('subject'));
blocks.push(block('pattern'));
blocks.push(block('showQueryResults'));
blocks.push(block('literal'));
blocks.push(block('dateElement'));
blocks.push(block('filter'));
blocks.push(block('languageOf'));
blocks.push(block('label'));
blocks.push('-');
blocks.push(block('getColumn'));
blocks.push(block('getRow'));
blocks.push('-');
blocks.push(block('searchEntity'));
blocks.push(block('searchProperty'));
blocks.push('-');
blocks.push(block('executeQueryBlock'));
blocks.push(block('translateQueryBlock'));
blocks.push('-');
blocks.push(block('defineEndpoint'));
}
return blocks;
};
// selector define for the new blocks
SpriteMorph.prototype.literal = function(string, lang){
let stringLiteral = '"' + string + '"';
if(lang !== undefined &&
lang !== null &&
lang !== '')
stringLiteral += "@" + lang;
return stringLiteral;
};
SpriteMorph.prototype.dateElement = function(string){
let stringLiteral = '"' + string + '"^^xsd:dateTime';
return stringLiteral;
};
SpriteMorph.prototype.subject = function(subject, patternBlock){
return subject;
};
SpriteMorph.prototype.pattern = function(predicate, object){
return predicate + ' ' + object;
};
SpriteMorph.prototype.filter = function(element){
return element;
};
SpriteMorph.prototype.queryBlock = function (vars, ep, block, order, direction, limit) {
let endpoint = null;
let query = null;
try{
if(!ep)
return 'Please select an endpoint.';
if(ep[0] === "WikiData")
endpoint = new WikiDataEndpoint(null, this);
else
endpoint = new Endpoint(ep[0], null, this);
query = new Query(vars, endpoint, block, order, direction, limit);
query.prepareRequest();
}
catch(e){
return e.message;
}
return query;
};
// Creates a global variable named with the value of varName and containing value
// it also adds a watcher to the stage
SpriteMorph.prototype.createResultVar = function (varName, value){
let ide = world.children[0];
let scene = ide.scene;
let stage = this.parentThatIsA(StageMorph);
scene.globalVariables.addVar(varName, value);
ide.flushBlocksCache('variables');
ide.refreshPalette();
let watcher = this.findVariableWatcher(varName);
if (watcher !== null) {
watcher.show();
watcher.fixLayout(); // re-hide hidden parts
watcher.keepWithin(stage);
ide.flushBlocksCache('variables');
ide.refreshPalette();
}
else
this.toggleVariableWatcher(varName, true);
};
//Handles readyState changes and showes query's results
SpriteMorph.prototype.showResults = function (result){
let queryResults = null;
if (result.readyState == 4 && result.status == 200) {
let response = JSON.parse(result.responseText);
let rows = response.results.bindings.length;
if(rows === 0){
queryResults = new QueryResult(null, 1);
this.createResultVar('Results', queryResults);
this.showQueryResults('Results');
return;
}
let entry = Object.entries(response.results.bindings[0]);
let cols = entry.length;
let resultTable = new Table(cols, rows);
for(i = 0; i<cols; i++)
resultTable.setColName(i-1, entry[i][0]);
for(i = 0; i<rows; i++){
for(j = 0; j<cols; j++){
entry = Object.entries(response.results.bindings[i]);
resultTable.set(entry[j][1].value, j+1, i+1);
}
}
queryResults = new QueryResult(resultTable, 0);
this.createResultVar("Results", queryResults);
this.showQueryResults("Results");
}
else if (result.readyState == 4 && result.status == 400) {
queryResults = new QueryResult(null, 2);
this.createResultVar('Results', queryResults);
this.showQueryResults('Results');
}
};
function UnvalidBlockException(message){
this.message = message;
};
//shows query results saved inside varName
SpriteMorph.prototype.showQueryResults = function(varName){
let ide = world.children[0];
let queryResults = ide.getVar(varName);
if(queryResults && queryResults.table){
let tableMorph = new TableMorph(queryResults.table);
let tableDialogMorph = new TableDialogMorph(
tableMorph.table,
tableMorph.globalColWidth,
tableMorph.colWidths,
tableMorph.rowHeight
);
tableDialogMorph.userMenu = function () {
var menu = new MenuMorph(this);
menu.addItem(
'export as JSON',
() => ide.saveFileAs(
JSON.stringify(queryResults),
'text/plain;charset=utf-8',
varName
)
);
menu.addItem(
'export as CSV',
() => ide.saveFileAs(
queryResults.toCSV(),
'text/plain;charset=utf-8',
varName
)
);
return menu;
};
tableDialogMorph.popUp(this.world());
}
else if(queryResults || queryResults === 0 || queryResults === ''){
let dialogBox = new DialogBoxMorph();
dialogBox.userMenu = function () {
var menu = new MenuMorph(this);
menu.addItem(
'export',
() => ide.saveFileAs(
JSON.stringify(queryResults),
'text/plain;charset=utf-8',
varName
)
);
return menu;
};
let description = queryResults.toString();
dialogBox.inform('Results', description, world);
}
return 'Showing results.';
};
// Allow the user to get a single column from a query result
SpriteMorph.prototype.getColumn = function (index, varName){
let ide = world.children[0];
let queryResults = ide.getVar(varName);
if(typeof(index) !== 'number')
return queryResults;
let table = queryResults.table;
if(!table)
return new QueryResult(null, 1);
let resultTable = new Table(1, table.rows());
resultTable.setColName(-1, table.colName(index));
let tableColumn = table.col(index);
if(index > table.cols() || index < 1)
return new QueryResult(null, 1);
for(i = 1; i<=table.rows(); i++){
resultTable.set(tableColumn[i-1], 1, i);
}
let column = new QueryResult(resultTable, 0);
return column;
};
// Allow the user to get a single row from a query result
SpriteMorph.prototype.getRow = function (index, varName){
let ide = world.children[0];
let queryResults = ide.getVar(varName);
if(typeof(index) !== 'number')
return queryResults;
let table = queryResults.table;
if(!table)
return new QueryResult(null, 1);
let resultTable = new Table(table.cols(), 1);
resultTable.setColNames(table.columnNames());
let tableRow = table.row(index);
if(index > table.rows() || index < 1)
return new QueryResult(null, 1);
for(i = 1; i<=table.cols(); i++){
resultTable.set(tableRow[i-1], i, 1);
}
let row = new QueryResult(resultTable, 0);
return row;
};
// Allow the user to search for an entity in a knowledge graph
SpriteMorph.prototype.searchEntity = function(search, ep, lang) {
let endpoint = null;
if(!ep)
return 'Please select an endpoint.';
if(ep[0] === "WikiData")
endpoint = new WikiDataEndpoint(lang, this);
else
endpoint = new Endpoint(ep[0], lang, this);
endpoint.searchEntity(search, 'item');
return 'Loading...';
};
// Allow the user to search for a property in a knowledge graph
SpriteMorph.prototype.searchProperty = function(search, ep, lang) {
let endpoint = null;
if(!ep)
return 'Please select an endpoint.';
if(ep[0] === "WikiData")
endpoint = new WikiDataEndpoint(lang, this);
else
endpoint = new Endpoint(ep[0], lang, this);
endpoint.searchEntity(search, 'property');
return 'Loading...';
};
// show search results saved inside varName
SpriteMorph.prototype.showSearchResults = function(varName){
let ide = world.children[0];
let searchResults = ide.getVar(varName);
let dialogBox = new DialogBoxMorph();
let description = '';
if(searchResults.error === 1 || searchResults.error === 2)
description = searchResults.toString();
else
description = searchResults.label + '\n' + searchResults.description + '\n' + searchResults.concepturi;
dialogBox.inform('Search Results', description, world);
// add a menu for exporting results
dialogBox.userMenu = function () {
var menu = new MenuMorph(this);
menu.addItem(
'export as JSON',
() => ide.saveFileAs(
JSON.stringify(searchResults),
'text/plain;charset=utf-8',
localize('data')
)
);
menu.addItem(
'export as CSV',
() => ide.saveFileAs(
searchResults.toCSV(),
'text/plain;charset=utf-8',
localize('data')
)
);
return menu;
};
return null;
};
SpriteMorph.prototype.translateQueryBlock = function(block) {
let ide = world.children[0];
let dialogBox = new DialogBoxMorph();
let description = block.queryString;
// add a menu for exporting results
dialogBox.userMenu = function () {
var menu = new MenuMorph(this);
menu.addItem(
'export',
() => ide.saveFileAs(
description,
'text/plain;charset=utf-8',
'SPARQLQuery'
)
);
return menu;
};
dialogBox.inform('SPARQL Query', description, world);
let body = dialogBox.body;
body.setAlignmentToLeft();
return block.queryString;
};
SpriteMorph.prototype.executeQueryBlock = function(block) {
let result = new XMLHttpRequest();
result.open('GET', block.preparedUrl, true);
result.send(null);
result.onreadystatechange = () => this.showResults(result);
return "Loading...";
};
SpriteMorph.prototype.defineEndpoint = function(name, url) {
if(!name || name === '')
return 'Assign a valid name.'
if(!url || url === '')
return 'Assign a valid url.'
Endpoint.prototype.addEndpoint(name, url);
return "A new endpoint has been added.";
};
// StageMorph ///////////////////////////////////////////////////////////
StageMorph.prototype.oldBlockTemplates = StageMorph.prototype.blockTemplates;
StageMorph.prototype.blockTemplates = function (
category = 'motion',
all = false
){
var myself = this;
function block(selector) {
if (myself.hiddenPrimitives[selector] && !all) {
return null;
}
var newBlock = SpriteMorph.prototype.blockForSelector(selector, true);
newBlock.isTemplate = true;
return newBlock;
}
blocks = this.oldBlockTemplates(category, all);
if (category === 'KGQueries'){
blocks.push('-');
blocks.push(block('queryBlock'));
blocks.push(block('subject'));
blocks.push(block('pattern'));
blocks.push(block('showQueryResults'));
blocks.push(block('literal'));
blocks.push(block('dateElement'));
blocks.push(block('filter'));
blocks.push(block('languageOf'));
blocks.push(block('label'));
blocks.push('-');
blocks.push(block('getColumn'));
blocks.push(block('getRow'));
blocks.push('-');
blocks.push(block('searchEntity'));
blocks.push(block('searchProperty'));
blocks.push('-');
blocks.push(block('executeQueryBlock'));
blocks.push(block('translateQueryBlock'));
blocks.push('-');
blocks.push(block('defineEndpoint'));
}
return blocks;
}
StageMorph.prototype.literal
= SpriteMorph.prototype.literal;
StageMorph.prototype.dateElement
= SpriteMorph.prototype.dateElement;
StageMorph.prototype.subject
= SpriteMorph.prototype.subject;
StageMorph.prototype.pattern
= SpriteMorph.prototype.pattern;
StageMorph.prototype.queryBlock
= SpriteMorph.prototype.queryBlock;
StageMorph.prototype.createResultVar
= SpriteMorph.prototype.createResultVar;
StageMorph.prototype.showResults
= SpriteMorph.prototype.showResults;
StageMorph.prototype.showQueryResults
= SpriteMorph.prototype.showQueryResults;
StageMorph.prototype.filter
= SpriteMorph.prototype.filter;
StageMorph.prototype.languageOf
= SpriteMorph.prototype.languageOf;
StageMorph.prototype.label
= SpriteMorph.prototype.label;
StageMorph.prototype.getColumn
= SpriteMorph.prototype.getColumn;
StageMorph.prototype.getRow
= SpriteMorph.prototype.getRow;
StageMorph.prototype.searchEntity
= SpriteMorph.prototype.searchEntity;
StageMorph.prototype.searchProperty
= SpriteMorph.prototype.searchProperty;
StageMorph.prototype.showSearchResults
= SpriteMorph.prototype.showSearchResults;
StageMorph.prototype.translateQueryBlock
= SpriteMorph.prototype.translateQueryBlock;
StageMorph.prototype.executeQueryBlock
= SpriteMorph.prototype.executeQueryBlock;
StageMorph.prototype.defineEndpoint
= SpriteMorph.prototype.defineEndpoint;
// SyntaxElementMorph ///////////////////////////////////////////////////////////
SyntaxElementMorph.prototype.labelParts['%ord'] = {
type: 'input',
tags: 'read-only static',
menu: {
'ASC' : ['ASC'],
'DESC' : ['DESC']
}
};
SyntaxElementMorph.prototype.labelParts['%kg'] = {
type: 'input',
tags: 'read-only static',
menu: {
'WikiData' : ['WikiData']
}
};
// Endpoint ///////////////////////////////////////////////////////////
// Represents the generic endpoint for making SPARQL query requests
Endpoint.prototype.constructor = Endpoint;
function Endpoint(endpointName, language, morph){
this.init(endpointName, language, morph);
};
Endpoint.prototype.EndpointNames = new Map();
Endpoint.prototype.initializeEndpointNames = function(){
Endpoint.prototype.EndpointNames.set('WikiData', 'https://query.wikidata.org/sparql');
}
Endpoint.prototype.initializeEndpointNames();
Endpoint.prototype.addEndpoint = function(name, url){
Endpoint.prototype.EndpointNames.set(name, url);
let menu = SyntaxElementMorph.prototype.labelParts['%kg'].menu;
if(!menu[name])
menu[name] = [name];
else
throw new UnvalidBlockException('An endpoint with that name is alredy defined.');
}
Endpoint.prototype.init = function(endpointName, language, morph){
this.baseUrl = Endpoint.prototype.EndpointNames.get(endpointName);
if(language && language !== '')
this.language = language;
else
this.language = 'en';
this.morph = morph; // is a SpriteMorph or a StageMorph (if the block is used on a Sprite or a Stage)
this.entityPrefix = '';
this.propertyPrefix = '';
};
Endpoint.prototype.searchEntity = function(search, type){
let requestUrl = this.baseUrl + '?format=json&query=';
let queryString = '';
if(type === "property")
queryString = 'SELECT DISTINCT ?result WHERE {?s ?result ?o. ?result ' +
'rdfs:label ?label. FILTER(?label="' + search + '"@' + this.language +') }';
else
queryString = 'SELECT DISTINCT ?result WHERE {?result ?p ?o. ?result ' +
'rdfs:label ?label. FILTER(?label="' + search + '"@' + this.language +') }';
requestUrl += queryString;
let result = new XMLHttpRequest();
result.open('GET', requestUrl, true);
result.send(null);
result.onreadystatechange = () => {
if (result.readyState == 4 && result.status == 200) {
json = JSON.parse(result.response);
let resultList = json.results.bindings;
if(resultList.length === 0) {
searchResult = new SearchResult(null, null, null, null, null, 1);
}
else {
let first = resultList[0].result.value;
if(type === 'item')
dataType = 'entity';
else if(type === 'property')
dataType = 'property';
let label = search;
let description = '';
searchResult = new SearchResult('<' + first + '>', dataType, label, description, first, 0);
}
this.morph.createResultVar('searchResult', searchResult);
this.morph.showSearchResults('searchResult');
return;
}
else if(result.readyState == 4 && result.status == 400){
searchResult = new SearchResult(null, null, null, null, null, 2);
this.morph.createResultVar('searchResult', searchResult);
this.morph.showSearchResults('searchResult');
}
}
return search;
};
// WikiDataEndpoint ///////////////////////////////////////////////////////////
WikiDataEndpoint.prototype = new Endpoint();
WikiDataEndpoint.prototype.constructor = WikiDataEndpoint;
WikiDataEndpoint.uber = Endpoint.prototype;
function WikiDataEndpoint(language, morph){
this.init(language, morph);
};
WikiDataEndpoint.prototype.init = function(language, morph){
this.baseUrl = 'https://query.wikidata.org/sparql';
if(language && language !== '')
this.language = language;
else
this.language = 'en';
this.morph = morph; // is a SpriteMorph or a StageMorph (if the block is used on a Sprite or a Stage)
this.entityPrefix = 'wd:';
this.propertyPrefix = 'wdt:';
};
WikiDataEndpoint.prototype.searchEntity = function(search, type){
let searchResult = null;
let json = null;
let requestUrl = 'https://www.wikidata.org/w/api.php?action=wbsearchentities&language='
+ this.language +'&uselang=' + this.language + '&type=' + type
+ '&format=json&origin=*&search=' + search;
let result = new XMLHttpRequest();
result.open('GET', requestUrl, true);
result.send(null);
result.onreadystatechange = () => {
if (result.readyState == 4 && result.status == 200) {
json = JSON.parse(result.response);
if(json.search.length === 0) {
searchResult = new SearchResult(null, null, null, null, null, 1);
}
else {
let first = json.search[0];
if(type === 'item')
dataType = 'entity';
else if(type === 'property')
dataType = 'property';
let label = first.display.label ? first.display.label.value : 'Empty';
let description = first.display.description ? first.display.description.value : 'Empty';
searchResult = new SearchResult(first.id, dataType, label, description, first.concepturi, 0);
}
this.morph.createResultVar('searchResult', searchResult);
this.morph.showSearchResults('searchResult');
return;
}
else if(result.readyState == 4 && result.status == 400){
searchResult = new SearchResult(null, null, null, null, null, 2);
this.morph.createResultVar('searchResult', searchResult);
this.morph.showSearchResults('searchResult');
}
}
};
// QueryFunction ///////////////////////////////////////////////////////////
QueryFunction.prototype.constructor = QueryFunction;
function QueryFunction(block){
this.block = block;
this.type = '';
if(block.selector === 'languageOf')
this.type = 'lang';
}
QueryFunction.prototype.getValue = function (){
let stringLiteral = '';
if(this.type === 'lang')
stringLiteral += 'LANG(' + this.getSlotValue(0) + ') = "' + this.getSlotValue(1) + '"';
return stringLiteral;
}
QueryFunction.prototype.getSlotValue = function(index){
let slot = this.block.inputs()[index];
if(slot.selector === 'reportGetVar'){
let varName = slot.blockSpec;
let ide = world.children[0];
let variable = ide.getVar(varName);
return variable;
}
else return slot.allEntryFields()[0].text;
}
// Literal ///////////////////////////////////////////////////////////
Literal.prototype.constructor = Literal;
function Literal(block){
this.block = block;
}
Literal.prototype.getValue = function (){
let stringLiteral = '"';
stringLiteral += this.getSlotValue(0) + '"';
let lang = this.getSlotValue(1);
if(lang !== undefined &&
lang !== null &&
lang !== '')
stringLiteral += "@" + lang;
return stringLiteral;
}
Literal.prototype.getSlotValue = function(index){
let slot = this.block.inputs()[index];
if(slot.selector === 'reportGetVar'){
let varName = slot.blockSpec;
let ide = world.children[0];
let variable = ide.getVar(varName);
return variable;
}
else return slot.allEntryFields()[0].text;
}
// DateElement ///////////////////////////////////////////////////////////
DateElement.prototype = new Literal();
DateElement.prototype.constructor = DateElement;
DateElement.uber = Literal.prototype;
function DateElement(block){
this.block = block;
}
DateElement.prototype.getValue = function (){
let stringLiteral = '"';
stringLiteral += this.getSlotValue(0) + '"';
stringLiteral += "^^xsd:dateTime";
return stringLiteral;
}
// Pattern ///////////////////////////////////////////////////////////
Pattern.prototype.constructor = Pattern;
function Pattern(block, endpoint){
this.block = block;
this.endpoint = endpoint;
this.propertyValue = this.getSlotValue(0);
this.entityValue = this.getSlotValue(1);
}
//index is the slot's position index which we want to get the value
Pattern.prototype.getSlotValue = function(index){
let slot = this.block.inputs()[index];
if(slot.category === 'variables'){
let varName = slot.blockSpec;
let ide = world.children[0];
let variable = ide.getVar(varName);
if(variable.type === 'entity')
return this.endpoint.entityPrefix + variable.id;
if(variable.type === 'property')
return this.endpoint.propertyPrefix + variable.id;
return variable;
}
else if(slot.selector === 'literal'){
return new Literal(slot).getValue();
}
else if(slot.selector === 'dateElement'){
return new DateElement(slot).getValue();
}
else if(slot.selector === 'label'){
return 'rdfs:label';
}
else return slot.allEntryFields()[0].text;
}
// Subject ///////////////////////////////////////////////////////////
Subject.prototype.constructor = Subject;
function Subject(rootBlock, endpoint){
this.rootBlock = rootBlock;
this.endpoint = endpoint;
this.patternBlocks = [];
this.varValue = this.getSlotValue();
let inputs = rootBlock.inputs();
let block = inputs[1].inputs()[0];
while(block){
if(block.selector !== 'pattern'){
this.patternBlocks = [];
throw new UnvalidBlockException('Invalid blocks.');
}
let pattern = new Pattern(block, endpoint);
this.patternBlocks.push(pattern);
block = block.nextBlock();
}
};
Subject.prototype.getTriples = function(){
let patternBlock = null;
let predicate = null;
let object = null;
let triples = null;
if(this.rootBlock !== null && this.rootBlock.selector === 'subject'){
let subjectValue = this.varValue;
triples = subjectValue + ' ';
for(let i = 0; i<this.patternBlocks.length; i++){
patternBlock = this.patternBlocks[i];
predicate = patternBlock.propertyValue;
object = patternBlock.entityValue;
triples += predicate + ' ';
triples += object;
if(i !== this.patternBlocks.length-1)
triples += '; \n';
}
triples += '. \n';
}
return triples;
};
Subject.prototype.getSlotValue = function() {
let slot = this.rootBlock.inputs()[0];
if(slot.category === 'variables'){
let varName = slot.blockSpec;
let ide = world.children[0];
let variable = ide.getVar(varName);
if(variable.type === 'entity')
return this.endpoint.entityPrefix + variable.id;
if(variable.type === 'property')
return this.endpoint.propertyPrefix + variable.id;
return variable;
}
else return slot.allEntryFields()[0].text;
}
// LogicOperator ///////////////////////////////////////////////////////////
LogicOperator.prototype.constructor = LogicOperator;
function LogicOperator(block, endpoint){
this.block = block;
this.endpoint = endpoint;
this.selector = block.selector;
this.text = '';
this.logicOperators = [];
this.buildAll();
}
LogicOperator.prototype.buildAll = function(){
if(this.selector === undefined){
this.selector = 'plainText';
let entryField = this.block.allEntryFields();
if(entryField.length === 0)
throw new UnvalidBlockException('Invalid blocks.');
this.text = entryField[0].text;
}
else if(this.selector === 'languageOf'){
this.selector = 'plainText';
let fun = new QueryFunction(this.block);
this.text = fun.getValue();
}