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