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",
56 "Authors": "Forfattere",
60 "Facets": "Termlists",
61 "Next": "Næste",
63 "Search": "Søg",
64 "Sort by": "Sorter efter",
66 "per page": "per side",
67 "Displaying": "Viser",
72 "Author": "Forfatter",
73 "author": "forfatter",
77 "Location": "Lokation",
86 // We may be using a separate copy
87 if (typeof(mkws_jQuery) !== "undefined") {
93 // It's ridiculous that JSNLog doesn't provide this
94 mkws.stringToLevel = function(s) {
96 return JL.getTraceLevel();
97 } else if (s === 'debug') {
98 return JL.getDebugLevel();
99 } else if (s === 'info') {
100 return JL.getInfoLevel();
101 } else if (s === 'warn') {
102 return JL.getWarnLevel();
103 } else if (s === 'error') {
104 return JL.getErrorLevel();
105 } else if (s === 'fatal') {
106 return JL.getFatalLevel();
108 throw "bad log-level '" + s + "'";
112 mkws.logger = JL('mkws');
113 var consoleAppender = JL.createConsoleAppender('consoleAppender');
114 mkws.logger.setOptions({ "appenders": [consoleAppender] });
118 var argsAsARealArray = Array.prototype.slice.call(arguments);
119 var fn = argsAsARealArray.shift();
120 fn.apply(mkws.logger, argsAsARealArray);
122 mkws.trace = function(x) { _log(mkws.logger.trace, x) };
123 mkws.debug = function(x) { _log(mkws.logger.debug, x) };
124 mkws.info = function(x) { _log(mkws.logger.info, x) };
125 mkws.warn = function(x) { _log(mkws.logger.warn, x) };
126 mkws.error = function(x) { _log(mkws.logger.error, x) };
127 mkws.fatal = function(x) { _log(mkws.logger.fatal, x) };
130 // Translation function.
131 mkws.M = function(word) {
132 var lang = mkws.config.lang;
134 if (!lang || !mkws.locale_lang[lang])
137 return mkws.locale_lang[lang][word] || word;
141 // This function is taken from a StackOverflow answer
142 // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
143 mkws.getParameterByName = function(name, url) {
144 if (!url) url = location.search;
145 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
146 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
147 results = regex.exec(url);
148 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
152 mkws.registerWidgetType = function(name, fn) {
153 if(mkws._old2new.hasOwnProperty(name)) {
154 mkws.warn("registerWidgetType old widget name: " + name + " => " + mkws._old2new[name]);
155 name = mkws._old2new[name];
158 mkws.widgetType2function[name] = fn;
159 mkws.info("registered widget-type '" + name + "'");
162 mkws.promotionFunction = function(name) {
163 return mkws.widgetType2function[name];
167 mkws.setMkwsConfig = function(overrides) {
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.info("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.info("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.debug("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.debug("Generated new window token '" + token + "'");
298 window.name = window.location.hostname + window.location.pathname + '/' + token;
299 mkws.info("Using window.name '" + window.name + "'");
302 // wrapper to provide local copy of the jQuery object.
304 var _old2new = { // Maps old-style widget names to new-style
305 'Authname': 'auth-name',
306 'ConsoleBuilder': 'console-builder',
307 'Coverart': 'cover-art',
308 'GoogleImage': 'google-image',
310 'MOTDContainer': 'motd-container',
311 'Perpage': 'per-page',
312 'SearchForm': 'search-form',
313 'ReferenceUniverse': 'reference-universe',
314 'Termlists': 'facets'
316 // Annoyingly, there is no built-in way to invert a hash
318 for (var key in _old2new) {
319 if(_old2new.hasOwnProperty(key)) {
320 _new2old[_old2new[key]] = key;
324 mkws._old2new = _old2new;
326 function handleNodeWithTeam(node, callback) {
327 // First branch for DOM objects; second branch for jQuery objects
328 var classes = node.className || node.attr('class');
330 // For some reason, if we try to proceed when classes is
331 // undefined, we don't get an error message, but this
332 // function and its callers, up several stack level,
333 // silently return. What a crock.
334 mkws.fatal("handleNodeWithTeam() called on node with no classes");
337 var list = classes.split(/\s+/)
340 for (var i = 0; i < list.length; i++) {
342 if (cname.match(/^mkws-team-/)) {
343 // New-style teamnames of the form mkws-team-xyz
344 teamName = cname.replace(/^mkws-team-/, '');
345 } else if (cname.match(/^mkwsTeam_/)) {
346 // Old-style teamnames of the form mkwsTeam_xyz
347 teamName = cname.replace(/^mkwsTeam_/, '');
348 } else if (cname.match(/^mkws-/)) {
349 // New-style names of the from mkws-foo-bar
350 type = cname.replace(/^mkws-/, '');
351 } else if (cname.match(/^mkws/)) {
352 // Old-style names of the form mkwsFooBar
353 var tmp = cname.replace(/^mkws/, '');
354 type = _old2new[tmp] || tmp.toLowerCase();
358 // Widgets without a team are on team "AUTO"
361 // Autosearch widgets don't join team AUTO if there is already an
362 // autosearch on the team or the team has otherwise gotten a query
363 if (node.getAttribute("autosearch")) {
364 if (mkws.autoHasAuto ||
365 mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
366 mkws.warn("AUTO team already has a query, using unique team");
369 mkws.autoHasAuto = true;
373 // Widgets on team "UNIQUE" get a random team
374 if (teamName === "UNIQUE") {
375 teamName = Math.floor(Math.random() * 100000000).toString();
378 callback.call(node, teamName, type);
382 function resizePage() {
383 var threshhold = mkws.config.responsive_design_width;
384 var width = $(window).width();
385 var from, to, method;
387 if ((mkws.width === undefined || mkws.width > threshhold) &&
388 width <= threshhold) {
389 from = "wide"; to = "narrow"; method = "hide";
390 } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
391 width > threshhold) {
392 from = "narrow"; to = "wide"; method = "show";
397 mkws.info("changing from " + from + " to " + to + ": " + width);
398 for (var tname in mkws.teams) {
399 var team = mkws.teams[tname];
400 team.visitWidgets(function(t, w) {
401 var w1 = team.widget(t + "-container-" + from);
402 var w2 = team.widget(t + "-container-" + to);
408 w.node.appendTo(w2.node);
411 team.queue("resize-" + to).publish();
418 * Run service-proxy authentication in background (after page load).
419 * The username/password is configured in the apache config file
422 function authenticateSession(auth_url, auth_domain, pp2_url) {
423 mkws.authenticating = true;
424 mkws.info("service proxy authentication on URL: " + auth_url);
427 auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
428 mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
431 var request = new pzHttpRequest(auth_url, function(err) {
432 alert("HTTP call for authentication failed: " + err)
436 request.get(null, function(data) {
437 mkws.authenticating = false;
438 if (!$.isXMLDoc(data)) {
439 alert("Service Proxy authentication response is not a valid XML document");
442 var status = $(data).find("status");
443 if (status.text() != "OK") {
444 var message = $(data).find("message");
445 alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
449 mkws.info("service proxy authentication successful");
450 mkws.authenticated = true;
451 var authName = $(data).find("displayName").text();
452 // You'd think there would be a better way to do this:
453 var realm = $(data).find("realm:not(realmAttributes realm)").text();
454 for (var teamName in mkws.teams) {
455 mkws.teams[teamName].queue("authenticated").publish(authName, realm);
463 function runAutoSearches() {
464 mkws.info("running auto searches");
466 for (var teamName in mkws.teams) {
467 mkws.teams[teamName].queue("ready").publish();
472 function selectorForAllWidgets() {
473 if (mkws.config && mkws.config.scan_all_nodes) {
474 // This is the old version, which works by telling jQuery to
475 // find every node that has a class beginning with "mkws". In
476 // theory it should be slower than the class-based selector; but
477 // instrumentation suprisingly shows this is consistently
478 // faster. It also has the advantage that any widgets of
479 // non-registered types are logged as warnings rather than
481 return '[class^="mkws"],[class*=" mkws"]';
483 // This is the new version, which works by looking up the
484 // specific classes of all registered widget types and their
485 // resize containers. Because all it requires jQuery to do is
486 // some hash lookups in pre-built tables, it should be very
487 // fast; but it silently ignores widgets of unregistered types.
489 for (var type in mkws.widgetType2function) {
491 s += '.mkws-' + type;
492 s += ',.mkws-' + type + "-container-wide";
493 s += ',.mkws-' + type + "-container-narrow";
494 // Annoyingly, we also need to recognise old-style names
495 var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
496 s += ',.mkws' + oldtype;
497 s += ',.mkws' + oldtype + "-Container-wide";
498 s += ',.mkws' + oldtype + "-Container-narrow";
505 function makeWidgetsWithin(level, node) {
506 if (node) var widgetNodes = node.find(selectorForAllWidgets());
507 else widgetNodes = $(selectorForAllWidgets());
508 // Return false if we parse no widgets
509 if (widgetNodes.length < 1) return false;
510 widgetNodes.each(function() {
511 handleNodeWithTeam(this, function(tname, type) {
512 var myTeam = mkws.teams[tname];
514 myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
517 var oldHTML = this.innerHTML;
518 var myWidget = mkws.makeWidget($, myTeam, type, this);
519 myTeam.addWidget(myWidget);
520 var newHTML = this.innerHTML;
521 if (newHTML !== oldHTML) {
522 myTeam.info("widget " + type + " HTML changed: reparsing");
523 makeWidgetsWithin(level+1, $(this));
531 // The second "rootsel" parameter is passed to jQuery and is a DOM node
532 // or a selector string you would like to constrain the search for widgets to.
534 // This function has no side effects if run again on an operating session,
535 // even if the element/selector passed causes existing widgets to be reparsed:
537 // (TODO: that last bit isn't true and we currently have to avoid reinitialising
538 // widgets, MKWS-261)
540 // * configuration is not regenerated
541 // * authentication is not performed again
542 // * autosearches are not re-run
543 mkws.init = function(message, rootsel) {
544 var greet = "MKWS initialised";
545 if (rootsel) greet += " (limited to " + rootsel + ")"
546 if (message) greet += " :: " + message;
549 // MKWS is not active until init() has been run against an object with widget nodes.
550 // We only set initial configuration when MKWS is first activated.
551 if (!mkws.isActive) {
552 var widgetSelector = selectorForAllWidgets();
553 if ($(widgetSelector).length < 1) {
554 mkws.warn("no widgets found");
558 // Initial configuration
559 mkws.autoHasAuto = false;
561 if (typeof mkws_config === 'undefined') {
562 mkws.info("setting empty config");
565 mkws.info("using config: " + $.toJSON(mkws_config));
566 saved_config = mkws_config;
568 mkws.setMkwsConfig(saved_config);
570 for (var key in mkws.config) {
571 if (mkws.config.hasOwnProperty(key)) {
572 if (key.match(/^language_/)) {
573 var lang = key.replace(/^language_/, "");
574 // Copy custom languages into list
575 mkws.locale_lang[lang] = mkws.config[key];
576 mkws.info("added locally configured language '" + lang + "'");
581 var lang = mkws.getParameterByName("lang") || mkws.config.lang;
582 if (!lang || !mkws.locale_lang[lang]) {
583 mkws.config.lang = ""
585 mkws.config.lang = lang;
588 mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
590 // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
591 if (mkws.pazpar2_url().match(/^\/\//)) {
592 mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
593 mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
596 if (mkws.config.responsive_design_width) {
597 // Responsive web design - change layout on the fly based on
598 // current screen width. Required for mobile devices.
599 $(window).resize(resizePage);
600 // initial check after page load
601 $(document).ready(resizePage);
606 // If we've made no widgets, return without starting an SP session
607 // or marking MKWS active.
608 if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
613 mkws.info("walking MKWS nodes took " + (now-then) + " ms");
614 for (var tName in mkws.teams) {
615 var myTeam = mkws.teams[tName]
617 myTeam.info("made PZ2 object");
619 myTeam.visitWidgets(function(t, w) {
620 mkws.debug(" has widget of type '" + t + "': " + w);
625 function sp_auth_url(config) {
626 if (config.service_proxy_auth) {
627 mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
628 return config.service_proxy_auth;
631 s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
633 s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
634 var q = config.sp_auth_query;
638 var c = config.sp_auth_credentials;
640 s += ('&username=' + c.substr(0, c.indexOf('/')) +
641 '&password=' + c.substr(c.indexOf('/')+1));
643 mkws.info("generated sp_auth_url '" + s + "'");
648 if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
649 authenticateSession(sp_auth_url(mkws.config),
650 mkws.config.service_proxy_auth_domain,
652 } else if (!mkws.authenticating) {
653 // raw pp2 or we have a session already open
657 mkws.isActive = true;
661 $(document).ready(function() {
662 if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
667 // Set global log_level flag early so that _log() works
668 if (typeof mkws_config !== 'undefined') {
669 var tmp = mkws_config.log_level;
670 if (typeof tmp !== 'undefined') {
671 mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });