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