176e6d78e8f26eaf62454fd7043a0b680e1d9329
[mkws-moved-to-github.git] / src / mkws-core.js
1 /*! MKWS, the MasterKey Widget Set.
2  *  Copyright (C) 2013-2014 Index Data
3  *  See the file LICENSE for details
4  */
5
6 "use strict";
7
8
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.
11 //
12 // We set it as a property of window to make the global explicit as
13 // some things complain about an implicit global.
14 window.mkws = {
15   $: $, // Our own local copy of the jQuery object
16   authenticated: false,
17   authenticating: false,
18   active: false,
19   logger: undefined,
20   log_level: "info",
21   teams: {},
22   widgetType2function: {},
23   defaultTemplates: {},
24
25   locale_lang: {
26     "de": {
27       "Authors": "Autoren",
28       "Subjects": "Schlagwörter",
29       "Sources": "Daten und Quellen",
30       "source": "datenquelle",
31       "Facets": "Termlisten",
32       "Next": "Weiter",
33       "Prev": "Zurück",
34       "Search": "Suche",
35       "Sort by": "Sortieren nach",
36       "and show": "und zeige",
37       "per page": "pro Seite",
38       "Displaying": "Zeige",
39       "to": "von",
40       "of": "aus",
41       "found": "gefunden",
42       "Title": "Titel",
43       "Author": "Autor",
44       "author": "autor",
45       "Date": "Datum",
46       "Subject": "Schlagwort",
47       "subject": "schlagwort",
48       "Location": "Ort",
49       "Records": "Datensätze",
50       "Targets": "Datenbanken",
51
52       "dummy": "dummy"
53     },
54
55     "da": {
56       "Authors": "Forfattere",
57       "Subjects": "Emner",
58       "Sources": "Kilder",
59       "source": "kilder",
60       "Facets": "Termlists",
61       "Next": "Næste",
62       "Prev": "Forrige",
63       "Search": "Søg",
64       "Sort by": "Sorter efter",
65       "and show": "og vis",
66       "per page": "per side",
67       "Displaying": "Viser",
68       "to": "til",
69       "of": "ud af",
70       "found": "fandt",
71       "Title": "Title",
72       "Author": "Forfatter",
73       "author": "forfatter",
74       "Date": "Dato",
75       "Subject": "Emneord",
76       "subject": "emneord",
77       "Location": "Lokation",
78       "Records": "Poster",
79       "Targets": "Baser",
80
81       "dummy": "dummy"
82     }
83   }
84 };
85
86 // We may be using a separate copy
87 if (typeof(mkws_jQuery) !== "undefined") {
88   mkws.$ = mkws_jQuery;
89 } else {
90   mkws.$ = jQuery;
91 }
92
93 // It's ridiculous that JSNLog doesn't provide this
94 mkws.stringToLevel = function(s) {
95   if (s === 'trace') {
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();
107   } else {
108     throw "bad log-level '" + s + "'";
109   }
110 }
111
112 mkws.logger = JL('mkws');
113 var consoleAppender = JL.createConsoleAppender('consoleAppender');
114 mkws.logger.setOptions({ "appenders": [consoleAppender] });
115
116
117 function _log(fn, string) {
118   if (!mkws.log_level)
119     return;
120
121   // you need to disable use strict at the top of the file!!!
122   if (mkws.log_level >= 3) {
123     // Works in Chrome; not sure about elsewhere
124     console.trace();
125   } else if (mkws.log_level >= 2) {
126
127   }
128   fn.call(mkws.logger, string);
129 };
130
131
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) };
138
139
140 // Translation function.
141 mkws.M = function(word) {
142   var lang = mkws.config.lang;
143
144   if (!lang || !mkws.locale_lang[lang])
145     return word;
146
147   return mkws.locale_lang[lang][word] || word;
148 };
149
150
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, " "));
159 }
160
161
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];
166   }
167
168   mkws.widgetType2function[name] = fn;
169   mkws.info("registered widget-type '" + name + "'");
170 };
171
172 mkws.promotionFunction = function(name) {
173   return mkws.widgetType2function[name];
174 };
175
176
177 mkws.setMkwsConfig = function(overrides) {
178   // Set global log_level flag early so that _log() works
179   var tmp = overrides.log_level;
180   if (typeof(tmp) !== 'undefined') {
181     console.log("setting level to '" + tmp + "'");
182     mkws.logger.setOptions({ "level": mkws.stringToLevel(tmp) });
183   }
184
185   var config_default = {
186     use_service_proxy: true,
187     pazpar2_url: undefined,
188     pp2_hostname: "sp-mkws.indexdata.com",
189     pp2_path: "service-proxy/",
190     service_proxy_auth: undefined,
191     sp_auth_path: undefined,
192     sp_auth_query: "command=auth&action=perconfig",
193     sp_auth_credentials: undefined,
194     lang: "",
195     sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
196     perpage_options: [10, 20, 30, 50],
197     sort_default: "relevance",
198     perpage_default: 20,
199     show_lang: true,    /* show/hide language menu */
200     show_sort: true,    /* show/hide sort menu */
201     show_perpage: true, /* show/hide perpage menu */
202     show_switch: true,  /* show/hide switch menu */
203     lang_options: [],   /* display languages links for given languages, [] for all */
204     facets: ["xtargets", "subject", "author"], /* display facets, in this order, [] for none */
205     responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
206     log_level: 1,     /* log level for development: 0..2 */
207     template_vars: {}, /* values that may be exposed to templates */
208
209     dummy: "dummy"
210   };
211
212   mkws.config = mkws.objectInheritingFrom(config_default);
213   for (var k in overrides) {
214     mkws.config[k] = overrides[k];
215   }
216 };
217
218
219 // This code is from Douglas Crockford's article "Prototypal Inheritance in JavaScript"
220 // http://javascript.crockford.com/prototypal.html
221 // mkws.objectInheritingFrom behaves the same as Object.create,
222 // but since the latter is not available in IE8 we can't use it.
223 //
224 mkws.objectInheritingFrom = function(o) {
225   function F() {}
226   F.prototype = o;
227   return new F();
228 }
229
230
231 // The following functions are dispatchers for team methods that
232 // are called from the UI using a team-name rather than implicit
233 // context.
234 mkws.switchView = function(tname, view) {
235   mkws.teams[tname].switchView(view);
236 };
237
238 mkws.showDetails = function(tname, prefixRecId) {
239   mkws.teams[tname].showDetails(prefixRecId);
240 };
241
242 mkws.limitTarget  = function(tname, id, name) {
243   mkws.teams[tname].limitTarget(id, name);
244 };
245
246 mkws.limitQuery  = function(tname, field, value) {
247   mkws.teams[tname].limitQuery(field, value);
248 };
249
250 mkws.limitCategory  = function(tname, id) {
251   mkws.teams[tname].limitCategory(id);
252 };
253
254 mkws.delimitTarget = function(tname, id) {
255   mkws.teams[tname].delimitTarget(id);
256 };
257
258 mkws.delimitQuery = function(tname, field, value) {
259   mkws.teams[tname].delimitQuery(field, value);
260 };
261
262 mkws.showPage = function(tname, pageNum) {
263   mkws.teams[tname].showPage(pageNum);
264 };
265
266 mkws.pagerPrev = function(tname) {
267   mkws.teams[tname].pagerPrev();
268 };
269
270 mkws.pagerNext = function(tname) {
271   mkws.teams[tname].pagerNext();
272 };
273
274
275 mkws.pazpar2_url = function() {
276   if (mkws.config.pazpar2_url) {
277     mkws.info("using pre-baked pazpar2_url '" + mkws.config.pazpar2_url + "'");
278     return mkws.config.pazpar2_url;
279   } else {
280     var s = document.location.protocol + "//" + mkws.config.pp2_hostname + "/" + mkws.config.pp2_path;
281     mkws.info("generated pazpar2_url '" + s + "'");
282     return s;
283   }
284 };
285
286
287 // We put a session token in window.name, as it's the only place to
288 // keep data that is preserved across reloads and within-site
289 // navigation. pz2.js picks this up and uses it as part of the
290 // cookie-name, to ensure we get a new session when we need one.
291 //
292 // We want to use different sessions for different windows/tabs (so
293 // they don't receive each other's messages), different hosts and
294 // different paths on a host (since in general these will
295 // authenticate as different libraries). So the window name needs to
296 // include the hostname and the path from the URL, plus the token.
297 //
298 var token;
299 if (window.name) {
300   token = window.name.replace(/.*\//, '');
301   mkws.debug("Reusing existing window token '" + token + "'");
302 } else {
303   // Incredible that the standard JavaScript runtime doesn't define a
304   // unique windowId. Instead, we have to make one up. And since there's
305   // no global area shared between windows, the best we can do for
306   // ensuring uniqueness is generating a random ID and crossing our
307   // fingers.
308   //
309   // Ten chars from 26 alpha-numerics = 36^10 = 3.65e15 combinations.
310   // At one per second, it will take 116 million years to duplicate a token
311   token = Math.random().toString(36).slice(2, 12);
312   mkws.debug("Generated new window token '" + token + "'");
313 }
314
315 window.name = window.location.hostname + window.location.pathname + '/' + token;
316 mkws.info("Using window.name '" + window.name + "'");
317
318
319 // wrapper to provide local copy of the jQuery object.
320 (function($) {
321   var _old2new = { // Maps old-style widget names to new-style
322     'Authname': 'auth-name',
323     'ConsoleBuilder': 'console-builder',
324     'Coverart': 'cover-art',
325     'GoogleImage': 'google-image',
326     'MOTD': 'motd',
327     'MOTDContainer': 'motd-container',
328     'Perpage': 'per-page',
329     'SearchForm': 'search-form',
330     'ReferenceUniverse': 'reference-universe',
331     'Termlists': 'facets'
332   };
333   // Annoyingly, there is no built-in way to invert a hash
334   var _new2old = {};
335   for (var key in _old2new) {
336     if(_old2new.hasOwnProperty(key)) {
337       _new2old[_old2new[key]] = key;
338     }
339   }
340
341   mkws._old2new = _old2new;
342
343   function handleNodeWithTeam(node, callback) {
344     // First branch for DOM objects; second branch for jQuery objects
345     var classes = node.className || node.attr('class');
346     if (!classes) {
347       // For some reason, if we try to proceed when classes is
348       // undefined, we don't get an error message, but this
349       // function and its callers, up several stack level,
350       // silently return. What a crock.
351       mkws.fatal("handleNodeWithTeam() called on node with no classes");
352       return;
353     }
354     var list = classes.split(/\s+/)
355     var teamName, type;
356
357     for (var i = 0; i < list.length; i++) {
358       var cname = list[i];
359       if (cname.match(/^mkws-team-/)) {
360         // New-style teamnames of the form mkws-team-xyz
361         teamName = cname.replace(/^mkws-team-/, '');
362       } else if (cname.match(/^mkwsTeam_/)) {
363         // Old-style teamnames of the form mkwsTeam_xyz
364         teamName = cname.replace(/^mkwsTeam_/, '');
365       } else if (cname.match(/^mkws-/)) {
366         // New-style names of the from mkws-foo-bar
367         type = cname.replace(/^mkws-/, '');
368       } else if (cname.match(/^mkws/)) {
369         // Old-style names of the form mkwsFooBar
370         var tmp = cname.replace(/^mkws/, '');
371         type = _old2new[tmp] || tmp.toLowerCase();
372       }
373     }
374
375     // Widgets without a team are on team "AUTO"
376     if (!teamName) {
377       teamName = "AUTO";
378       // Autosearch widgets don't join team AUTO if there is already an
379       // autosearch on the team or the team has otherwise gotten a query
380       if (node.getAttribute("autosearch")) {
381         if (mkws.autoHasAuto ||
382             mkws.teams["AUTO"] && mkws.teams["AUTO"].config["query"]) {
383           mkws.warn("AUTO team already has a query, using unique team");
384           teamName = "UNIQUE";
385         }
386         mkws.autoHasAuto = true;
387       }
388     }
389
390     // Widgets on team "UNIQUE" get a random team
391     if (teamName === "UNIQUE") {
392       teamName = Math.floor(Math.random() * 100000000).toString();
393     }
394
395     callback.call(node, teamName, type);
396   }
397
398
399   function resizePage() {
400     var threshhold = mkws.config.responsive_design_width;
401     var width = $(window).width();
402     var from, to, method;
403
404     if ((mkws.width === undefined || mkws.width > threshhold) &&
405         width <= threshhold) {
406       from = "wide"; to = "narrow"; method = "hide";
407     } else if ((mkws.width === undefined || mkws.width <= threshhold) &&
408                width > threshhold) {
409       from = "narrow"; to = "wide"; method = "show";
410     }
411     mkws.width = width;
412
413     if (from) {
414       mkws.info("changing from " + from + " to " + to + ": " + width);
415       for (var tname in mkws.teams) {
416         var team = mkws.teams[tname];
417         team.visitWidgets(function(t, w) {
418           var w1 = team.widget(t + "-container-" + from);
419           var w2 = team.widget(t + "-container-" + to);
420           if (w1) {
421             w1.node.hide();
422           }
423           if (w2) {
424             w2.node.show();
425             w.node.appendTo(w2.node);
426           }
427         });
428         team.queue("resize-" + to).publish();
429       }
430     }
431   };
432
433
434   /*
435    * Run service-proxy authentication in background (after page load).
436    * The username/password is configured in the apache config file
437    * for the site.
438    */
439   function authenticateSession(auth_url, auth_domain, pp2_url) {
440     mkws.authenticating = true;
441     mkws.info("service proxy authentication on URL: " + auth_url);
442
443     if (!auth_domain) {
444       auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
445       mkws.info("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
446     }
447
448     var request = new pzHttpRequest(auth_url, function(err) {
449       alert("HTTP call for authentication failed: " + err)
450       return;
451     }, auth_domain);
452
453     request.get(null, function(data) {
454       mkws.authenticating = false;
455       if (!$.isXMLDoc(data)) {
456         alert("Service Proxy authentication response is not a valid XML document");
457         return;
458       }
459       var status = $(data).find("status");
460       if (status.text() != "OK") {
461         var message = $(data).find("message");
462         alert("Service Proxy authentication response: " + status.text() + " (" + message.text() + ")");
463         return;
464       }
465
466       mkws.info("service proxy authentication successful");
467       mkws.authenticated = true;
468       var authName = $(data).find("displayName").text();
469       // You'd think there would be a better way to do this:
470       var realm = $(data).find("realm:not(realmAttributes realm)").text();
471       for (var teamName in mkws.teams) {
472         mkws.teams[teamName].queue("authenticated").publish(authName, realm);
473       }
474
475       runAutoSearches();
476     });
477   }
478
479
480   function runAutoSearches() {
481     mkws.info("running auto searches");
482
483     for (var teamName in mkws.teams) {
484       mkws.teams[teamName].queue("ready").publish();
485     }
486   }
487
488
489   function selectorForAllWidgets() {
490     if (mkws.config && mkws.config.scan_all_nodes) {
491       // This is the old version, which works by telling jQuery to
492       // find every node that has a class beginning with "mkws". In
493       // theory it should be slower than the class-based selector; but
494       // instrumentation suprisingly shows this is consistently
495       // faster. It also has the advantage that any widgets of
496       // non-registered types are logged as warnings rather than
497       // silently ignored.
498       return '[class^="mkws"],[class*=" mkws"]';
499     } else {
500       // This is the new version, which works by looking up the
501       // specific classes of all registered widget types and their
502       // resize containers. Because all it requires jQuery to do is
503       // some hash lookups in pre-built tables, it should be very
504       // fast; but it silently ignores widgets of unregistered types.
505       var s = "";
506       for (var type in mkws.widgetType2function) {
507         if (s) s += ',';
508         s += '.mkws-' + type;
509         s += ',.mkws-' + type + "-container-wide";
510         s += ',.mkws-' + type + "-container-narrow";
511         // Annoyingly, we also need to recognise old-style names
512         var oldtype = _new2old[type] || type.charAt(0).toUpperCase() + type.slice(1);
513         s += ',.mkws' + oldtype;
514         s += ',.mkws' + oldtype + "-Container-wide";
515         s += ',.mkws' + oldtype + "-Container-narrow";
516       }
517       return s;
518     }
519   }
520
521
522   function makeWidgetsWithin(level, node) {
523     if (node) var widgetNodes = node.find(selectorForAllWidgets());
524     else widgetNodes = $(selectorForAllWidgets());
525     // Return false if we parse no widgets
526     if (widgetNodes.length < 1) return false;
527     widgetNodes.each(function() {
528       handleNodeWithTeam(this, function(tname, type) {
529         var myTeam = mkws.teams[tname];
530         if (!myTeam) {
531           myTeam = mkws.teams[tname] = mkws.makeTeam($, tname);
532         }
533
534         var oldHTML = this.innerHTML;
535         var myWidget = mkws.makeWidget($, myTeam, type, this);
536         myTeam.addWidget(myWidget);
537         var newHTML = this.innerHTML;
538         if (newHTML !== oldHTML) {
539           myTeam.info("widget " + type + " HTML changed: reparsing");
540           makeWidgetsWithin(level+1, $(this));
541         }
542       });
543     });
544     return true;
545   }
546
547
548   // The second "rootsel" parameter is passed to jQuery and is a DOM node
549   // or a selector string you would like to constrain the search for widgets to.
550   //
551   // This function has no side effects if run again on an operating session,
552   // even if the element/selector passed causes existing widgets to be reparsed: 
553   //
554   // (TODO: that last bit isn't true and we currently have to avoid reinitialising
555   // widgets, MKWS-261)
556   //
557   // * configuration is not regenerated
558   // * authentication is not performed again
559   // * autosearches are not re-run
560   mkws.init = function(message, rootsel) {
561     var greet = "MKWS initialised";
562     if (rootsel) greet += " (limited to " + rootsel + ")"
563     if (message) greet += " :: " + message; 
564     mkws.info(greet);
565
566     // MKWS is not active until init() has been run against an object with widget nodes.
567     // We only set initial configuration when MKWS is first activated.
568     if (!mkws.isActive) {
569       var widgetSelector = selectorForAllWidgets();
570       if ($(widgetSelector).length < 1) {
571         mkws.warn("no widgets found");
572         return;
573       }
574
575       // Initial configuration
576       mkws.autoHasAuto = false;
577       var saved_config;
578       if (typeof mkws_config === 'undefined') {
579         mkws.info("setting empty config");
580         saved_config = {};
581       } else {
582         mkws.info("using config: " + $.toJSON(mkws_config));
583         saved_config = mkws_config;
584       }
585       mkws.setMkwsConfig(saved_config);
586
587       for (var key in mkws.config) {
588         if (mkws.config.hasOwnProperty(key)) {
589           if (key.match(/^language_/)) {
590             var lang = key.replace(/^language_/, "");
591             // Copy custom languages into list
592             mkws.locale_lang[lang] = mkws.config[key];
593             mkws.info("added locally configured language '" + lang + "'");
594           }
595         }
596       }
597
598       var lang = mkws.getParameterByName("lang") || mkws.config.lang;
599       if (!lang || !mkws.locale_lang[lang]) {
600         mkws.config.lang = ""
601       } else {
602         mkws.config.lang = lang;
603       }
604
605       mkws.info("using language: " + (mkws.config.lang ? mkws.config.lang : "none"));
606
607       // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
608       if (mkws.pazpar2_url().match(/^\/\//)) {
609         mkws.config.pazpar2_url = document.location.protocol + mkws.config.pazpar2_url;
610         mkws.info("adjusted protocol independent link to " + mkws.pazpar2_url());
611       }
612
613       if (mkws.config.responsive_design_width) {
614         // Responsive web design - change layout on the fly based on
615         // current screen width. Required for mobile devices.
616         $(window).resize(resizePage);
617         // initial check after page load
618         $(document).ready(resizePage);
619       }
620     }
621
622     var then = $.now();
623     // If we've made no widgets, return without starting an SP session
624     // or marking MKWS active.
625     if (makeWidgetsWithin(1, rootsel ? $(rootsel) : undefined) === false) {
626       return false;
627     }
628     var now = $.now();
629
630     mkws.info("walking MKWS nodes took " + (now-then) + " ms");
631     for (var tName in mkws.teams) {
632       var myTeam = mkws.teams[tName]
633       myTeam.makePz2();
634       myTeam.info("made PZ2 object");
635       /*
636         myTeam.visitWidgets(function(t, w) {
637           mkws.debug("  has widget of type '" + t + "': " + w);
638         });
639       */
640     }
641
642     function sp_auth_url(config) {
643       if (config.service_proxy_auth) {
644         mkws.info("using pre-baked sp_auth_url '" + config.service_proxy_auth + "'");
645         return config.service_proxy_auth;
646       } else {
647         var s = '//';
648         s += config.sp_auth_hostname ? config.sp_auth_hostname : config.pp2_hostname;
649         s += '/';
650         s += config.sp_auth_path ? config.sp_auth_path : config.pp2_path;
651         var q = config.sp_auth_query;
652         if (q) {
653           s += '?' + q;
654         }
655         var c = config.sp_auth_credentials;
656         if (c) {
657           s += ('&username=' + c.substr(0, c.indexOf('/')) +
658                 '&password=' + c.substr(c.indexOf('/')+1));
659         }
660         mkws.info("generated sp_auth_url '" + s + "'");
661         return s;
662       }
663     }
664
665     if (mkws.config.use_service_proxy && !mkws.authenticated && !mkws.authenticating) {
666       authenticateSession(sp_auth_url(mkws.config),
667                           mkws.config.service_proxy_auth_domain,
668                           mkws.pazpar2_url());
669     } else if (!mkws.authenticating) {
670       // raw pp2 or we have a session already open
671       runAutoSearches();
672     }
673     
674     mkws.isActive = true;
675     return true;
676   };
677
678   $(document).ready(function() {
679     if (!window.mkws_noready && !mkws.authenticating && !mkws.active) {
680        mkws.init();
681     }
682   });
683
684 })(mkws.$);