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