Merge branch 'master' into urlstate
[mkws-moved-to-github.git] / src / mkws-team.js
1 "use strict";
2 // Factory function for team objects. As much as possible, this uses
3 // only member variables (prefixed "m_") and inner functions with
4 // private scope.
5 //
6 // Some functions are visible as member-functions to be called from
7 // outside code -- specifically, from generated HTML. These functions
8 // are that.switchView(), showDetails(),
9 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
10 // pagerPrev(), pagerNext().
11 //
12 // Before the team can be used for searching and related operations,
13 // its pz2 object must be created by calling team.makePz2().
14 //
15 mkws.makeTeam = function($, teamName) {
16   var that = {};
17
18   // Member variables are separated into two categories
19
20   // 1. Persistent state (to be coded in URL fragment)
21   var m_state = {
22     query: null,                // initially undefined
23     sort: null,                 // will be set below
24     size: null,                 // will be set below
25     page: 1,
26     recid: '',
27     filters: filterSet(that)
28   }
29
30   // 2. Internal state (not to be coded)
31   var m_teamName = teamName;
32   var m_paz; // will be initialised below
33   var m_submitted = false;
34   var m_totalRecordCount = 0;
35   var m_currentRecordData = null;
36   var m_logTime = {
37     // Timestamps for logging
38     "start": $.now(),
39     "last": $.now()
40   };
41   var m_templateText = {}; // widgets can register templates to be compiled
42   var m_template = {}; // compiled templates, from any source
43   var m_widgets = {}; // Maps widget-type to array of widget objects
44   var m_gotRecords = false;
45   
46   var config = mkws.objectInheritingFrom(mkws.config);
47   that.config = config;
48
49   that.toString = function() { return '[Team ' + teamName + ']'; };
50
51   // Accessor methods for individual widgets: readers
52   that.name = function() { return m_teamName; };
53   that.submitted = function() { return m_submitted; };
54   that.sortOrder = function() { return m_state.sort; };
55   that.perpage = function() { return m_state.size; };
56   that.query = function() { return m_state.query; };
57   that.totalRecordCount = function() { return m_totalRecordCount; };
58   that.currentPage = function() { return m_state.page; };
59   that.currentRecordId = function() { return m_state.recid; };
60   that.currentRecordData = function() { return m_currentRecordData; };
61   that.filters = function() { return m_state.filters; };
62   that.gotRecords = function() { return m_gotRecords; };
63
64   // Accessor methods for individual widgets: writers
65   that.set_sortOrder = function(val) { m_state.sort = val };
66   that.set_perpage = function(val) { m_state.size = val };
67
68   m_state.sort = config.sort_default;
69   m_state.size = config.perpage_default;
70
71   var m_default = $.extend(true, {}, m_state);
72   var tmp = m_default.filters;
73   delete m_default.filters;
74   $.extend(m_default, tmp.fragmentItems());
75
76   that.urlFragment = function(overrides) {
77     var s;
78
79     // Expand the filterSet into a set of key=value properties 
80     var state = $.extend(true, {}, m_state, overrides ? overrides : {});
81     var tmp = state.filters;
82     delete state.filters;
83     $.extend(state, tmp.fragmentItems());
84
85     for (var key in state) {
86       if (state.hasOwnProperty(key) &&
87           state[key] != m_default[key]) {
88         if (!s) {
89           var s = 'mkws';
90           if (m_teamName !== 'AUTO') s += m_teamName;
91           s += '=';
92         } else {
93           s += "@";
94         }
95
96         // ### how do we need to quote this?
97         s += key + '=' + state[key];
98       }
99     }
100
101     return s;
102   }
103
104   // ### what quoting do we need to undo? Complement of previous function
105   that.parseFragment = function(s) {
106     var x = {};
107
108     var list = s.split('@');
109     for (var i in list) {
110       var a = list[i].split('=');
111       x[a[0]] = a[1];
112     }
113
114     return x;
115   }
116
117   that.handleChanges = function(oldState, newState) {
118     var reSearch = false;
119     var reShow = false;
120     var showPage = undefined;
121
122     for (var key in newState) {
123       var val = newState[key];
124       if (newState.hasOwnProperty(key) &&
125           (!oldState || val != oldState[key])) {
126         that.warn("changed property " + key + ": " + 
127                   (oldState ? ("'" + oldState[key] + "'") : "undefined") +
128                   " -> '" + val + "'");
129         if (key === 'query') {
130           m_state.query = val;
131           reSearch = true;
132         } else if (key === 'page') {
133           showPage = parseInt(val);
134         } else if (key === 'sort') {
135           that.set_sortOrder(val);
136           if (m_state.query) reShow = true;
137         } else if (key === 'size') {
138           that.set_perpage(val);
139           if (m_state.query) reShow = true;
140         } else if (key.indexOf('xt-') == 0) {
141           limitTarget(key.substring(3), val);
142           that.warn("limited target to " + val + ": m_state.query=" + m_state.query);
143           if (m_state.query) reSearch = true;
144         } else if (key.indexOf('xf-') == 0) {
145           var a = key.split('-');
146           limitQuery(a[1], a[2]);
147           if (m_state.query) reSearch = true;
148         } else {
149           that.warn("unsupported fragment property '" + key + "'='" + val + "'");
150         }
151       }
152     }
153
154     if (reSearch) {
155       that.warn("searching");
156       triggerSearch();
157     } else if (showPage) {
158       that.warn("showing page " + showPage);
159       that.showPage(showPage);
160     } else if (reShow) {
161       that.warn("showing");
162       that.reShow();      
163     }
164   };
165
166
167   // The following PubSub code is modified from the jQuery manual:
168   // http://api.jquery.com/jQuery.Callbacks/
169   //
170   // Use as:
171   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
172   //    team.queue("eventName").publish(arg1, arg2, ...);
173   //
174   var m_queues = {};
175   function queue(id) {
176     if (!m_queues[id]) {
177       var callbacks = $.Callbacks();
178       m_queues[id] = {
179         publish: callbacks.fire,
180         subscribe: callbacks.add,
181         unsubscribe: callbacks.remove
182       };
183     }
184     return m_queues[id];
185   };
186   that.queue = queue;
187
188
189   function _log(fn, s) {
190     var now = $.now();
191     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
192                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
193     m_logTime.last = now;
194     fn.call(mkws.log, m_teamName + ": " + timestamp + s);
195     that.queue("log").publish(m_teamName, timestamp, s);
196   }
197
198   that.trace = function(x) { _log(mkws.trace, x) };
199   that.debug = function(x) { _log(mkws.debug, x) };
200   that.info = function(x) { _log(mkws.info, x) };
201   that.warn = function(x) { _log(mkws.warn, x) };
202   that.error = function(x) { _log(mkws.error, x) };
203   that.fatal = function(x) { _log(mkws.fatal, x) };
204
205   that.info("making new widget team");
206
207   // pz2.js event handlers:
208   function onInit() {
209     that.info("init");
210     m_paz.stat();
211     m_paz.bytarget();
212   }
213
214   function onBytarget(data) {
215     that.info("bytarget");
216     queue("targets").publish(data);
217   }
218
219   function onStat(data) {
220     queue("stat").publish(data);
221     var hitcount = parseInt(data.hits[0], 10);
222     if (!m_gotRecords && hitcount > 0) {
223       m_gotRecords = true;
224       queue("firstrecords").publish(hitcount);
225     }
226     if (parseInt(data.activeclients[0], 10) === 0) {
227       that.info("complete");
228       queue("complete").publish(hitcount);
229     }
230   }
231
232   function onTerm(data) {
233     that.info("term");
234     queue("facets").publish(data);
235   }
236
237   function onShow(data, teamName) {
238     that.info("show");
239     m_totalRecordCount = data.merged;
240     that.info("found " + m_totalRecordCount + " records");
241     queue("pager").publish(data);
242     queue("records").publish(data);
243   }
244
245   function onRecord(data, args, teamName) {
246     that.info("record");
247     // FIXME: record is async!!
248     clearTimeout(m_paz.recordTimer);
249     queue("record").publish(data);
250     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
251     if (detRecordDiv.length) {
252       // in case on_show was faster to redraw element
253       return;
254     }
255     m_currentRecordData = data;
256     var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
257     var html = renderDetails(m_currentRecordData);
258     $(recordDiv).append(html);
259   }
260
261
262   // create a parameters array and pass it to the pz2's constructor
263   // then register the form submit event with the pz2.search function
264   // autoInit is set to true on default
265   that.makePz2 = function() {
266     that.debug("m_queues=" + $.toJSON(m_queues));
267     var params = {
268       "windowid": teamName,
269       "pazpar2path": mkws.pazpar2_url(),
270       "usesessions" : config.use_service_proxy ? false : true,
271       "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
272       "termlist": config.facets.join(',')
273     };
274
275     params.oninit = onInit;
276     if (m_queues.targets) {
277       params.onbytarget = onBytarget;
278       that.info("setting bytarget callback");
279     }
280     if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
281       params.onstat = onStat;
282       that.info("setting stat callback");
283     }
284     if (m_queues.facets && config.facets.length) {
285       params.onterm = onTerm;
286       that.info("setting term callback");
287     }
288     if (m_queues.records) {
289       that.info("setting show callback");
290       params.onshow = onShow;
291       // Record callback is subscribed from records callback
292       that.info("setting record callback");
293       params.onrecord = onRecord;
294     }
295
296     m_paz = new pz2(params);
297     that.info("created main pz2 object");
298   }
299
300
301   // Used by the Records widget and onRecord()
302   function recordElementId(s) {
303     return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
304   }
305   that.recordElementId = recordElementId;
306
307   // Used by onRecord(), showDetails() and renderDetails()
308   function recordDetailsId(s) {
309     return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
310   }
311
312
313   that.targetFiltered = function(id) {
314     return m_state.filters.targetFiltered(id);
315   };
316
317
318   function limitTarget(id, name) {
319     that.info("limitTarget(id=" + id + ", name=" + name + ")");
320     m_state.filters.add(targetFilter(id, name));
321     return false;
322   };
323
324
325   function limitQuery(field, value) {
326     that.info("limitQuery(field=" + field + ", value=" + value + ")");
327     m_state.filters.add(fieldFilter(field, value));
328     return false;
329   };
330
331
332   that.limitCategory = function(id) {
333     that.info("limitCategory(id=" + id + ")");
334     // Only one category filter at a time
335     m_state.filters.removeMatching(function(f) { return f.type === 'category' });
336     if (id !== '') m_state.filters.add(categoryFilter(id));
337     if (m_state.query) triggerSearch();
338     return false;
339   };
340
341
342   that.delimitTarget = function(id) {
343     that.info("delimitTarget(id=" + id + ")");
344     m_state.filters.removeMatching(function(f) { return f.type === 'target' });
345     if (m_state.query) triggerSearch();
346     return false;
347   };
348
349
350   that.delimitQuery = function(field, value) {
351     that.info("delimitQuery(field=" + field + ", value=" + value + ")");
352     m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
353                                              field == f.field && value == f.value });
354     if (m_state.query) triggerSearch();
355     return false;
356   };
357
358
359   that.showPage = function(pageNum) {
360     m_state.page = pageNum;
361     m_paz.showPage(m_state.page - 1);
362     that.warn("fragment: " + that.urlFragment());
363   };
364
365
366   that.pagerNext = function() {
367     if (m_totalRecordCount - m_state.size * m_state.page > 0) {
368       m_paz.showNext();
369       m_state.page++;
370       that.warn("fragment: " + that.urlFragment());
371     }
372   };
373
374
375   that.pagerPrev = function() {
376     if (m_paz.showPrev() != false) {
377       m_state.page--;
378       that.warn("fragment: " + that.urlFragment());
379     }
380   };
381
382
383   that.reShow = function() {
384     resetPage();
385     m_paz.show(0, m_state.size, m_state.sort);
386     // ### not really the right place for this but it will do for now.
387     that.warn("fragment: " + that.urlFragment());
388   };
389
390
391   function resetPage() {
392     m_state.page = 1;
393     m_totalRecordCount = 0;
394     m_gotRecords = false;
395   }
396   that.resetPage = resetPage;
397
398
399   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
400     that.info("newSearch: " + query);
401
402     if (config.use_service_proxy && !mkws.authenticated) {
403       alert("searching before authentication");
404       return;
405     }
406
407     m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
408     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
409     switchView('records'); // In case it's configured to start off as hidden
410     m_submitted = true;
411   }
412   that.newSearch = newSearch;
413
414
415   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
416     resetPage();
417
418     // Continue to use previous query/sort-order unless new ones are specified
419     if (query) m_state.query = query;
420     if (sortOrder) m_state.sort = sortOrder;
421     if (perpage) m_state.size = perpage;
422     if (targets) m_state.filters.add(targetFilter(targets, targets));
423
424     var pp2filter = m_state.filters.pp2filter();
425     var pp2limit = m_state.filters.pp2limit(limit);
426     var pp2catLimit = m_state.filters.pp2catLimit();
427     if (pp2catLimit) {
428       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
429     }
430
431     var params = {};
432     if (pp2limit) params.limit = pp2limit;
433     if (maxrecs) params.maxrecs = maxrecs;
434     if (torusquery) {
435       if (!mkws.config.use_service_proxy)
436         alert("can't narrow search by torusquery when not authenticated");
437       params.torusquery = torusquery;
438     }
439
440     that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
441         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
442
443     m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
444     queue("searchtriggered").publish();
445
446     // ### not really the right place for this but it will do for now.
447     that.warn("fragment: " + that.urlFragment());
448   }
449
450   // fetch record details to be retrieved from the record queue
451   that.fetchDetails = function(recId) {
452     that.info("fetchDetails() requesting record '" + recId + "'");
453     m_paz.record(recId);
454     that.warn("fragment: " + that.urlFragment());
455   };
456
457
458   // switching view between targets and records
459   function switchView(view) {
460     var targets = widgetNode('targets');
461     var results = widgetNode('results') || widgetNode('records');
462     var blanket = widgetNode('blanket');
463     var motd    = widgetNode('motd');
464
465     switch(view) {
466     case 'targets':
467       if (targets) $(targets).show();
468       if (results) $(results).hide();
469       if (blanket) $(blanket).hide();
470       if (motd) $(motd).hide();
471       break;
472     case 'records':
473       if (targets) $(targets).hide();
474       if (results) $(results).show();
475       if (blanket) $(blanket).show();
476       if (motd) $(motd).hide();
477       break;
478     default:
479       alert("Unknown view '" + view + "'");
480     }
481   }
482   that.switchView = switchView;
483
484
485   // detailed record drawing
486   that.showDetails = function(recId) {
487     var oldRecordId = m_state.recid;
488     m_state.recid = recId;
489
490     // remove current detailed view if any
491     findnode('#' + recordDetailsId(oldRecordId)).remove();
492
493     // if the same clicked, just hide
494     if (recId == oldRecordId) {
495       m_state.recid = '';
496       m_currentRecordData = null;
497       return;
498     }
499     // request the record
500     that.info("showDetails() requesting record '" + recId + "'");
501     m_paz.record(recId);
502   };
503
504
505   // Finds the node of the specified class within the current team
506   function findnode(selector, teamName) {
507     teamName = teamName || m_teamName;
508
509     if (teamName === 'AUTO') {
510       selector = (selector + '.mkws-team-' + teamName + ',' +
511                   selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
512     } else {
513       selector = selector + '.mkws-team-' + teamName;
514     }
515
516     var node = $(selector);
517     //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
518     return node;
519   }
520
521
522   function widgetNode(type) {
523     var w = that.widget(type);
524     return w ? w.node : undefined;
525   }
526
527   function renderDetails(data, marker) {
528     var template = loadTemplate("details");
529     var details = template(data);
530     return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
531       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
532   }
533   that.renderDetails = renderDetails;
534
535
536   that.registerTemplate = function(name, text) {
537     if(mkws._old2new.hasOwnProperty(name)) {
538       that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
539       name = mkws._old2new[name];
540     }
541     m_templateText[name] = text;
542   };
543
544
545   function loadTemplate(name, fallbackString) {
546     if(mkws._old2new.hasOwnProperty(name)) {
547        that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
548        name = mkws._old2new[name];
549     }
550
551     var template = m_template[name];
552     if (template === undefined && Handlebars.compile) {
553       var source;
554       var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
555       if (node && node.length < 1) {
556         node = $(".mkws-template-" + name);
557       }
558       if (node) source = node.html();
559       if (!source) source = m_templateText[name];
560       if (source) {
561         template = Handlebars.compile(source);
562         that.info("compiled template '" + name + "'");
563       }
564     }
565     //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
566     if (template === undefined && Handlebars.templates) {
567       template = Handlebars.templates["mkws-template-" + name];
568     }
569     if (template === undefined && mkws.defaultTemplates) {
570       template = mkws.defaultTemplates[name];
571     }
572     if (template) {
573       m_template[name] = template;
574       return template;
575     }
576     else {
577       that.info("No MKWS template for " + name);
578       return null;
579     }  
580   }
581   that.loadTemplate = loadTemplate;
582
583
584   that.addWidget = function(w) {
585     if (m_widgets[w.type] === undefined) {
586       m_widgets[w.type] = [ w ];
587     } else {
588       m_widgets[w.type].push(w);
589     }
590   }
591
592   that.widget = function(type) {
593     var list = m_widgets[type];
594
595     if (!list)
596       return undefined;
597     if (list.length > 1) {
598       alert("widget('" + type + "') finds " + list.length + " widgets: using first");
599     }
600     return list[0];
601   }
602
603   that.visitWidgets = function(callback) {
604     for (var type in m_widgets) {
605       var list = m_widgets[type];
606       for (var i = 0; i < list.length; i++) {
607         var res = callback(type, list[i]);
608         if (res !== undefined) {
609           return res;
610         }
611       }
612     }
613     return undefined;
614   };
615
616   return that;
617 };