-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathplayground.js
1681 lines (1480 loc) · 49.2 KB
/
playground.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
/**
* The JSON-LD playground is used to test out JavaScript Object Notation
* for Linked Data.
*
* @author Manu Sporny <[email protected]>
* @author Dave Longley <[email protected]>
* @author Nicholas Bollweg
* @author Markus Lanthaler
*/
;(function($, CodeMirror, jsonld, Promise){
"use strict";
// assume nothing
var window = this,
console = window.console,
setTimeout = window.setTimeout,
document = window.document,
// create the playground instance if it doesn't already exist
playground = window.playground = {},
// given this is needed, we probably need a `Document` class...
docs = function(){
return {
markup: null,
frame: null,
context: null
};
};
// the codemirror editors
playground.editors = docs();
// ... and outputs
playground.outputs = {};
// default theme
playground.theme = "neat";
// the last parsed version of same
playground.lastParsed = docs();
// set the active tab to the expanded view
playground.activeTab = 'tab-expanded';
// map of original to modifed contexts
playground.contextMap = {
// be careful when working with redirectors as as Chrome (not firefox)
// will drop Accept: application/ld+json after redirecting
};
// map of currently active mapped contexts for user feedback use
playground.activeContextMap = {};
// JSON schema for JSON-LD documents
playground.schema = null;
// copy context from the input
playground.copyContext = false;
// currently-active urls
playground.remoteUrl = docs();
// whether a remote document should be used
playground.useRemote = docs();
/**
* Get a query parameter by name.
*
* Code from:
* http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript/5158301#5158301
*
* @param name a query parameter name.
*
* @return the value of the parameter or null if it does not exist
*/
function getParameterByName(name) {
var match = new RegExp('[#?&]' + name + '=([^&]*)')
.exec(window.location.hash || window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
/**
* Consistent human-readable JSON formatting.
*
* @param the object or string to humanize.
*
* @return a string containing the humanized string.
*/
playground.humanize = function(value) {
switch($.type(value)) {
case 'string':
return value;
case 'error':
// TODO: limit output size
var str = value.toString();
if('details' in value) {
// TODO: improve error handling
// special cases as of jsonld.js 8.0.0
if('event' in value.details) {
str += '\n' + JSON.stringify(value.details.event, null, 2);
}
// some error and event details can be verbose and need good handling
// all errors and events should have type codes that can be used
}
return str;
default:
return JSON.stringify(value, null, 2);
}
};
/**
* Handle URL query parameters.
*
* Checks 'json-ld', 'context', and 'frame' parameters. If they look
* like JSON then interpret as JSON strings else interpret as URLs of remote
* resources. Note: URLs must be CORS enabled to load due to browser same
* origin policy issues.
*
* If 'startTab' is present, select that tab automatically.
*/
playground.processQueryParameters = function() {
// data from the query
var queryData = docs();
/**
* Read a parameter as JSON or create an jQuery AJAX Deferred call
* to read the data.
*
* @param param a query parameter value.
* @param fieldName the field name to populate in queryData object.
* @param msgName the param name to use in UI messages.
*
* @return jQuery Deferred or null.
*/
function handleParameter(param, fieldName) {
// the ajax deferred or null
var rval = null;
// check 'json-ld' parameter
if(param !== null) {
if(param.length === 0 || param[0] === '{' || param[0] === '[') {
// param looks like JSON, try to parse it
try {
queryData[fieldName] = JSON.parse(param);
playground.setRemoteUrl(fieldName, null);
}
catch(e) {
queryData[fieldName] = param;
}
}
else {
rval = playground.setRemoteUrl(fieldName, param);
playground.toggleRemote(fieldName, true);
if(rval){
rval.then(function(data){
queryData[fieldName] = data;
});
}
}
}
return rval;
}
function handleGist(gist){
/**
* Turn the contents of a gist into the equivalent of the legacy URL
* scheme
* @param gist: a gist id
*/
var deferreds = [],
manifest = JSON.parse(gist.files["playground.jsonld"].content),
done = function(){
$('#' + manifest["startTab"]).tab('show');
playground.populateWithJSON(queryData);
};
playground.copyContext = manifest["copyContext"];
$.each(queryData, function(key, val){
val = manifest[key];
if(val){
// is within this gist?
if(val[0] === "."){
var file = gist.files[val.slice(2)];
if(!file.truncated){
queryData[key] = JSON.parse(file.content);
playground.setRemoteUrl(key, null);
}else{
deferreds.push($.get(file.raw_url).done(function(data){
queryData[fieldName] = JSON.parse(data);
}));
}
}else{
playground.toggleRemote(key, true);
var rval = playground.setRemoteUrl(key, val);
if(rval){
rval.then(function(data){
queryData[fieldName] = data;
});
deferreds.push(rval);
}
}
}
});
return deferreds.length ?
$.when.apply($, deferreds).done(done) :
done();
}
var gistId = new RegExp('^#/gist/(.*)').exec(window.location.hash);
if(gistId){
playground.gist(gistId[1]).done(handleGist);
return;
}
// build deferreds
var jsonLdDeferred = handleParameter(
getParameterByName('json-ld'), 'markup', 'JSON-LD');
var frameDeferred = handleParameter(
getParameterByName('frame'), 'frame', 'frame');
var contextDeferred = handleParameter(
getParameterByName('context'), 'context', 'context');
var paramDeferred = handleParameter(
getParameterByName('param'), 'param', 'param');
var startTab = getParameterByName('startTab');
if(startTab) {
$('#' + startTab).tab('show');
}
playground.copyContext = getParameterByName('copyContext') === "true";
// wait for ajax if needed
// failures handled in AJAX calls
$.when(jsonLdDeferred, frameDeferred, contextDeferred, paramDeferred)
.done(function() {
// Maintain backwards permalink compatability
if(queryData.param && !(queryData.frame || queryData.context)) {
queryData.frame = queryData.context = queryData.param;
}
// populate UI with data
playground.populateWithJSON(queryData);
});
};
/**
* Used to initialize the UI, call once on document load.
*/
playground.init = function() {
// options storage
playground.options = {
api: {
// TODO: add other API options
processingMode: '',
base: '',
baseUrl: '',
compactArrays: true,
compactToRelative: true,
rdfDirection: '',
safe: ''
}
};
// enable bootstrap tabs
$('#input-tabs a,' +
'#context-tabs a,' +
'#frame-tabs a,' +
'#privatekey-rsa-tabs a,' +
'#privatekey-koblitz-tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('#output-tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
}).on("show", playground.tabSelected);
// show keybaord shortcuts
$('.popover-info').popover({
placement: "left",
html: true,
content: $(".popover-info-content").html()
});
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.showHint(cm, CodeMirror.hint.jsonld, {
lastParsed: playground.lastParsed[cm.options._playground_key],
completeSingle: false,
schemata: function(){
return playground.schema ? [playground.schema] : [];
}
});
};
CodeMirror.commands.at_autocomplete = function(cm) {
CodeMirror.showHint(cm, CodeMirror.hint.jsonld, {
isAt: true,
completeSingle: false,
lastParsed: playground.lastParsed[cm.options._playground_key],
schemata: function(){
return playground.schema ? [playground.schema] : [];
}
});
};
$(".codemirror-input").each(function(){ playground.init.editor(this); });
$(".codemirror-output").each(function(){ playground.init.output(this); });
playground.makeResizer($("#markup-container"), playground.editors);
playground.makeResizer($("#output-container"), playground.outputs);
$("#copy-context").click(function(){
playground.toggleCopyContext();
});
$(".editor-option").each(function(){
var option = $(this),
key = option.data("editor");
option.find("input").bind("input", function(){
playground.setRemoteUrl(key, this.value);
});
option.find("button").bind("click", function(){
playground.toggleRemote(key);
});
});
// setup options
$("#options-api-processingMode-default").prop(
'checked', playground.options.api.processingMode === '');
$("#options-api-processingMode-1-0").prop(
'checked', playground.options.api.processingMode === 'json-ld-1.0');
$("#options-api-processingMode-1-1").prop(
'checked', playground.options.api.processingMode === 'json-ld-1.1');
$("#options-api-base-default").prop(
'checked', playground.options.api.base === '');
$("#options-api-base-custom").prop(
'checked', playground.options.api.base === 'custom');
$("#options-api-base-url").value = playground.options.api.baseUrl;
$("#options-api-compactArrays").prop(
'checked', playground.options.api.compactArrays);
$("#options-api-compactToRelative").prop(
'checked', playground.options.api.compactToRelative);
$("#options-api-rdfDirection-default").prop(
'checked', playground.options.api.rdfDirection === '');
$("#options-api-rdfDirection-i18n-datatype").prop(
'checked', playground.options.api.rdfDireciton === 'i18n-datatype');
//$("#options-api-rdfDirection-compound-literal").prop(
// 'checked', playground.options.api.rdfDirection === 'compound-literal');
$("#options-api-safe-default").prop(
'checked', playground.options.api.safe === '');
$("#options-api-safe-false").prop(
'checked', playground.options.api.safe === false);
$("#options-api-safe-true").prop(
'checked', playground.options.api.safe === true);
// process on option changes
$("#options-api-processingMode-default, " +
"#options-api-processingMode-1-0, " +
"#options-api-processingMode-1-1").change(function(e) {
playground.options.api.processingMode = e.target.value;
playground.process();
});
$("#options-api-base-default, " +
"#options-api-base-custom").change(function(e) {
playground.options.api.base = e.target.value;
playground.process();
});
$("#options-api-base-url").on('keypress', function(e) {
var keyPressed = e.keyCode || e.which;
if(keyPressed === 13) {
e.preventDefault();
return false;
}
});
$("#options-api-base-url").on('input', function(e) {
playground.options.api.baseUrl = e.target.value;
playground.process();
});
$("#options-api-compactArrays").change(function(e) {
playground.options.api.compactArrays = e.target.checked;
playground.process();
});
$("#options-api-compactToRelative").change(function(e) {
playground.options.api.compactToRelative = e.target.checked;
playground.process();
});
$("#options-api-rdfDirection-default" ).change(function(e) {
playground.options.api.rdfDirection = '';
playground.process();
});
$("#options-api-rdfDirection-i18n-datatype").change(function(e) {
playground.options.api.rdfDirection = 'i18n-datatype';
playground.process();
});
//$("#options-api-rdfDirection-compound-literal").change(function(e) {
// playground.options.api.rdfDirection = 'compound-literal';
// playground.process();
//});
$("#options-api-safe-default" ).change(function(e) {
playground.options.api.safe = '';
playground.process();
});
$("#options-api-safe-false").change(function(e) {
playground.options.api.safe = false;
playground.process();
});
$("#options-api-safe-true").change(function(e) {
playground.options.api.safe = true;
playground.process();
});
$("[title]").tooltip();
$(window).bind("hashchange", function(){
if(window.location.href !== playground.permalink.url){
playground.processQueryParameters();
$("#permalink").popover("hide");
}
});
// load the schema
$.ajax({
url: "/schemas/jsonld-schema.json",
dataType: "json"
})
.done(function(schema){
playground.schema = schema;
})
.fail(function(){
console.warn("Schema could not be loaded. Schema validation disabled.");
});
if(window.location.search || window.location.hash) {
playground.processQueryParameters();
}
$(".loading").fadeOut(function(){
$(this).remove();
$(".loaded").fadeIn();
playground.editor.refresh();
playground.editor.refresh(playground.outputs);
});
};
/**
* return a debounced copy of a function
* thanks to @cwarden
* https://github.com/cwarden/promising-debounce/blob/master/src/debounce.js
*
* @param a function
* @param a number of milliseconds
*
* @return the function, which will only be called every `delay` milliseconds,
* which will then, in turn, return a $.Deferred
*/
playground.debounce = function(fn, wait, immediate) {
var timer = null;
return function() {
var context = this;
var args = arguments;
var resolve;
var promise = new Promise(function(_resolve) {
resolve = _resolve;
}).then(function() {
return fn.apply(context, args);
});
if(!!immediate && !timer) {
resolve();
}
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
timer = null;
if(!immediate) {
resolve();
}
}, wait);
return promise;
};
};
/**
* Initialize a CodeMirror editor
*
* @param a `<textarea>`
*
* @return the CodeMirror editor
*/
playground.init.editor = function(node){
var key = node.id;
var editor;
// don't use JSON-LD for PEM data
if(key === 'privatekey-rsa' || key === 'privatekey-koblitz' ||
key === 'publickey-koblitz') {
editor = CodeMirror.fromTextArea(node, {
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: false,
mode: 'text',
theme: playground.theme,
_playground_key: key
});
} else {
editor = CodeMirror.fromTextArea(node, {
matchBrackets: true,
autoCloseBrackets: true,
lineWrapping: true,
mode: "application/ld+json",
gutters: ["CodeMirror-lint-markers"],
theme: playground.theme,
lintWith: {
getAnnotations: CodeMirror.lint.jsonSchema,
async: true,
schemata: function(){
return playground.schema ? [playground.schema] : [];
}
},
extraKeys: {
"Ctrl-Space": "autocomplete"
},
_playground_key: key
});
}
playground.editors[key] = editor;
// set up 'process' areas to process JSON-LD after typing
editor.on("change", function(){
if(playground.copyContext && key === "markup"){
if(playground.toggleCopyContext.copy()){
return;
}
}
playground.process();
});
// check on every keyup for `@`: doesn't get caught by (extra|custom)Keys
editor.on("keyup", function(editor, evt) {
// these are the keys that move the cursor
var noHint = [
8, // backspace
9, // hey! where's my tab?
33, 34, 35, 46, // pg/home/end
37, 38, 39, 40, // arrows
12, // enter
27 //escape
];
if(noHint.indexOf(evt.keyCode) >= 0) { return; }
var cursor = editor.getCursor(),
token = editor.getTokenAt(cursor),
chr = token.string[cursor.ch - token.start - 1];
if(chr === "@") {
CodeMirror.commands.at_autocomplete(editor, evt);
}
});
return editor;
};
/**
* Initialize a read-only CodeMirror viewer
*
* @param a `<textarea>`
*
* @return the CodeMirror editor
*/
playground.init.output = function(node) {
var key = node.id,
output = playground.outputs[key] = CodeMirror.fromTextArea(node, {
readOnly: true,
lineWrapping: true,
mode: ["canonized", "nquads"].indexOf(key) > -1 ?
"text/n-triples" :
"application/ld+json",
theme: playground.theme
});
return output;
};
/**
* Toggle whether the output context will be updated from the input
*
* @param the new value of the setting. If not provided, invert current
*
* @return the JSON that was actually set, or `undefined` if nothing was set
*/
playground.toggleCopyContext = function(val){
var editor = playground.editors.context;
playground.copyContext = val = arguments.length ?
Boolean(val) :
!playground.copyContext;
playground.editor.setReadOnly(editor, val);
setTimeout(function(){
$("#copy-context").toggleClass("toggle", val);
}, 1);
if(val){
return playground.toggleCopyContext.copy();
}
};
/**
* Copy the context right now.
*
* @return the JSON that was set, or `undefined` if nothing was set
*/
playground.toggleCopyContext.copy = function(){
var editor = playground.editors.context,
json = playground.humanize({
"@context": playground.lastParsed.markup ?
playground.lastParsed.markup["@context"] :
{}});
if(json !== editor.getValue()){
playground.editors.context.setValue(json);
return json;
}
};
/**
* Set the remote URL for an editor, then fetch (if enabled).
*
* @param the key for the editor
* @param the value
*
* @return jQuery deferred, or `undefined`
*/
playground.setRemoteUrl = function(key, val){
var opt = $("[data-editor=" + key + "]"),
btn = opt.find("button"),
inp = opt.find("input");
playground.remoteUrl[key] = val ? val : null;
if(inp.val() != val){
inp.val(val);
}
// the button state is no longer valid
btn.removeClass("btn-danger btn-info");
return playground.fetchRemote(key);
};
/**
* Toggle (or set) whether a remote document will be used for an editor.
*
* @param the key for the editor
* @param the value: omit to toggle
*
* @return jQuery deferred, or `undefined`
*/
playground.toggleRemote = function(key, val){
var btn = $("[data-editor=" + key + "] button");
playground.useRemote[key] = val = arguments.length === 2 ?
Boolean(val) :
!playground.useRemote[key];
playground.editor.setReadOnly(key, val);
// the button state is no longer valid
setTimeout(function(){
btn.removeClass("btn-danger btn-info" + (!val ? " active" : ""));
}, 1);
return playground.fetchRemote(key);
};
// Cache of fetched remote urls
playground.fetchRemoteCache = {};
playground.fetchRemoteFails = {};
/**
* Fetch a remote document and populate an editor.
*
* @param the key for the editor
*
* @return jQuery deferred, or `undefined`
*/
playground.fetchRemote = playground._fetchRemote = function(key){
if(!playground.useRemote[key]){ return; }
var btn = $("[data-editor=" + key + "] button"),
debounced = playground.fetchRemote !== playground._fetchRemote,
url = playground.remoteUrl[key],
hit = playground.fetchRemoteCache[url],
fail = playground.fetchRemoteFails[url],
success = function(data){
playground.fetchRemoteCache[url] = data;
btn.addClass("btn-info active");
// setValue always triggers a .process()
playground.editors[key].setValue(playground.humanize(data));
playground.fetchRemote = playground._fetchRemote;
},
error = function(err) {
playground.fetchRemoteFails[url] = err;
btn.addClass("btn-danger active");
$('#processing-errors')
.text('Error loading ' + key + ' URL: ' + playground.remoteUrl[key])
.show();
playground.fetchRemote = debounced ?
playground.fetchRemote :
playground.debounce(playground._fetchRemote, 500);
};
return hit ? success(hit) :
fail ? error(fail) :
jsonld.documentLoader(url).then(function(remoteDoc) {
/* Note: Do injection of Link header @context; this could possibly
be done in a less obfuscated way (to the user) or use the expandContext
API option, or better integrate debouncing in the remote document
loader defined elsewhere. However, this approach was the least
intrusive to do now to restore Link header functionality and has the
advantage of allowing the document to be edited inline w/the
injected @context. */
if(remoteDoc.contextUrl) {
// TODO: flash link header injection notice on UI
if(typeof remoteDoc.document === 'string') {
remoteDoc.document = JSON.parse(remoteDoc.document);
}
if(Array.isArray(remoteDoc.document)) {
remoteDoc.document = {
'@context': remoteDoc.contextUrl,
'@graph': remoteDoc.document
};
} else if(typeof remoteDoc.document === 'object') {
// inject @context as first key
var obj = {'@context': remoteDoc.contextUrl};
for(var key in remoteDoc.document) {
obj[key] = remoteDoc.document[key];
}
remoteDoc.document = obj;
} else {
console.error("remoteDoc.document: unknown type");
}
}
success(remoteDoc.document);
}).catch(error);
};
/**
* Make one or more editor resizeable together.
*
* @param parent the dom element to which the button should be attached
* @param an object or list of CodeMirror instances to be resized together
*
* @return the resizer button DOM
*/
playground.makeResizer = function(parent, targets){
targets = $.map(targets, function(val){ return val; });
var start_y,
start_height,
handlers = {},
btn = $("<button/>", {"class": "btn resizer"})
.mousedown(handlers.mousedown = function(evt){
start_y = evt.screenY;
start_height = targets[0].display.wrapper.clientHeight;
$(window)
.bind("mousemove.resizer", function(evt){
targets.map(function(tgt){
tgt.setSize(null, start_height - (start_y - evt.screenY));
});
})
.bind("mouseup.resizer", function(){
$(window).unbind(".resizer");
btn.blur();
});
})
.appendTo(parent);
return btn[0];
};
/**
* Namespace for editor functions, and utility for doing things against them
*
* @param a keyed object of editors, the name of an editor, an editor
* or a list of editors. or nothing, which assumes all of them.
* @param the action to peform, of the form `function(editor, key)`
*
* @return the result of the action
*/
playground.editor = function(editors, action){
var key,
editor;
if($.type(editors) === "string"){
key = editors;
editors = {};
editors[key] = playground.editors[key];
}else if(editors instanceof CodeMirror){
key = editors.getTextArea().id;
editor = editors;
editors = {};
editors[key] = editor;
}else if(!editors){
editors = playground.editors;
}
return $.map(editors, action);
};
/**
* Make a CodeMirror editor (temporarily) read-only.
*
* @param see `playground.editor`
* @param whether the CodeMirror editor should be editable
*
* @return the new value of the read-only setting
*/
playground.editor.setReadOnly = function(editors, value){
value = Boolean(value);
playground.editor(editors, function(editor){
editor.setOption("readOnly", value);
$(editor.getWrapperElement()).toggleClass("read-only", value);
});
return value;
};
/**
* Refresh one or more CodeMirror editors, such as after being revealed.
*
* @param see `playground.editor`
*/
playground.editor.refresh = function(editor){
return playground.editor(editor, function(editor){
editor.refresh();
});
};
/**
* Callback for when tabs are selected in the UI.
*
* @param event the event that fired when the tab was selected.
*
* @return the process() promise
*/
playground.tabSelected = function(evt) {
var id = playground.activeTab = evt.target.id;
if(['tab-compacted', 'tab-flattened', 'tab-framed',
/*'tab-signed-rsa', 'tab-signed-koblitz'*/].indexOf(id) > -1) {
// these options require more UI inputs, so compress UI space
$('#markup-div').removeClass('span12').addClass('span6');
$('#frame-div, #privatekey-rsa-div, #privatekey-koblitz-div, ' +
'#context-div').hide();
if(id === 'tab-compacted' || id === 'tab-flattened') {
$('#param-type').html('JSON-LD Context');
$('#context-div').show();
} else if(id==='tab-framed') {
$('#param-type').html('JSON-LD Frame');
$('#frame-div').show();
} else if(id === 'tab-signed-rsa') {
$('#param-type').html('PEM-encoded Private Key');
$('#privatekey-rsa-div').show();
} else if(id === 'tab-signed-koblitz') {
$('#param-type').html('Base 58 Encoded Private Key');
$('#privatekey-koblitz-div').show();
}
}
else {
// else no input textarea required
$('#context-div, #frame-div, #privatekey-rsa-div, ' +
'#privatekey-koblitz-div').hide();
$('#markup-div').removeClass('span6').addClass('span12');
$('#param-type').html('');
}
// refresh all the editors
playground.editor.refresh();
playground.editor.refresh(playground.outputs);
// perform processing on the data provided in the input boxes
return playground.process();
};
/**
* Returns a Promise to perform the JSON-LD API action based on the active
* tab.
*
* @param input the JSON-LD object input or null no error.
* @param param the JSON-LD param to use.
*
* @return a promise to perform the action
*/
playground.performAction = function(input, param) {
// set options
var options = {};
if(playground.options.api.processingMode !== '') {
options.processingMode = playground.options.api.processingMode;
}
if(playground.options.api.base === 'custom') {
options.base = playground.options.api.baseUrl || '';
} else {
// default base IRI is based on remote url or set to null
options.base =
(playground.useRemote.markup && playground.remoteUrl.markup) || null;
}
options.compactArrays = playground.options.api.compactArrays;
options.compactToRelative = playground.options.api.compactToRelative;
if(playground.options.api.rdfDirection !== '') {
options.rdfDirection = playground.options.api.rdfDirection;
}
if(playground.options.api.safe !== '') {
options.safe = playground.options.api.safe;
}
var promise;
if(playground.activeTab === 'tab-compacted') {
promise = jsonld.compact(input, param, options);
}
else if(playground.activeTab === 'tab-expanded') {
promise = jsonld.expand(input, options);
}
else if(playground.activeTab === 'tab-flattened') {
promise = jsonld.flatten(input, param, options);
}
else if(playground.activeTab === 'tab-framed') {
promise = jsonld.frame(input, param, options);
}
else if(playground.activeTab === 'tab-nquads') {
options.format = 'application/n-quads';
promise = jsonld.toRDF(input, options);
}
else if(playground.activeTab === 'tab-canonized') {
options.format = 'application/n-quads';
promise = jsonld.canonize(input, options);
}
else if(playground.activeTab === 'tab-table') {
return jsonld.toRDF(input, options)
.then(_datasetToTable($('#table tbody')));
}
else if(playground.activeTab === 'tab-visualized') {
// early return because this isn't an editor
return new Promise(function() {
$('#visualized').empty();
d3.jsonldVis(input, '#visualized');
});
}
else if(playground.activeTab === 'tab-signed-rsa') {
options.format = 'application/ld+json';
var jsigs = window.jsigs || window['jsonld-signatures'];
var pkey = playground.editors['privatekey-rsa'].getValue();
var secCtx = jsigs.SECURITY_CONTEXT_URL;
var algorithm;
var newerJsigs = 'suites' in jsigs && 'RsaSignature2018' in jsigs.suites;
// FIXME: remove when jsonld.js updated
var v11Ctx = {'@version': 1.1};
if(newerJsigs) {
algorithm = 'RsaSignature2018';
} else {
algorithm = 'LinkedDataSignature2015';
}
// add security context to input
if(!('@context' in input)) {
input['@context'] = secCtx;
} else if(Array.isArray(input['@context'])) {