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