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