1 /*! MKWS, the MasterKey Widget Set.
2 * Copyright (C) 2013-2014 Index Data
3 * See the file LICENSE for details
6 "use strict"; // HTML5: disable for log_level >= 2
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,
20 log_level: 1, // Will be overridden from mkws.config, but
21 // initial value allows jQuery popup to use logging.
23 widgetType2function: {},
29 "Subjects": "Schlagwörter",
30 "Sources": "Daten und Quellen",
31 "source": "datenquelle",
32 "Facets": "Termlisten",
34 "Prev": "Zurück",
36 "Sort by": "Sortieren nach",
37 "and show": "und zeige",
38 "per page": "pro Seite",
39 "Displaying": "Zeige",
47 "Subject": "Schlagwort",
48 "subject": "schlagwort",
50 "Records": "Datensätze",
51 "Targets": "Datenbanken",
57 "Authors": "Forfattere",
61 "Facets": "Termlists",
62 "Next": "Næste",
64 "Search": "Søg",
65 "Sort by": "Sorter efter",
67 "per page": "per side",
68 "Displaying": "Viser",
73 "Author": "Forfatter",
74 "author": "forfatter",
78 "Location": "Lokation",
87 // We may be using a separate copy
88 if (typeof(mkws_jQuery) !== "undefined") {
94 mkws.logger = JL('mkws');
95 var consoleAppender = JL.createConsoleAppender('consoleAppender');
96 mkws.logger.setOptions({ "appenders": [consoleAppender]} );
99 function _log(fn, string) {
103 // you need to disable use strict at the top of the file!!!
104 if (mkws.log_level >= 3) {
105 // Works in Chrome; not sure about elsewhere
107 } else if (mkws.log_level >= 2) {
110 fn.call(mkws.logger, string);
114 // ### transitional placeholder function until we have promoted all invocations
115 mkws.log = function(x) { _log(mkws.logger.debug, "LEGACY LOG: " + x) };
117 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
118 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
119 mkws.info = function(x) { _log(mkws.logger.info, x) };
120 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
121 mkws.error = function(x) { _log(mkws.logger.error, x) };
122 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
125 // Translation function.
126 mkws.M = function(word) {
127 var lang = mkws.config.lang;
129 if (!lang || !mkws.locale_lang[lang])
132 return mkws.locale_lang[lang][word] || word;
136 // This function is taken from a StackOverflow answer
137 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
138 mkws.getParameterByName = function(name, url) {
139 if (!url) url = location.search;
140 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
141 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
142 results = regex.exec(url);
143 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
147 mkws.registerWidgetType = function(name, fn) {
148 if(mkws._old2new.hasOwnProperty(name)) {
149 mkws.warn("Warning: registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
150 name = mkws._old2new[name];
153 mkws.widgetType2function[name] = fn;
154 mkws.info("registered widget-type '" + name + "'");
157 mkws.promotionFunction = function(name) {
158 return mkws.widgetType2function[name];
162 mkws.setMkwsConfig = function(overrides) {
163 // Set global log_level flag early so that _log() works
164 var tmp = overrides.log_level;
165 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
167 var config_default = {
168 use_service_proxy: true,
169 pazpar2_url: undefined,
170 pp2_hostname: "sp-mkws.indexdata.com",
171 pp2_path: "service-proxy/",
172 service_proxy_auth: undefined,
173 sp_auth_path: undefined,
174 sp_auth_query: "command=auth&action=perconfig",
175 sp_auth_credentials: undefined,
177 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
178 perpage_options: [10, 20, 30, 50],
179 sort_default: "relevance",
181 show_lang: true, /* show/hide language menu */
182 show_sort: true, /* show/hide sort menu */
183 show_perpage: true, /* show/hide perpage menu */
184 show_switch: true, /* show/hide switch menu */
185 lang_options: [], /* display languages links for given languages, [] for all */
186 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
187 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
188 log_level: 1, /* log level for development: 0..2 */
189 template_vars: {}, /* values that may be exposed to templates */
194 mkws.config = mkws.objectInheritingFrom(config_default);
195 for (var k in overrides) {
196 mkws.config[k] = overrides[k];
201 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
202 // http://javascript.crockford.com/prototypal.html
203 // mkws.objectInheritingFrom behaves the same as Object.create,
204 // but since the latter is not available in IE8 we can't use it.
206 mkws.objectInheritingFrom = function(o) {
213 // The following functions are dispatchers for team methods that
214 // are called from the UI using a team-name rather than implicit
216 mkws.switchView = function(tname, view) {
217 mkws.teams[tname].switchView(view);
220 mkws.showDetails = function(tname, prefixRecId) {
221 mkws.teams[tname].showDetails(prefixRecId);
224 mkws.limitTarget = function(tname, id, name) {
225 mkws.teams[tname].limitTarget(id, name);
228 mkws.limitQuery = function(tname, field, value) {
229 mkws.teams[tname].limitQuery(field, value);
232 mkws.limitCategory = function(tname, id) {
233 mkws.teams[tname].limitCategory(id);
236 mkws.delimitTarget = function(tname, id) {
237 mkws.teams[tname].delimitTarget(id);
240 mkws.delimitQuery = function(tname, field, value) {
241 mkws.teams[tname].delimitQuery(field, value);
244 mkws.showPage = function(tname, pageNum) {
245 mkws.teams[tname].showPage(pageNum);
248 mkws.pagerPrev = function(tname) {
249 mkws.teams[tname].pagerPrev();
252 mkws.pagerNext = function(tname) {
253 mkws.teams[tname].pagerNext();
257 mkws.pazpar2_url = function() {
258 if (mkws.config.pazpar2_url) {
259 mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
260 return mkws.config.pazpar2_url;
262 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
263 mkws.info("generated pazpar2_url '" + s + "'");
269 // We put a session token in window.name, as it's the only place to
270 // keep data that is preserved across reloads and within-site
271 // navigation. pz2.js picks this up and uses it as part of the
272 // cookie-name, to ensure we get a new session when we need one.
274 // We want to use different sessions for different windows/tabs (so
275 // they don't receive each other's messages), different hosts and
276 // different paths on a host (since in general these will
277 // authenticate as different libraries). So the window name needs to
278 // include the hostname and the path from the URL, plus the token.
282 token = window.name.replace(/.*\//, '');
283 mkws.debug("Reusing existing window token '" + token + "'");
285 // Incredible that the standard JavaScript runtime doesn't define a
286 // unique windowId. Instead, we have to make one up. And since there's
287 // no global area shared between windows, the best we can do for
288 // ensuring uniqueness is generating a random ID and crossing our
291 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
292 // At one per second, it will take 116 million years to duplicate a token
293 token = Math.random().toString(36).slice(2, 12);
294 mkws.debug("Generated new window token '" + token + "'");
297 window.name = window.location.hostname + window.location.pathname + '/' + token;
298 mkws.info("Using window.name '" + window.name + "'");
301 // wrapper to provide local copy of the jQuery object.
303 var _old2new = { // Maps old-style widget names to new-style
304 'Authname': 'auth-name',
305 'ConsoleBuilder': 'console-builder',
306 'Coverart': 'cover-art',
307 'GoogleImage': 'google-image',
309 'MOTDContainer': 'motd-container',
310 'Perpage': 'per-page',
311 'SearchForm': 'search-form',
312 'ReferenceUniverse': 'reference-universe',
313 'Termlists': 'facets'
315 // Annoyingly, there is no built-in way to invert a hash
317 for (var key in _old2new) {
318 if(_old2new.hasOwnProperty(key)) {
319 _new2old[_old2new[key]] = key;
323 mkws._old2new = _old2new;
325 function handleNodeWithTeam(node, callback) {
326 // First branch for DOM objects; second branch for jQuery objects
327 var classes = node.className || node.attr('class');
329 // For some reason, if we try to proceed when classes is
330 // undefined, we don't get an error message, but this
331 // function and its callers, up several stack level,
332 // silently return. What a crock.
333 mkws.fatal("handleNodeWithTeam() called on node with no classes");
336 var list = classes.split(/\s+/)
339 for (var i = 0; i < list.length; i++) {
341 if (cname.match(/^mkws-team-/)) {
342 // New-style teamnames of the form mkws-team-xyz
343 teamName = cname.replace(/^mkws-team-/, '');
344 } else if (cname.match(/^mkwsTeam_/)) {
345 // Old-style teamnames of the form mkwsTeam_xyz
346 teamName = cname.replace(/^mkwsTeam_/, '');
347 } else if (cname.match(/^mkws-/)) {
348 // New-style names of the from mkws-foo-bar
349 type = cname.replace(/^mkws-/, '');
350 } else if (cname.match(/^mkws/)) {
351 // Old-style names of the form mkwsFooBar
352 var tmp = cname.replace(/^mkws/, '');
353 type = _old2new[tmp] || tmp.toLowerCase();
357 // Widgets without a team are on team "AUTO"
360 // Autosearch widgets don't join team AUTO if there is already an
361 // autosearch on the team or the team has otherwise gotten a query
362 if (node.getAttribute("autosearch")) {
363 if (mkws.autoHasAuto ||
364 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
365 mkws.warn("AUTO team already has a query, using unique team");
368 mkws.autoHasAuto = true;
372 // Widgets on team "UNIQUE" get a random team
373 if (teamName === "UNIQUE") {
374 teamName = Math.floor(Math.random() * 100000000).toString();
377 callback.call(node, teamName, type);
381 function resizePage() {
382 var threshhold = mkws.config.responsive_design_width;
383 var width = $(window).width();
384 var from, to, method;
386 if ((mkws.width === undefined || mkws.width > threshhold) &&
387 width <= threshhold) {
388 from = "wide"; to = "narrow"; method = "hide";
389 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
390 width > threshhold) {
391 from = "narrow"; to = "wide"; method = "show";
396 mkws.info("changing from " + from + " to " + to + ": " + width);
397 for (var tname in mkws.teams) {
398 var team = mkws.teams[tname];
399 team.visitWidgets(function(t, w) {
400 var w1 = team.widget(t + "-container-" + from);
401 var w2 = team.widget(t + "-container-" + to);
407 w.node.appendTo(w2.node);
410 team.queue("resize-" + to).publish();
417 * Run service-proxy authentication in background (after page load).
418 * The username/password is configured in the apache config file
421 function authenticateSession(auth_url, auth_domain, pp2_url) {
422 mkws.authenticating = true;
423 mkws.info("service proxy authentication on URL: " + auth_url);
426 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
427 mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
430 var request = new pzHttpRequest(auth_url, function(err) {
431 alert("HTTP call for authentication failed: " + err)
435 request.get(null, function(data) {
436 mkws.authenticating = false;
437 if (!$.isXMLDoc(data)) {
438 alert("Service Proxy authentication response is not a valid XML document");
441 var status = $(data).find("status");
442 if (status.text() != "OK") {
443 var message = $(data).find("message");
444 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
448 mkws.info("service proxy authentication successful");
449 mkws.authenticated = true;
450 var authName = $(data).find("displayName").text();
451 // You'd think there would be a better way to do this:
452 var realm = $(data).find("realm:not(realmAttributes realm)").text();
453 for (var teamName in mkws.teams) {
454 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
462 function runAutoSearches() {
463 mkws.info("running auto searches");
465 for (var teamName in mkws.teams) {
466 mkws.teams[teamName].queue("ready").publish();
471 function selectorForAllWidgets() {
472 if (mkws.config && mkws.config.scan_all_nodes) {
473 // This is the old version, which works by telling jQuery to
474 // find every node that has a class beginning with "mkws". In
475 // theory it should be slower than the class-based selector; but
476 // instrumentation suprisingly shows this is consistently
477 // faster. It also has the advantage that any widgets of
478 // non-registered types are logged as warnings rather than
480 return '[class^="mkws"],[class*=" mkws"]';
482 // This is the new version, which works by looking up the
483 // specific classes of all registered widget types and their
484 // resize containers. Because all it requires jQuery to do is
485 // some hash lookups in pre-built tables, it should be very
486 // fast; but it silently ignores widgets of unregistered types.
488 for (var type in mkws.widgetType2function) {
490 s += '.mkws-' + type;
491 s += ',.mkws-' + type + "-container-wide";
492 s += ',.mkws-' + type + "-container-narrow";
493 // Annoyingly, we also need to recognise old-style names
494 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
495 s += ',.mkws' + oldtype;
496 s += ',.mkws' + oldtype + "-Container-wide";
497 s += ',.mkws' + oldtype + "-Container-narrow";
504 function makeWidgetsWithin(level, node) {
505 if (node) var widgetNodes = node.find(selectorForAllWidgets());
506 else widgetNodes = $(selectorForAllWidgets());
507 // Return false if we parse no widgets
508 if (widgetNodes.length < 1) return false;
509 widgetNodes.each(function() {
510 handleNodeWithTeam(this, function(tname, type) {
511 var myTeam = mkws.teams[tname];
513 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
516 var oldHTML = this.innerHTML;
517 var myWidget = mkws.makeWidget($, myTeam, type, this);
518 myTeam.addWidget(myWidget);
519 var newHTML = this.innerHTML;
520 if (newHTML !== oldHTML) {
521 myTeam.log("widget " + type + " HTML changed: reparsing");
522 makeWidgetsWithin(level+1, $(this));
530 // The second "rootsel" parameter is passed to jQuery and is a DOM node
531 // or a selector string you would like to constrain the search for widgets to.
533 // This function has no side effects if run again on an operating session,
534 // even if the element/selector passed causes existing widgets to be reparsed:
536 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
537 // widgets, MKWS-261)
539 // * configuration is not regenerated
540 // * authentication is not performed again
541 // * autosearches are not re-run
542 mkws.init = function(message, rootsel) {
543 var greet = "MKWS initialised";
544 if (rootsel) greet += " (limited to " + rootsel + ")"
545 if (message) greet += " :: " + message;
548 // MKWS is not active until init() has been run against an object with widget nodes.
549 // We only set initial configuration when MKWS is first activated.
550 if (!mkws.isActive) {
551 var widgetSelector = selectorForAllWidgets();
552 if ($(widgetSelector).length < 1) {
553 mkws.warn("no widgets found");
557 // Initial configuration
558 mkws.autoHasAuto = false;
560 if (typeof mkws_config === 'undefined') {
561 mkws.info("setting empty config");
564 mkws.info("using config: " + $.toJSON(mkws_config));
565 saved_config = mkws_config;
567 mkws.setMkwsConfig(saved_config);
569 for (var key in mkws.config) {
570 if (mkws.config.hasOwnProperty(key)) {
571 if (key.match(/^language_/)) {
572 var lang = key.replace(/^language_/, "");
573 // Copy custom languages into list
574 mkws.locale_lang[lang] = mkws.config[key];
575 mkws.info("added locally configured language '" + lang + "'");
580 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
581 if (!lang || !mkws.locale_lang[lang]) {
582 mkws.config.lang = ""
584 mkws.config.lang = lang;
587 mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
589 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
590 if (mkws.pazpar2_url().match(/^\/\//)) {
591 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
592 mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
595 if (mkws.config.responsive_design_width) {
596 // Responsive web design - change layout on the fly based on
597 // current screen width. Required for mobile devices.
598 $(window).resize(resizePage);
599 // initial check after page load
600 $(document).ready(resizePage);
605 // If we've made no widgets, return without starting an SP session
606 // or marking MKWS active.
607 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
612 mkws.info("walking MKWS nodes took " + (now-then) + " ms");
613 for (var tName in mkws.teams) {
614 var myTeam = mkws.teams[tName]
616 myTeam.log("made PZ2 object");
618 myTeam.visitWidgets(function(t, w) {
619 mkws.debug(" has widget of type '" + t + "': " + w);
624 function sp_auth_url(config) {
625 if (config.service_proxy_auth) {
626 mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
627 return config.service_proxy_auth;
630 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
632 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
633 var q = config.sp_auth_query;
637 var c = config.sp_auth_credentials;
639 s += ('&username=' + c.substr(0, c.indexOf('/')) +
640 '&password=' + c.substr(c.indexOf('/')+1));
642 mkws.info("generated sp_auth_url '" + s + "'");
647 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
648 authenticateSession(sp_auth_url(mkws.config),
649 mkws.config.service_proxy_auth_domain,
651 } else if (!mkws.authenticating) {
652 // raw pp2 or we have a session already open
656 mkws.isActive = true;
660 $(document).ready(function() {
661 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {