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