1 /*! MKWS, the MasterKey Widget Set.
2 * Copyright (C) 2013-2014 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",
49 "Records": "Datensätze",
50 "Targets": "Datenbanken",
52 "relevance": "Relevanz",
55 "oldest": "Älteste",
61 "Authors": "Forfattere",
65 "Facets": "Termlists",
66 "Next": "Næste",
68 "Search": "Søg",
69 "Sort by": "Sorter efter",
71 "per page": "per side",
72 "Displaying": "Viser",
77 "Author": "Forfatter",
78 "author": "forfatter",
82 "Location": "Lokation",
86 "relevance": "Relevans",
96 // We may be using a separate copy
97 if (typeof(mkws_jQuery) !== "undefined") {
103 // It's ridiculous that JSNLog doesn't provide this
104 mkws.stringToLevel = function(s) {
106 return JL.getTraceLevel();
107 } else if (s === 'debug') {
108 return JL.getDebugLevel();
109 } else if (s === 'info') {
110 return JL.getInfoLevel();
111 } else if (s === 'warn') {
112 return JL.getWarnLevel();
113 } else if (s === 'error') {
114 return JL.getErrorLevel();
115 } else if (s === 'fatal') {
116 return JL.getFatalLevel();
118 throw "bad log-level '" + s + "'";
122 mkws.logger = JL('mkws');
123 var consoleAppender = JL.createConsoleAppender('consoleAppender');
124 mkws.logger.setOptions({ "appenders": [consoleAppender] });
128 var argsAsARealArray = Array.prototype.slice.call(arguments);
129 var fn = argsAsARealArray.shift();
130 fn.apply(mkws.logger, argsAsARealArray);
132 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
133 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
134 mkws.info = function(x) { _log(mkws.logger.info, x) };
135 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
136 mkws.error = function(x) { _log(mkws.logger.error, x) };
137 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
140 // Translation function.
141 mkws.M = function(word) {
142 var lang = mkws.config.lang;
144 if (!lang || !mkws.locale_lang[lang])
147 return mkws.locale_lang[lang][word] || word;
151 // This function is taken from a StackOverflow answer
152 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
153 mkws.getParameterByName = function(name, url) {
154 if (!url) url = location.search;
155 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
156 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
157 results = regex.exec(url);
158 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
162 mkws.registerWidgetType = function(name, fn) {
163 if(mkws._old2new.hasOwnProperty(name)) {
164 mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
165 name = mkws._old2new[name];
168 mkws.widgetType2function[name] = fn;
169 mkws.info("registered widget-type '" + name + "'");
172 mkws.aliasWidgetType = function(newName, oldName) {
173 mkws.widgetType2function[newName] = mkws.widgetType2function[oldName];
174 mkws.info("aliased widget-type '" + newName + "' to '" + oldName + "'");
178 mkws.promotionFunction = function(name) {
179 return mkws.widgetType2function[name];
183 mkws.setMkwsConfig = function(overrides) {
184 var config_default = {
185 use_service_proxy: true,
186 pazpar2_url: undefined,
187 pp2_hostname: "sp-mkws.indexdata.com",
188 pp2_path: "service-proxy/",
189 service_proxy_auth: undefined,
190 sp_auth_path: undefined,
191 sp_auth_query: "command=auth&action=perconfig",
192 sp_auth_credentials: undefined,
194 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
195 perpage_options: [10, 20, 30, 50],
196 sort_default: "relevance",
198 show_lang: true, /* show/hide language menu */
199 show_sort: true, /* show/hide sort menu */
200 show_perpage: true, /* show/hide perpage menu */
201 show_switch: true, /* show/hide switch menu */
202 lang_options: [], /* display languages links for given languages, [] for all */
203 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
204 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
205 log_level: 1, /* log level for development: 0..2 */
206 template_vars: {}, /* values that may be exposed to templates */
211 mkws.config = mkws.objectInheritingFrom(config_default);
212 for (var k in overrides) {
213 mkws.config[k] = overrides[k];
218 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
219 // http://javascript.crockford.com/prototypal.html
220 // mkws.objectInheritingFrom behaves the same as Object.create,
221 // but since the latter is not available in IE8 we can't use it.
223 mkws.objectInheritingFrom = function(o) {
230 // The following functions are dispatchers for team methods that
231 // are called from the UI using a team-name rather than implicit
233 mkws.switchView = function(tname, view) {
234 mkws.teams[tname].switchView(view);
237 mkws.showDetails = function(tname, prefixRecId) {
238 mkws.teams[tname].showDetails(prefixRecId);
241 mkws.limitTarget = function(tname, id, name) {
242 mkws.teams[tname].limitTarget(id, name);
245 mkws.limitQuery = function(tname, field, value) {
246 mkws.teams[tname].limitQuery(field, value);
249 mkws.limitCategory = function(tname, id) {
250 mkws.teams[tname].limitCategory(id);
253 mkws.delimitTarget = function(tname, id) {
254 mkws.teams[tname].delimitTarget(id);
257 mkws.delimitQuery = function(tname, field, value) {
258 mkws.teams[tname].delimitQuery(field, value);
261 mkws.showPage = function(tname, pageNum) {
262 mkws.teams[tname].showPage(pageNum);
265 mkws.pagerPrev = function(tname) {
266 mkws.teams[tname].pagerPrev();
269 mkws.pagerNext = function(tname) {
270 mkws.teams[tname].pagerNext();
274 mkws.pazpar2_url = function() {
275 if (mkws.config.pazpar2_url) {
276 mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
277 return mkws.config.pazpar2_url;
279 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
280 mkws.info("generated pazpar2_url '" + s + "'");
286 // We put a session token in window.name, as it's the only place to
287 // keep data that is preserved across reloads and within-site
288 // navigation. pz2.js picks this up and uses it as part of the
289 // cookie-name, to ensure we get a new session when we need one.
291 // We want to use different sessions for different windows/tabs (so
292 // they don't receive each other's messages), different hosts and
293 // different paths on a host (since in general these will
294 // authenticate as different libraries). So the window name needs to
295 // include the hostname and the path from the URL, plus the token.
299 token = window.name.replace(/.*\//, '');
300 mkws.debug("Reusing existing window token '" + token + "'");
302 // Incredible that the standard JavaScript runtime doesn't define a
303 // unique windowId. Instead, we have to make one up. And since there's
304 // no global area shared between windows, the best we can do for
305 // ensuring uniqueness is generating a random ID and crossing our
308 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
309 // At one per second, it will take 116 million years to duplicate a token
310 token = Math.random().toString(36).slice(2, 12);
311 mkws.debug("Generated new window token '" + token + "'");
314 window.name = window.location.hostname + window.location.pathname + '/' + token;
315 mkws.info("Using window.name '" + window.name + "'");
318 // wrapper to provide local copy of the jQuery object.
320 var _old2new = { // Maps old-style widget names to new-style
321 'Authname': 'auth-name',
322 'ConsoleBuilder': 'console-builder',
323 'Coverart': 'cover-art',
324 'GoogleImage': 'google-image',
326 'MOTDContainer': 'motd-container',
327 'Perpage': 'per-page',
328 'SearchForm': 'search-form',
329 'ReferenceUniverse': 'reference-universe',
330 'Termlists': 'facets'
332 // Annoyingly, there is no built-in way to invert a hash
334 for (var key in _old2new) {
335 if(_old2new.hasOwnProperty(key)) {
336 _new2old[_old2new[key]] = key;
340 mkws._old2new = _old2new;
342 function handleNodeWithTeam(node, callback) {
343 // First branch for DOM objects; second branch for jQuery objects
344 var classes = node.className || node.attr('class');
346 // For some reason, if we try to proceed when classes is
347 // undefined, we don't get an error message, but this
348 // function and its callers, up several stack level,
349 // silently return. What a crock.
350 mkws.fatal("handleNodeWithTeam() called on node with no classes");
353 var list = classes.split(/\s+/)
356 for (var i = 0; i < list.length; i++) {
358 if (cname.match(/^mkws-team-/)) {
359 // New-style teamnames of the form mkws-team-xyz
360 teamName = cname.replace(/^mkws-team-/, '');
361 } else if (cname.match(/^mkwsTeam_/)) {
362 // Old-style teamnames of the form mkwsTeam_xyz
363 teamName = cname.replace(/^mkwsTeam_/, '');
364 } else if (cname.match(/^mkws-/)) {
365 // New-style names of the from mkws-foo-bar
366 type = cname.replace(/^mkws-/, '');
367 } else if (cname.match(/^mkws/)) {
368 // Old-style names of the form mkwsFooBar
369 var tmp = cname.replace(/^mkws/, '');
370 type = _old2new[tmp] || tmp.toLowerCase();
374 // Widgets without a team are on team "AUTO"
377 // Autosearch widgets don't join team AUTO if there is already an
378 // autosearch on the team or the team has otherwise gotten a query
379 if (node.getAttribute("autosearch")) {
380 if (mkws.autoHasAuto ||
381 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
382 mkws.warn("AUTO team already has a query, using unique team");
385 mkws.autoHasAuto = true;
389 // Widgets on team "UNIQUE" get a random team
390 if (teamName === "UNIQUE") {
391 teamName = Math.floor(Math.random() * 100000000).toString();
394 callback.call(node, teamName, type);
398 function resizePage() {
399 var threshhold = mkws.config.responsive_design_width;
400 var width = $(window).width();
401 var from, to, method;
403 if ((mkws.width === undefined || mkws.width > threshhold) &&
404 width <= threshhold) {
405 from = "wide"; to = "narrow"; method = "hide";
406 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
407 width > threshhold) {
408 from = "narrow"; to = "wide"; method = "show";
413 mkws.info("changing from " + from + " to " + to + ": " + width);
414 for (var tname in mkws.teams) {
415 var team = mkws.teams[tname];
416 team.visitWidgets(function(t, w) {
417 var w1 = team.widget(t + "-container-" + from);
418 var w2 = team.widget(t + "-container-" + to);
424 w.node.appendTo(w2.node);
427 team.queue("resize-" + to).publish();
434 * Run service-proxy authentication in background (after page load).
435 * The username/password is configured in the apache config file
438 function authenticateSession(auth_url, auth_domain, pp2_url) {
439 mkws.authenticating = true;
440 mkws.info("service proxy authentication on URL: " + auth_url);
443 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
444 mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
447 var request = new pzHttpRequest(auth_url, function(err) {
448 alert("HTTP call for authentication failed: " + err)
452 request.get(null, function(data) {
453 mkws.authenticating = false;
454 if (!$.isXMLDoc(data)) {
455 alert("Service Proxy authentication response is not a valid XML document");
458 var status = $(data).find("status");
459 if (status.text() != "OK") {
460 var message = $(data).find("message");
461 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
465 mkws.info("service proxy authentication successful");
466 mkws.authenticated = true;
467 var authName = $(data).find("displayName").text();
468 // You'd think there would be a better way to do this:
469 var realm = $(data).find("realm:not(realmAttributes realm)").text();
470 for (var teamName in mkws.teams) {
471 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
479 function runAutoSearches() {
480 mkws.info("running auto searches");
482 for (var teamName in mkws.teams) {
483 mkws.teams[teamName].queue("ready").publish();
488 function selectorForAllWidgets() {
489 if (mkws.config && mkws.config.scan_all_nodes) {
490 // This is the old version, which works by telling jQuery to
491 // find every node that has a class beginning with "mkws". In
492 // theory it should be slower than the class-based selector; but
493 // instrumentation suprisingly shows this is consistently
494 // faster. It also has the advantage that any widgets of
495 // non-registered types are logged as warnings rather than
497 return '[class^="mkws"],[class*=" mkws"]';
499 // This is the new version, which works by looking up the
500 // specific classes of all registered widget types and their
501 // resize containers. Because all it requires jQuery to do is
502 // some hash lookups in pre-built tables, it should be very
503 // fast; but it silently ignores widgets of unregistered types.
505 for (var type in mkws.widgetType2function) {
507 s += '.mkws-' + type;
508 s += ',.mkws-' + type + "-container-wide";
509 s += ',.mkws-' + type + "-container-narrow";
510 // Annoyingly, we also need to recognise old-style names
511 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
512 s += ',.mkws' + oldtype;
513 s += ',.mkws' + oldtype + "-Container-wide";
514 s += ',.mkws' + oldtype + "-Container-narrow";
521 function makeWidgetsWithin(level, node) {
522 if (node) var widgetNodes = node.find(selectorForAllWidgets());
523 else widgetNodes = $(selectorForAllWidgets());
524 // Return false if we parse no widgets
525 if (widgetNodes.length < 1) return false;
526 widgetNodes.each(function() {
527 handleNodeWithTeam(this, function(tname, type) {
528 var myTeam = mkws.teams[tname];
530 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
533 var oldHTML = this.innerHTML;
534 var myWidget = mkws.makeWidget($, myTeam, type, this);
535 myTeam.addWidget(myWidget);
536 var newHTML = this.innerHTML;
537 if (newHTML !== oldHTML) {
538 myTeam.info("widget " + type + " HTML changed: reparsing");
539 makeWidgetsWithin(level+1, $(this));
547 // The second "rootsel" parameter is passed to jQuery and is a DOM node
548 // or a selector string you would like to constrain the search for widgets to.
550 // This function has no side effects if run again on an operating session,
551 // even if the element/selector passed causes existing widgets to be reparsed:
553 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
554 // widgets, MKWS-261)
556 // * configuration is not regenerated
557 // * authentication is not performed again
558 // * autosearches are not re-run
559 mkws.init = function(message, rootsel) {
560 var greet = "MKWS initialised";
561 if (rootsel) greet += " (limited to " + rootsel + ")"
562 if (message) greet += " :: " + message;
565 // MKWS is not active until init() has been run against an object with widget nodes.
566 // We only set initial configuration when MKWS is first activated.
567 if (!mkws.isActive) {
568 var widgetSelector = selectorForAllWidgets();
569 if ($(widgetSelector).length < 1) {
570 mkws.warn("no widgets found");
574 // Initial configuration
575 mkws.autoHasAuto = false;
577 if (typeof mkws_config === 'undefined') {
578 mkws.info("setting empty config");
581 mkws.info("using config: " + $.toJSON(mkws_config));
582 saved_config = mkws_config;
584 mkws.setMkwsConfig(saved_config);
586 for (var key in mkws.config) {
587 if (mkws.config.hasOwnProperty(key)) {
588 if (key.match(/^language_/)) {
589 var lang = key.replace(/^language_/, "");
590 // Copy custom languages into list
591 mkws.locale_lang[lang] = mkws.config[key];
592 mkws.info("added locally configured language '" + lang + "'");
597 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
598 if (!lang || !mkws.locale_lang[lang]) {
599 mkws.config.lang = ""
601 mkws.config.lang = lang;
604 mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
606 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
607 if (mkws.pazpar2_url().match(/^\/\//)) {
608 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
609 mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
612 if (mkws.config.responsive_design_width) {
613 // Responsive web design - change layout on the fly based on
614 // current screen width. Required for mobile devices.
615 $(window).resize(resizePage);
616 // initial check after page load
617 $(document).ready(resizePage);
622 // If we've made no widgets, return without starting an SP session
623 // or marking MKWS active.
624 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
629 mkws.info("walking MKWS nodes took " + (now-then) + " ms");
630 for (var tName in mkws.teams) {
631 var myTeam = mkws.teams[tName]
633 myTeam.info("made PZ2 object");
635 myTeam.visitWidgets(function(t, w) {
636 mkws.debug(" has widget of type '" + t + "': " + w);
641 function sp_auth_url(config) {
642 if (config.service_proxy_auth) {
643 mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
644 return config.service_proxy_auth;
647 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
649 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
650 var q = config.sp_auth_query;
654 var c = config.sp_auth_credentials;
656 s += ('&username=' + c.substr(0, c.indexOf('/')) +
657 '&password=' + c.substr(c.indexOf('/')+1));
659 mkws.info("generated sp_auth_url '" + s + "'");
664 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
665 authenticateSession(sp_auth_url(mkws.config),
666 mkws.config.service_proxy_auth_domain,
668 } else if (!mkws.authenticating) {
669 // raw pp2 or we have a session already open
671 for (var teamName in mkws.teams) {
672 mkws.teams[teamName].queue("authenticated").publish();
676 mkws.isActive = true;
680 $(document).ready(function() {
681 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
686 // Set global log_level flag early so that _log() works
687 if (typeof mkws_config !== 'undefined') {
688 var tmp = mkws_config.log_level;
689 if (typeof tmp !== 'undefined') {
690 mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });