-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathscripts.js
548 lines (497 loc) · 18.5 KB
/
scripts.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
/* exported getUrlParams, getHrefForUri, readCookie, createCookie, debounce, updateContent, updateJsonLD, updateTopbarLang, updateTitle, updateSidebar, setLangCookie, clearResultsAndAddSpinner, loadLimitations, loadPage, hideCrumbs, hidePropertyValues, shortenProperties, countAndSetOffset, combineStatistics, loadLimitedResults, naturalCompare, makeCallbacks, escapeHtml, makeSelection, copyToClickboard, renderPropertyMappingValues, renderPropertyMappings, loadMappingProperties */
/*
* Creates a cookie value and stores it for the user. Takes the given
* value label, the value itself and the number of days until expires.
* The function is used when storing data about concept views, hidden
* properties and bookmarks.
* @param {String} name
* @param {String} value
* @param {Integer} days
*/
function createCookie(name,value,days) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) === ' ') { c = c.substring(1,c.length); }
if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
}
return null;
}
function getUrlParams() {
var params = {};
window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
});
return params;
}
/**
* Get a href value for a concept URI in current vocab urispace
*
* @param uri string concept URI
* @param plainReturnValue boolean indicates whether to return a plain string or a href-key key-value-pair
* @return string|object Plain href link (string) or href-key key-value-pair if parameter plainReturnValue evaluates to false
*
*/
function getHrefForUri(uri, plainReturnValue) {
var clangParam = (content_lang !== lang) ? "clang=" + content_lang : "";
var clangSeparator = "?";
if (uri.indexOf(window.uriSpace) !== -1) {
var page = uri.substr(window.uriSpace.length);
if (/[^a-zA-Z0-9-_\.~]/.test(page) || page.indexOf("/") > -1 ) {
// contains special characters or contains an additional '/' - fall back to full URI
page = '?uri=' + encodeURIComponent(uri);
clangSeparator = "&";
}
} else {
// not within URI space - fall back to full URI
page = '?uri=' + encodeURIComponent(uri);
clangSeparator = "&";
}
var href = window.vocab + '/' + window.lang + '/page/' + page + (clangParam !== "" ? clangSeparator + clangParam : "");
return plainReturnValue ? href : { "href" : href };
}
// Debounce function from underscore.js
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
/*
* Ajax query queue that keeps track of ongoing queries
* so they can be cancelled if a another event is triggered.
* originally taken from https://stackoverflow.com/a/11612641
*/
$.ajaxQ = (function(){
var id = 0, Q = {};
$(document).ajaxSend(function(e, jqXHR, settings){
jqXHR._id = ++id;
jqXHR['req_kind'] = settings.req_kind !== undefined ? settings.req_kind: $.ajaxQ.requestKind.PLUGIN;
Q[jqXHR._id] = jqXHR;
});
$(document).ajaxComplete(function(e, jqXHR){
delete Q[jqXHR._id];
});
return {
abortAll: function(){
var r = [];
$.each(Q, function(i, jqXHR){
r.push(jqXHR._id);
jqXHR.abort();
});
return r;
},
abortContentQueries: function(){
// includes the ones generated by plugins
var r = [];
$.each(Q, function(i, jqXHR){
r.push(jqXHR._id);
if (jqXHR.req_kind == $.ajaxQ.requestKind.CONTENT || jqXHR.req_kind == $.ajaxQ.requestKind.PLUGIN) {
jqXHR.abort();
}
});
return r;
},
abortSidebarQueries: function(all=false){
var r = [];
$.each(Q, function(i, jqXHR){
r.push(jqXHR._id);
if (jqXHR.req_kind == $.ajaxQ.requestKind.SIDEBAR || all && jqXHR.req_kind == $.ajaxQ.requestKind.SIDEBAR_PRIVILEGED) {
jqXHR.abort();
}
});
return r;
},
requestKind: {GLOBAL: 0, SIDEBAR: 1, SIDEBAR_PRIVILEGED: 2, CONTENT: 3, PLUGIN: 4}
}
})();
function updateContent(data) {
var $content = $('.content');
$content.empty();
var response = $('.content', data).html();
$content.append(response);
}
function updateJsonLD(data) {
var $jsonld = $('script[type="application/ld+json"]');
var $newJsonLD = $(data).filter('script[type="application/ld+json"]');
if ($jsonld[0]) {
$jsonld[0].innerHTML = "{}";
if ($newJsonLD[0]) {
$jsonld[0].innerHTML = $newJsonLD[0].innerHTML;
}
}
else if ($newJsonLD[0]) {
// insert after the first JS script as it is in the template
var elemBefore = $('script[type="text/javascript"]')[0];
if (elemBefore) {
$newJsonLD.insertAfter(elemBefore);
}
}
}
function updateTopbarLang(data) {
var $language = $('#language');
$language.empty();
var langBut = $('#language', data).html();
$language.append(langBut);
}
function updateTitle(data) {
var title = $(data).filter('title').text();
document.title = title;
}
function updateSidebar(data) {
var $sidebar = $('#sidebar');
$sidebar.empty();
var response = $('#sidebar', data).html();
$sidebar.append(response);
}
// sets the language cookie for 365 days
function setLangCookie(lang) {
createCookie('SKOSMOS_LANGUAGE', lang, 365);
}
function clearResultsAndAddSpinner() {
var $loading = $("<div class='search-result'><p>" + loading_text + "…<span class='spinner'></span></p></div>");
$('.search-result-listing').empty().append($loading);
}
function loadLimitations() {
var $typeLimit = $('#type-limit');
var $schemeLimit = $('#scheme-limit');
var groupLimit = $('#group-limit').val();
var parentLimit = $('#parent-limit').attr('data-uri');
var typeLimit = $typeLimit.val() ? $typeLimit.val().join('+') : $typeLimit.val();
var schemeLimit = $schemeLimit.val() ? $schemeLimit.val().join('+') : $schemeLimit.val();
if (schemeLimit && schemeLimit[0] === '+') { // filtering the empty selection out of the search string
schemeLimit = schemeLimit.substring(1);
}
if (typeLimit && typeLimit[0] === '+') { // filtering the empty selection out of the search string
typeLimit = typeLimit.substring(1);
}
return $.param({'type' : typeLimit, 'group' : groupLimit, 'parent': parentLimit, 'scheme': schemeLimit});
}
function loadLimitedResults(parameters) {
clearResultsAndAddSpinner();
$.ajax({
data: parameters,
complete : function(jqXHR, textStatus) {
var data = jqXHR.responseText;
var response = $('.search-result-listing', data).html();
if (window.history.pushState) { window.history.pushState({url: this.url}, '', this.url); }
$('.search-result-listing').append(response);
$('.spinner').parent().parent().detach();
updateTitle(data);
}
});
}
function loadPage(targetUrl) {
$.ajax({
url : targetUrl,
success : function(data) {
if (targetUrl.indexOf('index') !== -1 || targetUrl.indexOf('groups') !== -1) {
updateSidebar(data);
} else {
$('.activated-concept').removeClass('activated-concept');
$('.jstree-clicked').removeClass('jstree-clicked');
updateContent(data);
$('a[href="' + $('.uri-input-box').text() + '"]').addClass('jstree-clicked');
}
updateTitle(data);
updateTopbarLang(data);
// take the content language buttons from the response
$('.header-float .dropdown-menu').empty().append($('.header-float .dropdown-menu', data).html());
makeCallbacks(data);
}
});
}
// if there are multiple breadcrumb paths hide those and generate a button for displaying those
function hideCrumbs() {
var $crumbs = $('.crumb-path');
if ($crumbs.length > 4) {
for (var i = 4; i < $crumbs.length; i++) {
$($crumbs[i]).addClass('hidden-path');
}
if ($('.restore-breadcrumbs').length === 0) {
$($crumbs[0]).after('<a class="versal restore-breadcrumbs" href="#">[' + expand_paths.replace('#',($crumbs.length)) + ']</a>');
}
}
}
// if there are too many property values on the concept page, hide some of them
function hidePropertyValues() {
var maxValues = 15; // hide extras if there are more values than this
var $propertyValueLists = $('.property-value-wrapper ul');
for (var i = 0; i < $propertyValueLists.length; ++i) {
var $propertyValueList = $($propertyValueLists[i]);
if ($propertyValueList.hasClass('expand-propvals')) {
continue; // already shortened - and expanded by user
}
if ($propertyValueList.find('.restore-propvals').length > 0) {
continue; // already shortened by this function
}
var nValues = $propertyValueLists[i].children.length;
if (nValues > maxValues) {
var $propertyValues = $($propertyValueLists[i].children);
for (var j = maxValues; j < $propertyValues.length; ++j) {
$($propertyValues[j]).addClass('hidden-propval');
}
$propertyValueList.append('<li><a class="restore-propvals" href="#">[' + expand_propvals.replace('#', nValues) + ']</a></li>');
}
}
}
// Shortens the properties that don't fit on one row on the search result view.
function shortenProperties() {
var $properties = $('.property-values');
for (var i = 0; i < $properties.length; i++) {
var $property = $($properties[i]);
if ($property.height() > 24) {
$property.addClass('shortened-property');
var count = $property.children('.value').length;
var uri = $property.parent().siblings('a.prefLabel')[0].href;
var shortened = '<a href="' + uri +'" class="versal shortened-symbol" style="">... (' + count +')</a>';
$property.parent().append(shortened);
}
}
}
/**
* Combines the different properties into an object with the language codes as
* keys and an another array of property counts as the value.
* @return object
*/
function combineStatistics(input) {
var combined = {};
for (var i = 0; i < input.length; i++) {
var langdata = input[i];
combined[langdata.literal] = [langdata.literal];
for (var j = 0; j < langdata.properties.length; j++) {
combined[langdata.literal].push(langdata.properties[j].labels);
}
}
return combined;
}
// Calculates and sets how many vertical pixels the sidebar height should be at the current scroll position.
function countAndSetOffset() {
/* calculates the sidebars content maximum height and sets it as an inline style.
the .css() can't set important so using .attr() instead. */
$('.sidebar-grey').attr('style', function() {
var pixels = $('.nav-tabs').height() + 2; // the 2 pixels are for the borders
if ($('#sidebar > .pagination').is(':visible')) { pixels += $('.pagination').height(); }
return 'height: calc(100% - ' + pixels + 'px) !important';
});
var $sidebar = $('#sidebar');
if ($sidebar.length && !$sidebar.hasClass('fixed')) {
var yOffset = window.innerHeight - ( $sidebar.offset().top - window.pageYOffset);
$sidebar.css('height', yOffset);
}
}
// Natural sort from: http://stackoverflow.com/a/15479354/3894569
function naturalCompare(a, b) {
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]); });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]); });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1], lang);
if(nn) return nn;
}
return ax.length - bx.length;
}
function makeCallbacks(data, pageType) {
if (!pageType) {
pageType = 'page';
}
var variables = data ? data.substring(data.indexOf('var uri ='), data.indexOf('var uriSpace =')).split('\n') : '';
var newUri = data ? variables[0].substring(variables[0].indexOf('"')+1, variables[0].indexOf(';')-1) : window.uri;
var newPrefs = data ? JSON.parse(variables[1].substring(variables[1].indexOf('['), variables[1].lastIndexOf(']')+1)) : window.prefLabels;
var $ldJsonScript = $('script[type="application/ld+json"]');
var embeddedJsonLd = $ldJsonScript[0] ? JSON.parse($ldJsonScript[0].innerHTML) : {};
var params = {'uri': newUri, 'prefLabels': newPrefs, 'page': pageType, "json-ld": embeddedJsonLd};
if (window.pluginCallbacks) {
for (var i in window.pluginCallbacks) {
var fname = window.pluginCallbacks[i];
var callback = window[fname];
if (typeof callback === 'function') {
callback(params);
}
}
}
}
function escapeHtml(string) {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
// Make a selection of an element for copy pasting.
function makeSelection(e, elem) {
var $clicked = elem || $(this);
var text = $clicked[0];
var range;
if (document.body.createTextRange) { // ms
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
return false;
}
// copy to clickboard
function copyToClipboard() {
var $btn = $(this);
var id = $btn.attr('for');
var $elem = $(id);
makeSelection(undefined, $elem);
document.execCommand('copy');
}
function renderPropertyMappingValues(groupedByType) {
var propertyMappingValues = [];
var source = document.getElementById("property-mapping-values-template").innerHTML;
var template = Handlebars.compile(source);
var context = {
property: {
uri: conceptMappingPropertyValue.uri,
label: conceptMappingPropertyValue.prefLabel,
}
};
propertyMappingValues.push({'body': template(context)});
return propertyMappingValues;
}
function renderPropertyMappings(concept, contentLang, properties) {
var source = document.getElementById("property-mappings-template").innerHTML;
// handlebarjs helper functions
Handlebars.registerHelper('ifDeprecated', function(conceptType, value, opts) {
if(conceptType == value) {
return opts.fn(this);
}
return opts.inverse(this);
});
Handlebars.registerHelper('toUpperCase', function(str) {
if (str === undefined) {
return '';
}
return str.toUpperCase();
});
Handlebars.registerHelper('ifNotInDescription', function(type, description, opts) {
if (type === undefined) {
return opts.inverse(this);
}
if (description === undefined) {
return opts.inverse(this);
}
if (description.indexOf(type) > 0 && description.indexOf('_help') > 0) {
return opts.inverse(this);
}
return opts.fn(this);
});
Handlebars.registerHelper('ifDifferentLabelLang', function(labelLang, opts) {
if (labelLang !== undefined && labelLang !== '' && labelLang !== null) {
if (explicitLangCodes || labelLang !== contentLang) {
return opts.fn(this);
}
}
return opts.inverse(this);
});
var template = Handlebars.compile(source);
var context = {
concept: concept,
properties: properties
};
return template(context);
}
/**
* Load mapping properties, via the JSKOS REST endpoint. Then, render the concept mapping properties template. This
* template is comprised of another template, for concept mapping property values.
*
* @param concept dictionary/object populated with data from the Concept object
* @param lang language used in the UI
* @param contentLang the content language
* @param $htmlElement HTML (a div) parent object (initially hidden)
* @param conceptData concept page data returned via ajax, passed to makeCallback only
*/
function loadMappingProperties(concept, lang, contentLang, $htmlElement, conceptData) {
// display with the spinner
$htmlElement
.removeClass('hidden')
.append('<div class="spinner row"></div>');
$.ajax({
url: rest_base_url + vocab + '/mappings',
req_kind: $.ajaxQ.requestKind.CONTENT,
data: $.param({'uri': concept.uri, lang: lang, clang: contentLang}),
success: function(data) {
// The JSKOS REST mapping properties call will have added more resources into the graph. The graph
// is returned alongside the mapping properties, so now we just need to replace it on the UI.
$('script[type="application/ld+json"]')[0].innerHTML = data.graph;
var conceptProperties = [];
for (var i = 0; i < data.mappings.length; i++) {
/**
* @var conceptMappingPropertyValue JSKOS transformed ConceptMappingPropertyValue
*/
var conceptMappingPropertyValue = data.mappings[i];
var found = false;
var conceptProperty = null;
for (var j = 0; j < conceptProperties.length; j++) {
conceptProperty = conceptProperties[j];
if (conceptProperty.type === conceptMappingPropertyValue.type[0]) {
conceptProperty.values.push(conceptMappingPropertyValue);
found = true;
break;
}
}
if (!found) {
conceptProperty = {
'type': conceptMappingPropertyValue.type[0],
'id': conceptMappingPropertyValue.type[0].replace(/[^A-Za-z-]/g, '_'),
'label': conceptMappingPropertyValue.typeLabel,
'notation': conceptMappingPropertyValue.notation,
'description': conceptMappingPropertyValue.description,
'values': []
};
conceptProperty.values.push(conceptMappingPropertyValue);
conceptProperties.push(conceptProperty);
}
}
if (conceptProperties.length > 0) {
var template = renderPropertyMappings(concept, contentLang, conceptProperties);
$htmlElement.empty();
$htmlElement.append(template);
} else {
// No concept properties found
$htmlElement.empty();
$htmlElement.addClass("hidden");
}
},
error: function(data) {
console.log("Error retrieving mapping properties for [" + $htmlElement.data('concept-uri') + "]: " + data.responseText);
},
complete: function() {
makeCallbacks(conceptData);
}
});
}