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