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