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.log = function(x) { _log(mkws.logger.debug, x) };
116 trace("message with severity trace");
117 debug("message with severity debug");
118 info("message with severity info");
119 warn("message with severity warn");
120 error("message with severity error");
121 fatal("message with severity fatal");
126 // Translation function.
127 mkws.M = function(word) {
128 var lang = mkws.config.lang;
130 if (!lang || !mkws.locale_lang[lang])
133 return mkws.locale_lang[lang][word] || word;
137 // This function is taken from a StackOverflow answer
138 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
139 mkws.getParameterByName = function(name, url) {
140 if (!url) url = location.search;
141 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
142 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
143 results = regex.exec(url);
144 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
148 mkws.registerWidgetType = function(name, fn) {
149 if(mkws._old2new.hasOwnProperty(name)) {
150 mkws.log("Warning: registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
151 name = mkws._old2new[name];
154 mkws.widgetType2function[name] = fn;
155 mkws.log("registered widget-type '" + name + "'");
158 mkws.promotionFunction = function(name) {
159 return mkws.widgetType2function[name];
163 mkws.setMkwsConfig = function(overrides) {
164 // Set global log_level flag early so that mkws.log() works
165 var tmp = overrides.log_level;
166 if (typeof(tmp) !== 'undefined') mkws.log_level = tmp;
168 var config_default = {
169 use_service_proxy: true,
170 pazpar2_url: undefined,
171 pp2_hostname: "sp-mkws.indexdata.com",
172 pp2_path: "service-proxy/",
173 service_proxy_auth: undefined,
174 sp_auth_path: undefined,
175 sp_auth_query: "command=auth&action=perconfig",
176 sp_auth_credentials: undefined,
178 sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
179 perpage_options: [10, 20, 30, 50],
180 sort_default: "relevance",
182 show_lang: true, /* show/hide language menu */
183 show_sort: true, /* show/hide sort menu */
184 show_perpage: true, /* show/hide perpage menu */
185 show_switch: true, /* show/hide switch menu */
186 lang_options: [], /* display languages links for given languages, [] for all */
187 facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
188 responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
189 log_level: 1, /* log level for development: 0..2 */
190 template_vars: {}, /* values that may be exposed to templates */
195 mkws.config = mkws.objectInheritingFrom(config_default);
196 for (var k in overrides) {
197 mkws.config[k] = overrides[k];
202 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
203 // http://javascript.crockford.com/prototypal.html
204 // mkws.objectInheritingFrom behaves the same as Object.create,
205 // but since the latter is not available in IE8 we can't use it.
207 mkws.objectInheritingFrom = function(o) {
214 // The following functions are dispatchers for team methods that
215 // are called from the UI using a team-name rather than implicit
217 mkws.switchView = function(tname, view) {
218 mkws.teams[tname].switchView(view);
221 mkws.showDetails = function(tname, prefixRecId) {
222 mkws.teams[tname].showDetails(prefixRecId);
225 mkws.limitTarget = function(tname, id, name) {
226 mkws.teams[tname].limitTarget(id, name);
229 mkws.limitQuery = function(tname, field, value) {
230 mkws.teams[tname].limitQuery(field, value);
233 mkws.limitCategory = function(tname, id) {
234 mkws.teams[tname].limitCategory(id);
237 mkws.delimitTarget = function(tname, id) {
238 mkws.teams[tname].delimitTarget(id);
241 mkws.delimitQuery = function(tname, field, value) {
242 mkws.teams[tname].delimitQuery(field, value);
245 mkws.showPage = function(tname, pageNum) {
246 mkws.teams[tname].showPage(pageNum);
249 mkws.pagerPrev = function(tname) {
250 mkws.teams[tname].pagerPrev();
253 mkws.pagerNext = function(tname) {
254 mkws.teams[tname].pagerNext();
258 mkws.pazpar2_url = function() {
259 if (mkws.config.pazpar2_url) {
260 mkws.log("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
261 return mkws.config.pazpar2_url;
263 var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
264 mkws.log("generated pazpar2_url '" + s + "'");
270 // We put a session token in window.name, as it's the only place to
271 // keep data that is preserved across reloads and within-site
272 // navigation. pz2.js picks this up and uses it as part of the
273 // cookie-name, to ensure we get a new session when we need one.
275 // We want to use different sessions for different windows/tabs (so
276 // they don't receive each other's messages), different hosts and
277 // different paths on a host (since in general these will
278 // authenticate as different libraries). So the window name needs to
279 // include the hostname and the path from the URL, plus the token.
283 token = window.name.replace(/.*\//, '');
284 mkws.log("Reusing existing window token '" + token + "'");
286 // Incredible that the standard JavaScript runtime doesn't define a
287 // unique windowId. Instead, we have to make one up. And since there's
288 // no global area shared between windows, the best we can do for
289 // ensuring uniqueness is generating a random ID and crossing our
292 // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
293 // At one per second, it will take 116 million years to duplicate a token
294 token = Math.random().toString(36).slice(2, 12);
295 mkws.log("Generated new window token '" + token + "'");
298 window.name = window.location.hostname + window.location.pathname + '/' + token;
299 mkws.log("Using window.name '" + window.name + "'");
302 // wrapper to provide local copy of the jQuery object.
305 var _old2new = { // Maps old-style widget names to new-style
306 'Authname': 'auth-name',
307 'ConsoleBuilder': 'console-builder',
308 'Coverart': 'cover-art',
309 'GoogleImage': 'google-image',
311 'MOTDContainer': 'motd-container',
312 'Perpage': 'per-page',
313 'SearchForm': 'search-form',
314 'ReferenceUniverse': 'reference-universe',
315 'Termlists': 'facets'
317 // Annoyingly, there is no built-in way to invert a hash
319 for (var key in _old2new) {
320 if(_old2new.hasOwnProperty(key)) {
321 _new2old[_old2new[key]] = key;
325 mkws._old2new = _old2new;
327 function handleNodeWithTeam(node, callback) {
328 // First branch for DOM objects; second branch for jQuery objects
329 var classes = node.className || node.attr('class');
331 // For some reason, if we try to proceed when classes is
332 // undefined, we don't get an error message, but this
333 // function and its callers, up several stack level,
334 // silently return. What a crock.
335 log("handleNodeWithTeam() called on node with no classes");
338 var list = classes.split(/\s+/)
341 for (var i = 0; i < list.length; i++) {
343 if (cname.match(/^mkws-team-/)) {
344 // New-style teamnames of the form mkws-team-xyz
345 teamName = cname.replace(/^mkws-team-/, '');
346 } else if (cname.match(/^mkwsTeam_/)) {
347 // Old-style teamnames of the form mkwsTeam_xyz
348 teamName = cname.replace(/^mkwsTeam_/, '');
349 } else if (cname.match(/^mkws-/)) {
350 // New-style names of the from mkws-foo-bar
351 type = cname.replace(/^mkws-/, '');
352 } else if (cname.match(/^mkws/)) {
353 // Old-style names of the form mkwsFooBar
354 var tmp = cname.replace(/^mkws/, '');
355 type = _old2new[tmp] || tmp.toLowerCase();
359 // Widgets without a team are on team "AUTO"
362 // Autosearch widgets don't join team AUTO if there is already an
363 // autosearch on the team or the team has otherwise gotten a query
364 if (node.getAttribute("autosearch")) {
365 if (mkws.autoHasAuto ||
366 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
367 log("AUTO team already has a query, using unique team");
370 mkws.autoHasAuto = true;
374 // Widgets on team "UNIQUE" get a random team
375 if (teamName === "UNIQUE") {
376 teamName = Math.floor(Math.random() * 100000000).toString();
379 callback.call(node, teamName, type);
383 function resizePage() {
384 var threshhold = mkws.config.responsive_design_width;
385 var width = $(window).width();
386 var from, to, method;
388 if ((mkws.width === undefined || mkws.width > threshhold) &&
389 width <= threshhold) {
390 from = "wide"; to = "narrow"; method = "hide";
391 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
392 width > threshhold) {
393 from = "narrow"; to = "wide"; method = "show";
398 log("changing from " + from + " to " + to + ": " + width);
399 for (var tname in mkws.teams) {
400 var team = mkws.teams[tname];
401 team.visitWidgets(function(t, w) {
402 var w1 = team.widget(t + "-container-" + from);
403 var w2 = team.widget(t + "-container-" + to);
409 w.node.appendTo(w2.node);
412 team.queue("resize-" + to).publish();
419 * Run service-proxy authentication in background (after page load).
420 * The username/password is configured in the apache config file
423 function authenticateSession(auth_url, auth_domain, pp2_url) {
424 mkws.authenticating = true;
425 log("service proxy authentication on URL: " + auth_url);
428 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
429 log("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
432 var request = new pzHttpRequest(auth_url, function(err) {
433 alert("HTTP call for authentication failed: " + err)
437 request.get(null, function(data) {
438 mkws.authenticating = false;
439 if (!$.isXMLDoc(data)) {
440 alert("Service Proxy authentication response is not a valid XML document");
443 var status = $(data).find("status");
444 if (status.text() != "OK") {
445 var message = $(data).find("message");
446 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
450 log("service proxy authentication successful");
451 mkws.authenticated = true;
452 var authName = $(data).find("displayName").text();
453 // You'd think there would be a better way to do this:
454 var realm = $(data).find("realm:not(realmAttributes realm)").text();
455 for (var teamName in mkws.teams) {
456 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
464 function runAutoSearches() {
465 log("running auto searches");
467 for (var teamName in mkws.teams) {
468 mkws.teams[teamName].queue("ready").publish();
473 function selectorForAllWidgets() {
474 if (mkws.config && mkws.config.scan_all_nodes) {
475 // This is the old version, which works by telling jQuery to
476 // find every node that has a class beginning with "mkws". In
477 // theory it should be slower than the class-based selector; but
478 // instrumentation suprisingly shows this is consistently
479 // faster. It also has the advantage that any widgets of
480 // non-registered types are logged as warnings rather than
482 return '[class^="mkws"],[class*=" mkws"]';
484 // This is the new version, which works by looking up the
485 // specific classes of all registered widget types and their
486 // resize containers. Because all it requires jQuery to do is
487 // some hash lookups in pre-built tables, it should be very
488 // fast; but it silently ignores widgets of unregistered types.
490 for (var type in mkws.widgetType2function) {
492 s += '.mkws-' + type;
493 s += ',.mkws-' + type + "-container-wide";
494 s += ',.mkws-' + type + "-container-narrow";
495 // Annoyingly, we also need to recognise old-style names
496 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
497 s += ',.mkws' + oldtype;
498 s += ',.mkws' + oldtype + "-Container-wide";
499 s += ',.mkws' + oldtype + "-Container-narrow";
506 function makeWidgetsWithin(level, node) {
507 if (node) var widgetNodes = node.find(selectorForAllWidgets());
508 else widgetNodes = $(selectorForAllWidgets());
509 // Return false if we parse no widgets
510 if (widgetNodes.length < 1) return false;
511 widgetNodes.each(function() {
512 handleNodeWithTeam(this, function(tname, type) {
513 var myTeam = mkws.teams[tname];
515 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
518 var oldHTML = this.innerHTML;
519 var myWidget = mkws.makeWidget($, myTeam, type, this);
520 myTeam.addWidget(myWidget);
521 var newHTML = this.innerHTML;
522 if (newHTML !== oldHTML) {
523 myTeam.log("widget " + type + " HTML changed: reparsing");
524 makeWidgetsWithin(level+1, $(this));
532 // The second "rootsel" parameter is passed to jQuery and is a DOM node
533 // or a selector string you would like to constrain the search for widgets to.
535 // This function has no side effects if run again on an operating session,
536 // even if the element/selector passed causes existing widgets to be reparsed:
538 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
539 // widgets, MKWS-261)
541 // * configuration is not regenerated
542 // * authentication is not performed again
543 // * autosearches are not re-run
544 mkws.init = function(message, rootsel) {
545 var greet = "MKWS initialised";
546 if (rootsel) greet += " (limited to " + rootsel + ")"
547 if (message) greet += " :: " + message;
550 // MKWS is not active until init() has been run against an object with widget nodes.
551 // We only set initial configuration when MKWS is first activated.
552 if (!mkws.isActive) {
553 var widgetSelector = selectorForAllWidgets();
554 if ($(widgetSelector).length < 1) {
555 mkws.log("no widgets found");
559 // Initial configuration
560 mkws.autoHasAuto = false;
562 if (typeof mkws_config === 'undefined') {
563 log("setting empty config");
566 log("using config: " + $.toJSON(mkws_config));
567 saved_config = mkws_config;
569 mkws.setMkwsConfig(saved_config);
571 for (var key in mkws.config) {
572 if (mkws.config.hasOwnProperty(key)) {
573 if (key.match(/^language_/)) {
574 var lang = key.replace(/^language_/, "");
575 // Copy custom languages into list
576 mkws.locale_lang[lang] = mkws.config[key];
577 log("added locally configured language '" + lang + "'");
582 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
583 if (!lang || !mkws.locale_lang[lang]) {
584 mkws.config.lang = ""
586 mkws.config.lang = lang;
589 log("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
591 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
592 if (mkws.pazpar2_url().match(/^\/\//)) {
593 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
594 log("adjusted protocol independent link to " + mkws.pazpar2_url());
597 if (mkws.config.responsive_design_width) {
598 // Responsive web design - change layout on the fly based on
599 // current screen width. Required for mobile devices.
600 $(window).resize(resizePage);
601 // initial check after page load
602 $(document).ready(resizePage);
607 // If we've made no widgets, return without starting an SP session
608 // or marking MKWS active.
609 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
614 log("walking MKWS nodes took " + (now-then) + " ms");
615 for (var tName in mkws.teams) {
616 var myTeam = mkws.teams[tName]
618 myTeam.log("made PZ2 object");
620 myTeam.visitWidgets(function(t, w) {
621 log(" has widget of type '" + t + "': " + w);
626 function sp_auth_url(config) {
627 if (config.service_proxy_auth) {
628 mkws.log("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
629 return config.service_proxy_auth;
632 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
634 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
635 var q = config.sp_auth_query;
639 var c = config.sp_auth_credentials;
641 s += ('&username=' + c.substr(0, c.indexOf('/')) +
642 '&password=' + c.substr(c.indexOf('/')+1));
644 mkws.log("generated sp_auth_url '" + s + "'");
649 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
650 authenticateSession(sp_auth_url(mkws.config),
651 mkws.config.service_proxy_auth_domain,
653 } else if (!mkws.authenticating) {
654 // raw pp2 or we have a session already open
658 mkws.isActive = true;
662 $(document).ready(function() {
663 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {