1 /*! MKWS, the MasterKey Widget Set.
2 * Copyright (C) 2013-2015 Index Data
3 * See the file LICENSE for details
9 // Set up global mkws object. Contains truly global state such as SP
10 // authentication, and a hash of team objects, indexed by team-name.
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
15 $: $, // Our own local copy of the jQuery object
17 authenticating: false,
22 widgetType2function: {},
28 "Subjects": "Schlagwörter",
29 "Sources": "Daten und Quellen",
30 "source": "datenquelle",
31 "Facets": "Termlisten",
33 "Prev": "Zurück",
35 "Sort by": "Sortieren nach",
36 "and show": "und zeige",
37 "per page": "pro Seite",
38 "Displaying": "Zeige",
46 "Subject": "Schlagwort",
47 "subject": "schlagwort",
48 "Location": "Bestand",
49 "Locations": "Bestand",
50 "Records": "Datensätze",
51 "Targets": "Datenbanken",
53 "relevance": "Relevanz",
56 "oldest": "Älteste",
62 "Authors": "Forfattere",
66 "Facets": "Termlists",
67 "Next": "Næste",
69 "Search": "Søg",
70 "Sort by": "Sorter efter",
72 "per page": "per side",
73 "Displaying": "Viser",
78 "Author": "Forfatter",
79 "author": "forfatter",
83 "Location": "Lokation",
84 "Locations": "Lokationer",
88 "relevance": "Relevans",
98 // We may be using a separate copy
99 if (typeof(mkws_jQuery) !== "undefined") {
100 mkws.$ = mkws_jQuery;
105 // It's ridiculous that JSNLog doesn't provide this
106 mkws.stringToLevel = function(s) {
108 return JL.getTraceLevel();
109 } else if (s === 'debug') {
110 return JL.getDebugLevel();
111 } else if (s === 'info') {
112 return JL.getInfoLevel();
113 } else if (s === 'warn') {
114 return JL.getWarnLevel();
115 } else if (s === 'error') {
116 return JL.getErrorLevel();
117 } else if (s === 'fatal') {
118 return JL.getFatalLevel();
120 throw "bad log-level '" + s + "'";
124 mkws.logger = JL('mkws');
125 var consoleAppender = JL.createConsoleAppender('consoleAppender');
126 mkws.logger.setOptions({ "appenders": [consoleAppender] });
130 var argsAsARealArray = Array.prototype.slice.call(arguments);
131 var fn = argsAsARealArray.shift();
132 fn.apply(mkws.logger, argsAsARealArray);
134 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
135 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
136 mkws.info = function(x) { _log(mkws.logger.info, x) };
137 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
138 mkws.error = function(x) { _log(mkws.logger.error, x) };
139 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
142 // Translation function.
143 mkws.M = function(word) {
144 var lang = mkws.config.lang;
146 if (!lang || !mkws.locale_lang[lang])
149 return mkws.locale_lang[lang][word] || word;
153 // This function is taken from a StackOverflow answer
154 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
155 mkws.getParameterByName = function(name, url) {
156 if (!url) url = location.search;
157 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
158 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
159 results = regex.exec(url);
160 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
164 mkws.registerWidgetType = function(name, fn) {
165 if(mkws._old2new.hasOwnProperty(name)) {
166 mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
167 name = mkws._old2new[name];
170 mkws.widgetType2function[name] = fn;
171 mkws.info("registered widget-type '" + name + "'");
174 mkws.aliasWidgetType = function(newName, oldName) {
175 mkws.widgetType2function[newName] = mkws.widgetType2function[oldName];
176 mkws.info("aliased widget-type '" + newName + "' to '" + oldName + "'");
180 mkws.promotionFunction = function(name) {
181 return mkws.widgetType2function[name];
185 mkws.setMkwsConfig = function(overrides) {
186 var config_default = {
187 use_service_proxy: true,
188 pazpar2_url: undefined,
189 pp2_hostname: "sp-mkws.indexdata.com",
190 pp2_path: "service-proxy/",
191 service_proxy_auth: undefined,
192 sp_auth_path: undefined,
193 sp_auth_query: "command=auth&action=perconfig",
194 sp_auth_credentials: undefined,
196 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
197 perpage_options: [10, 20, 30, 50],
198 sort_default: "relevance",
200 show_lang: true, /* show/hide language menu */
201 show_sort: true, /* show/hide sort menu */
202 show_perpage: true, /* show/hide perpage menu */
203 show_switch: true, /* show/hide switch menu */
204 lang_options: [], /* display languages links for given languages, [] for all */
205 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
206 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
207 log_level: 1, /* log level for development: 0..2 */
208 template_vars: {}, /* values that may be exposed to templates */
213 mkws.config = mkws.objectInheritingFrom(config_default);
214 for (var k in overrides) {
215 mkws.config[k] = overrides[k];
220 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
221 // http://javascript.crockford.com/prototypal.html
222 // mkws.objectInheritingFrom behaves the same as Object.create,
223 // but since the latter is not available in IE8 we can't use it.
225 mkws.objectInheritingFrom = function(o) {
232 // The following functions are dispatchers for team methods that
233 // are called from the UI using a team-name rather than implicit
235 mkws.switchView = function(tname, view) {
236 mkws.teams[tname].switchView(view);
239 mkws.showDetails = function(tname, prefixRecId) {
240 mkws.teams[tname].showDetails(prefixRecId);
243 mkws.limitTarget = function(tname, id, name) {
244 mkws.teams[tname].limitTarget(id, name);
247 mkws.limitQuery = function(tname, field, value) {
248 mkws.teams[tname].limitQuery(field, value);
251 mkws.limitCategory = function(tname, id) {
252 mkws.teams[tname].limitCategory(id);
255 mkws.delimitTarget = function(tname, id) {
256 mkws.teams[tname].delimitTarget(id);
259 mkws.delimitQuery = function(tname, field, value) {
260 mkws.teams[tname].delimitQuery(field, value);
263 mkws.showPage = function(tname, pageNum) {
264 mkws.teams[tname].showPage(pageNum);
267 mkws.pagerPrev = function(tname) {
268 mkws.teams[tname].pagerPrev();
271 mkws.pagerNext = function(tname) {
272 mkws.teams[tname].pagerNext();
276 mkws.pazpar2_url = function() {
277 if (mkws.config.pazpar2_url) {
278 mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
279 return mkws.config.pazpar2_url;
281 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
282 mkws.info("generated pazpar2_url '" + s + "'");
288 // We put a session token in window.name, as it's the only place to
289 // keep data that is preserved across reloads and within-site
290 // navigation. pz2.js picks this up and uses it as part of the
291 // cookie-name, to ensure we get a new session when we need one.
293 // We want to use different sessions for different windows/tabs (so
294 // they don't receive each other's messages), different hosts and
295 // different paths on a host (since in general these will
296 // authenticate as different libraries). So the window name needs to
297 // include the hostname and the path from the URL, plus the token.
301 token = window.name.replace(/.*\//, '');
302 mkws.debug("Reusing existing window token '" + token + "'");
304 // Incredible that the standard JavaScript runtime doesn't define a
305 // unique windowId. Instead, we have to make one up. And since there's
306 // no global area shared between windows, the best we can do for
307 // ensuring uniqueness is generating a random ID and crossing our
310 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
311 // At one per second, it will take 116 million years to duplicate a token
312 token = Math.random().toString(36).slice(2, 12);
313 mkws.debug("Generated new window token '" + token + "'");
316 window.name = window.location.hostname + window.location.pathname + '/' + token;
317 mkws.info("Using window.name '" + window.name + "'");
320 // wrapper to provide local copy of the jQuery object.
322 var _old2new = { // Maps old-style widget names to new-style
323 'Authname': 'auth-name',
324 'ConsoleBuilder': 'console-builder',
325 'Coverart': 'cover-art',
326 'GoogleImage': 'google-image',
328 'MOTDContainer': 'motd-container',
329 'Perpage': 'per-page',
330 'SearchForm': 'search-form',
331 'ReferenceUniverse': 'reference-universe',
332 'Termlists': 'facets'
334 // Annoyingly, there is no built-in way to invert a hash
336 for (var key in _old2new) {
337 if(_old2new.hasOwnProperty(key)) {
338 _new2old[_old2new[key]] = key;
342 mkws._old2new = _old2new;
344 function handleNodeWithTeam(node, callback) {
345 // First branch for DOM objects; second branch for jQuery objects
346 var classes = node.className || node.attr('class');
348 // For some reason, if we try to proceed when classes is
349 // undefined, we don't get an error message, but this
350 // function and its callers, up several stack level,
351 // silently return. What a crock.
352 mkws.fatal("handleNodeWithTeam() called on node with no classes");
355 var list = classes.split(/\s+/)
358 for (var i = 0; i < list.length; i++) {
360 if (cname.match(/^mkws-team-/)) {
361 // New-style teamnames of the form mkws-team-xyz
362 teamName = cname.replace(/^mkws-team-/, '');
363 } else if (cname.match(/^mkwsTeam_/)) {
364 // Old-style teamnames of the form mkwsTeam_xyz
365 teamName = cname.replace(/^mkwsTeam_/, '');
366 } else if (cname.match(/^mkws-/)) {
367 // New-style names of the from mkws-foo-bar
368 type = cname.replace(/^mkws-/, '');
369 } else if (cname.match(/^mkws/)) {
370 // Old-style names of the form mkwsFooBar
371 var tmp = cname.replace(/^mkws/, '');
372 type = _old2new[tmp] || tmp.toLowerCase();
376 // Widgets without a team are on team "AUTO"
379 // Autosearch widgets don't join team AUTO if there is already an
380 // autosearch on the team or the team has otherwise gotten a query
381 if (node.getAttribute("autosearch")) {
382 if (mkws.autoHasAuto ||
383 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
384 mkws.warn("AUTO team already has a query, using unique team");
387 mkws.autoHasAuto = true;
391 // Widgets on team "UNIQUE" get a random team
392 if (teamName === "UNIQUE") {
393 teamName = Math.floor(Math.random() * 100000000).toString();
396 callback.call(node, teamName, type);
400 function resizePage() {
401 var threshhold = mkws.config.responsive_design_width;
402 var width = $(window).width();
403 var from, to, method;
405 if ((mkws.width === undefined || mkws.width > threshhold) &&
406 width <= threshhold) {
407 from = "wide"; to = "narrow"; method = "hide";
408 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
409 width > threshhold) {
410 from = "narrow"; to = "wide"; method = "show";
415 mkws.info("changing from " + from + " to " + to + ": " + width);
416 for (var tname in mkws.teams) {
417 var team = mkws.teams[tname];
418 team.visitWidgets(function(t, w) {
419 var w1 = team.widget(t + "-container-" + from);
420 var w2 = team.widget(t + "-container-" + to);
426 w.node.appendTo(w2.node);
429 team.queue("resize-" + to).publish();
436 * Run service-proxy authentication in background (after page load).
437 * The username/password is configured in the apache config file
440 function authenticateSession(auth_url, auth_domain, pp2_url) {
441 mkws.authenticating = true;
442 mkws.info("service proxy authentication on URL: " + auth_url);
445 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
446 mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
449 var request = new pzHttpRequest(auth_url, function(err) {
450 alert("HTTP call for authentication failed: " + err)
454 request.get(null, function(data) {
455 mkws.authenticating = false;
456 if (!$.isXMLDoc(data)) {
457 alert("Service Proxy authentication response is not a valid XML document");
460 var status = $(data).find("status");
461 if (status.text() != "OK") {
462 var message = $(data).find("message");
463 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
467 mkws.info("service proxy authentication successful");
468 mkws.authenticated = true;
469 var authName = $(data).find("displayName").text();
470 // You'd think there would be a better way to do this:
471 var realm = $(data).find("realm:not(realmAttributes realm)").text();
472 for (var teamName in mkws.teams) {
473 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
481 function runAutoSearches() {
482 mkws.info("running auto searches");
484 for (var teamName in mkws.teams) {
485 mkws.teams[teamName].queue("ready").publish();
490 function selectorForAllWidgets() {
491 if (mkws.config && mkws.config.scan_all_nodes) {
492 // This is the old version, which works by telling jQuery to
493 // find every node that has a class beginning with "mkws". In
494 // theory it should be slower than the class-based selector; but
495 // instrumentation suprisingly shows this is consistently
496 // faster. It also has the advantage that any widgets of
497 // non-registered types are logged as warnings rather than
499 return '[class^="mkws"],[class*=" mkws"]';
501 // This is the new version, which works by looking up the
502 // specific classes of all registered widget types and their
503 // resize containers. Because all it requires jQuery to do is
504 // some hash lookups in pre-built tables, it should be very
505 // fast; but it silently ignores widgets of unregistered types.
507 for (var type in mkws.widgetType2function) {
509 s += '.mkws-' + type;
510 s += ',.mkws-' + type + "-container-wide";
511 s += ',.mkws-' + type + "-container-narrow";
512 // Annoyingly, we also need to recognise old-style names
513 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
514 s += ',.mkws' + oldtype;
515 s += ',.mkws' + oldtype + "-Container-wide";
516 s += ',.mkws' + oldtype + "-Container-narrow";
523 function makeWidgetsWithin(level, node) {
524 if (node) var widgetNodes = node.find(selectorForAllWidgets());
525 else widgetNodes = $(selectorForAllWidgets());
526 // Return false if we parse no widgets
527 if (widgetNodes.length < 1) return false;
528 widgetNodes.each(function() {
529 handleNodeWithTeam(this, function(tname, type) {
530 var myTeam = mkws.teams[tname];
532 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
535 var oldHTML = this.innerHTML;
536 var myWidget = mkws.makeWidget($, myTeam, type, this);
537 myTeam.addWidget(myWidget);
538 var newHTML = this.innerHTML;
539 if (newHTML !== oldHTML) {
540 myTeam.info("widget " + type + " HTML changed: reparsing");
541 makeWidgetsWithin(level+1, $(this));
549 // The second "rootsel" parameter is passed to jQuery and is a DOM node
550 // or a selector string you would like to constrain the search for widgets to.
552 // This function has no side effects if run again on an operating session,
553 // even if the element/selector passed causes existing widgets to be reparsed:
555 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
556 // widgets, MKWS-261)
558 // * configuration is not regenerated
559 // * authentication is not performed again
560 // * autosearches are not re-run
561 mkws.init = function(message, rootsel) {
562 var greet = "MKWS initialised";
563 if (rootsel) greet += " (limited to " + rootsel + ")"
564 if (message) greet += " :: " + message;
567 // MKWS is not active until init() has been run against an object with widget nodes.
568 // We only set initial configuration when MKWS is first activated.
569 if (!mkws.isActive) {
570 var widgetSelector = selectorForAllWidgets();
571 if ($(widgetSelector).length < 1) {
572 mkws.warn("no widgets found");
576 // Initial configuration
577 mkws.autoHasAuto = false;
579 if (typeof mkws_config === 'undefined') {
580 mkws.info("setting empty config");
583 mkws.info("using config: " + $.toJSON(mkws_config));
584 saved_config = mkws_config;
586 mkws.setMkwsConfig(saved_config);
588 for (var key in mkws.config) {
589 if (mkws.config.hasOwnProperty(key)) {
590 if (key.match(/^language_/)) {
591 var lang = key.replace(/^language_/, "");
592 // Copy custom languages into list
593 mkws.locale_lang[lang] = mkws.config[key];
594 mkws.info("added locally configured language '" + lang + "'");
599 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
600 if (!lang || !mkws.locale_lang[lang]) {
601 mkws.config.lang = ""
603 mkws.config.lang = lang;
606 mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
608 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
609 if (mkws.pazpar2_url().match(/^\/\//)) {
610 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
611 mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
614 if (mkws.config.responsive_design_width) {
615 // Responsive web design - change layout on the fly based on
616 // current screen width. Required for mobile devices.
617 $(window).resize(resizePage);
618 // initial check after page load
619 $(document).ready(resizePage);
624 // If we've made no widgets, return without starting an SP session
625 // or marking MKWS active.
626 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
631 mkws.info("walking MKWS nodes took " + (now-then) + " ms");
632 for (var tName in mkws.teams) {
633 var myTeam = mkws.teams[tName]
635 myTeam.info("made PZ2 object");
637 myTeam.visitWidgets(function(t, w) {
638 mkws.debug(" has widget of type '" + t + "': " + w);
643 function sp_auth_url(config) {
644 if (config.service_proxy_auth) {
645 mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
646 return config.service_proxy_auth;
649 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
651 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
652 var q = config.sp_auth_query;
656 var c = config.sp_auth_credentials;
658 s += ('&username=' + c.substr(0, c.indexOf('/')) +
659 '&password=' + c.substr(c.indexOf('/')+1));
661 mkws.info("generated sp_auth_url '" + s + "'");
666 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
667 authenticateSession(sp_auth_url(mkws.config),
668 mkws.config.service_proxy_auth_domain,
670 } else if (!mkws.authenticating) {
671 // raw pp2 or we have a session already open
673 for (var teamName in mkws.teams) {
674 mkws.teams[teamName].queue("authenticated").publish();
678 mkws.isActive = true;
682 $(document).ready(function() {
683 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
688 // Set global log_level flag early so that _log() works
689 if (typeof mkws_config !== 'undefined') {
690 var tmp = mkws_config.log_level;
691 if (typeof tmp !== 'undefined') {
692 mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });