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 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
115 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
116 mkws.info = function(x) { _log(mkws.logger.info, x) };
117 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
118 mkws.error = function(x) { _log(mkws.logger.error, x) };
119 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
122 // Translation function.
123 mkws.M = function(word) {
124 var lang = mkws.config.lang;
126 if (!lang || !mkws.locale_lang[lang])
129 return mkws.locale_lang[lang][word] || word;
133 // This function is taken from a StackOverflow answer
134 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
135 mkws.getParameterByName = function(name, url) {
136 if (!url) url = location.search;
137 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
138 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
139 results = regex.exec(url);
140 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
144 mkws.registerWidgetType = function(name, fn) {
145 if(mkws._old2new.hasOwnProperty(name)) {
146 mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
147 name = mkws._old2new[name];
150 mkws.widgetType2function[name] = fn;
151 mkws.info("registered widget-type '" + name + "'");
154 mkws.promotionFunction = function(name) {
155 return mkws.widgetType2function[name];
159 mkws.setMkwsConfig = function(overrides) {
160 // Set global log_level flag early so that _log() works
161 var tmp = overrides.log_level;
162 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
164 var config_default = {
165 use_service_proxy: true,
166 pazpar2_url: undefined,
167 pp2_hostname: "sp-mkws.indexdata.com",
168 pp2_path: "service-proxy/",
169 service_proxy_auth: undefined,
170 sp_auth_path: undefined,
171 sp_auth_query: "command=auth&action=perconfig",
172 sp_auth_credentials: undefined,
174 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
175 perpage_options: [10, 20, 30, 50],
176 sort_default: "relevance",
178 show_lang: true, /* show/hide language menu */
179 show_sort: true, /* show/hide sort menu */
180 show_perpage: true, /* show/hide perpage menu */
181 show_switch: true, /* show/hide switch menu */
182 lang_options: [], /* display languages links for given languages, [] for all */
183 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
184 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
185 log_level: 1, /* log level for development: 0..2 */
186 template_vars: {}, /* values that may be exposed to templates */
191 mkws.config = mkws.objectInheritingFrom(config_default);
192 for (var k in overrides) {
193 mkws.config[k] = overrides[k];
198 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
199 // http://javascript.crockford.com/prototypal.html
200 // mkws.objectInheritingFrom behaves the same as Object.create,
201 // but since the latter is not available in IE8 we can't use it.
203 mkws.objectInheritingFrom = function(o) {
210 // The following functions are dispatchers for team methods that
211 // are called from the UI using a team-name rather than implicit
213 mkws.switchView = function(tname, view) {
214 mkws.teams[tname].switchView(view);
217 mkws.showDetails = function(tname, prefixRecId) {
218 mkws.teams[tname].showDetails(prefixRecId);
221 mkws.limitTarget = function(tname, id, name) {
222 mkws.teams[tname].limitTarget(id, name);
225 mkws.limitQuery = function(tname, field, value) {
226 mkws.teams[tname].limitQuery(field, value);
229 mkws.limitCategory = function(tname, id) {
230 mkws.teams[tname].limitCategory(id);
233 mkws.delimitTarget = function(tname, id) {
234 mkws.teams[tname].delimitTarget(id);
237 mkws.delimitQuery = function(tname, field, value) {
238 mkws.teams[tname].delimitQuery(field, value);
241 mkws.showPage = function(tname, pageNum) {
242 mkws.teams[tname].showPage(pageNum);
245 mkws.pagerPrev = function(tname) {
246 mkws.teams[tname].pagerPrev();
249 mkws.pagerNext = function(tname) {
250 mkws.teams[tname].pagerNext();
254 mkws.pazpar2_url = function() {
255 if (mkws.config.pazpar2_url) {
256 mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
257 return mkws.config.pazpar2_url;
259 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
260 mkws.info("generated pazpar2_url '" + s + "'");
266 // We put a session token in window.name, as it's the only place to
267 // keep data that is preserved across reloads and within-site
268 // navigation. pz2.js picks this up and uses it as part of the
269 // cookie-name, to ensure we get a new session when we need one.
271 // We want to use different sessions for different windows/tabs (so
272 // they don't receive each other's messages), different hosts and
273 // different paths on a host (since in general these will
274 // authenticate as different libraries). So the window name needs to
275 // include the hostname and the path from the URL, plus the token.
279 token = window.name.replace(/.*\//, '');
280 mkws.debug("Reusing existing window token '" + token + "'");
282 // Incredible that the standard JavaScript runtime doesn't define a
283 // unique windowId. Instead, we have to make one up. And since there's
284 // no global area shared between windows, the best we can do for
285 // ensuring uniqueness is generating a random ID and crossing our
288 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
289 // At one per second, it will take 116 million years to duplicate a token
290 token = Math.random().toString(36).slice(2, 12);
291 mkws.debug("Generated new window token '" + token + "'");
294 window.name = window.location.hostname + window.location.pathname + '/' + token;
295 mkws.info("Using window.name '" + window.name + "'");
298 // wrapper to provide local copy of the jQuery object.
300 var _old2new = { // Maps old-style widget names to new-style
301 'Authname': 'auth-name',
302 'ConsoleBuilder': 'console-builder',
303 'Coverart': 'cover-art',
304 'GoogleImage': 'google-image',
306 'MOTDContainer': 'motd-container',
307 'Perpage': 'per-page',
308 'SearchForm': 'search-form',
309 'ReferenceUniverse': 'reference-universe',
310 'Termlists': 'facets'
312 // Annoyingly, there is no built-in way to invert a hash
314 for (var key in _old2new) {
315 if(_old2new.hasOwnProperty(key)) {
316 _new2old[_old2new[key]] = key;
320 mkws._old2new = _old2new;
322 function handleNodeWithTeam(node, callback) {
323 // First branch for DOM objects; second branch for jQuery objects
324 var classes = node.className || node.attr('class');
326 // For some reason, if we try to proceed when classes is
327 // undefined, we don't get an error message, but this
328 // function and its callers, up several stack level,
329 // silently return. What a crock.
330 mkws.fatal("handleNodeWithTeam() called on node with no classes");
333 var list = classes.split(/\s+/)
336 for (var i = 0; i < list.length; i++) {
338 if (cname.match(/^mkws-team-/)) {
339 // New-style teamnames of the form mkws-team-xyz
340 teamName = cname.replace(/^mkws-team-/, '');
341 } else if (cname.match(/^mkwsTeam_/)) {
342 // Old-style teamnames of the form mkwsTeam_xyz
343 teamName = cname.replace(/^mkwsTeam_/, '');
344 } else if (cname.match(/^mkws-/)) {
345 // New-style names of the from mkws-foo-bar
346 type = cname.replace(/^mkws-/, '');
347 } else if (cname.match(/^mkws/)) {
348 // Old-style names of the form mkwsFooBar
349 var tmp = cname.replace(/^mkws/, '');
350 type = _old2new[tmp] || tmp.toLowerCase();
354 // Widgets without a team are on team "AUTO"
357 // Autosearch widgets don't join team AUTO if there is already an
358 // autosearch on the team or the team has otherwise gotten a query
359 if (node.getAttribute("autosearch")) {
360 if (mkws.autoHasAuto ||
361 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
362 mkws.warn("AUTO team already has a query, using unique team");
365 mkws.autoHasAuto = true;
369 // Widgets on team "UNIQUE" get a random team
370 if (teamName === "UNIQUE") {
371 teamName = Math.floor(Math.random() * 100000000).toString();
374 callback.call(node, teamName, type);
378 function resizePage() {
379 var threshhold = mkws.config.responsive_design_width;
380 var width = $(window).width();
381 var from, to, method;
383 if ((mkws.width === undefined || mkws.width > threshhold) &&
384 width <= threshhold) {
385 from = "wide"; to = "narrow"; method = "hide";
386 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
387 width > threshhold) {
388 from = "narrow"; to = "wide"; method = "show";
393 mkws.info("changing from " + from + " to " + to + ": " + width);
394 for (var tname in mkws.teams) {
395 var team = mkws.teams[tname];
396 team.visitWidgets(function(t, w) {
397 var w1 = team.widget(t + "-container-" + from);
398 var w2 = team.widget(t + "-container-" + to);
404 w.node.appendTo(w2.node);
407 team.queue("resize-" + to).publish();
414 * Run service-proxy authentication in background (after page load).
415 * The username/password is configured in the apache config file
418 function authenticateSession(auth_url, auth_domain, pp2_url) {
419 mkws.authenticating = true;
420 mkws.info("service proxy authentication on URL: " + auth_url);
423 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
424 mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
427 var request = new pzHttpRequest(auth_url, function(err) {
428 alert("HTTP call for authentication failed: " + err)
432 request.get(null, function(data) {
433 mkws.authenticating = false;
434 if (!$.isXMLDoc(data)) {
435 alert("Service Proxy authentication response is not a valid XML document");
438 var status = $(data).find("status");
439 if (status.text() != "OK") {
440 var message = $(data).find("message");
441 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
445 mkws.info("service proxy authentication successful");
446 mkws.authenticated = true;
447 var authName = $(data).find("displayName").text();
448 // You'd think there would be a better way to do this:
449 var realm = $(data).find("realm:not(realmAttributes realm)").text();
450 for (var teamName in mkws.teams) {
451 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
459 function runAutoSearches() {
460 mkws.info("running auto searches");
462 for (var teamName in mkws.teams) {
463 mkws.teams[teamName].queue("ready").publish();
468 function selectorForAllWidgets() {
469 if (mkws.config && mkws.config.scan_all_nodes) {
470 // This is the old version, which works by telling jQuery to
471 // find every node that has a class beginning with "mkws". In
472 // theory it should be slower than the class-based selector; but
473 // instrumentation suprisingly shows this is consistently
474 // faster. It also has the advantage that any widgets of
475 // non-registered types are logged as warnings rather than
477 return '[class^="mkws"],[class*=" mkws"]';
479 // This is the new version, which works by looking up the
480 // specific classes of all registered widget types and their
481 // resize containers. Because all it requires jQuery to do is
482 // some hash lookups in pre-built tables, it should be very
483 // fast; but it silently ignores widgets of unregistered types.
485 for (var type in mkws.widgetType2function) {
487 s += '.mkws-' + type;
488 s += ',.mkws-' + type + "-container-wide";
489 s += ',.mkws-' + type + "-container-narrow";
490 // Annoyingly, we also need to recognise old-style names
491 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
492 s += ',.mkws' + oldtype;
493 s += ',.mkws' + oldtype + "-Container-wide";
494 s += ',.mkws' + oldtype + "-Container-narrow";
501 function makeWidgetsWithin(level, node) {
502 if (node) var widgetNodes = node.find(selectorForAllWidgets());
503 else widgetNodes = $(selectorForAllWidgets());
504 // Return false if we parse no widgets
505 if (widgetNodes.length < 1) return false;
506 widgetNodes.each(function() {
507 handleNodeWithTeam(this, function(tname, type) {
508 var myTeam = mkws.teams[tname];
510 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
513 var oldHTML = this.innerHTML;
514 var myWidget = mkws.makeWidget($, myTeam, type, this);
515 myTeam.addWidget(myWidget);
516 var newHTML = this.innerHTML;
517 if (newHTML !== oldHTML) {
518 myTeam.info("widget " + type + " HTML changed: reparsing");
519 makeWidgetsWithin(level+1, $(this));
527 // The second "rootsel" parameter is passed to jQuery and is a DOM node
528 // or a selector string you would like to constrain the search for widgets to.
530 // This function has no side effects if run again on an operating session,
531 // even if the element/selector passed causes existing widgets to be reparsed:
533 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
534 // widgets, MKWS-261)
536 // * configuration is not regenerated
537 // * authentication is not performed again
538 // * autosearches are not re-run
539 mkws.init = function(message, rootsel) {
540 var greet = "MKWS initialised";
541 if (rootsel) greet += " (limited to " + rootsel + ")"
542 if (message) greet += " :: " + message;
545 // MKWS is not active until init() has been run against an object with widget nodes.
546 // We only set initial configuration when MKWS is first activated.
547 if (!mkws.isActive) {
548 var widgetSelector = selectorForAllWidgets();
549 if ($(widgetSelector).length < 1) {
550 mkws.warn("no widgets found");
554 // Initial configuration
555 mkws.autoHasAuto = false;
557 if (typeof mkws_config === 'undefined') {
558 mkws.info("setting empty config");
561 mkws.info("using config: " + $.toJSON(mkws_config));
562 saved_config = mkws_config;
564 mkws.setMkwsConfig(saved_config);
566 for (var key in mkws.config) {
567 if (mkws.config.hasOwnProperty(key)) {
568 if (key.match(/^language_/)) {
569 var lang = key.replace(/^language_/, "");
570 // Copy custom languages into list
571 mkws.locale_lang[lang] = mkws.config[key];
572 mkws.info("added locally configured language '" + lang + "'");
577 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
578 if (!lang || !mkws.locale_lang[lang]) {
579 mkws.config.lang = ""
581 mkws.config.lang = lang;
584 mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
586 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
587 if (mkws.pazpar2_url().match(/^\/\//)) {
588 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
589 mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
592 if (mkws.config.responsive_design_width) {
593 // Responsive web design - change layout on the fly based on
594 // current screen width. Required for mobile devices.
595 $(window).resize(resizePage);
596 // initial check after page load
597 $(document).ready(resizePage);
602 // If we've made no widgets, return without starting an SP session
603 // or marking MKWS active.
604 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
609 mkws.info("walking MKWS nodes took " + (now-then) + " ms");
610 for (var tName in mkws.teams) {
611 var myTeam = mkws.teams[tName]
613 myTeam.info("made PZ2 object");
615 myTeam.visitWidgets(function(t, w) {
616 mkws.debug(" has widget of type '" + t + "': " + w);
621 function sp_auth_url(config) {
622 if (config.service_proxy_auth) {
623 mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
624 return config.service_proxy_auth;
627 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
629 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
630 var q = config.sp_auth_query;
634 var c = config.sp_auth_credentials;
636 s += ('&username=' + c.substr(0, c.indexOf('/')) +
637 '&password=' + c.substr(c.indexOf('/')+1));
639 mkws.info("generated sp_auth_url '" + s + "'");
644 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
645 authenticateSession(sp_auth_url(mkws.config),
646 mkws.config.service_proxy_auth_domain,
648 } else if (!mkws.authenticating) {
649 // raw pp2 or we have a session already open
653 mkws.isActive = true;
657 $(document).ready(function() {
658 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {