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