Do not pass unused field "field" into facet template.
[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(), limitTarget(), limitQuery(),
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     for (var key in newState) {
119       var val = newState[key];
120       if (newState.hasOwnProperty(key) &&
121           (!oldState || val != oldState[key])) {
122         that.warn("changed property " + key + ": " + 
123                   (oldState ? ("'" + oldState[key] + "'") : "undefined") +
124                   " -> '" + val + "'");
125         if (key === 'page') {
126           that.showPage(parseInt(val));
127         } else if (key === 'sort') {
128           that.set_sortOrder(val);
129           if (that.submitted()) {
130             that.reShow();
131           }
132         } else if (key === 'size') {
133           that.set_perpage(val);
134           if (that.submitted()) {
135             that.reShow();
136           }
137         }
138       }
139     }
140   };
141
142
143   // The following PubSub code is modified from the jQuery manual:
144   // http://api.jquery.com/jQuery.Callbacks/
145   //
146   // Use as:
147   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
148   //    team.queue("eventName").publish(arg1, arg2, ...);
149   //
150   var m_queues = {};
151   function queue(id) {
152     if (!m_queues[id]) {
153       var callbacks = $.Callbacks();
154       m_queues[id] = {
155         publish: callbacks.fire,
156         subscribe: callbacks.add,
157         unsubscribe: callbacks.remove
158       };
159     }
160     return m_queues[id];
161   };
162   that.queue = queue;
163
164
165   function _log(fn, s) {
166     var now = $.now();
167     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
168                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
169     m_logTime.last = now;
170     fn.call(mkws.log, m_teamName + ": " + timestamp + s);
171     that.queue("log").publish(m_teamName, timestamp, s);
172   }
173
174   that.trace = function(x) { _log(mkws.trace, x) };
175   that.debug = function(x) { _log(mkws.debug, x) };
176   that.info = function(x) { _log(mkws.info, x) };
177   that.warn = function(x) { _log(mkws.warn, x) };
178   that.error = function(x) { _log(mkws.error, x) };
179   that.fatal = function(x) { _log(mkws.fatal, x) };
180
181   that.info("making new widget team");
182
183   // pz2.js event handlers:
184   function onInit() {
185     that.info("init");
186     m_paz.stat();
187     m_paz.bytarget();
188   }
189
190   function onBytarget(data) {
191     that.info("bytarget");
192     queue("targets").publish(data);
193   }
194
195   function onStat(data) {
196     queue("stat").publish(data);
197     var hitcount = parseInt(data.hits[0], 10);
198     if (!m_gotRecords && hitcount > 0) {
199       m_gotRecords = true;
200       queue("firstrecords").publish(hitcount);
201     }
202     if (parseInt(data.activeclients[0], 10) === 0) {
203       that.info("complete");
204       queue("complete").publish(hitcount);
205     }
206   }
207
208   function onTerm(data) {
209     that.info("term");
210     queue("facets").publish(data);
211   }
212
213   function onShow(data, teamName) {
214     that.info("show");
215     m_totalRecordCount = data.merged;
216     that.info("found " + m_totalRecordCount + " records");
217     queue("pager").publish(data);
218     queue("records").publish(data);
219   }
220
221   function onRecord(data, args, teamName) {
222     that.info("record");
223     // FIXME: record is async!!
224     clearTimeout(m_paz.recordTimer);
225     queue("record").publish(data);
226     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
227     if (detRecordDiv.length) {
228       // in case on_show was faster to redraw element
229       return;
230     }
231     m_currentRecordData = data;
232     var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
233     var html = renderDetails(m_currentRecordData);
234     $(recordDiv).append(html);
235   }
236
237
238   // create a parameters array and pass it to the pz2's constructor
239   // then register the form submit event with the pz2.search function
240   // autoInit is set to true on default
241   that.makePz2 = function() {
242     that.debug("m_queues=" + $.toJSON(m_queues));
243     var params = {
244       "windowid": teamName,
245       "pazpar2path": mkws.pazpar2_url(),
246       "usesessions" : config.use_service_proxy ? false : true,
247       "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
248       "termlist": config.facets.join(',')
249     };
250
251     params.oninit = onInit;
252     if (m_queues.targets) {
253       params.onbytarget = onBytarget;
254       that.info("setting bytarget callback");
255     }
256     if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
257       params.onstat = onStat;
258       that.info("setting stat callback");
259     }
260     if (m_queues.facets && config.facets.length) {
261       params.onterm = onTerm;
262       that.info("setting term callback");
263     }
264     if (m_queues.records) {
265       that.info("setting show callback");
266       params.onshow = onShow;
267       // Record callback is subscribed from records callback
268       that.info("setting record callback");
269       params.onrecord = onRecord;
270     }
271
272     m_paz = new pz2(params);
273     that.info("created main pz2 object");
274   }
275
276
277   // Used by the Records widget and onRecord()
278   function recordElementId(s) {
279     return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
280   }
281   that.recordElementId = recordElementId;
282
283   // Used by onRecord(), showDetails() and renderDetails()
284   function recordDetailsId(s) {
285     return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
286   }
287
288
289   that.targetFiltered = function(id) {
290     return m_state.filters.targetFiltered(id);
291   };
292
293
294   that.limitTarget = function(id, name) {
295     that.info("limitTarget(id=" + id + ", name=" + name + ")");
296     m_state.filters.add(targetFilter(id, name));
297     if (m_state.query) triggerSearch();
298     return false;
299   };
300
301
302   that.limitQuery = function(field, value) {
303     that.info("limitQuery(field=" + field + ", value=" + value + ")");
304     m_state.filters.add(fieldFilter(field, value));
305     if (m_state.query) triggerSearch();
306     return false;
307   };
308
309
310   that.limitCategory = function(id) {
311     that.info("limitCategory(id=" + id + ")");
312     // Only one category filter at a time
313     m_state.filters.removeMatching(function(f) { return f.type === 'category' });
314     if (id !== '') m_state.filters.add(categoryFilter(id));
315     if (m_state.query) triggerSearch();
316     return false;
317   };
318
319
320   that.delimitTarget = function(id) {
321     that.info("delimitTarget(id=" + id + ")");
322     m_state.filters.removeMatching(function(f) { return f.type === 'target' });
323     if (m_state.query) triggerSearch();
324     return false;
325   };
326
327
328   that.delimitQuery = function(field, value) {
329     that.info("delimitQuery(field=" + field + ", value=" + value + ")");
330     m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
331                                              field == f.field && value == f.value });
332     if (m_state.query) triggerSearch();
333     return false;
334   };
335
336
337   that.showPage = function(pageNum) {
338     m_state.page = pageNum;
339     m_paz.showPage(m_state.page - 1);
340     that.warn("fragment: " + that.urlFragment());
341   };
342
343
344   that.pagerNext = function() {
345     if (m_totalRecordCount - m_state.size * m_state.page > 0) {
346       m_paz.showNext();
347       m_state.page++;
348       that.warn("fragment: " + that.urlFragment());
349     }
350   };
351
352
353   that.pagerPrev = function() {
354     if (m_paz.showPrev() != false) {
355       m_state.page--;
356       that.warn("fragment: " + that.urlFragment());
357     }
358   };
359
360
361   that.reShow = function() {
362     resetPage();
363     m_paz.show(0, m_state.size, m_state.sort);
364     // ### not really the right place for this but it will do for now.
365     that.warn("fragment: " + that.urlFragment());
366   };
367
368
369   function resetPage() {
370     m_state.page = 1;
371     m_totalRecordCount = 0;
372     m_gotRecords = false;
373   }
374   that.resetPage = resetPage;
375
376
377   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
378     that.info("newSearch: " + query);
379
380     if (config.use_service_proxy && !mkws.authenticated) {
381       alert("searching before authentication");
382       return;
383     }
384
385     m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
386     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
387     switchView('records'); // In case it's configured to start off as hidden
388     m_submitted = true;
389   }
390   that.newSearch = newSearch;
391
392
393   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
394     resetPage();
395
396     // Continue to use previous query/sort-order unless new ones are specified
397     if (query) m_state.query = query;
398     if (sortOrder) m_state.sort = sortOrder;
399     if (perpage) m_state.size = perpage;
400     if (targets) m_state.filters.add(targetFilter(targets, targets));
401
402     var pp2filter = m_state.filters.pp2filter();
403     var pp2limit = m_state.filters.pp2limit(limit);
404     var pp2catLimit = m_state.filters.pp2catLimit();
405     if (pp2catLimit) {
406       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
407     }
408
409     var params = {};
410     if (pp2limit) params.limit = pp2limit;
411     if (maxrecs) params.maxrecs = maxrecs;
412     if (torusquery) {
413       if (!mkws.config.use_service_proxy)
414         alert("can't narrow search by torusquery when not authenticated");
415       params.torusquery = torusquery;
416     }
417
418     that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
419         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
420
421     m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
422     queue("searchtriggered").publish();
423
424     // ### not really the right place for this but it will do for now.
425     that.warn("fragment: " + that.urlFragment());
426   }
427
428   // fetch record details to be retrieved from the record queue
429   that.fetchDetails = function(recId) {
430     that.info("fetchDetails() requesting record '" + recId + "'");
431     m_paz.record(recId);
432     that.warn("fragment: " + that.urlFragment());
433   };
434
435
436   // switching view between targets and records
437   function switchView(view) {
438     var targets = widgetNode('targets');
439     var results = widgetNode('results') || widgetNode('records');
440     var blanket = widgetNode('blanket');
441     var motd    = widgetNode('motd');
442
443     switch(view) {
444     case 'targets':
445       if (targets) $(targets).show();
446       if (results) $(results).hide();
447       if (blanket) $(blanket).hide();
448       if (motd) $(motd).hide();
449       break;
450     case 'records':
451       if (targets) $(targets).hide();
452       if (results) $(results).show();
453       if (blanket) $(blanket).show();
454       if (motd) $(motd).hide();
455       break;
456     default:
457       alert("Unknown view '" + view + "'");
458     }
459   }
460   that.switchView = switchView;
461
462
463   // detailed record drawing
464   that.showDetails = function(recId) {
465     var oldRecordId = m_state.recid;
466     m_state.recid = recId;
467
468     // remove current detailed view if any
469     findnode('#' + recordDetailsId(oldRecordId)).remove();
470
471     // if the same clicked, just hide
472     if (recId == oldRecordId) {
473       m_state.recid = '';
474       m_currentRecordData = null;
475       return;
476     }
477     // request the record
478     that.info("showDetails() requesting record '" + recId + "'");
479     m_paz.record(recId);
480   };
481
482
483   // Finds the node of the specified class within the current team
484   function findnode(selector, teamName) {
485     teamName = teamName || m_teamName;
486
487     if (teamName === 'AUTO') {
488       selector = (selector + '.mkws-team-' + teamName + ',' +
489                   selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
490     } else {
491       selector = selector + '.mkws-team-' + teamName;
492     }
493
494     var node = $(selector);
495     //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
496     return node;
497   }
498
499
500   function widgetNode(type) {
501     var w = that.widget(type);
502     return w ? w.node : undefined;
503   }
504
505   function renderDetails(data, marker) {
506     var template = loadTemplate("details");
507     var details = template(data);
508     return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
509       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
510   }
511   that.renderDetails = renderDetails;
512
513
514   that.registerTemplate = function(name, text) {
515     if(mkws._old2new.hasOwnProperty(name)) {
516       that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
517       name = mkws._old2new[name];
518     }
519     m_templateText[name] = text;
520   };
521
522
523   function loadTemplate(name, fallbackString) {
524     if(mkws._old2new.hasOwnProperty(name)) {
525        that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
526        name = mkws._old2new[name];
527     }
528
529     var template = m_template[name];
530     if (template === undefined && Handlebars.compile) {
531       var source;
532       var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
533       if (node && node.length < 1) {
534         node = $(".mkws-template-" + name);
535       }
536       if (node) source = node.html();
537       if (!source) source = m_templateText[name];
538       if (source) {
539         template = Handlebars.compile(source);
540         that.info("compiled template '" + name + "'");
541       }
542     }
543     //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
544     if (template === undefined && Handlebars.templates) {
545       template = Handlebars.templates["mkws-template-" + name];
546     }
547     if (template === undefined && mkws.defaultTemplates) {
548       template = mkws.defaultTemplates[name];
549     }
550     if (template) {
551       m_template[name] = template;
552       return template;
553     }
554     else {
555       that.info("No MKWS template for " + name);
556       return null;
557     }  
558   }
559   that.loadTemplate = loadTemplate;
560
561
562   that.addWidget = function(w) {
563     if (m_widgets[w.type] === undefined) {
564       m_widgets[w.type] = [ w ];
565     } else {
566       m_widgets[w.type].push(w);
567     }
568   }
569
570   that.widget = function(type) {
571     var list = m_widgets[type];
572
573     if (!list)
574       return undefined;
575     if (list.length > 1) {
576       alert("widget('" + type + "') finds " + list.length + " widgets: using first");
577     }
578     return list[0];
579   }
580
581   that.visitWidgets = function(callback) {
582     for (var type in m_widgets) {
583       var list = m_widgets[type];
584       for (var i = 0; i < list.length; i++) {
585         var res = callback(type, list[i]);
586         if (res !== undefined) {
587           return res;
588         }
589       }
590     }
591     return undefined;
592   };
593
594   return that;
595 };